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
dc3b53f5953750c3b7ee4be6e46c1dc1fbf80d85
Ruby
maxgrok/ruby-objects-belong-to-lab-cb-000
/lib/author.rb
UTF-8
112
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Author attr_accessor :name def initialize @name = name end def author @name end #has name end
true
967e71cf7e41905c847d5e6b052ab6ebbde7613b
Ruby
choncou/exercism_solutions
/ruby/rail-fence-cipher/rail_fence_cipher.rb
UTF-8
1,777
3.078125
3
[]
no_license
class RailFenceCipher VERSION = 1 def self.encode(data, rails) return data if rails == 1 @chars = data.chars @encoded_table = [] rails.times { @encoded_table << Array.new(2) } current = -1 while @chars.size > 0 0.upto(rails-2).each do |row| current += 1 @encoded_table[row][current] = @chars.shift end (rails-1).downto(1).each do |row| current += 1 @encoded_table[row][current] = @chars.shift end end @encoded_table.join end def self.decode(encoded, rails) return encoded if rails == 1 || encoded == '' cycle = (rails*2)-2 @chars = encoded.chars units = @chars.size/cycle @encoded_table = [].tap do |x| rails.times { x << Array.new(units * cycle + (@chars.size % units)) } end # insert encoded chars into the table/puzzle prev = nil @encoded_table.map!.with_index do |row, rail| if rail > 0 prev.each_with_index do |val, index| next unless val if rail == 1 row[index - 1] = @chars.shift unless row[index - 1] || index == 0 end row[index+rail] = @chars.shift unless row[index+rail] || index == row.size-rail end else col = 0 until col > row.size row[col] = @chars.shift col += cycle end end prev = row if rail == 0 row end # read through the puzzle to decode current = -1 while @chars.size <= encoded.size 0.upto(rails-2).each do |row| current += 1 @chars << @encoded_table[row][current] end (rails-1).downto(1).each do |row| current += 1 @chars << @encoded_table[row][current] end end @chars.join end end
true
08ed77e28c7872362b97e2e33f01bd7343f78f7e
Ruby
cucumber/aruba
/lib/aruba/matchers/command/have_output.rb
UTF-8
1,073
2.625
3
[ "MIT" ]
permissive
require "aruba/matchers/base/message_indenter" # @!method have_output # This matchers checks if <command> has created output # # @return [Boolean] The result # # false: # * if command has not created output # true: # * if command created output # # @example Use matcher # # RSpec.describe do # it { expect(last_command_started).to have_output } # end RSpec::Matchers.define :have_output do |expected| match do |actual| @old_actual = actual unless @old_actual.respond_to? :output raise "Expected #{@old_actual} to respond to #output" end @old_actual.stop @actual = sanitize_text(actual.output) values_match?(expected, @actual) end diffable description { "have output: #{description_of expected}" } failure_message do |_actual| "expected `#{@old_actual.commandline}` to have output #{description_of expected}\n" \ "but was:\n#{Aruba::Matchers::Base::MessageIndenter.indent_multiline_message @actual}" end end RSpec::Matchers.alias_matcher :a_command_having_output, :have_output
true
5dc7f7407390371abbe443bd8f59a3bbbd6fdf6c
Ruby
sleepingkingstudios/active_model-sleeping_king_studios
/lib/active_model/sleeping_king_studios/validations/relations/one.rb
UTF-8
1,148
2.640625
3
[ "MIT" ]
permissive
# lib/active_model/sleeping_king_studios/validations/relations/one.rb require 'active_model/sleeping_king_studios/validations/relations/base' module ActiveModel::SleepingKingStudios::Validations::Relations # The base validator for validating a one-to-one relation. class One < ActiveModel::SleepingKingStudios::Validations::Relations::Base # Checks the validity of the related model and merges any errors into the # primary model's #errors object. # # @param record [Object] An object extending ActiveModel::Validations and # with the specified relation. def validate record relation = record.send(relation_name) return if relation.blank? || (relation.errors.blank? && relation.valid?) relation.errors.each do |attribute, message| record.errors.add error_key(relation, attribute), message end # each end # method validate private def error_key relation, attribute serializer.serialize relation_name, *serializer.deserialize(attribute) end # method relation_key def relation_name :relation end # method relation_name end # class end # module
true
1fea7add3c1180edda97188ee1b5e3692d237aa8
Ruby
sepandb/learn_ruby
/exercise3/game.rb
UTF-8
1,148
3.28125
3
[]
no_license
class Game def score(array) total_score = 0 partion_score = organize_score(array) partion_score.each_with_index do |frame, index| if frame[0] == 10 next_2_frames = (partion_score[index +1].to_a + partion_score[index+2].to_a).flatten total_score = total_score + frame.inject(:+) + next_2_frames[0].to_i + next_2_frames[1].to_i elsif frame.inject(:+) == 10 total_score = total_score + frame.inject(:+) + partion_score[index+1][0].to_i else total_score = total_score + frame.inject(:+) end end return total_score end def organize_score(scores_array) new_array = [] while scores_array.length > 0 if scores_array[0] == 10 scores_array.delete_at(0) new_array.push([10]) else first_el = scores_array[0].to_i second_el = scores_array[1].to_i new_array.push([first_el, second_el]) scores_array.delete_at(0) scores_array.delete_at(0) end if new_array.length == 9 new_array.push([scores_array].flatten) scores_array = [] end end new_array end end
true
96acf97e7d426df77eedb3d10db953063c7ea97e
Ruby
sunny-b/backend_practice
/180_SQL/7/query.rb
UTF-8
1,056
2.59375
3
[]
no_license
require 'sequel' DB = Sequel.connect("postgres://localhost/sequel-single-table") def format_money(number) format('%.2f', number.to_f) end dataset = DB[:menu_items] dataset = dataset.select { [item, menu_price, ingredient_cost, ((prep_time / 60.0) * 12.0).as(labor), (menu_price - ingredient_cost - ((prep_time / 60.0) * 12.0)).as(profit)] } dataset.each do |row| puts row[:item] puts "menu price: $#{format_money(row[:menu_price])}" puts "ingredient cost: $#{format_money(row[:ingredient_cost])}" puts "labor: $#{format_money(row[:labor])}" puts "profit: $#{format_money(row[:profit])}" puts end DB[:events].select { [ events__name.as(event), events__starts_at, sections__name.as(section), seats__row, seats__number.as(seat) ] }.inner_join(:tickets, event_id: :events__id).inner_join(:seats, id: :tickets__seat_id).inner_join(:sections, id: :seats__section_id).inner_join(:customers, id: :tickets__customer_id).where(customers__email: 'gennaro.rath@mcdermott.co').all
true
2f9771abfab064f9831bda42d8745d940760c31e
Ruby
farski/rack-coffee_filter
/lib/rack-coffee_filter/filter.rb
UTF-8
944
2.515625
3
[ "MIT" ]
permissive
require "coffee-script" module Rack module CoffeeFilter class Filter def initialize(app, wrap_js = false) @wrap_js = wrap_js @app = app end def filtered_response(env) status, headers, body = @app.call(env) if !(200..299).cover?(status) return @app.call(env) else parts = [] body.each { |part| parts << part.to_s } javascript = [::CoffeeScript.compile(parts.join, { bare: !@wrap_js })] headers['Content-Length'] = javascript.length.to_s headers['Content-Type'] = 'application/javascript;charset=utf-8' headers['Cache-Control'] = 'private, max-age=0, no-cache' headers['Last-Modified'] = Time.now.to_s [200, headers, javascript] end end def call(env) env['PATH_INFO'].match(/\.coffee$/) ? filtered_response(env) : @app.call(env) end end end end
true
5adf4d5a24887f1a3df6b8fbc4a74a99d46d9bf7
Ruby
StephenVarela/multi_class_programs
/Cart.rb
UTF-8
720
3.46875
3
[]
no_license
require './Product.rb' class Cart def initialize @shopping_cart=[] end def add_item(name, price) @shopping_cart << Product.new(name,price) end def delete_item(item) @shopping_cart.delete(item) end def cost_before_tax cost = 0 @shopping_cart.each do |item| cost += item.base_price end return cost end def cost_after_tax cost = 0 @shopping_cart.each do |item| cost += item.total_price end return cost end end my_cart = Cart.new my_cart.add_item('Guitar1', 200) my_cart.add_item('Guitar2', 200) my_cart.add_item('Guitar3', 200) my_cart.add_item('Guitar4', 200) p before_tax = my_cart.cost_before_tax p after_tax = my_cart.cost_after_tax
true
921e2a73ee4aea107763aad9892a35a894a045f5
Ruby
vtasheva/ruby-retrospective-1
/solutions/03.rb
UTF-8
3,967
3.5625
4
[]
no_license
require 'bigdecimal' require 'bigdecimal/util' class Inventory attr_accessor :inventory def initialize @inventory = [] end def register(name, price, promotion = {}) new_product = Product.new(name, price, promotion) if @inventory.include? new_product raise "This product is already registered." end @inventory << new_product end def new_cart Cart.new inventory end end class Cart FRAMEWORK = "|------------------------------------------------|----------|\n" LINE = "+------------------------------------------------+----------+\n" ITEM_DEFINITION = "------------------------------------------------" PRICE_DEFINITION = "----------" attr_accessor :cart, :inventory def initialize(inventory) @cart = {} @inventory = inventory end def add(name, amount = 1) if !@inventory.select { |item| item.name == name } raise "This product does not exist in inventory." end if @cart.has_key? name add_existing_product name, amount else add_not_existing_product name, amount end end def total total = BigDecimal('') @cart.each do |key, amount| product = @inventory.select { |item| item.name == key }.first total += product.price * amount if product.promotion.has_key? :get_one_free total -= (amount / product.promotion[:get_one_free]) * product.price end end "%.2f" % total end def invoice items = get_items items_template = items.map { |product, value| process_item(product, value) } invoice_header << items_template.join << invoice_footer end private def get_items items = {} @cart.each do |key, amount| product = @inventory.select { |item| item.name == key}.first items[product.name] = product.price * amount if product.promotion.has_key? :get_one_free times = (amount / product.promotion[:get_one_free]) items[product.name] -= times * product.price end end items end def add_existing_product(name, amount) if @cart[name] + amount <= 0 || @cart[name] + amount > 99 raise "Not valid value for amount" end @cart[name] += amount end def add_not_existing_product(name, amount) if amount <= 0 raise "Not valid value for amount" end @cart[name] = amount end def process_item(product, v) line = '' price = "%.2f" % v.round(2) product_price = @cart[product].to_s exceed = product.length + product_price.length number_spaces = ITEM_DEFINITION.length - exceed spaces = " " * number_spaces line = FRAMEWORK.gsub(ITEM_DEFINITION, product + spaces + product_price) number_spaces = PRICE_DEFINITION.length - price.length line.gsub(PRICE_DEFINITION, " " * number_spaces + price) end def invoice_header result = LINE number_spaces = ITEM_DEFINITION.length - "Name".length - "qty".length spaces = " " * number_spaces line = FRAMEWORK.gsub(ITEM_DEFINITION, "Name" + spaces + "qty") number_spaces = PRICE_DEFINITION.length - "price".length line = line.gsub(PRICE_DEFINITION, " " * number_spaces + "price") result << line << LINE end def invoice_footer result = LINE price = total number_spaces = ITEM_DEFINITION.length - "TOTAL".length line = FRAMEWORK.gsub(ITEM_DEFINITION, "TOTAL" + " " * number_spaces) number_spaces = PRICE_DEFINITION.length - price.length line = line.gsub(PRICE_DEFINITION, " " * number_spaces + price) result << line << LINE end end class Product attr_accessor :name, :price, :promotion def initialize(name, price, promotion) if name.length > 40 raise "Name cannot be longer than 40 symbols." end range = 0.01..999.99 if !range.include? price.to_d raise "Price is not in the range 0.01..999.99" end @name, @price, @promotion = name, price.to_d, promotion end def ===(other) self.name == other.name end end
true
3c24d8ae61d50bd94cb65109651112c9d1a24ced
Ruby
smartpension/staging_estimator
/lib/staging_estimator/staging_date_exception.rb
UTF-8
522
2.5625
3
[ "MIT" ]
permissive
module StagingEstimator class StagingDateException < Struct.new(:reference) Data = Struct.new(:value, :date) EXCEPTIONS = [ Data.new('BX', Date.new(2015, 7, 1)), Data.new('BY', Date.new(2015, 9, 1)), Data.new('BZ', Date.new(2015, 11, 1)), Data.new('92', Date.new(2015, 6, 1)), Data.new('00', Date.new(2016, 2, 1)), Data.new('01', Date.new(2016, 3, 1)) ] def find EXCEPTIONS.find do |exception| exception.value == reference end end end end
true
494104b0d6745e9c0c0ba53cadb433daac5c0d04
Ruby
karrick/amber
/old-ruby-version/test/test-file-management.rb
UTF-8
2,063
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'fileutils' require 'test/unit' $:.unshift File.expand_path(File.join(File.dirname(__FILE__), '..', 'bin')) load 'amber' # NOTE: would be interesting to have unit tests that load amber and # invoke its methods, while also having integration tests that merely # execute the binary and check for expected behavior class TestFileManagement < Test::Unit::TestCase def setup $save_dir = Dir.pwd $test_root = File.expand_path(File.join(File.dirname(__FILE__), 'data', File.basename(__FILE__, '.*'))) FileUtils.rm_rf($test_root) FileUtils.mkdir_p(File.join($test_root, '.amber')) Dir.chdir($test_root) end def teardown Dir.chdir $save_dir FileUtils.rm_rf($test_root) end ################ def test_with_temp_file_contents_catches_missing_block assert_raises ArgumentError do with_temp_file_contents('foo') end end def test_with_temp_file_contents_writes_file tempfile = nil with_temp_file_contents('foo') do |temp| tempfile = temp assert_equal('foo', File.read(temp)) end assert(!File.file?(tempfile)) end ################ def test_create_directory_and_install_file with_temp_file_contents("foo\nbar\nbaz") do |temp| FileUtils.rm_rf("foo") if File.exists?("foo") create_directory_and_install_file(temp, "foo/bar/baz") assert_equal('01e06a68df2f0598042449c4088842bb4e92ca75', file_hash("foo/bar/baz")) end end ################ def test_address_to_pathname_puts_files_in_amber_archive address = '01e06a68df2f0598042449c4088842bb4e92ca75' assert_match(/^.amber\/archive\//, address_to_pathname(address)) end def test_address_to_pathname_puts_splits_hash address = '01e06a68df2f0598042449c4088842bb4e92ca75' result = address_to_pathname(address) result.gsub!(/^.amber\/archive\//, '') assert_match(/\//, result) assert_equal(address, result.gsub('/', '')) end end
true
7574d14eb0d813ee841ab0c857986efa0905673b
Ruby
ingenuine/awesome-support
/app/pdfs/report_pdf.rb
UTF-8
1,301
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true # Creates report pdf class ReportPdf < Prawn::Document require 'prawn/table' def initialize(tickets) super() @tickets = tickets _header _table _footer end def _header define_grid(columns: 5, rows: 20, gutter: 0) grid([0, 0], [1, 2]).bounding_box do text 'Report - Solved Tickets Last Month', size: 16 text "Date: #{Date.current}", size: 10 end end def _table table (head + body), header: true, width: 540 do cells.style size: 9, align: :center, padding: [5, 5], border_width: 0.5, border_color: 'DDDDDD' row(0).style font_style: :bold, padding: [10, 15] end end def _footer bounding_box([bounds.right - 50, bounds.bottom], width: 60, height: 20) do page_count.times do |i| go_to_page(i + 1) text "Page #{(i + 1)} from #{page_count}", size: 7, color: 'CCCCCC' end end bounding_box([bounds.left, bounds.bottom], width: 160, height: 20) do text 'Made by Awesome Support', size: 7, color: 'CCCCCC' end end private def head [%w(Title Created Customer Status)] end def body @tickets.map do |item| [item.title, item.created_at.strftime('%d. %m. %Y'), item.user.name, item.status] end end end
true
8d4a8979c315cf6f3183117773c76229d05e4b2e
Ruby
HugoLnx/hugolnx-blog
/app/models/infrastructure/postfile.rb
UTF-8
734
2.671875
3
[]
no_license
module Infrastructure class Postfile include Comparable attr_reader :path attr_reader :title attr_reader :id attr_reader :location def initialize(path) filename = File.basename path @title = title_from(filename).force_encoding('utf-8') @id = filename[0..2].to_i @location = File.dirname(path).match(/^#{File.join(Post::POSTS_DIRECTORY,'(.*)')}/)[1] end def title_from(filename) string_beetween_id_prefix_and_extension_of filename end def string_beetween_id_prefix_and_extension_of(filename) match = filename.match /^[0-9]{3}\-(.*)\.html(\..*|)$/ match[1] end def <=>(other_postfile) @id <=> other_postfile.id end end end
true
c7021d2b05ce3ac1b1c45af7c2228424842452e9
Ruby
jimmy2/launchschool_109_assessment_ruby_and_general_programming
/video_example.rb
UTF-8
521
4.28125
4
[]
no_license
# def amethod(param) # param += " world" # param << " world" # end # str = "hello" # amethod(str) # puts str # a = "hello" # b = a # b << " world" # puts a # puts b # a += b # b << " universe" # puts a # puts b # def prefix!(str) # str.prepend("Mr. ") # end # name = "Joe" # prefix!(name) # puts name # a = [1,2,3,4,5,6,7,8,9,10] # output = a.map do | n | # puts n # end # p output def some_method(number) number = 7 # this is implicitly returned by the method end a = 5 some_method(a) puts a
true
8fae4746a0009c2ced75ccab9c6ec06678252a50
Ruby
elailai94/Watts
/source-code/screens/kinematics-screens/average_speed_screen.rb
UTF-8
3,239
2.90625
3
[ "MIT" ]
permissive
#============================================================================== # Watts # # @description: Module for providing functions to work with AverageSpeedScreen # objects # @author: Elisha Lai # @version: 0.0.1 15/06/2015 #============================================================================== # Average speed screen module (average_speed_screen.rb) require_relative '../../elements/screen_header.rb' require_relative '../../elements/screen_label.rb' require_relative '../../elements/screen_edit_line.rb' require_relative '../../data_validation/data_validation.rb' # Object definition class AverageSpeedScreen < Shoes url('/title_screen/kinematics_screen/average_speed_screen', :average_speed_screen) # Draws the average speed screen on the Shoes app window. def average_speed_screen @heading = 'Average speed = distance / time' background('images/kinematics_large.png') # Average speed screen header ScreenHeader.new(self, '/title_screen/kinematics_screen', @@font, @heading) # Average speed screen content flow(:height => 640, :width => 1080, :scroll => true) do # Left margin offset stack(:height => 640, :width => 80) do end # Content column stack(:height => 640, :width => 1000) do ScreenLabel.new(self, @@font, @heading, 'Distance') flow do @distance = ScreenEditLine.new(self, @@font, @heading) @distance_unit = para(strong(' m')) @distance_unit.style(@@screen_unit_text_styles) end ScreenLabel.new(self, @@font, @heading, 'Time') flow do @time = ScreenEditLine.new(self, @@font, @heading) @time_unit = para(strong(' s')) @time_unit.style(@@screen_unit_text_styles) end @calculate = button('Calculate') @result_display = flow @error_display = flow @calculate.click do #@error = false #@error_display.clear #begin # validate_distance # validate_time #rescue TypeError, RangeError # @error = true #end #if !@error @result_display.clear do @result = Joules.avg_speed(@distance.text.to_f, @time.text.to_f) @avg_speed = para(@result.to_s) @avg_speed_unit = para(' ms', sup('-1')) @avg_speed.style(@@screen_result_text_styles) @avg_speed_unit.style(@@screen_result_text_styles) end #end end end end end def validate_distance if !(@distance.text.numeric?) @error_display.append do para('Distance can only be a numeric value') end raise TypeError end if (@distance.text.to_f < 0) @error_display.append do para('Distance must be a value greater than or equal to 0') end raise RangeError end end def validate_time if !(@time.text.numeric?) @error_display.append do para('Time can only be a numeric value') end raise TypeError end if !(@time.text.to_f > 0) @error_display.append do para('Time must be a value greater than 0') end raise RangeError end end end
true
f18681104c4d5ee80c6a403b14b04b5e9e239d72
Ruby
cielavenir/codeiq_solutions
/nabetani_takenori/tyama_codeiq3050.rb
UTF-8
1,025
3.078125
3
[]
no_license
#!/usr/bin/env ruby #1000以下なら総当りでいいよね =begin T=[ [[0,-1,2,1],[-1,0,4,0],[0,0,1,3],[0,0,5,2],[0,-1,3,4]], [[-1,0,3,1],[-1,1,5,0],[0,0,2,3],[0,0,0,2],[-1,0,4,4]], [[-1,1,4,1],[0,1,0,0],[0,0,3,3],[0,0,1,2],[-1,1,5,4]], [[0,1,5,1],[1,0,1,0],[0,0,4,3],[0,0,2,2],[0,1,0,4]], [[1,0,0,1],[1,-1,2,0],[0,0,5,3],[0,0,3,2],[1,0,1,4]], [[1,-1,1,1],[0,-1,3,0],[0,0,0,3],[0,0,4,2],[1,-1,2,4]], ] =end D=[[0,-1],[-1,0],[-1,1],[0,1],[1,0],[1,-1]] T=6.times.map{|i| [[*D[i],(i+2)%6,1],[*D[(i+1)%6],(i+4)%6,0],[0,0,(i+1)%6,3],[0,0,(i+5)%6,2],[*D[i],(i+3)%6,4]] } cur=[0,0,0,1] # this 1 is dummy mapping={} trail=Hash.new{|h,k|h[k]=[]} trail[mapping[cur[0,3]]]=[] mapping[cur[0,3]]=1 2.upto(1500){|i| x,y,z,d=cur (-1).downto(-4){|j| #go clockwise dx,dy,dz,dd=T[z][(d+j)%5] nxt=[x+dx,y+dy,dz,dd] f=mapping.has_key?(nxt[0,3]) mapping[nxt[0,3]]=i if !f trail[mapping[nxt[0,3]]]<<mapping[cur[0,3]] trail[mapping[cur[0,3]]]<<mapping[nxt[0,3]] (cur=nxt;break) if !f } } puts trail[gets.to_i].sort*','
true
3b1cd73a41c2069821438c5fa9ccb289d5af2f7e
Ruby
zezutom/euler
/problem_002.rb
UTF-8
570
4
4
[]
no_license
#!/usr/bin/env ruby class FibSummary attr_accessor :limit def initialize(limit = 10) @limit = limit end def count total = 2 fib = [1, 2] while true do index = fib.size term = fib[index - 1] + fib[index - 2] if (term > limit) break end if (term % 2 == 0) total += term end fib.insert(index, term) end #puts fib return total end def print_results puts "Sum of even-valued terms with a maximum value of #{@limit} is #{count}" end end fs = FibSummary.new(4000000) fs.print_results
true
4b028bff4734fb70e004045d1b65298ddd9611c7
Ruby
averysmith65/launch_school
/subscription_course/rb101_rb109_small_problems/easy_6/right_triangles.rb
UTF-8
136
3.171875
3
[]
no_license
def triangle(n) count = 1 until count == n + 1 p ' ' * (n - count) + '*' * count count += 1 end end triangle(5) triangle(9)
true
40eb7d4511ad9a5d93415d5fd56f6d2a544b1ed4
Ruby
bemurphy/berg
/lib/authentication/encrypt_password.rb
UTF-8
260
2.65625
3
[ "MIT" ]
permissive
require "bcrypt" module Authentication class EncryptPassword include BCrypt def call(input) Password.create(input) end def same?(hash, password) return false if hash.nil? Password.new(hash) == password end end end
true
ce88afe83a0a812cdfff1db15b05fb8b9a398843
Ruby
bkerley/archaeopteryx
/lib/pitches.rb
UTF-8
1,782
3.3125
3
[]
no_license
# not talking about the queens, but what? the pitches # parts stolen from jvoorhis music.rb, idea partly original, partly jvoorhis-stolen also SCALE = {"C" => 0, "C#" => 1, "D" => 2, "D#" => 3, "E" => 4, "F" => 5, "F#" => 6, "G" => 7, "G#" => 8, "A" => 9, "A#" => 10, "B" => 11} # assuming C major! this isn't quite right. we're not really representing notes here # but positions in the scale. OCTAVES = {-1 => (0..11), # starting note is C-1 0 => (12..23), 1 => (24..35), 2 => (36..47), 3 => (48..59), 4 => (60..71), 5 => (72..83), 6 => (84..95), 7 => (96..107), 8 => (108..119), 9 => (120..127)} # the 9th octave is incomplete and only goes as far as G # chords! this can also happen with scales! MINOR_7TH = [0, 2, 6, 9] MAJOR_7TH = [0, 4, 7, 11] MAJOR_TRIAD = [0,4,7] MAJOR_SCALE = [0, 2, 4, 5, 7, 9, 11] MINOR_SCALE = [0, 2, 3, 5, 7, 8, 10] # higher-resolution nomenclature exists but I won't have time to use it CIRCLE_OF_FIFTHS = %w{C G D A E B F# C# G# D# A# F} # relative minor is always x + 3 # this data structure is of course a ring CIRCLE_OF_FOURTHS = CIRCLE_OF_FIFTHS.reverse # [CIRCLE_OF_FIFTHS, CIRCLE_OF_FOURTHS].each do |array| # class << array # def next # @current ||= -1 # @current += 1 # @current = 0 if @current >= size # self[@current] # end # end # end # this makes them into ring structures. I may need to do this for all these arrays. class Array def next @current ||= -1 @current += 1 @current = 0 if @current >= size self[@current] end end
true
2baf233e4b7a2954af6ba03557af1258e0edd838
Ruby
mlibrary/favorites
/lib/favorites/presenters/favorites.rb
UTF-8
310
2.625
3
[]
no_license
module Favorites module Presenters class Favorites include Enumerable def initialize(favorites) @favorites = favorites end def each(&block) @favorites.each do |favorite| block.call(Favorites::Presenter(favorite)) end end end end end
true
9977a3decb0519f33747deeacf8fd54b9b821fba
Ruby
RiotGamesMinions/motherbrain
/lib/mb/errors.rb
UTF-8
14,068
2.640625
3
[ "Apache-2.0" ]
permissive
module MotherBrain module Errors class << self # @return [Hash] def error_codes @error_codes ||= Hash.new end # @param [MBError] klass # # @raise [RuntimeError] def register(klass) if error_codes.has_key?(klass.error_code) msg = "Unable to register exception #{klass}. The error_code #{klass.error_code} is already" msg << " in use by #{error_codes[klass.error_code]}." raise RuntimeError, msg end error_codes[klass.error_code] = klass end # @param [MBError] klass def unregister(klass) error_codes.delete(klass.error_code) end end end class MBError < StandardError DEFAULT_EXIT_CODE = 1 class << self # @param [Integer] code # # @return [Integer] def exit_code(code = DEFAULT_EXIT_CODE) @exit_code ||= code end # @param [Integer] code # # @return [Integer] def error_code(code = -1) return @error_code if @error_code @error_code = code Errors.register(self) @error_code end end # @param [String] message def initialize(message = nil) super(message) @message = message end # @return [Integer] def exit_code self.class.exit_code end # @return [Integer] def error_code self.class.error_code end # @return [String] def message @message || self.class.to_s end def to_s "[err_code]: #{error_code} [message]: #{message}" end def to_hash { code: error_code, message: message } end # @param [Hash] options # a set of options to pass to MultiJson.encode # # @return [String] def to_json(options = {}) MultiJson.encode(self.to_hash, options) end end class APIError < MBError DEFAULT_HTTP_STATUS_CODE = 500 class << self # @param [Integer] code # # @return [Integer] def http_status_code(code = DEFAULT_HTTP_STATUS_CODE) @exit_code ||= code end end def http_status_code self.class.http_status_code end end # Internal errors class InternalError < MBError exit_code(99) error_code(1000) end class ArgumentError < InternalError error_code(1001) end class AbstractFunction < InternalError error_code(1002) end class ReservedGearKeyword < InternalError error_code(1003) end class DuplicateGearKeyword < InternalError error_code(1004) end class InvalidProvisionerClass < InternalError error_code(1005) end class ProvisionerRegistrationError < InternalError error_code(1006) end class ProvisionerNotRegistered < InternalError error_code(1007) end class RemoteScriptError < InternalError error_code(1008) end class RemoteCommandError < InternalError attr_reader :host def initialize(message, host=nil) super(message) @host = host if host end error_code(1009) end class RemoteFileCopyError < InternalError error_code(1010) end class ActionNotSupported < InternalError exit_code(103) error_code(1011) end # TODO plugin error class ServiceRunListNotFound < InternalError def initialize(services) if services.respond_to?(:join) services = services.join(", ") end super("Service run list not found for the following services: #{services})") end error_code(1013) end # Plugin loading errors class PluginSyntaxError < MBError exit_code(100) error_code(2000) end class DuplicateGroup < PluginSyntaxError error_code(2001) end class DuplicateChefAttribute < PluginSyntaxError error_code(2002) end class ValidationFailed < PluginSyntaxError error_code(2003) end class DuplicateAction < PluginSyntaxError error_code(2004) end class DuplicateGear < PluginSyntaxError error_code(2005) end class ActionNotFound < PluginSyntaxError error_code(2006) end class GroupNotFound < PluginSyntaxError error_code(2007) end class PluginLoadError < MBError exit_code(101) error_code(2008) end class InvalidCookbookMetadata < PluginLoadError error_code(2009) attr_reader :errors def initialize(errors) @errors = errors end end # Standard errors class ChefRunnerError < MBError exit_code(102) error_code(3000) end class NoValueForAddressAttribute < ChefRunnerError error_code(3001) end class JobNotFound < MBError exit_code(106) error_code(3002) attr_reader :job_id def initialize(id) @job_id = id end def message "No job with ID: '#{job_id}' found" end end class PluginNotFound < MBError exit_code(107) error_code(3003) attr_reader :name attr_reader :version def initialize(name, version = nil) @name = name @version = version end def message msg = "No plugin named '#{name}'" msg << " of version (#{version})" unless version.nil? msg << " found" end end class NoBootstrapRoutine < MBError exit_code(108) error_code(3004) end class PluginDownloadError < MBError exit_code(109) error_code(3005) end class CommandNotFound < MBError exit_code(110) error_code(3006) attr_reader :name attr_reader :parent # @param [String] name # name of the command that was not found # @param [MB::Plugin, MB::Component] parent # plugin that we searched for the command on def initialize(name, parent) @name = name @parent = parent end def message "#{parent.class} '#{parent}' does not have the command: '#{name}'" end end class ComponentNotFound < MBError exit_code(111) error_code(3007) attr_reader :name attr_reader :plugin # @param [String] name # @param [MB::Plugin] plugin def initialize(name, plugin) @name = name @plugin = plugin end def message "Plugin #{plugin} does not have the component: '#{name}'" end end class InvalidConfig < MBError exit_code(13) error_code(3009) # @return [ActiveModel::Errors] attr_reader :errors # @param [ActiveModel::Errors] errors def initialize(errors) @errors = errors end def message msg = errors.collect do |key, messages| "* #{key}: #{messages.join(', ')}" end msg.unshift "-----" msg.unshift "Invalid Configuration File" msg.join("\n") end end class ConfigNotFound < MBError exit_code(14) error_code(3010) end class ConfigExists < MBError exit_code(15) error_code(3011) end class ChefConnectionError < MBError exit_code(16) error_code(3012) end class InvalidBootstrapManifest < MBError exit_code(17) error_code(3013) end class ResourceLocked < MBError exit_code(18) error_code(3014) end class InvalidProvisionManifest < MBError exit_code(19) error_code(3015) end class ManifestNotFound < MBError exit_code(20) error_code(3016) end class InvalidManifest < MBError exit_code(21) error_code(3017) end class ComponentNotVersioned < MBError exit_code(22) error_code(3018) attr_reader :component_name def initialize(component_name) @component_name = component_name end def message [ "Component '#{component_name}' is not versioned", "You can version components with:", " versioned # defaults to \"#{component_name}.version\"", " versioned_with \"custom.version.attribute\"" ].join "\n" end end class InvalidLockType < MBError exit_code(23) error_code(3019) end class ConfigOptionMissing < MBError exit_code(24) error_code(3026) end class GearError < MBError exit_code(104) error_code(3020) end class ChefRunFailure < MBError exit_code(105) error_code(3021) def initialize(errors) @errors = errors end end class ChefTestRunFailure < MBError error_code(3022) end class RequiredFileNotFound < MBError error_code(3023) attr_reader :filename attr_reader :required_for def initialize(filename, options = {}) @filename = filename @required_for = options[:required_for] end def message msg = "#{@filename} does not exist, but is required" msg += " for #{@required_for}" if @required_for msg += "." msg end end class BootstrapTemplateNotFound < MBError exit_code(106) error_code(3024) end class InvalidEnvironmentJson < MBError error_code(3025) def initialize(path, json_error=nil) @path = path end def message msg = "Environment JSON contained in #{path} is invalid." msg << "\n#{json_error.message}" if json_error and json_error.responds_to?(:message) msg end end class FileNotFound < MBError error_code(3027) def initialize(path) @path = path end def message "File does not exist: #{path}" end end class InvalidDynamicService < MBError error_code(3028) def initialize(component, service_name) @component = component @service_name = service_name end def message msg = "Both component: #{@component} and service name: #{@service_name} are required." msg << "\nFormat should be in a dotted form - COMPONENT.SERVICE" end end # Bootstrap errors class BootstrapError < MBError exit_code(24) error_code(4000) end class GroupBootstrapError < BootstrapError error_code(4001) # @return [Array<String>] attr_reader :groups # @return [Hash] attr_reader :host_errors # @param [Hash] host_errors # # "cloud-3.riotgames.com" => { # groups: ["database_slave::default"], # result: { # status: :ok # message: "" # bootstrap_type: :partial # } # } def initialize(host_errors) @groups = Set.new @host_errors = Hash.new host_errors.each do |host, host_info| @host_errors[host] = host_info host_info[:groups].each { |group| @groups.add(group) } end end def message err = "" groups.each do |group| err << "failure bootstrapping group #{group}\n" host_errors.each do |host, host_info| if host_info[:groups].include?(group) err << " * #{host} #{host_info[:result]}\n" end end err << "\n" end err end end class CookbookConstraintNotSatisfied < BootstrapError error_code(4002) end class InvalidAttributesFile < BootstrapError error_code(4003) end class ValidatorPemNotFound < RequiredFileNotFound error_code(4004) def initialize(filename, options = { required_for: 'bootstrap' }) super end end # Provision errors class ProvisionError < MBError exit_code(20) error_code(5000) end class UnexpectedProvisionCount < ProvisionError error_code(5001) attr_reader :expected attr_reader :got def initialize(expected, got) @expected = expected @got = got end def message "Expected '#{expected}' nodes to be provisioned but got: '#{got}'" end end class ProvisionerNotStarted < ProvisionError error_code(5002) attr_reader :provisioner_id def initialize(provisioner_id) @provisioner_id = provisioner_id end def message "No provisioner registered or started that matches the ID: '#{provisioner_id}'.\n" "Registered provisioners are: #{MB::Provisioner.all.map(&:provisioner_id).join(', ')}" end end # Chef errors class ChefError < MBError exit_code(26) error_code(9000) end class NodeNotFound < ChefError error_code(9001) attr_reader :name def initialize(name) @name = name end def message "A node named '#{name}' could not be found on the Chef server" end end class EnvironmentNotFound < MBError exit_code(12) error_code(9002) attr_reader :name def initialize(name) @name = name end def message "An environment named '#{name}' could not be found" end end class DataBagNotFound < ChefError error_code(9003) attr_reader :name def initialize(name) @name = name end def message "A Data Bag named '#{name}' could not be found" end end class DataBagItemNotFound < ChefError error_code(9004) attr_reader :data_bag_name attr_reader :item_name def initialize(data_bag_name, item_name) @data_bag_name = data_bag_name @item_name = item_name end def message "An item named '#{item_name}' was not found in the '#{data_bag_name}' data bag." end end class PrerequisiteNotInstalled < MBError error_code(9005) end class EnvironmentExists < ChefError error_code(9006) attr_reader :name def initialize(name) @name = name end def message "An environment named '#{name}' already exists in the Chef Server." end end class NodeSaveFailed < ChefError error_code(9007) attr_reader :name def initialize(name) @name = name end def message "Saving #{@name} failed. Node is not tagged as disabled in it's run list." end end class NodeDisabled < ChefError error_code(9008) attr_reader :name def initialize(name) @name = name end def message "#{@name} is disabled." end end class OmnibusUpgradeError < MBError exit_code(25) error_code(3029) end class ApplicationPaused < APIError error_code(3330) http_status_code(503) def message "MotherBrain is paused. It will not accept new requests until it is resumed." end end end
true
4a3e0f086cc3eebbaf02c26968e41687a6b6bcbe
Ruby
thib123/TPJ
/Notes/Ruby/sample_code/ex0259.rb
UTF-8
90
2.96875
3
[ "MIT" ]
permissive
# Sample code from Programing Ruby, page 100 if false a = 1 end 3.times {|i| a = i } a
true
e86df50a824d8530031a08d44124f741c8397df1
Ruby
martinmoradi/THP-J7-Ruby_ex
/exo_03.rb
UTF-8
314
3.359375
3
[]
no_license
=begin Reprends ton programme exo_02.rb, puis écris un programme exo_03.rb qui est le même, mais avec # devant la ligne 2. Peux-tu me dire ce qu'il se passe ? =end puts "Bonjour, monde !" # puts "Et avec une voix sexy, ça donne : Bonjour, monde !" # => La ligne 2 est un commentaire donc n'est pas executée.
true
7232321096a6a76826eb83c355b90bc6d25c7e44
Ruby
ruby/rss
/test/test-setup-maker-itunes.rb
UTF-8
4,538
2.59375
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
# frozen_string_literal: false require_relative "rss-testcase" require "rss/maker" module RSS class TestSetupMakerITunes < TestCase def test_setup_maker_simple author = "John Doe" block = true categories = ["Audio Blogs"] image = "http://example.com/podcasts/everything/AllAboutEverything.jpg" duration = "4:05" duration_components = [0, 4, 5] explicit = true keywords = ["salt", "pepper", "shaker", "exciting"] owner = {:name => "John Doe", :email => "john.doe@example.com"} subtitle = "A show about everything" summary = "All About Everything is a show about " + "everything. Each week we dive into any " + "subject known to man and talk about it " + "as much as we can. Look for our Podcast " + "in the iTunes Music Store" feed = RSS::Maker.make("rss2.0") do |maker| setup_dummy_channel(maker) setup_dummy_item(maker) channel = maker.channel channel.itunes_author = author channel.itunes_block = block categories.each do |category| channel.itunes_categories.new_category.text = category end channel.itunes_image = image channel.itunes_explicit = explicit channel.itunes_keywords = keywords channel.itunes_owner.itunes_name = owner[:name] channel.itunes_owner.itunes_email = owner[:email] channel.itunes_subtitle = subtitle channel.itunes_summary = summary item = maker.items.last item.itunes_image = image item.itunes_author = author item.itunes_block = block item.itunes_duration = duration item.itunes_explicit = explicit item.itunes_keywords = keywords item.itunes_subtitle = subtitle item.itunes_summary = summary end assert_not_nil(feed) new_feed = RSS::Maker.make("rss2.0") do |maker| feed.setup_maker(maker) end assert_not_nil(new_feed) channel = new_feed.channel item = new_feed.items.last assert_equal(author, channel.itunes_author) assert_equal(author, item.itunes_author) assert_equal(block, channel.itunes_block?) assert_equal(block, item.itunes_block?) assert_equal(categories, collect_itunes_categories(channel.itunes_categories)) assert_equal(image, channel.itunes_image.href) assert_equal(image, item.itunes_image.href) assert_equal(duration_components, [item.itunes_duration.hour, item.itunes_duration.minute, item.itunes_duration.second]) assert_equal(explicit, channel.itunes_explicit?) assert_equal(explicit, item.itunes_explicit?) assert_equal(keywords, channel.itunes_keywords) assert_equal(keywords, item.itunes_keywords) assert_equal(owner, { :name => channel.itunes_owner.itunes_name, :email => channel.itunes_owner.itunes_email }) assert_equal(subtitle, channel.itunes_subtitle) assert_equal(subtitle, item.itunes_subtitle) assert_equal(summary, channel.itunes_summary) assert_equal(summary, item.itunes_summary) end def test_setup_maker_with_nested_categories categories = [["Arts & Entertainment", "Games"], ["Technology", "Computers"], "Audio Blogs"] feed = RSS::Maker.make("rss2.0") do |maker| setup_dummy_channel(maker) setup_dummy_item(maker) channel = maker.channel categories.each do |category| target = channel.itunes_categories if category.is_a?(Array) category.each do |sub_category| target = target.new_category target.text = sub_category end else target.new_category.text = category end end end assert_not_nil(feed) new_feed = RSS::Maker.make("rss2.0") do |maker| feed.setup_maker(maker) end assert_not_nil(new_feed) channel = new_feed.channel assert_equal(categories, collect_itunes_categories(channel.itunes_categories)) end private def collect_itunes_categories(categories) categories.collect do |c| rest = collect_itunes_categories(c.itunes_categories) if rest.empty? c.text else [c.text, *rest] end end end end end
true
2880af91b2af3e016e6ec55900484c2d13c7e002
Ruby
wordjelly/Auth
/app/models/auth/concerns/owner_concern.rb
UTF-8
3,469
2.734375
3
[ "MIT" ]
permissive
module Auth::Concerns::OwnerConcern extend ActiveSupport::Concern include Auth::Concerns::ChiefModelConcern included do ## applicability of the model which implements this concern. ## every model has to be explicitly set as applicable. ## it is NOT APPLICABLE BY DEFAULT. field :applicable, type: Boolean, default: false ## doc_version ## you can use it to do find_and_update field :doc_version, type: Integer, default: 0 ## but if a resource id is present, then a resource class must be provided. field :resource_id, type: String field :resource_class, type: String ## THERE ARE BASICALLY THREE KINDS OF USERS THAT WE MAY NEED. ## ONE : The resource that is considered as the owner of the object . this uses the resource_id and resource_class. It is got by calling get_resource on the object. attr_accessor :owner_resource ## SIGNED_IN_RESOURCE : the resource that is currently signed in, and should be assigned to this model instance, in the controller. In the controller this can be got by calling the method currently_signed_in_resource, provided that the controller implements the token_concern. attr_accessor :signed_in_resource validates_presence_of :resource_class, if: Proc.new{|c| !c.resource_id.nil?} ## you cannot change the resource_id or owner of the object once it is set. validate :resource_id_not_changed end module ClassMethods ## used in cart_item_controller_concern#show ## if the resource is nil, will look for a cart item, which has a resource of nil, otherwise will look for a cart item, with the provided resource id. ## def find_self(_id,resource,options={}) conditions = {:_id => _id} conditions[:resource_id] = resource.id.to_s if !resource.is_admin? #puts "conditions are:" #puts conditions.to_s all = self.where(conditions) #puts "the resultant size:" #puts all.size.to_s return all.first if all.size > 0 return nil end end ## returns the resource that was associated with the object when the object was created. ## it basically uses the resource_id and resource_class that were saved, when creating the resource. ## since resources can be created without the resource_class and resource_id being provided, it may return nil if these two are not present. def get_resource return unless (self.resource_class && self.resource_id) unless owner_resource owner_resource = self.resource_class.capitalize.constantize.find(self.resource_id) end owner_resource end ## checks if the owner of the current object is the same as the owner of the other object passed in. ## this is currently used in payment_concern, in a before_save validation def. ## this is also used in the cart_item_concern, as a before_update validation , if the parent_id is changing, where we check if the cart_item owner is the same as that of the cart. def owner_matches(other_object) return false unless other_object.respond_to? :resource_id return false if self.resource_id != other_object.resource_id end def is_applicable? ## what if this is embedded. self.applicable end private def resource_id_not_changed ##this method will give you access to be able to reset the resource_id in case the admin is modifying the resource. ##need to check if that can be done? if resource_id_changed? && resource_id_was errors.add(:resource_id, "You cannot change the ownership of this entity") end end end
true
6807246c81b957ba5abf1de1ada8b711594f16e9
Ruby
adam-barton/favorite-wines
/db/seeds.rb
UTF-8
1,079
2.65625
3
[ "MIT" ]
permissive
# 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) DATA = { :wine_keys => ["label", "category", "grape", "year", "region"], :wines => [ ["Yorkville Cellars", "Red", "Merlot", 2016, "Mendocino County, CA"], ["Yorkville Cellars", "Red Blend", "Richard the Lion Heart", 2016, "Mendocino County, CA"], ["Kunde", "Red Blend", "Red Dirt Red", 2017, "Sonoma County, CA"], ["Kim Crawford", "White", "Sauvignon Blanc", 2017, "Marlborough"], ["Restless Earth", "Red", "Petit Sirah", 2017, "Santa Barbara County, CA"] ] } def make_wines DATA[:wines].each do |wine| new_wine = Wine.new wine.each_with_index do |attribute, i| new_wine.send(DATA[:wine_keys][i]+"=", attribute) end new_wine.save end end make_wines
true
dfe23f6eadedd06d46aed0f8533efc6b9aa9d0e7
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/rna-transcription/e76a99ac3035476ba2d718dd0f9d65b8.rb
UTF-8
380
3.0625
3
[]
no_license
class Complement COMPLEMENT_MAP = { 'G' => 'C', 'C' => 'G', 'T' => 'A', 'A' => 'U' } class << self def of_dna(dna) regex = Regexp.new COMPLEMENT_MAP.keys.join '|' dna.gsub regex, COMPLEMENT_MAP end def of_rna(rna) regex = Regexp.new COMPLEMENT_MAP.values.join '|' rna.gsub regex, COMPLEMENT_MAP.invert end end end
true
9458ac91f978d958335190acb29e5cf933b766aa
Ruby
care0717/slack_bot
/src/common/gcp_vision_api.rb
UTF-8
2,346
2.546875
3
[]
no_license
require 'gcp/vision' require 'base64' require 'rest-client' require 'json' require 'open-uri' require 'nokogiri' module GcpVisionApi def analyze_receipt(image_file_id) token = ENV['PGRP_LEGACY_TOKEN'] public_api_url = "https://slack.com/api/files.sharedPublicURL?token=#{token}&file=#{image_file_id}" revoke_api_url = "https://slack.com/api/files.revokePublicURL?token=#{token}&file=#{image_file_id}" res = JSON.parse(RestClient.get(public_api_url)) public_url = res['file']['permalink_public'] charset = nil fh = open( public_url ).read receipt = ocr_receipt(Nokogiri::HTML.parse(fh, nil, charset).css('img').attribute('src').value) RestClient.get revoke_api_url return receipt end private def ocr_receipt(url) Gcp::Vision.configure do |config| config.api_key = ENV['GCP_VISION_TOKEN'] end request = { requests: [ { image:{ content: Base64.encode64(Net::HTTP.get_response(URI.parse(url)).body) }, features: [ { type: "TEXT_DETECTION", maxResults: 10 } ] } ] } result = Gcp::Vision.annotate_image(request) texts = result.responses[0].annotations["textAnnotations"][0]["description"].split(/\R/) jans = texts.select {|text| /\d.*JAN/ =~ text } hontai= texts.select {|text| (/\d.*JAN/ =~ text) == nil } temp = hontai.select {|item| /#|¥.*\d+$/ =~ item } irregular = temp.select {|item| (/^#.*\d+$/ =~ item) == nil && (/^¥.*\d+$/ =~ item) == nil } hontai = hontai - irregular temp = hontai.flat_map{|i| i.split("¥")} hontai = temp.flat_map{|i| i.split("#")}.compact.reject(&:empty?) temp = irregular.flat_map{|i| i.split("¥")} irregular = temp.flat_map{|i| i.split("#")}.compact.reject(&:empty?) hontai = hontai + irregular prices = hontai.select {|item| /^\d+$/ =~ item }.map { |price| (price.to_i*1.08).ceil} products = hontai.select {|item| (/^\d+$/ =~ item) == nil } products.size.times { |i| if (/^\d\D.*\d+$/ =~ products[i] ) then products[i-1] += (" " + products[i]) end } products.delete_if {|item| /^\d\D.*\d+$/ =~ item } res = {} products.size.times{ |i| res[products[i]] = prices[i] } return res end end
true
c04da6cac2c306f88d4d33f6e445ec765d74ab4d
Ruby
dafi/tumblr_downloader
/image_downloader.rb
UTF-8
4,729
2.75
3
[]
no_license
#!/usr/bin/env ruby # Download images from photo tumblr's posts require 'open-uri' require 'uri' require 'json' require 'fileutils' require 'optparse' require 'ostruct' require 'logger' LOG_PATH = 'images.log'.freeze ROUND_UP_PIXEL = [75, 100, 250, 400, 500, 540, 1280].freeze def parse_command_line cmd_opts = OpenStruct.new cmd_opts.json_path = nil cmd_opts.image_path = nil optparse = OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($PROGRAM_NAME)} [options]" opts.on('-j', '--json-path path', 'The path containing the blog json files') do |v| cmd_opts.json_path = v end opts.on('-o', '--output path', 'The path where to save the images') do |v| cmd_opts.image_path = v end opts.separator '' opts.on_tail('-h', '--help', 'This help text') do puts opts exit end end begin optparse.parse! mandatory = %i[json_path image_path] missing = mandatory.select { |param| cmd_opts[param].nil? } unless missing.empty? puts "Missing options: #{missing.join(', ')}" puts optparse exit end rescue OptionParser::InvalidOption, OptionParser::MissingArgument puts $ERROR_INFO.to_s puts optparse exit end cmd_opts end # Error raised when an image can't be downloaded class DownloadError < RuntimeError attr_reader :post def initialize(post) @post = post end end # Download images from photo tumblr's posts class ImageDownloader def initialize(opts) @opts = opts @log = Logger.new(LOG_PATH) end def download FileUtils.mkdir_p(@opts.image_path) unless Dir.exist?(@opts.image_path) m = Dir.glob(File.join(@opts.json_path, '*.json')).sort! do |a, b| a.match(%r{.*/(\d+)})[1].to_i <=> b.match(%r{.*/(\d+)})[1].to_i end file_count = m.length m.each_with_index do |f, i| perc = (i + 1) * 100.0 / file_count puts "File #{File.basename(f)} of #{i + 1}/#{file_count} #{'%.2f' % perc}%" begin process_json_file(f, @opts.image_path, false) rescue DownloadError => err log_download_error(err, File.basename(f)) # sleep 25 end end end def log_download_error(err, file_name) post = err.post puts "logged error for #{post['tags']}" @log.fatal("#{post['id']} #{post['tags']} file #{file_name}") @log.fatal(err.cause.to_s) end def process_json_file(json_path, root_dir, overwrite) json = JSON.parse(open(json_path).read) json['response']['posts'].each do |post| photo_info_list = [] add_original_size_to_photo_info(post).each do |photo_info| path = build_destination_path(photo_info, root_dir, post) photo_info_list << [path, photo_info] if overwrite || !File.exist?(path) end begin save_url_from_post(post, photo_info_list) unless photo_info_list.empty? rescue raise DownloadError, post end end end # add original_size photo to alt_szies # if it differs from the largest image present on alt_sizes def add_original_size_to_photo_info(post) first_photo = post['photos'][0] alt_sizes = first_photo['alt_sizes'] if alt_sizes[0]['url'] != first_photo['original_size']['url'] alt_sizes << first_photo['original_size'] end alt_sizes end def save_url_from_post(post, path_photo_info_tuple) tag = post['tags'].empty? ? 'untagged' : post['tags'][0].downcase print "downloading #{post['id']} for #{tag}:" threads = path_photo_info_tuple.map do |tuple| Thread.new do path, photo_info = tuple save_url(photo_info['url'], path) print " #{find_width(photo_info)}" end end threads.each(&:join) puts end def build_destination_path(photo_info, root_dir, post) size = find_width(photo_info) || 'unknown_width' dest_dir = File.join(root_dir, dest_dir_by_tags(post['tags']), size) FileUtils.mkdir_p(dest_dir) unless Dir.exist?(dest_dir) url = photo_info['url'] ext_file = url[/^.*(\..*)/, 1] || '.jpg' File.join(dest_dir, "#{post['id']}#{ext_file}") end def find_width(photo_info) m = photo_info['url'].match(/(\d+)(?!.*\d)/) return m[1] if m width = photo_info['width'] ROUND_UP_PIXEL.find { |w| width <= w }.to_s end def dest_dir_by_tags(tags) return 'untagged' if tags.empty? tag = tags[0].downcase File.join(tag[0, 1], tag) end def save_url(url, dest_path) # read file before create the output # so if some exception is raised the empty file isn't created content = open(url, read_timeout: 2, open_timeout: 3).read open(dest_path, 'wb') { |f| f << content } end end ImageDownloader.new(parse_command_line).download
true
797174600ecc20cc0f4954a695b4099bb804ac8d
Ruby
kevinkey/klank
/dungeon.rb
UTF-8
5,280
2.90625
3
[]
no_license
module Klank require_relative "deck.rb" require_relative "utils.rb" class Dungeon COUNT = 6 attr_reader :hand def initialize(game) @game = game @deck = Deck.new(game, "dungeon.yml") @hand = [] if @game.sunken_treasures @deck.add(game, "sunken_treasures/dungeon.yml") end if (@game.promo) @deck.add(game, "promo.yml") end while @hand.count < COUNT if @deck.peek.dragon @deck.reshuffle!() else @hand << @deck.draw(1)[0] end end end def danger() @hand.select { |c| c.danger }.count end def replenish() count = [COUNT - @hand.count, @deck.stack.count].min if count > 0 @game.broadcast("\nReplenishing the dungeon...") attack = false cards = @deck.draw(count) cards.each do |c| c.arrive() if c.dragon attack = true end end @hand += cards if attack @game.dragon.attack() end end view end def acquire(player, card = nil, pickpocket = false) if @hand.include? card if card.type == :monster if card.defeat(player) card = @hand.delete_at(@hand.index(card)) @game.broadcast("#{player.name} killed #{card.name} in the dungeon!") end elsif card.acquire(player, pickpocket) card = @hand.delete_at(@hand.index(card)) @game.broadcast("#{player.name} acquired #{card.name} from the dungeon!") if card.type != :device player.deck.discard([card]) end end else loop do player.output("\n" + Klank.table([{"SKILL" => player.skill, "ATTACK" => player.attack, "CLANK" => player.clank_remove}])) c = menu("BUY OR DEFEAT A CARD", player) break if c == "N" if @hand[c.to_i].type == :monster if @hand[c.to_i].defeat(player) card = @hand.delete_at(c.to_i) @game.broadcast("#{player.name} killed #{card.name} in the dungeon!") end elsif @hand[c.to_i].acquire(player) card = @hand.delete_at(c.to_i) @game.broadcast("#{player.name} bought #{card.name} from the dungeon!") if card.type != :device player.deck.discard([card]) end end if @hand.count == 0 break elsif !afford?(player) break end end end end def afford?(player) result = @hand.count > 0 if result result = ((player.skill >= @hand.map { |c| c.player_cost(player) }.min) or (player.attack >= @hand.map { |c| c.attack }.min)) end result end def crystal_golem() @hand.find { |card| card.name == "Crystal Golem"} end def pickpocket(player, cost, companion) if @hand.any? { |c| (c.cost <= cost) && (!companion || c.type == :companion) } c = menu("ACQUIRE A CARD", player, cost, companion) if c != "N" card = @hand.select { |j| (j.cost <= cost) && (!companion || j.type == :companion) }[c.to_i] acquire(player, card, true) end end end def replace_card(player) c = menu("REPLACE A CARD", player) if c != "N" removed = @hand.delete_at(c.to_i) added = @deck.draw(1)[0] @hand << added @game.broadcast("#{player.name} removed #{removed.name} and #{added.name} replaced it!") end end def view(player = nil) dungeon = [] @hand.each do |c| dungeon << c.buy_desc(false) end if (player != nil) player.output("\nDUNGEON\n#{Klank.table(dungeon)}") else @game.broadcast("\nDUNGEON\n#{Klank.table(dungeon)}") end end private def menu(title, player, max_cost = 1000000, companion = false) options = [] @hand.select { |c| (c.cost <= max_cost) && (!companion || c.type == :companion) }.each_with_index do |c, i| options << [i, c.buy_desc(player.has_played?("Gem Collector"))] end card = player.menu(title, options, true) end end end
true
a5d184ea68fc5671542dbb2ecedea9c406488838
Ruby
adamish/weathersupermarket
/app/helpers/providers/bbc.rb
UTF-8
1,595
2.734375
3
[]
no_license
require 'nokogiri' require 'extraction' require 'fetcher' class ProviderBbc attr_accessor :fetcher def search(search) url = "http://www.bbc.co.uk/locator/default/en-GB/autocomplete.json?search=#{search}&filter=international" content = @fetcher.getUrl(url) elements = JSON.parse(content) locations = Array.new elements.each do |it| locations.push(Location.new(:token => it['id'], :name => it['fullName'])) end locations end def fetch(forecast_id) url = "http://www.bbc.co.uk/weather/#{forecast_id}" content = @fetcher.getUrl(url) doc = Nokogiri::HTML(content) dates = Array.new doc.css('ul.daily li').each do |it| m = /day-(\d+{4})(\d+{2})(\d+{2})\s+.*/.match(it.attr('class')) dates.push(DateTime.new(m[1].to_i,m[2].to_i,m[3].to_i)) end returnValue = Array.new i = 0 doc.css('#forecast-data-table tr.day').each do |it| forecast = Forecast.new forecast.date = dates[i] forecast.daytime = it.css('td.dayname').text.strip forecast.summary = it.css('td.weather').text.strip forecast.temp_max = Extraction.temperature(it.css('td.max-temp span.temperature-value-unit-c').text) forecast.temp_min = Extraction.temperature(it.css('td.min-temp span.temperature-value-unit-c').text) forecast.wind_speed = Extraction.wind(it.css('td.wind span.windspeed-value-unit-kph').text) forecast.wind_dir = Extraction.wind(it.css('td.wind span.wind-direction').text) forecast.link = url returnValue.push forecast i = i + 1 end returnValue end end
true
b85019aa745306feafb3575b04f12d1e60d04460
Ruby
MaratMikushkin/RubequeTasks
/tests/test_separating_numbers.rb
UTF-8
608
2.75
3
[]
no_license
require './test_helper.rb' class TestSeparator < MiniTest::Unit::TestCase def setup @register = Separator.new end def test_ assert_equal "1", @register.separate_with_comma(1) assert_equal "10", @register.separate_with_comma(10) assert_equal "100", @register.separate_with_comma(100) assert_equal "1,000", @register.separate_with_comma(1000) assert_equal "10,000", @register.separate_with_comma(10000) assert_equal "100,000", @register.separate_with_comma(100000) assert_equal "1,000,000", @register.separate_with_comma(1000000) end end
true
7ac8892df7313fb67a9c3fb0e03b51edd834039c
Ruby
candaceww/kwk-l1-flowchart-project-template-kwk-students-l1-seattle-072318
/app/controllers/application_controller.rb
UTF-8
799
3.03125
3
[]
no_license
require './config/environment' #require './app/models/quizz.rb' class ApplicationController < Sinatra::Base configure do set :public_folder, 'public' set :views, 'app/views' end get '/' do erb :index end post '/results' do answers = [] answers << params.values @total = 0 #at the beginning of the quiz answers.each do |x| #goes to the array of values num = 0 while num < 4 new_count = x[num].to_i @total += new_count #adds up numbers that user chose -- also convert to integer bc we're taking in numbers num += 1 end end puts "here is the total: #{@total}" @combo = cool_generator(@total) if @combo == "You're an FBI agent!" erb :success elsif @combo == "You're fired from the FBI team" erb :failure end end end
true
1968e4c0e60634c004bb4bebbe0a220109281b19
Ruby
polyfox/moon-packages
/lib/moon/packages/std/core_ext/numeric.rb
UTF-8
1,239
3.53125
4
[ "MIT" ]
permissive
class Numeric # Linear interpolation between self and target # # @param [Numeric] target # @param [Float] d # @return [Numeric] def lerp(target, d) self + (target - self) * d end # Converts the number to a degree from radians # # @return [Float] def to_degrees (57.2957795 * self).round end # Converts the number to a radian from degrees # # @return [Float] def to_radians self / 57.2957795 end # @return [Moon::Vector1] def to_vec1 Moon::Vector1.new self end # @return [Moon::Vector2] def to_vec2 Moon::Vector2.new self, self end # @return [Moon::Vector3] def to_vec3 Moon::Vector3.new self, self, self end # @return [Moon::Vector4] def to_vec4 Moon::Vector4.new self, self, self, self end # # @param [Numeric] n # @return [Numeric] def max(n) if n > self n else self end end # # @param [Numeric] n # @return [Numeric] def min(n) if n < self n else self end end # # @param [Numeric] mn the minimum # @param [Numeric] mx the maximum # @return [Numeric] def clamp(mn, mx) if self < mn mn elsif self > mx mx else self end end end
true
80b096b19e668fa9abf6c6352c6d87514f0ff10d
Ruby
tiinus/advent-of-code-2018
/day-02/day-02.rb
UTF-8
755
3.21875
3
[]
no_license
require 'pp' input = File.read("input.txt") box_ids = input.split("\n") count_two = 0 count_three = 0 box_ids.each do |tag| tag = tag .chars .group_by(&:itself) .map { |letter, list| [letter, list.count] } count_two += 1 unless tag.select { |a| a[1] == 2 }.empty? count_three += 1 unless tag.select { |a| a[1] == 3 }.empty? end pp count_two * count_three box_ids.each_with_index do |id_1, i| box_ids.drop(i).each do |id_2| count_differ_index = [] id_1.chars.each_with_index do |c, c_i| count_differ_index << c_i if c != id_2[c_i] end if count_differ_index.length == 1 id_1_chars = id_1.chars.to_a id_1_chars.delete_at(count_differ_index[0]) pp id_1_chars.join exit end end end
true
abbc9c5d15e0e123956025661dfa95dda388c3a8
Ruby
JLeech/introns_postgres
/ortho_group_fixer.rb
UTF-8
3,473
3.15625
3
[]
no_license
require 'csv' # class Statistics # attr_accessor :gene_id_hash # attr_accessor :path # def initialize(path) # self.path = path # self.gene_id_hash = Hash.new { |hash, key| hash[key] = empty_record } # end # def fill_and_save # puts "filling exons" # fill_exons # puts "filling introns" # fill_introns # puts "saving" # save # end # def fill_exons # counter = 0 # CSV.foreach("#{self.path}/exons.csv", headers: false) do |row| # gene_id = row[2] # phase = row[10] # gene_id_hash[gene_id]["exon_all"] += 1 # gene_id_hash[gene_id]["exon_phase_#{phase}"] += 1 # counter += 1 # puts "#{counter}/35449402" if (counter%1000000 == 0) # end # end # def fill_introns # counter = 0 # CSV.foreach("#{self.path}/introns.csv", headers: false) do |row| # gene_id = row[2] # phase = row[14] # error = row[18].to_i # if (error == 1) # gene_id_hash[gene_id]["intron_with_error"] += 1 # gene_id_hash[gene_id]["intron_err_phase_#{phase}"] += 1 # end # gene_id_hash[gene_id]["intron_all"] += 1 # gene_id_hash[gene_id]["intron_phase_#{phase}"] += 1 # counter += 1 # puts "#{counter}/31499836" if (counter%1000000 == 0) # end # end # def empty_record # return ({"exon_phase_0"=>0,"exon_phase_1"=>0,"exon_phase_2"=>0,"exon_all"=>0, # "intron_phase_0"=>0,"intron_phase_1"=>0,"intron_phase_2"=>0,"intron_all"=>0,"intron_err_phase_0"=>0,"intron_err_phase_1"=>0,"intron_err_phase_2"=>0,"intron_with_error"=>0}) # end # def save # `rm #{path}/gene_stat.csv` # File.open("#{self.path}/gene_stat.csv", 'w') do |state_csv| # gene_id_hash.each do |key, value| # state_csv.write(([key] + value.values).join(",") + "\n") # end # end # end # end class OrthoGroupSetter attr_accessor :ortho_counter attr_accessor :ortho_hash def initialize(ortho_path) self.ortho_counter = Hash.new { |hash, key| hash[key] = 0 } self.ortho_hash = Hash.new { |hash, key| hash[key] = false } CSV.foreach(ortho_path, headers: false, col_sep: ";") do |row| ortho_hash[row[1]] = row[2] ortho_counter[row[2]] = 0 end end def set_ortho(path) gene_hash = Hash.new { |hash, key| hash[key] = 0 } counter = 0 fixed_gene_path = "#{path}/fixed_genes.csv" File.open(fixed_gene_path, 'a') do |csv| CSV.foreach("#{path}/genes.csv", headers: false) do |row| if ortho_hash[row[5]] != false ortho_counter[ortho_hash[row[5]]] += 1 row[3] = ortho_hash[row[5]] end row[4] = "\"#{row[4]}\"" row[5] = "\"#{row[5]}\"" csv.write(row.join(",")+"\n") puts "#{counter}/1096698" if counter%100000 == 0 counter += 1 end end #puts "N: #{(ortho_gr.keys.length - (ortho_hash.keys & gene_hash.keys).length)}" end def set_ortho_res_genes(path) CSV.foreach("#{path}/genes.csv", headers: false) { |row| ortho_hash[row[5]] += 1 } end end res_path = '/home/eve/Documents/introns_postgres/from_db/res' ortho_path = '/home/eve/Documents/introns_postgres/common_ortho_table.csv' ortho_setter = OrthoGroupSetter.new(ortho_path) ortho_setter.set_ortho(res_path) # Dir.chdir(res_path) # folders = Dir.glob('*').select {|f| File.directory? f} # folders.sort.each do |folder| # next if !File.exist?("#{folder}/genes.csv") # next if folder == "res" # end # stat = Statistics.new(res_path) # stat.fill_and_save # wc -l from_db/res/introns.csv # 35449402 # 31499836
true
355d0e432fc47db24956030cc7ceabf61ddcba1a
Ruby
Tasha25/LRTHW2016
/ex35_game_b.rb
UTF-8
3,291
3.796875
4
[]
no_license
class GamePoints def correct puts "points = #{points} in if @correct" @user_points_total = @user_points_total + 10 puts "You have #{@user_points_total} points." puts "The computer has #{@computer_points_total} points." if @user_points_total || @computer_points_total > 0 if @user_points_total > 50 puts "You won!" elsif @computer_points_total > 50 puts "Computer won!" else puts "Keep playing to win" start end start end def incorrect puts "points = #{points} in else @incorrect" @computer_points_total = @computer_points_total + 10 puts "You have #{@user_points_total} points." puts "The computer has #{@computer_points_total} points." if @user_points_total || @computer_points_total > 0 if @user_points_total > 50 puts "You won!" elsif @computer_points_total > 50 puts "Computer won!" else puts "Keep playing to win" start end start end end end end class Game < GamePoints def politics puts "You picked #{@question.capitalize}." puts "Are you ready for you question?" print "Yes or No > " ready = $stdin.gets.chomp.downcase if ready == "yes" politics_bank else puts "I will wait when you are ready." end end def mathematics puts "You picked #{@question.capitalize}." end def chemistry puts "You picked #{@question.capitalize}." end def politics_bank array_politics = ["Who is the president of the United States?", "Who is the vice-president of the United States?", "Who is the secretary of the United States", "Who was the first Roman Catholic to be Vice President of the United States of America?", "Who was the first First Lady to be elected to public office?", "How many US Supreme Court justices are there?"] bank_politics = {"Who is the president of the United States?" => "Barak Obama", "Who is the vice-president of the United States?" => "Joe Biden", "Who is the secretary of the United States" => "John Kerry", "Who was the first Roman Catholic to be Vice President of the United States of America?" => "Joe Biden", "Who was the first First Lady to be elected to public office?" => "Hillary Clinton", "How many US Supreme Court justices are there?" => "9"} # pick a random question from bank # print question out on screen sample_question = array_politics.sample puts sample_question print "> " # user answers question answer = $stdin.gets.chomp if answer == bank_politics[sample_question] puts "You get 10 points." GamePoints.correct # start else answer == !bank_politics[sample_question] puts "The computer gets 10 points." GamePoints.incorrect # start end end end def start puts "Pick the category you would like a question from: Politics, Mathematics, or Chemistry" print "> " @question = $stdin.gets.chomp.downcase if @question == "politics" politics elsif @question == "mathematics" mathematics elsif @question == "chemistry" chemistry else puts "I don't understand your choice." end end def init @user_points_total = 0 @computer_points_total = 0 start end
true
e6a2cad7dfcfa29e92b54575719f72a6668419b4
Ruby
rabram66/20120730
/test/unit/event_test.rb
UTF-8
1,390
2.59375
3
[]
no_license
require 'test_helper' class EventTest < ActiveSupport::TestCase setup do @event = events(:anonymous) end context 'geocoding' do should "happen when address changed" do @event.address = '2578 Binghamton Drive, Atlanta, GA' @event.expects(:geocode).once @event.save! end should "not happen when description changed" do @event.description = 'Whoville Town Celebration' @event.expects(:geocode).never @event.save! end end context 'full address' do should "be parsed into address, city, and state" do @event.full_address = "123 Herodian Way, Suite 104, Smyrna, GA" assert_equal "123 Herodian Way, Suite 104", @event.address assert_equal "Smyrna", @event.city assert_equal "GA", @event.state assert_equal "123 Herodian Way, Suite 104, Smyrna, GA", @event.full_address end end context 'defaults' do should 'rank default to 1' do e = Event.new assert_equal 1, e.rank end should 'thumbnail_url should default to event icon' do e = Event.new assert_equal '/images/event_icon.jpg', e.thumbnail_url end should 'allow non-defaults on initialization' do e = Event.new(:rank => 10, :thumbnail_url => "http://foo.com/bar.gif") assert_equal 10, e.rank assert_equal "http://foo.com/bar.gif", e.thumbnail_url end end end
true
4a97337af0b8fe840e6642958f25968aa37361d4
Ruby
gitter-badger/transonerate
/lib/transonerate/transonerate.rb
UTF-8
661
2.703125
3
[]
no_license
module Transonerate class Transonerate def initialize assembly, genome, gtf @assembly = assembly @genome = genome @gtf = gtf @exonerate = Exonerate.new @assembly, @genome @annotation = Gtf.new @gtf end def score threads @exonerate.run threads @exonerate.parse_output results = {} @exonerate.hits.each do |query_name, hit| coverage = @annotation.search hit pq = (hit.qstop-hit.qstart)/hit.qlen.to_f # puts "#{query_name}\t#{pq}\t#{coverage}\t#{hit.pi}\t#{coverage*hit.pi}" results[query_name]=[pq, coverage, hit.pi] end results end end end
true
f9267f5bb4d69161050b70717608e526fd275f54
Ruby
brianwang/gftop
/learning/railsLearning/BuildYourOwnRubyOnRailsWebApplications/chapter03/20_unless_else.rb
UTF-8
152
2.796875
3
[]
no_license
unless kitt.is_a?(StretchLimo) puts "This car only has room for two people." else puts "This car is licensed to carry up to 10 passengers." end
true
e771e875f8d92a187cd3db07a2fa336261344af5
Ruby
qamk/chess-top
/lib/board.rb
UTF-8
2,916
3.234375
3
[]
no_license
# frozen-string-literal: true require_relative 'pieces/knight' require_relative 'pieces/bishop' require_relative 'pieces/rook' require_relative 'pieces/queen' require_relative 'pieces/king' require_relative 'pieces/pawn' # Mechanics for interacting with the chess board class Board attr_reader :board, :old_board, :pseudo_board, :move_validator def initialize(board = Array.new(8) { Array.new(8) }) @board = board @pseudo_board = nil @old_board = board end def create_starting_board pawn_location = [[1, :black], [6, :white]] unique_pieces_location = [[0, :black], [7, :white]] pawn_location.each { |rank, colour| create_pawn_rank(rank, colour) } unique_pieces_location.each { |rank, colour| create_unique_pieces_rank(rank, colour) } end def copy(obj) Marshal.load(Marshal.dump(obj)) end def create_unique_pieces_rank(rank, colour) @board[rank] = [ Rook.new(colour, [rank, 0]), Knight.new(colour, [rank, 1]), Bishop.new(colour, [rank, 2]), Queen.new(colour, [rank, 3]), King.new(colour, [rank, 4]), Bishop.new(colour, [rank, 5]), Knight.new(colour, [rank, 6]), Rook.new(colour, [rank, 7]) ] end def create_pawn_rank(rank, colour) file = [0, 1, 2, 3, 4, 5, 6, 7] @board[rank] = (0..7).map { Pawn.new(colour, [rank, file.shift]) } end def promote(pawn, new_piece) pieces = { q: Queen, r: Rook, b: Bishop, n: Knight } pawn_rank, pawn_file = pawn.location board[pawn_rank][pawn_file] = pieces[new_piece].new(pawn.colour, pawn.location) end def load_board(imported_board) pieces = { 'Rook' => Rook, 'Bishop' => Bishop, 'Knight' => Knight, 'Queen' => Queen, 'King' => King, 'Pawn' => Pawn } @board = imported_board board.each_with_index do |rank, r_index| rank.each_with_index do |square, f_index| next if square.nil? name, colour = square.split(':') piece = pieces[name] p_colour = colour.to_sym @board[r_index][f_index] = piece.new(p_colour, [r_index, f_index]) end end end def en_passant_cleanup(piece) rank, file = piece.location @board[rank][file] = nil end def update_castle(destination) old_rank, old_file, new_rank, new_file = destination piece = board[old_rank][old_file] new_destination = [new_rank, new_file] update_board(piece, new_destination) end def update_pseudo_board(piece, destination) @pseudo_board = copy(board) old_rank, old_file = piece.location new_rank, new_file = destination @pseudo_board[new_rank][new_file] = piece @pseudo_board[old_rank][old_file] = nil end def update_board(piece, destination) old_rank, old_file = piece.location new_rank, new_file = destination @board[new_rank][new_file] = piece @board[old_rank][old_file] = nil piece.update_location(destination) end end
true
5f21d9915510493f82b3e37984a49f0fe032123a
Ruby
krschacht/nebel
/test/factories/material_factory_test.rb
UTF-8
3,652
2.65625
3
[]
no_license
require "test_helper" class MaterialFactoryTest < ActiveSupport::TestCase setup do @exercise = exercises(:d5_part1) fixtures_root = Rails.root.join "test/fixtures/lesson_samples/" @a2 = Book::Lesson.new fixtures_root.join "volume_1/2nd_edition/a2.txt" @b22 = Book::Lesson.new fixtures_root.join "volume_2/2nd_edition/b22.txt" end test "#materials initializes an array of materials" do MaterialFactory.new(@a2).tap do |material_factory| @exercise.part = 1 assert_equal 3, material_factory.materials(@exercise).size @exercise.part = 2 assert_equal 2, material_factory.materials(@exercise).size @exercise.part = 3 assert_equal 1, material_factory.materials(@exercise).size end MaterialFactory.new(@b22).tap do |material_factory| @exercise.part = 1 assert_equal 7, material_factory.materials(@exercise).size end end test "#materials maps the original_name" do materials_factory = MaterialFactory.new(@a2) @exercise.part = 1 materials_factory.materials(@exercise).tap do |materials| assert_match /\AWater and various other liquids/, materials[0].original_name assert_match /syrup, shampoo, etc\.\)\z/, materials[0].original_name assert_match /\AVarious solid items from around/, materials[1].original_name assert_match /pencils, dishes, coins, etc\.\)\z/, materials[1].original_name assert_match /\AThree medium-sized cardboard/, materials[2].original_name assert_match /can be marked and labeled\.\z/, materials[2].original_name end @exercise.part = 2 materials_factory.materials(@exercise).tap do |materials| assert_match /\AWater in/, materials[0].original_name assert_match /a container\z/, materials[0].original_name assert_match /\AIce cubes/, materials[1].original_name assert_match /in a bowl\z/, materials[1].original_name end @exercise.part = 3 materials_factory.materials(@exercise).tap do |materials| assert_match /\ANo additional/, materials[0].original_name assert_match /materials needed\z/, materials[0].original_name end materials_factory = MaterialFactory.new(@b22) @exercise.part = 1 materials_factory.materials(@exercise).tap do |materials| assert_match /\AThis lesson entails ongoing/, materials[0].original_name assert_match /the following will be utilized\.\z/, materials[0].original_name assert_match /\ATape/, materials[1].original_name assert_match /measure\z/, materials[1].original_name assert_match /\AFine tipped/, materials[2].original_name assert_match /Sharpie™\z/, materials[2].original_name assert_match /\ADissecting microscope is ideal/, materials[3].original_name assert_match /pocket magnifiers\.\)\z/, materials[3].original_name assert_match /\ADissecting tools/, materials[4].original_name assert_match /teasing needles, etc\.\)\z/, materials[4].original_name assert_match /\ACompound microscope/, materials[5].original_name assert_match /sections of woody stems\z/, materials[5].original_name assert_match /\APhotomicrographs of the above/, materials[6].original_name assert_match /are included below\.\z/, materials[6].original_name end end test "#materials finds existing materials by original name" do materials = MaterialFactory.new(@a2).materials(@exercise) materials.each do |material| material.save! Requisition.create! exercise_id: @exercise.id, material_id: material.id end assert_equal materials, MaterialFactory.new(@a2).materials(@exercise) end end
true
ded340069d81153372af8b389af386f6c859c948
Ruby
vmoyade/restaurant_service
/app/models/restaurant.rb
UTF-8
894
2.828125
3
[]
no_license
require 'data_fetch/main.rb' class Restaurant < ActiveRecord::Base attr_accessor :business serialize :business class << self def all #Overridden Active record method Rails.logger.info "Run my custom Restaurant.all" restaurants = Rails.cache.fetch("businesses") { DataFetch::Main.get_restaurants} map_restaurants(restaurants) end def initialize(restaurant) @business = { restaurant_name: restaurant["name"], review_count: restaurant["review_count"], address: { latitude: restaurant["latitude"], longitude: restaurant["longitude"], city: restaurant["city"], state: restaurant["state"], zipcode: restaurant["zip"] }, rating: restaurant["avg_rating"] } @business end def map_restaurants(restaurants) restaurants_list = restaurants.map do |restaurant| Restaurant.initialize(restaurant) end end end end
true
926c41049a8c72f2acca82aa26f3d8a24bdb92c1
Ruby
ToUMenu/kanji-master
/lib/kanji_master/string_extension.rb
UTF-8
636
2.609375
3
[ "MIT" ]
permissive
module KanjiMaster module StringExtension def katakana; kana end def kana converter = Converter.new converter.kana(self) end def hiragana; hira end def hira converter = Converter.new converter.hira(self) end def alphabet? reader = Reader.new reader.alphabet?(self) end def maybe_kanji? reader = Reader.new reader.maybe_kanji?(self) end def kanji? reader = Reader.new reader.kanji?(self) end def jp_zip_code?; jp_zipcode? end def jp_zipcode? reader = Reader.new reader.zipcode?(self) end end end
true
c3cac722c78a59f12c3c9be5479782507b221f0b
Ruby
anoam/atms
/spec/dispatcher_spec.rb
UTF-8
1,233
2.703125
3
[]
no_license
require_relative "../dispatcher" RSpec.describe Dispatcher do let(:command_result) { double("something") } subject { Dispatcher.new } before do subject.register("first_command") { |arguments| { command: "first_command", arguments: arguments } } subject.register("second_command") { |arguments| { command: "second_command", arguments: arguments } } end it "runs command" do expect(subject.run("first_command")[:command]).to eql("first_command") end it "runs another command" do expect(subject.run("second_command")[:command]).to eql("second_command") end it "strips spaces" do expect(subject.run(" first_command ")[:command]).to eql("first_command") end it "returns error on unknown command" do expect(subject.run("unknown_command")).to eql("Command is unknown") end it "don't sends arguments if wasn't given" do expect(subject.run(" first_command ")[:arguments]).to be_nil end it "sends arguments" do expect(subject.run("second_command some_arguments here")[:arguments]).to eql("some_arguments here") end it "strip arguments' spaces" do expect(subject.run(" second_command some_arguments here ")[:arguments]).to eql("some_arguments here") end end
true
1f1c23f1f46520a34aa8c7709a3392745130c096
Ruby
ShanRubyist/algorithm
/dijkstra.rb
UTF-8
682
3.015625
3
[ "MIT" ]
permissive
inf = 2**32 map = [ [0, 1, 12, inf, inf, inf], [inf, 0, 9, 3 ,inf, inf], [inf, inf, 0, inf, 5, inf], [inf, inf, 4, 0, 13, 15], [inf, inf, inf, inf, 0, 4], [inf, inf, inf, inf, 0, 4] ] dis = map.first book = [] dis.each_with_index { |item, index| book[index] = 0 } u = 0 # core code for i in 0...map.size - 1 min = inf for j in 0...map.size if book[j].zero? && dis[j] < min min = dis[j] u = j end end book[u] = 1 for v in 0...map.size dis[v] = dis[u] + map[u][v] if map[u][v] < inf && dis[v] > dis[u] + map[u][v] end end # print result map.each do |item| item.each do |i| print i print ' ' end print "\n" break end
true
adfb0515cb859d3c9ab86b3d45ca091787ad885d
Ruby
hungdowp/learn_ruby
/09_book_titles/book.rb
UTF-8
334
3.484375
3
[]
no_license
class Book SMALL_WORDS = %w(a an and as at but by for in it nor of on or over the to up) attr_reader :title def title=(t) @title = titleize(t) end def titleize(s) words = s.split words.each { |word| word.capitalize! unless SMALL_WORDS.include?(word) } words.first.capitalize! words.join(" ") end end
true
31e87332a349fba888f480b704bb267be3769cfb
Ruby
fc-anjos/the-parrots-think
/repeated-string-hackerrank.rb
UTF-8
340
2.828125
3
[]
no_license
def repeatedString(s, n) a_total_counter = 0 remaining = 0 a_word_counter = s.count 'a' times_repeated = (n / s.length).floor() dif = n % s.length remaining = s[0...dif].count 'a' if dif != 0 a_total_counter += remaining a_total_counter += (a_word_counter * times_repeated) return a_total_counter end
true
dacab7021040d563b57c0bdbcf0ec7b093aa62d2
Ruby
Axelbruget/sharebox
/app/models/folder.rb
UTF-8
1,754
2.546875
3
[]
no_license
class Folder < ApplicationRecord belongs_to :user has_many :assets, :dependent => :destroy has_many :folders, foreign_key: "parent_id", :dependent => :destroy has_many :shared_folders, :dependent=> :destroy has_many :satisfactions, :dependent=> :destroy acts_as_tree validates :name, presence: true extend ActsAsTree::TreeWalker # Retourne Vrai si le dossier a été partagé au moins une fois def shared? !self.shared_folders.empty? end # Retourne vrai si un sondage est attribué au dossier def is_polled? # return true if self.poll_id != nil return true if Poll.where(id: self.poll_id).length != 0 end # Retourne vrai s'il existe au moins une réponse satisfaction pour le dossier def has_satisfaction_answer? if Satisfaction.find_by_folder_id(self.id) return true else return false end end # Vrai si le répertoire donné contient des fichiers def has_assets? return true if Asset.find_by_folder_id(self.id) end # Vrai si le répertoire donné contient des sous-répertoires ou des fichiers def has_childrens? if Asset.find_by_folder_id(self.id) || Folder.find_by_parent_id(self.id) return true else return false end end # retourne les fichiers d'un répertoire donné def get_assets return Asset.where(folder_id: self.id) end # Retournes tous les enfants d'un répertoire donné ( sous-répertoires + fichiers ) def get_childrens folders = Folder.where(parent_id: self.id) assets = Asset.where(folder_id: self.id) childrens = assets + folders folders.each do |c| if c.has_childrens? childrens += c.get_childrens end end return childrens end end
true
269c74f3bb4b1de0e015259ed94774435b40e8e3
Ruby
Isikapowers/flashcards
/lib/round.rb
UTF-8
2,143
3.90625
4
[]
no_license
class Round attr_reader :deck, :turns def initialize(deck) @deck = deck @turns = [] end def current_card @deck.cards.first end def take_turn(guess) new_turn = Turn.new(guess, current_card) @turns << new_turn @deck.cards.shift new_turn end def number_correct number = 0 @turns.each do |turn| if turn.correct? == true number += 1 end end number end def number_correct_by_category(category) number = 0 @turns.each do |turn| if turn.correct? == true && turn.card.category == category number += 1 end end number end def percent_correct (number_correct.to_f / @turns.count.to_f) * 100 end def percent_correct_by_category(category) total_num_of_cards_by_category = 0 @turns.each do |turn| if turn.card.category == category total_num_of_cards_by_category += 1 end end total_num_of_cards_by_category (number_correct_by_category(category).to_f/ total_num_of_cards_by_category.to_f) * 100 end def start(round) #Start the game card_num = 1 total_of_cards_in_deck = round.deck.count list_of_categories = round.deck.list_of_categories puts "Welcome! You're playing with #{total_of_cards_in_deck} cards." puts "-" * 30 while card_num >= 1 && card_num <= total_of_cards_in_deck puts "This is card number #{card_num} out of #{total_of_cards_in_deck}." puts "Question: #{round.current_card.question}" puts "Please enter your guess: " # Get an input from user guess = gets.chomp turn = round.take_turn(guess) check_guess = turn.correct? puts turn.feedback card_num += 1 if card_num > total_of_cards_in_deck puts "********** Game Over! **********" puts "You had #{round.number_correct} correct guesses out of #{total_of_cards_in_deck} for a total score of #{round.percent_correct}%." list_of_categories.each do |category| puts "#{category} - #{round.percent_correct_by_category(category)}% correct" end end end end end
true
9aaf22d30223f07644a3bafdeb5319bacba44c43
Ruby
sybillearmis/Jour7_Ruby
/exo_15.rb
UTF-8
232
3.546875
4
[]
no_license
puts "Quelle est ton année de naissance ?" print ">" birth_year = gets.chomp.to_i actual_year = 2020 i = birth_year while (i < actual_year) i += 1 puts i puts "En #{i}, tu avais #{i - birth_year} ans" end
true
70260e7b33c2897742b48e60b81e9cad3bdce223
Ruby
praveendhawan/training-exercises
/advanceruby/calculator/bin/main.rb
UTF-8
430
2.71875
3
[]
no_license
require_relative '../lib/calculator.rb' require_relative '../lib/user_input.rb' require_relative '../lib/calculator/not_valid_input_error.rb' require_relative '../lib/calculator/validate_input.rb' begin puts 'Please Enter the details' input_hash = UserInput.take_input calculator = Calculator.new(input_hash) rescue Calculator::NotValidInputError, StandardError => e puts e.message retry end puts calculator.calculate
true
4d7649309aed7177f24deeb1f8bc44855bda831d
Ruby
esopbaek/Minesweeper
/Minesweeper.rb
UTF-8
5,679
3.640625
4
[]
no_license
require 'colorize' require 'yaml' class Minesweeper def initialize self.play end def play size = get_user_setting @board = Board.new(size, size, size*2) until @board.over coordinates = get_user_coordinates action = get_user_action @board[coordinates].flag if action == 'f' @board[coordinates].reveal if action == 'r' @board.display save_prompt load_prompt end @board.display puts "You lose" end def save_prompt puts "Save game? (y/n)" response = gets.chomp if response == "y" File.open("saved_game.txt", "w") do |f| f.print @board.to_yaml end end end def load_prompt puts "Load game? (y/n)" response = gets.chomp if response == "y" loaded_file = File.readlines("saved_game.txt").join("\n") @board = YAML::load(loaded_file) @board.display end end def get_user_setting width = nil until width puts "Enter a size for your playing field (s, m, l)" size = gets.chomp if size == "s" width = 10 elsif size == "m" width = 15 elsif size == "l" width = 20 else puts "Invalid input" end end width end def get_user_coordinates coordinates = nil until coordinates puts "Please enter coordinates (x,y)" input = gets.chomp.split(",").map(&:to_i) if input.any? {|x| x >= @board.width || x < 0} puts "Please enter coordinates between 0 and #{@board.width-1}" elsif @board[[input[0],input[1]]].revealed puts "Square already revealed" else coordinates = input end end coordinates end def get_user_action puts "Enter f to flag, r to reveal" action = gets.chomp end end class Board attr_accessor :board, :over, :won attr_reader :height, :width def initialize(width,height,mines) @width = width @height = height @board = Array.new(height) { Array.new(width) } @mines = mines @over = false @won = false setup display end def [](pos) x, y = pos[0], pos[1] @board[x][y] end def []=(pos, tile) x, y = pos[0], pos[1] @board[x][y] = tile end def setup @height.times do |x| @width.times do |y| self[[x, y]] = Tile.new([x,y], self) end end self.fill_with_mines end def display @height.times do |x| @width.times do |y| print self[[x,y]].display + " " end puts end puts end def fill_with_mines get_mine_positions.each do |mine_pos| x,y = mine_pos[0], mine_pos[1] self[[x,y]].bombed = true end end def get_mine_positions mine_positions = [] until mine_positions.count == @mines mine = [rand(@height), rand(@width)] mine_positions << mine unless mine_positions.include?(mine) end mine_positions end def reveal_bombs @board.each do |rows| rows.each do |tile| tile.reveal if tile.bombed end end end def win_check @board.each do |rows| rows.each do |tile| return false if !tile.revealed && !tile.bombed end end return true end def over? @over end def won? @over = true if @won @won end end class Tile DELTAS = [[0,1], [0,-1], [1,0], [-1,0], [1,1], [-1,1], [-1,-1], [1,-1]] attr_reader :pos attr_accessor :flagged, :revealed, :bombed, :ignited def initialize(pos, board) @pos = pos @bombed = false @flagged = false @revealed = false @ignited = false @board = board end def bombed? @bombed end def flagged? @flagged end def neighbors neighbors = DELTAS.map {|x,y| [x + @pos[0],y + @pos[1]]} neighbors = neighbors.select { |x, y| x.between?(0,@board.height-1) && y.between?(0, @board.width-1)} neighbors = neighbors.reject { |x,y| @board[[x,y]].revealed} end def neighbor_bomb_count count = 0 self.neighbors.each {|neighbor| count += 1 if @board[neighbor].bombed? } count end def display if @board.over if self.flagged? "\u2691".encode('utf-8') elsif self.revealed if neighbor_bomb_count > 0 neighbor_bomb_count.to_s.blue else "\u00A0".encode('utf-8') # blank end else if self.bombed "X".red # bomb else "\u204E".encode('utf-8') # asterisk end end else # game not over if self.flagged? "\u2691".encode('utf-8') # flag elsif !revealed "\u204E".encode('utf-8') # asterisk else if neighbor_bomb_count > 0 neighbor_bomb_count.to_s.blue else "\u00A0".encode('utf-8') # blank end end end end def explore(tile) stack = [tile] until stack.empty? current = stack.shift current.neighbors.each do |pos| if @board[pos].neighbor_bomb_count == 0 && !stack.include?(@board[pos]) @board[pos].reveal stack.push @board[pos] elsif @board[pos].neighbor_bomb_count > 0 @board[pos].reveal end end end end def flag @flagged = true reveal end def reveal @revealed = true if self.flagged? display elsif self.bombed? @board.over = true display elsif self.neighbor_bomb_count > 0 display else explore(self) end @board.won = win_check end end if __FILE__ == $PROGRAM_NAME game = Minesweeper.new game.play end
true
e712c5b67cde655ffd07897964656b839058f491
Ruby
blambeau/anagram
/lib/anagram/matching/type_matcher.rb
UTF-8
422
3.03125
3
[ "MIT" ]
permissive
module Anagram module Matching # Matches when the matched object is of a given module. class TypeMatcher < Matcher # Create a type matcher for a specific module def initialize(mod) raise ArgumentError unless Module===mod @mod = mod end # Matching operator def ===(o) @mod === o end end # class TypeMatcher end end
true
e736cb46b22490ea54ff26edb9a07269f03bef13
Ruby
anton-3/discord-game-bot
/connect-4/board.rb
UTF-8
3,564
3.453125
3
[]
no_license
# frozen-string-literal: true module Connect4 # logic for all game boards class Board attr_reader :turn_count, :contents, :legal_moves def initialize(p1_color, p2_color) @turn_count = 1 @colors = { 1 => p1_color, -1 => p2_color } @legal_moves = (0..6).to_a @contents = [] 7.times { @contents.push(Array.new(6, 0)) } # empty is stored as 0 end def move(col, value) # assumes the move is legal (column isn't full) # player 1's move is stored as 1, player 2's stored as -1 col_ary = @contents[col] col_ary[col_ary.index(0)] = value @turn_count += 1 update_legal_moves(col) end def win? four_in_row? || four_in_col? || four_in_diag? end def full? contents.reduce(true) do |memo, col| memo && !col.include?(0) end end def to_s str = '' 6.times do |num| row(num).each do |x| str += x.zero? ? ':blue_circle:' : ":#{@colors[x]}_circle:" end str += "\n" end str end # returns array of all rows def rows row_arys = [] @contents[0].length.times do |num| row_arys.push(row(num)) end row_arys end # returns array of all diagonals def diagonals find_up_diags + find_down_diags end private # rows counted top to bottom, starts at 0 def row(num, contents = @contents) index = contents[0].length - 1 - num row_ary = [] contents.each do |col| row_ary.push(col[index]) end row_ary end # check if there's any sequence of four in any row on the board def four_in_row? output = false 6.times do |num| output ||= four_in_ary?(row(num + 1)) end output end # check if there's any sequence of four in any column on the board def four_in_col? @contents.reduce(false) do |memo, col| memo || four_in_ary?(col) end end # check if there's any sequence of four in any diagonal on the board def four_in_diag? diags = find_up_diags + find_down_diags diags.reduce(false) do |memo, diag| memo || four_in_ary?(diag) end end # check if there's any sequence of four in an array def four_in_ary?(array) longest_length = current_length = 1 array.each_with_index do |el, i| next if i.zero? !el.zero? && el == array[i - 1] ? current_length += 1 : current_length = 1 longest_length = current_length if current_length > longest_length end longest_length >= 4 end def find_up_diags copy = Marshal.load(Marshal.dump(@contents)) # deep copy # shift each column down proportionally to make the diagonals line up copy.each_with_index do |col, i| (6 - i).times { col.unshift(nil) } i.times { col.push(nil) } end make_diags(copy) end def find_down_diags copy = Marshal.load(Marshal.dump(@contents)) # deep copy # shift each column up proportionally to make the diagonals line up copy.each_with_index do |col, i| i.times { col.unshift(nil) } (6 - i).times { col.push(nil) } end make_diags(copy) end def make_diags(ary) diags = [] ary[0].length.times do |num| diag = row(num, ary) diag.delete(nil) diags.push(diag) end diags end def update_legal_moves(move) @legal_moves.delete(move) unless @contents[move].include?(0) end end end
true
4d69e41793d735c076dc114c41bfbc8064cb52e0
Ruby
jparker0190/sinatra-cms-app-assessment-v-000
/app/models/concerns/slugifiable.rb
UTF-8
247
2.71875
3
[]
no_license
module Slugifiable module InstanceMethods def slug self.username.downcase.gsub(" ", "-") end end module ClassMethods def find_by_slug(slug) name = slug.gsub("-", " ") self.all.find {|obj| obj.username == name} end end end
true
7789cde3b2a8a6c37b4918b17406ed30fadf17ce
Ruby
CritJen/apples-and-holidays-seattle-web-career-021819
/lib/holiday.rb
UTF-8
1,704
3.890625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def second_supply_for_fourth_of_july(holiday_supplies) holiday_supplies[:summer][:fourth_of_july][1] end def add_supply_to_winter_holidays(holiday_hash, supply) holiday_supplies[:winter][:christmas] << supply holiday_supplies[:winter][:new_years] << supply end def add_supply_to_memorial_day(holiday_hash, supply) holiday_supplies[:spring][:memorial_day] << supply # again, holiday_hash is the same as the ones above # add the second argument to the memorial day array end def add_new_holiday_with_supplies(holiday_hash, season, holiday_name, supply_array) holiday_hash[season][holiday_name] = supply_array return holiday_hash end def all_winter_holiday_supplies(holiday_hash) supplies = holiday_hash[:winter].values return supplies.flatten # return an array of all of the supplies that are used in the winter season end def all_supplies_in_holidays(holiday_hash) holiday_hash.each do |season, holiday| puts "#{season.to_s.capitalize}:" holiday.each do |name, supplies| puts" #{name.to_s.split("_").map(&:capitalize).join(' ')}: #{supplies.join(", ")}" end end end # iterate through holiday_hash and print items such that your readout resembles: # Winter: # Christmas: Lights, Wreath # New Years: Party Hats # Summer: # Fourth Of July: Fireworks, BBQ # etc. def all_holidays_with_bbq(holiday_hash) best_holidays = [] holiday_hash.each do |season, holiday| holiday.each do |name, supplies| if supplies.include?("BBQ") best_holidays << name end end end return best_holidays end # return an array of holiday names (as symbols) where supply lists # include the string "BBQ"
true
2099e07e75d109ffc523f70d3362924767d50b70
Ruby
kgjtrdghnboiuthtd/J7
/Ex1/exo_06.rb
UTF-8
101
3.140625
3
[]
no_license
puts "Choisi un nombre" i = gets.chomp.to_i i = i -1 i.times do puts "Salut, ça farte ?🍀" end
true
102d2ae30fe4d98a90d6525fe3cb0bb7df26edd9
Ruby
pietrogll/ruby_utils_algorithms
/design_patterns/behavioral_patterns/strategy.rb
UTF-8
1,234
3.765625
4
[]
no_license
# The strategy pattern (also known as the policy pattern) is a behavioral design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use. Strategy lets the algorithm vary independently from clients that use it. #It is about inject specific behaviour for defining object of the same class that behaves differently even if having the same interface class Duck def initialize fly_behaviour, quack_behaviour @fly_behaviour = fly_behaviour @quack_behaviour = quack_behaviour end def fly @fly_behaviour.run() end def quack @quack_behaviour.run() end end class JetFlyBehaviour def run 'I am flying as a jet' end end class NormalFlyBehaviour def run 'I am flying' end end class StrongQuackBehaviour def run "QUACK!!" end end class NormalQuackBehaviour def run "quack" end end common_duck = Duck.new(NormalFlyBehaviour.new, NormalQuackBehaviour.new) super_duck = Duck.new(JetFlyBehaviour.new, StrongQuackBehaviour.new) p "common_duck: #{common_duck.quack} - #{common_duck.fly}" p "super_duck: #{super_duck.quack} - #{super_duck.fly}"
true
c540f07cb3bf0ee4407cc74b5e336dfed103d2ff
Ruby
ColmTang/Advent_of_Code
/day1b.rb
UTF-8
272
3.546875
4
[]
no_license
input = [] IO.foreach("day1a.txt") do |line| input << line.to_i end input = input.map do |element| output = 0 until element <= 0 element = (element/3)-2 if element > 0 output += element end end output end puts input.inject {|sum, x| sum + x }
true
80cb830e35c27a375067babf05c444e6b3fcbc84
Ruby
marianosimone/jugame
/lib/strategy.rb
UTF-8
769
2.875
3
[ "Unlicense" ]
permissive
require 'observer' module JugaMe # Base class for all Strategies, it provides common functionality, like the ability to be notfied about the other players' last actions class Strategy include Observable include LovelyParent attr_reader :possible_actions, :others_actions def initialize(possible_actions) @possible_actions = possible_actions @checkpoint = false @others_actions = [] end def name self.class.name end def play res = do_play changed && notify_observers(res) res end def last_action_from_other others_actions.last end def update(action_from_other) others_actions << action_from_other end def checkpoint! @checkpoint = true end def checkpointed? @checkpoint end end end
true
5edf077db711400c1a685f770d8fb19873d2fc4e
Ruby
kachick/striuct
/test/test_subc-f_name.rb
UTF-8
13,967
2.6875
3
[ "MIT" ]
permissive
# frozen_string_literal: false require_relative 'helper' class Test_Striuct_Subclass_Name < Test::Unit::TestCase # for peep origin_autonyms = nil origin_aliases = nil Subclass = Striuct.define do origin_autonyms = @autonyms origin_aliases = @aliases member :foo member :bar alias_member :als_foo, :foo close_member end.freeze INSTANCE = Subclass.new.freeze TYPE_PAIRS = { Class: Subclass, Instance: INSTANCE }.freeze [:_autonyms].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_equal true, receiver.private_methods.include?(callee) assert_raises NoMethodError do receiver.public_send(callee) end assert_same origin_autonyms, receiver.__send__(callee) end end end [:autonyms, :members].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) ret = receiver.public_send(callee) assert_not_same origin_autonyms, ret assert_equal origin_autonyms, ret 10.times do ret2 = receiver.public_send(callee) assert_not_same ret, ret2 assert_equal ret, ret2 end end end end [:all_members].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) ret = receiver.public_send(callee) assert_equal [*origin_autonyms, :als_foo], ret 10.times do ret2 = receiver.public_send(callee) assert_not_same ret, ret2 assert_equal ret, ret2 end end end end [:aliases].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) ret = receiver.public_send(callee) assert_not_same(origin_aliases, ret) assert_equal({als_foo: :foo}, ret) 10.times do ret2 = receiver.public_send(callee) assert_not_same(origin_aliases, ret2) assert_not_same ret, ret2 assert_equal ret, ret2 end end end end [:autonym_for_alias].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) assert_raises NoMethodError, TypeError do receiver.public_send(callee, BasicObject.new) end assert_raises TypeError do receiver.public_send(callee, Object.new) end assert_raises NameError do receiver.public_send(callee, :foo) end assert_same :foo, receiver.public_send(callee, :als_foo) assert_raises NameError do receiver.public_send(callee, 'foo') end assert_same :foo, receiver.public_send(callee, 'als_foo') assert_raises TypeError do receiver.public_send(callee, 0) end assert_raises TypeError do receiver.public_send(callee, 0.9) end assert_raises NameError do receiver.public_send(callee, :bar) end assert_raises NameError do receiver.public_send(callee, :als_bar) end assert_raises NameError do receiver.public_send(callee, 'bar') end assert_raises NameError do receiver.public_send(callee, 'als_bar') end assert_raises TypeError do receiver.public_send(callee, 1) end assert_raises TypeError do receiver.public_send(callee, 1.9) end assert_raises NameError do receiver.public_send(callee, :none) end assert_raises NameError do receiver.public_send(callee, :als_none) end assert_raises NameError do receiver.public_send(callee, 'none') end assert_raises NameError do receiver.public_send(callee, 'als_none') end assert_raises TypeError do receiver.public_send(callee, 2) end assert_raises TypeError do receiver.public_send(callee, 2.9) end end end end [:autonym_for_member].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) assert_raises NoMethodError, TypeError do receiver.public_send(callee, BasicObject.new) end assert_raises TypeError do receiver.public_send(callee, Object.new) end assert_same :foo, receiver.public_send(callee, :foo) assert_same :foo, receiver.public_send(callee, :als_foo) assert_same :foo, receiver.public_send(callee, 'foo') assert_same :foo, receiver.public_send(callee, 'als_foo') assert_raises TypeError do receiver.public_send(callee, 0) end assert_raises TypeError do receiver.public_send(callee, 0.9) end assert_same :bar, receiver.public_send(callee, :bar) assert_raises NameError do receiver.public_send(callee, :als_bar) end assert_same :bar, receiver.public_send(callee, 'bar') assert_raises NameError do receiver.public_send(callee, 'als_bar') end assert_raises TypeError do receiver.public_send(callee, 1) end assert_raises TypeError do receiver.public_send(callee, 1.9) end assert_raises NameError do receiver.public_send(callee, :none) end assert_raises NameError do receiver.public_send(callee, :als_none) end assert_raises NameError do receiver.public_send(callee, 'none') end assert_raises NameError do receiver.public_send(callee, 'als_none') end assert_raises TypeError do receiver.public_send(callee, 2) end assert_raises TypeError do receiver.public_send(callee, 2.9) end end end end [:autonym_for_index].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) assert_raises NoMethodError, TypeError do receiver.public_send(callee, BasicObject.new) end assert_raises TypeError do receiver.public_send(callee, Object.new) end assert_raises TypeError do receiver.public_send(callee, :foo) end assert_raises TypeError do receiver.public_send(callee, :als_foo) end assert_raises TypeError do receiver.public_send(callee, 'foo') end assert_raises TypeError do receiver.public_send(callee, 'als_foo') end assert_same :foo, receiver.public_send(callee, 0) assert_same :foo, receiver.public_send(callee, 0.9) assert_same :foo, receiver.public_send(callee, -2) assert_same :foo, receiver.public_send(callee, -2.9) assert_raises TypeError do receiver.public_send(callee, :bar) end assert_raises TypeError do receiver.public_send(callee, :als_bar) end assert_raises TypeError do receiver.public_send(callee, 'bar') end assert_raises TypeError do receiver.public_send(callee, 'als_bar') end assert_same :bar, receiver.public_send(callee, 1) assert_same :bar, receiver.public_send(callee, 1.9) assert_same :bar, receiver.public_send(callee, -1) assert_same :bar, receiver.public_send(callee, -1.9) assert_raises TypeError do receiver.public_send(callee, :none) end assert_raises TypeError do receiver.public_send(callee, :als_none) end assert_raises TypeError do receiver.public_send(callee, 'none') end assert_raises TypeError do receiver.public_send(callee, 'als_none') end assert_raises IndexError do receiver.public_send(callee, 2) end assert_raises IndexError do receiver.public_send(callee, 2.9) end assert_raises IndexError do receiver.public_send(callee, -3) end assert_raises IndexError do receiver.public_send(callee, -3.9) end end end end [:autonym_for_key].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) assert_raises KeyError do receiver.public_send(callee, BasicObject.new) end assert_raises KeyError do receiver.public_send(callee, Object.new) end assert_same :foo, receiver.public_send(callee, :foo) assert_same :foo, receiver.public_send(callee, :als_foo) assert_same :foo, receiver.public_send(callee, 'foo') assert_same :foo, receiver.public_send(callee, 'als_foo') assert_same :foo, receiver.public_send(callee, 0) assert_same :foo, receiver.public_send(callee, 0.9) assert_same :foo, receiver.public_send(callee, -2) assert_same :foo, receiver.public_send(callee, -2.9) assert_same :bar, receiver.public_send(callee, :bar) assert_raises KeyError do assert_same :bar, receiver.public_send(callee, :als_bar) end assert_same :bar, receiver.public_send(callee, 'bar') assert_raises KeyError do assert_same :bar, receiver.public_send(callee, 'als_bar') end assert_same :bar, receiver.public_send(callee, 1) assert_same :bar, receiver.public_send(callee, 1.9) assert_same :bar, receiver.public_send(callee, -1) assert_same :bar, receiver.public_send(callee, -1.9) assert_raises KeyError do receiver.public_send(callee, :none) end assert_raises KeyError do receiver.public_send(callee, :als_none) end assert_raises KeyError do receiver.public_send(callee, 'none') end assert_raises KeyError do receiver.public_send(callee, 'als_none') end assert_raises KeyError do receiver.public_send(callee, 2) end assert_raises KeyError do receiver.public_send(callee, 2.9) end assert_raises KeyError do receiver.public_send(callee, -3) end assert_raises KeyError do receiver.public_send(callee, -3.9) end end end end [:aliases_for_autonym].each do |callee| TYPE_PAIRS.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}" do assert_same true, receiver.public_methods.include?(callee) assert_raises NoMethodError, TypeError do receiver.public_send(callee, BasicObject.new) end assert_raises TypeError do receiver.public_send(callee, Object.new) end assert_equal [:als_foo], receiver.public_send(callee, :foo) assert_raises NameError do receiver.public_send(callee, :als_foo) end assert_equal [:als_foo], receiver.public_send(callee, 'foo') assert_raises NameError do receiver.public_send(callee, 'als_foo') end assert_raises TypeError do receiver.public_send(callee, 0) end assert_raises TypeError do receiver.public_send(callee, 0.9) end assert_raises NameError do receiver.public_send(callee, :bar) end assert_raises NameError do receiver.public_send(callee, :als_bar) end assert_raises NameError do receiver.public_send(callee, 'bar') end assert_raises NameError do receiver.public_send(callee, 'als_bar') end assert_raises TypeError do receiver.public_send(callee, 1) end assert_raises TypeError do receiver.public_send(callee, 1.9) end assert_raises NameError do receiver.public_send(callee, :none) end assert_raises NameError do receiver.public_send(callee, :als_none) end assert_raises NameError do receiver.public_send(callee, 'none') end assert_raises NameError do receiver.public_send(callee, 'als_none') end assert_raises TypeError do receiver.public_send(callee, 2) end assert_raises TypeError do receiver.public_send(callee, 2.9) end end end end aliase_for_autonym_ext_pairs = {}.tap {|h| h[:Class] = Striuct.define do member :foo alias_member :als1_foo, :foo member :bar alias_member :als1_bar, :bar alias_member :als2_foo, :foo alias_member :als3_foo, :foo member :xyz end.freeze h[:Instance] = h[:Class].new.freeze }.freeze [:aliases_for_autonym].each do |callee| aliase_for_autonym_ext_pairs.each_pair do |type, receiver| define_method :"test_#{type}_#{callee}_2" do assert_equal [:als1_foo, :als2_foo, :als3_foo], receiver.public_send(callee, 'foo') assert_equal [:als1_bar], receiver.public_send(callee, 'bar') assert_raises NameError do receiver.public_send(callee, 'xyz') end end end end end
true
08bc4a9ea53c1d1d47eefbb23acbb9656ba1394f
Ruby
victornava/exercises
/2016.three-more-list-manipulation-exercisess.rb
UTF-8
1,698
4.03125
4
[]
no_license
# https://programmingpraxis.com/2016/10/14/three-more-list-manipulation-exercises/ # # THREE MORE LIST MANIPULATION EXERCISES # # We have three more list-manipulation exercises today, for those students midway # through their beginning programming course who need practice with linked lists: # # Task 1 # Define a function that takes two lists, the second of which is a list of # non-negative integers the same length as the first list, and returns a list of # elements from the first list, in reverse order, each repeated a number of times # as specified by the corresponding element of the second list. # # Task 2 # Rearrange the integers in a list so that all the odd numbers appear before all # the even numbers, with both odd and even numbers in the same relative order in # the output as they were in the input. # # Task 3 # Write a function that returns the nth item from the end of a list. def task_1(a, b) a.zip(b).flat_map { |x, n| Array.new(n, x) }.reverse end def task_2(list) list.partition(&:odd?).flatten end def task_3(list, n) list.reverse[n] end # TEST def test(output, target) puts "target: #{target}" puts "output: #{output}" puts "pass: #{output == target}" puts end puts "Task 1" test task_1(%w[a b c], [1,2,3]), %w[c c c b b a] test task_1(%w[d c b a], [3,0,0,1]), %w[a d d d] puts "Task 2" test task_2((1..20).to_a), [1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20] puts "Task 3" test task_3((1..20).to_a, 5), 15 __END__ SUBMISSION [sourcecode lang="ruby"] def task_1(a, b) a.zip(b).flat_map { |x, n| Array.new(n, x) }.reverse end def task_2(list) list.partition(&:odd?).flatten end def task_3(list, n) list.reverse[n] end [/sourcecode]
true
cc2fbb399852ca1456c2b2d2cb488357b4ad2306
Ruby
jungomi/mdn_query
/lib/mdn_query/document.rb
UTF-8
1,673
2.859375
3
[ "MIT" ]
permissive
module MdnQuery # A document of an entry of the Mozilla Developer Network documentation. class Document # @return [String] attr_reader :title, :url # @return [MdnQuery::Section] the top level section attr_reader :section # Creates a document filled with the content of the URL. # # @param url [String] the URL to the document on the web # @return [MdnQuery::Document] def self.from_url(url) begin response = RestClient::Request.execute(method: :get, url: url, headers: { accept: 'text/html' }) rescue RestClient::Exception, SocketError => e raise MdnQuery::HttpRequestFailed.new(url, e), 'Could not retrieve entry' end dom = Nokogiri::HTML(response.body) title = dom.css('h1').text article = dom.css('article') document = new(title, url) MdnQuery::TraverseDom.fill_document(article, document) document end # Creates a new document with an initial top level section. # # @param title [String] the titel of the top level section # @param url [String] the URL to the document on the web # @return [MdnQuery::Document] def initialize(title, url = nil) @title = title @url = url @section = MdnQuery::Section.new(title) end # Opens the document in the default web browser if a URL has been specified. # # @return [void] def open Launchy.open(@url) unless @url.nil? end # Returns the string representation of the document. # # @return [String] def to_s @section.to_s end alias to_md to_s end end
true
e23f9f2f7d08f14d784d4a2d3e8e1b6ff8c2e0fb
Ruby
jpclark6/backend_prework
/day_1/ex11.rb
UTF-8
629
4.34375
4
[]
no_license
print "How old are you? " age = gets.chomp print "How tall are you? " height = gets.chomp print "How much do you weigh? " weight = gets.chomp puts "So, you're #{age} old, #{height} tall and #{weight} heavy." print "What is your favorite color? " color = gets.chomp print "Where is your dream vacation? " vacation_location = gets.chomp print "What is your favorite word? " word = gets.chomp puts "Your favorite color is #{color}, your dream vacation location is #{vacation_location}, and your favorite word is #{word}!" print "What is your favorite number? " number = gets.chomp.to_i puts "So #{number * 2} is twice as good?"
true
efb1844a2d40fd8d7b3ba945e593f16d31e90cc1
Ruby
zapofafu/gitlab_ruby
/lib/gitlab_ruby/api_errors.rb
UTF-8
1,259
2.671875
3
[ "MIT" ]
permissive
module GitlabRuby def self.format_error(resp) resp.body end def self.check_response_status(resp) if resp.body case resp.status when 400 then raise BadRequestError, format_error(resp) when 401 then raise UnauthorizedError, format_error(resp) when 403 then raise ForbiddenError, format_error(resp) when 404 then raise NotFoundError, format_error(resp) when 405 then raise MethodNotAllowedError, format_error(resp) when 409 then raise ConflictError, format_error(resp) when 422 then raise UnprocessableError, format_error(resp) when 500 then raise ServerError, format_error(resp) end end if resp.status > 400 raise APIError, "[#{resp.status}] #{resp.body}" end end class APIError < RuntimeError end # Status 400 class BadRequestError < APIError end # Status 401 class UnauthorizedError < APIError end # Status 403 class ForbiddenError < APIError end # Status 404 class NotFoundError < APIError end # Status 405 class MethodNotAllowedError < APIError end # Status 409 class ConflictError < APIError end # Status 422 class UnprocessableError < APIError end # Status 500 class ServerError < APIError end end
true
e41eee354067add80cd0e4ad2a42df5997a162d9
Ruby
McGaelen/advent-of-code-2020
/utils.rb
UTF-8
241
3.1875
3
[]
no_license
def openInput(transform = :chomp) inputArray = [] file = open('input.txt') if file == nil puts "couldn't find file" exit 1 end file.each do |thing| inputArray.push thing.method(transform).call end inputArray end
true
b58991255f2cb9f20a9e7e2dca8606b56d4f7514
Ruby
ChelseaC13/solar-system
/planet.rb
UTF-8
507
3.6875
4
[]
no_license
class Planet attr_reader :name, :color, :mass_kg, :distance_from_the_sun_km, :fun_fact def initialize(name, color,mass_kg, distance_from_the_sun_km, fun_fact) @name = name @color = color @mass_kg = mass_kg @distance_from_the_sun_km = distance_from_the_sun_km @fun_fact = fun_fact end def summary return "#{@name} is #{@color} and weighs #{@mass_kg}kgs, while being #{@distance_from_the_sun_km} kms away from the sun. Little known fact is: #{@fun_fact}!" end end
true
35131ab68c973380f5a0d78805a5b22be519640e
Ruby
AjayMahen/Day2
/max.rb
UTF-8
739
4.03125
4
[]
no_license
# Find the maximum def maximum(arr) x = arr.length if x > 0 until x == 1 if arr[x-1] > arr[x-2] arr.delete_at(x-2) else arr.delete_at(x-1) end x = arr.length end return arr else return nil end end def maximum_b(arr) highest = arr.first arr.each do |x| highest = x > highest ? x : highest end highest end # expect it to return 42 below result = maximum_b([2, 42, 22, 02]) puts "max of 2, 42, 22, 02 is: #{result}" # expect it to return nil when empty array is passed in result = maximum([]) puts "max on empty set is: #{result.inspect}" result = maximum_b([-23, 0, -3]) puts "max of -23, 0, -3 is: #{result}" result = maximum([6]) puts "max of just 6 is: #{result}"
true
8c7e2ba180aab1543ca34a02a27f2a0f66bf8644
Ruby
destinyd/shenmajia
/lib/get_more_info.rb
UTF-8
1,476
2.515625
3
[]
no_license
class GetMoreInfo URLS={liantu: 'http://www.liantu.com/tiaoma/query.php'} #PARAMS={liantu: 'ean'} attr_accessor :provider, :params, :result, :url def initialize(args) @provider = args[:provider] @params = args[:params] @url = URLS[@provider] end def post barcode @result = RestClient.post @url, { ean: barcode } end def json str_result begin JSON.parse str_result unless str_result.blank? rescue end end def get_json barcode json post barcode end def self.liantu GetMoreInfo.new provider: :liantu end def self.urls URLS end def self.get_liantu thread_count = 100 total_pages = Good.page.total_pages @lt = GetMoreInfo.liantu @pages = (1..total_pages).to_a @threads = [] thread_count.times do |index| @threads << Thread.new { get_liantu_infos} end @start = Time.now end def self.p_process(timeout = 60) while true p "info count: #{Info.count},last page:#{@pages.last}, remain: #{@pages.count}, cost: #{Time.cc_time(@start)}" sleep timeout end end #private def self.get_liantu_infos while @pages.count > 0 page = @pages.pop get_liantu_info(@lt, page) end end def self.get_liantu_info(lt, page) Good.page(page).only(:barcode,:_id).each do |good| good.infos.create result: lt.post(good.barcode), provider: 'liantu' end end def self.threads @threads end end
true
59c06a2596af37776d611fc1d12a9b1b2e58fa50
Ruby
AEminium/plaid-lang
/tartan/lib/parser/ast/decl.rb
UTF-8
1,136
2.953125
3
[]
no_license
module Parser module AST class Decl attr_accessor :linum, :id, :indent_level, :parent_node, :children, :and_states attr_reader :primary_state def initialize(linum, indent_level, id, and_states, primary_state) @linum = linum @id = id @indent_level = indent_level @and_states = and_states @primary_state = primary_state @parent_node = nil @children = [] end def add_child(child) @children.push(child) child.parent_node = self end def state_id @primary_state.id end def to_s puts "-- decl --" puts "linum: #{@linum}" puts "id : #{@id}" puts "indent_level : #{@indent_level}" puts "and_states : #{@and_states.map{|s|s.id}.join(', ')}" puts "primary_state : #{@primary_state.id}" puts "parent_node : #{@parent_node.id}" if @parent_node puts "children : #{@children.select{|c|c.id.length>0}.map{|c|c.id}.join(', ')}" if @children.size > 0 end def accept(v) v.visit_variable_decl(self) end end end end
true
3e406053381be32b062c963a59a3be328c3459e1
Ruby
mvz/ripper_ruby_parser
/lib/ripper_ruby_parser/sexp_handlers/helper_methods.rb
UTF-8
3,459
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module RipperRubyParser module SexpHandlers # Utility methods used in several of the sexp handler modules module HelperMethods def extract_node_symbol(exp) ident, = extract_node_symbol_with_position(exp) ident end def extract_node_symbol_with_position(exp) _, ident, pos = exp.shift 3 return ident.to_sym, pos end def make_symbol(exp) return nil if exp.nil? raise "Unexpected number of children: #{exp.length}" if exp.length != 2 _, ident = exp.shift 2 ident.to_sym end def with_position(pos, exp = nil) (line,) = pos exp = yield if exp.nil? with_line_number line, exp end def with_line_number(line, exp) exp.line = line exp end def with_position_from_node_symbol(exp) sym, pos = extract_node_symbol_with_position exp with_position(pos, yield(sym)) end def generic_add_star(exp) _, args, splatarg, *rest = shift_all exp items = process args if splatarg items.push s(:splat, unwrap_begin(process(splatarg))) else items.push s(:splat) end items.push(*map_process_list(rest)) end def integer_literal?(exp) exp && exp.sexp_type == :lit && exp[1].is_a?(Integer) end def reject_void_stmt(body) body.reject { |sub_exp| sub_exp.sexp_type == :void_stmt } end def map_process_list_compact(list) reject_void_stmt map_unwrap_begin_list map_process_list list end def map_process_list(list) list.map { |exp| process(exp) } end def map_unwrap_begin_list(list) list.map { |exp| unwrap_begin(exp) } end def unwrap_nil(exp) if exp.sexp_type == :void_stmt nil else exp end end def safe_unwrap_void_stmt(exp) unwrap_nil(exp) || s() end def unwrap_begin(exp) if exp.sexp_type == :begin exp[1] else exp end end def unwrap_block(exp) case exp.sexp_type when :block exp.sexp_body when :void_stmt [nil] else [exp] end end def wrap_in_block(statements, line) case statements.length when 0 s(:void_stmt).line(line) when 1 statements.first else first = statements.shift s(:block, *unwrap_block(first), *statements) end end def convert_void_stmt_to_nil_symbol(block) case block.sexp_type when :void_stmt s(:nil) else block end end def convert_empty_to_nil_symbol(block) case block.length when 0 s(:nil) else block end end def handle_return_argument_list(arglist) args = process(arglist).sexp_body case args.length when 0 args when 1 arg = args.first if arg.sexp_type == :splat s(:svalue, arg) else arg end else s(:array, *args) end end def shift_all(exp) [].tap do |result| result << exp.shift until exp.empty? end end end end end
true
3ddedf35c5b07bd80cbf091ac8a86197ccdbed80
Ruby
semyondv/graphics
/test.rb
UTF-8
857
2.953125
3
[]
no_license
require 'ruby2d' @CENTER_X = (get :width) / 2 @CENTER_Y = (get :height) / 2 @MUL = (get :height) / 70 def fn(x) Math::cos(0.5*x) #x**2 #14/x end def reset_step(x, st, &f) y1 = f.call(x) y2 = f.call(x + st) if (y1 - y2).abs > 1.0 [st / (y1 - y2).abs, 0.001].max else st end end def draw_fn(interval, &func) step = 0.12 c_step = step arg = interval.min while arg < interval.max do c_step = step c_step = reset_step(arg, step) {|xx| fn(xx)} Line.new( x1: @CENTER_X + arg * @MUL, y1: @CENTER_Y - func.call(arg) * @MUL, x2: @CENTER_X + 1 + arg * @MUL, y2: @CENTER_Y + 1 - func.call(arg) * @MUL, width: 1, color: 'lime', z: 20 ) arg += c_step end end draw_fn((-80..80)) {|args| fn(args)} show #Window.screenshot
true
22e2c97d054f89944217192740b4a752698aabe4
Ruby
BENSEBTI/speedtest
/speedtest.rb
UTF-8
393
3.125
3
[]
no_license
def speed(size,speed) convert = speed * 0.125 result = (size / convert) time = result return "your estimated download time is : " + Time.at(time).utc.strftime("%H:%M:%S")+ " happy dowloading :)" end puts " please do tell your file size in MB ? " size = Integer(gets.chomp).to_f puts " please do tell your internet speed in Mbps ?" speed = Integer(gets.chomp).to_f speed(size,speed)
true
258df3d23264ceaa8b168132b80268e104e6c8e8
Ruby
isabel22/fake_tag
/lib/fake_tag/base.rb
UTF-8
1,313
2.8125
3
[ "MIT" ]
permissive
module FakeTag module Base def generate amount = nil result = [] if amount.nil? #result = self.loop 4 result = self.get_tag else #result = self.loop amount result = self.get_tag amount end result end protected def tag_pool # TODO change this for something better (dynamic tags) ['v60', 'lipstick', 'nails', 'blackwidow', 'skateboard', 'happy', 'selfie', 'bike', 'car', 'dress', 'computer', 'geekstuff', 'love', 'android', 'ipad', 'nyc'] end def loop amount result = [] tags = self.tag_pool while result.length < amount do data = tags[rand(0..tags.count-1)] result << data unless result.include? data end result end def get_tag amount = 4, uri = 'http://www.ariadne.ac.uk/buzz/trending/tf/feed/trending-factor-buzz.xml' tags = [] result = [] doc = Nokogiri::XML(open(uri)) for tag in doc.xpath("//node/term").map.to_a do tags << tag.text end if amount > tags.length then amount = tags.length end while result.length < amount do data = tags[rand(0..tags.count-1)] result << data unless result.include? data end result end end end
true
f2774260780a3afd18e28eaf37726cd4fbe3e42d
Ruby
csinitiative/simplemapper
/test/unit/attribute_pattern_test.rb
UTF-8
1,806
2.625
3
[]
no_license
require 'test_helper' class SimpleMapperAttributePatternTest < Test::Unit::TestCase context 'A SimpleMapper::Attribute::Pattern instance' do setup do @class = SimpleMapper::Attribute::Pattern @pattern = /^a+/ @instance = @class.new(@name = :pattern_collection, :pattern => @pattern) end should 'extend SimpleMapper::Attribute' do assert_equal true, @instance.is_a?(SimpleMapper::Attribute) end should 'have a pattern attribute' do assert_equal @pattern, @instance.pattern new_pattern = /foo/ @instance.pattern = new_pattern assert_equal new_pattern, @instance.pattern end should 'require a pattern value' do # no problem if it has a :match method item = stub('item', :match => true) @instance.pattern = item assert_equal item, @instance.pattern # no rikey if no :match item = stub('bad bad not-a-pattern') assert_raise(SimpleMapper::InvalidPatternException) do @instance.pattern = item end end context 'with a SimpleMapper::Attributes-derived object' do setup do # initialize with non-matching keys @source_values = {:b => 'Bad', :c => 'Cows', :d => 'Deathdog'} @object = stub('object', :simple_mapper_source => @source_values) end context 'for source value' do should 'return empty hash if no keys in the source match the pattern' do assert_equal({}, @instance.source_value(@object)) end should 'return hash with key/value pairs for only the keys matching pattern' do expected = {:a => 'A', :abc => 'ABC', :aarp => 'AARP'} @source_values.merge! expected assert_equal expected, @instance.source_value(@object) end end end end end
true
696c9a9054bf5bc6b2cc0e28910fca443b8038d2
Ruby
caiofct/pagseguro-ruby
/lib/pagseguro/credit_card.rb
UTF-8
973
2.5625
3
[ "Apache-2.0" ]
permissive
module PagSeguro class CreditCard include Extensions::MassAssignment include Extensions::EnsureType # The Credit Card Token attr_accessor :token # The installment quantity. attr_accessor :installment_quantity # The installment value. attr_accessor :installment_value # The amount of installments without interest attr_accessor :no_interest_installment_quantity # Set the card holder name attr_accessor :holder_name # Set the card holder cpf attr_accessor :holder_cpf # Set the card holder birth date attr_accessor :holder_birth_date # Set the card holder area code attr_accessor :holder_area_code # Set the card holder area code attr_accessor :holder_phone # Get the billing address object. attr_reader :billing_address # Set the billing address info. def billing_address=(billing_address) @billing_address = ensure_type(Address, billing_address) end end end
true
55b6c17e95d6bda824fb0b0008416ddaf32f2c8b
Ruby
SelenaSmall/search-term
/spec/models/term_spec.rb
UTF-8
1,647
2.796875
3
[]
no_license
require 'rails_helper' describe Term do # it 'returns null if there are no terms in the database' do # expect(Term).to receive(:count).and_return(0) # expect(Term.get_term(1)).to eq nil # end context '1 term in the database' do let(:mock_term) { double('term') } before do allow(Term).to receive(:count).and_return(1) allow(Term).to receive_message_chain('all.order').with(:created_at).and_return([mock_term]) end # it 'returns the term for round 0' do # expect(Term.get_term(0)).to eq mock_term # end # # it 'returns the term for round 1' do # expect(Term.get_term(1)).to eq mock_term # end # # it 'returns the term for round "1" passed as string' do # expect(Term.get_term('1')).to eq mock_term # end end context '3 terms in the database' do let(:mock_term_1) { double('term 1') } let(:mock_term_2) { double('term 2') } let(:mock_term_3) { double('term 3') } let(:terms) { [mock_term_1, mock_term_2, mock_term_3] } before do allow(Term).to receive(:count).and_return(terms.count) allow(Term).to receive_message_chain('all.order').with(:created_at).and_return(terms) end # it 'gets the modulus 1st term' do # expect(Term.get_term(1)).to eq mock_term_1 # end # # it 'gets the modulus 2nd term' do # expect(Term.get_term(2)).to eq mock_term_2 # end # # it 'gets the modulus 3rd term' do # expect(Term.get_term(3)).to eq mock_term_3 # end # # it 'gets the modulus 99th term' do # expect(Term.get_term(99)).to eq mock_term_3 # end end end
true
e2c1bbbfe4d56191526f9bf91e92b1ddc799b0a7
Ruby
bcfsu/playlister-sinatra-v-000
/app/models/artist.rb
UTF-8
316
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist < ActiveRecord::Base has_many :songs has_many :genres, :through => :songs #TODO: Strip out special characters as well: '"/?!@#$%^&*() def slug self.name.downcase.gsub(" ", "-") end def self.find_by_slug(slug) self.all.detect do |artist| artist.slug == slug end end end
true
312124d5871040185361b209dc1a9472cde4d32f
Ruby
simplay/rubynopoly
/rubynopoly.rb
UTF-8
1,130
2.859375
3
[ "MIT" ]
permissive
#!/usr/bin/env jruby require "rubygems" # require "imageruby" require "pry" require 'optparse' require_relative 'src/game.rb' require_relative 'src/view.rb' require_relative 'src/controller.rb' Version = "0.0.1" user_args = {} opt_parser = OptionParser.new do |opt| opt.banner = "Usage example: ruby rabpt.rb -p 4 -m 1000" opt.separator "" opt.on("-p", "--players P", Integer, "the number of players") do |player| user_args[:players] = player end opt.on("-m", "--money MONEY", Integer, "start money") do |money| user_args[:money] = money end opt.on_tail("-h", "--help", "Show this message") do puts opt exit end opt.on_tail("--version", "Show version") do puts "Rubynopoly v#{Version}" exit end end begin opt_parser.parse! required_args = [:players, :money] required_args.each do |arg| raise OptionParser::MissingArgument if user_args[arg].nil? end rescue OptionParser::MissingArgument puts "Incorrect input argument(s) passed\n" puts opt_parser.help exit end # MVC initialization game = Game.new user_args view = View.new(game) Controller.new(game, view)
true
e807a2454634ac3d0cde3661eb74e0da8920832c
Ruby
rcm32000/apollo_13
/spec/models/astronaut_spec.rb
UTF-8
1,555
2.703125
3
[]
no_license
=begin As a visitor, When I visit '/astronauts' I see the average age of all astronauts. (e.g. "Average Age: 34") =end require 'rails_helper' describe '/astronauts' do it 'should show average age of astronauts' do mission = SpaceMission.create(title: 'Apollo 8', trip_length: 100) astronaut1 = mission.astronauts.create(name: 'Neil Armstrong', age: 40, job: 'Commander') astronaut2 = mission.astronauts.create(name: 'Buzz Aldrin', age: 30, job: 'Navigator') expect(Astronaut.avg_age).to eq(35) end it 'should show a total time in space' do mission1 = SpaceMission.create(title: 'Apollo 8', trip_length: 100) mission1 = SpaceMission.create(title: 'Apollo 8', trip_length: 100) astronaut1 = mission1.astronauts.create(name: 'Neil Armstrong', age: 40, job: 'Commander') astronaut2 = mission1.astronauts.create(name: 'Buzz Aldrin', age: 30, job: 'Navigator') mission2 = SpaceMission.create(title: 'Apollo 13', trip_length: 20) astronaut3 = mission2.astronauts.create(name: 'Jim Lovell', age: 40, job: 'Commander') astronaut2 = mission2.astronauts.create(name: 'Buzz Aldrin', age: 30, job: 'Navigator') mission3 = SpaceMission.create(title: 'Apollo 10', trip_length: 50) astronaut4 = mission3.astronauts.create(name: 'Thomas Stafford', age: 40, job: 'Commander') astronaut3 = mission3.astronauts.create(name: 'Jim Lovell', age: 30, job: 'Navigator') expect(astronaut1.total_space).to eq(100) expect(astronaut2.total_space).to eq(120) expect(astronaut3.total_space).to eq(70) expect(astronaut4.total_space).to eq(50) end end
true
3456921f3124f4f70e836f8b8c7bc5b6fd96cf92
Ruby
brentvale/codingpractice
/TreeNode/00_tree_node.rb
UTF-8
1,139
3.671875
4
[]
no_license
class PolyTreeNode def initialize(value) @value = value @parent = nil @children = [] end def parent @parent end def parent=(parent) unless @parent == nil #remove this node from previous parent @parent.children.delete(self) end @parent = parent unless @parent == nil @parent.children << self end end def children @children end def value @value end def add_child(child_node) @children << child_node child_node.parent = self end def remove_child(child) raise "Exception" if child.parent == nil child.parent = nil @children.delete(child) end def dfs(target_value) return self if self.value == target_value children.each do |child| result = child.dfs(target_value) return result unless result.nil? end return nil end def bfs(target_value) array = [] array << self until array.empty? node = array.shift if node.value == target_value return node end array.concat(node.children) end return nil end end
true
cef9413c9c83c3823dfcb0115148e189eb65443e
Ruby
Diazware12/GIGIH_BE_Bangsa
/module7/session1/part1/payment.rb
UTF-8
357
2.953125
3
[]
no_license
class Payment attr_accessor :input, :tax def initialize(params) input: params['input'], tax: params['tax'] end def compute case working_level when @input == 1 3000000 - (3000000 * @tax) when @input == 2 4000000 - (4000000 * @tax) when @input == 3 5000000 - (5000000 * @tax) else "unknown level" end end end
true
3dd17603455b5b4d11370850151b0d7c4df8944d
Ruby
PoweredByRobots/song_genre_updater
/genre_updater.rb
UTF-8
3,464
3.0625
3
[]
no_license
#!/usr/bin/env ruby require 'bundler/setup' require 'musicbrainz' require 'mysql2' require 'pry' def options { host: ENV['SONGS_DB_HOSTNAME'], username: ENV['SONGS_DB_USER'], password: ENV['SONGS_DB_PWD'], database: ENV['SONGS_DB_NAME'] } end def preserve_genres %w(Christmas art01 fraser18 dhr) end def mysql_client @mysql_client ||= Mysql2::Client.new(options) end def musicbrainz_client @musicbrainz_client ||= MusicBrainz::Client.new end def pause sleep 10 end def remove_already_processed(songs) pruned = [] songs.each do |song| next if processed_ids.include? song.first pruned << song end pruned end def filename 'processed.songs' end def processed_ids create_file if file_not_found? File.readlines(filename).map(&:to_i) end def create_file File.write(filename, '') end def file_not_found? !File.file?(filename) end def sterilize(genres) genres.map(&:downcase) & preserve_genres.map(&:downcase) end def update_song(id, artist, title, existing_genres) @remaining -= 1 add_to_list(id) puts "\n#{artist} - #{title}..." genres = lookup_genres(artist, title) || existing_genres return if genres == existing_genres update_genres(id, genres) end def add_to_list(id) File.open(filename, 'a') { |f| f.puts(id) } end def lookup_songlist(songs = []) sql = 'SELECT ID, title, artist, grouping FROM songlist ' \ "WHERE songtype = \'S\'" results = mysql_client.query(sql) results.each do |s| songs << [ s['ID'], s['artist'].to_s, s['title'], s['grouping'].split(', ') ] end remove_already_processed(songs) end def find_tags(recordings) tag_data = [] song_data = Hash[recordings.map { |key, value| [key, value] }] song_data.each do |song| tag_data << nested_hash_value(song, 'tags') end tag_data end def find_genres(tag_data) genres = [] tag_data.each do |tag| next if tag.nil? tag.each { |genre| genres << genre['name'] } end genres end def lookup_genres(artist, title) recordings = musicbrainz_lookup(artist, title) return if recordings.nil? || recordings.empty? puts '-> song found' tag_data = find_tags(recordings) return unless tag_data.first puts '-> tags found' genres = find_genres(tag_data) return if genres.empty? puts "-> genres found: #{genres}" genres end def musicbrainz_lookup(artist, title) pause query = { artist: artist, recording: title } musicbrainz_client.recordings q: query rescue => error puts "MusicBrainz error: #{error.message}" end def update_genres(id, genres) sql = "UPDATE songlist SET grouping = \'#{genres.join(', ')}\' " \ "WHERE id = #{id}" puts 'Updating records' mysql_client.query(sql) rescue => error puts "Skipping #{id}\n#{error.message}" @mysql_error_count += 1 abort('Too many db errors') if @mysql_error_count > 3 end def nested_hash_value(obj, key) if obj.respond_to?(:key?) && obj.key?(key) obj[key] elsif obj.respond_to?(:each) r = nil obj.find { |*a| r = nested_hash_value(a.last, key) } r end end def configure_musicbrainz MusicBrainz.configure do |c| c.app_name = 'My Music App' c.app_version = '0.1' c.contact = 'your@email.com' end end system 'clear' configure_musicbrainz songs = lookup_songlist @remaining = songs.count @mysql_error_count = 0 puts "-==[#{@remaining}]==- songs to go!" songs.each do |id, artist, title, genres| update_song(id, artist, title, genres) end
true
1363e8833f8ca137686bbbe18d6aa198c38e3bdf
Ruby
dazuma/toys
/toys-core/lib/toys/standard_middleware/show_help.rb
UTF-8
15,022
2.578125
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Toys module StandardMiddleware ## # A middleware that shows help text for the tool when a flag (typically # `--help`) is provided. It can also be configured to show help by # default if the tool is a namespace that is not runnable. # # If a tool is not runnable, this middleware can also add a # `--[no-]recursive` flag, which, when set to `true` (the default), shows # all subtools recursively rather than only immediate subtools. This # middleware can also search for keywords in its subtools. # class ShowHelp ## # Default help flags # @return [Array<String>] # DEFAULT_HELP_FLAGS = ["-?", "--help"].freeze ## # Default usage flags # @return [Array<String>] # DEFAULT_USAGE_FLAGS = ["--usage"].freeze ## # Default list subtools flags # @return [Array<String>] # DEFAULT_LIST_FLAGS = ["--tools"].freeze ## # Default recursive flags # @return [Array<String>] # DEFAULT_RECURSIVE_FLAGS = ["-r", "--[no-]recursive"].freeze ## # Default search flags # @return [Array<String>] # DEFAULT_SEARCH_FLAGS = ["-s WORD", "--search=WORD"].freeze ## # Default show-all-subtools flags # @return [Array<String>] # DEFAULT_SHOW_ALL_SUBTOOLS_FLAGS = ["--all"].freeze ## # Key set when the show help flag is present # @return [Object] # SHOW_HELP_KEY = Object.new.freeze ## # Key set when the show usage flag is present # @return [Object] # SHOW_USAGE_KEY = Object.new.freeze ## # Key set when the show subtool list flag is present # @return [Object] # SHOW_LIST_KEY = Object.new.freeze ## # Key for the recursive setting # @return [Object] # RECURSIVE_SUBTOOLS_KEY = Object.new.freeze ## # Key for the search string # @return [Object] # SEARCH_STRING_KEY = Object.new.freeze ## # Key for the show-all-subtools setting # @return [Object] # SHOW_ALL_SUBTOOLS_KEY = Object.new.freeze ## # Key for the tool name # @return [Object] # TOOL_NAME_KEY = Object.new.freeze ## # Create a ShowHelp middleware. # # @param help_flags [Boolean,Array<String>,Proc] Specify flags to # display help. The value may be any of the following: # # * An array of flags. # * The `true` value to use {DEFAULT_HELP_FLAGS}. # * The `false` value for no flags. (Default) # * A proc that takes a tool and returns any of the above. # # @param usage_flags [Boolean,Array<String>,Proc] Specify flags to # display usage. The value may be any of the following: # # * An array of flags. # * The `true` value to use {DEFAULT_USAGE_FLAGS}. # * The `false` value for no flags. (Default) # * A proc that takes a tool and returns any of the above. # # @param list_flags [Boolean,Array<String>,Proc] Specify flags to # display subtool list. The value may be any of the following: # # * An array of flags. # * The `true` value to use {DEFAULT_LIST_FLAGS}. # * The `false` value for no flags. (Default) # * A proc that takes a tool and returns any of the above. # # @param recursive_flags [Boolean,Array<String>,Proc] Specify flags # to control recursive subtool search. The value may be any of the # following: # # * An array of flags. # * The `true` value to use {DEFAULT_RECURSIVE_FLAGS}. # * The `false` value for no flags. (Default) # * A proc that takes a tool and returns any of the above. # # @param search_flags [Boolean,Array<String>,Proc] Specify flags # to search subtools for a search term. The value may be any of # the following: # # * An array of flags. # * The `true` value to use {DEFAULT_SEARCH_FLAGS}. # * The `false` value for no flags. (Default) # * A proc that takes a tool and returns any of the above. # # @param show_all_subtools_flags [Boolean,Array<String>,Proc] Specify # flags to show all subtools, including hidden tools and non-runnable # namespaces. The value may be any of the following: # # * An array of flags. # * The `true` value to use {DEFAULT_SHOW_ALL_SUBTOOLS_FLAGS}. # * The `false` value for no flags. (Default) # * A proc that takes a tool and returns any of the above. # # @param default_recursive [Boolean] Whether to search recursively for # subtools by default. Default is `false`. # @param default_show_all_subtools [Boolean] Whether to show all subtools # by default. Default is `false`. # @param fallback_execution [Boolean] Cause the tool to display its own # help text if it is not otherwise runnable. This is mostly useful # for namespaces, which have children are not runnable. Default is # `false`. # @param allow_root_args [Boolean] If the root tool includes flags for # help or usage, and doesn't otherwise use positional arguments, # then a tool name can be passed as arguments to display help for # that tool. # @param show_source_path [Boolean] Show the source path section. Default # is `false`. # @param separate_sources [Boolean] Split up tool list by source root. # Defaults to false. # @param use_less [Boolean] If the `less` tool is available, and the # output stream is a tty, then use `less` to display help text. # @param stream [IO] Output stream to write to. Default is stdout. # @param styled_output [Boolean,nil] Cause the tool to display help text # with ansi styles. If `nil`, display styles if the output stream is # a tty. Default is `nil`. # def initialize(help_flags: false, usage_flags: false, list_flags: false, recursive_flags: false, search_flags: false, show_all_subtools_flags: false, default_recursive: false, default_show_all_subtools: false, fallback_execution: false, allow_root_args: false, show_source_path: false, separate_sources: false, use_less: false, stream: $stdout, styled_output: nil) @help_flags = help_flags @usage_flags = usage_flags @list_flags = list_flags @recursive_flags = recursive_flags @search_flags = search_flags @show_all_subtools_flags = show_all_subtools_flags @default_recursive = default_recursive ? true : false @default_show_all_subtools = default_show_all_subtools ? true : false @fallback_execution = fallback_execution @allow_root_args = allow_root_args @show_source_path = show_source_path @separate_sources = separate_sources @stream = stream @styled_output = styled_output @use_less = use_less && !Compat.jruby? end ## # Configure flags and default data. # # @private # def config(tool, loader) unless tool.argument_parsing_disabled? StandardMiddleware.append_common_flag_group(tool) has_subtools = loader.has_subtools?(tool.full_name) help_flags = add_help_flags(tool) usage_flags = add_usage_flags(tool) list_flags = has_subtools ? add_list_flags(tool) : [] can_display_help = !help_flags.empty? || !list_flags.empty? || !usage_flags.empty? || @fallback_execution if can_display_help && has_subtools add_recursive_flags(tool) add_search_flags(tool) add_show_all_subtools_flags(tool) end end yield end ## # Display help text if requested. # # @private # def run(context) if context[SHOW_USAGE_KEY] show_usage(context) elsif context[SHOW_LIST_KEY] show_list(context) elsif context[SHOW_HELP_KEY] show_help(context, true) else begin yield rescue NotRunnableError => e raise e unless @fallback_execution show_help(context, false) end end end private def terminal require "toys/utils/terminal" @terminal ||= Utils::Terminal.new(output: @stream, styled: @styled_output) end def show_usage(context) help_text = get_help_text(context, true) str = help_text.usage_string( recursive: context[RECURSIVE_SUBTOOLS_KEY], include_hidden: context[SHOW_ALL_SUBTOOLS_KEY], separate_sources: @separate_sources, wrap_width: terminal.width ) terminal.puts(str) end def show_list(context) help_text = get_help_text(context, true) str = help_text.list_string( recursive: context[RECURSIVE_SUBTOOLS_KEY], search: context[SEARCH_STRING_KEY], include_hidden: context[SHOW_ALL_SUBTOOLS_KEY], separate_sources: @separate_sources, wrap_width: terminal.width ) terminal.puts(str) end def show_help(context, use_extra_args) help_text = get_help_text(context, use_extra_args) str = help_text.help_string( recursive: context[RECURSIVE_SUBTOOLS_KEY], search: context[SEARCH_STRING_KEY], include_hidden: context[SHOW_ALL_SUBTOOLS_KEY], show_source_path: @show_source_path, separate_sources: @separate_sources, wrap_width: terminal.width ) require "toys/utils/pager" use_pager = @use_less && @stream.tty? Utils::Pager.start(command: use_pager, fallback_io: terminal) do |io| io.puts(str) end end def get_help_text(context, use_extra_args) require "toys/utils/help_text" if use_extra_args && @allow_root_args && context[Context::Key::TOOL].root? tool_name = Array(context[Context::Key::UNMATCHED_POSITIONAL]) unless tool_name.empty? cli = context[Context::Key::CLI] loader = cli.loader tool, rest = loader.lookup(tool_name) help_text = Utils::HelpText.new(tool, loader, cli.executable_name) report_usage_error(help_text, loader, tool.full_name, rest.first) unless rest.empty? return help_text end end Utils::HelpText.from_context(context) end def report_usage_error(help_text, loader, tool_name, next_word) dict = loader.list_subtools(tool_name).map(&:simple_name) suggestions = Compat.suggestions(next_word, dict) tool_name = (tool_name + [next_word]).join(" ") message = "Tool not found: \"#{tool_name}\"" unless suggestions.empty? suggestions_str = suggestions.join("\n ") message = "#{message}\nDid you mean... #{suggestions_str}" end terminal.puts(message, :bright_red, :bold) terminal.puts terminal.puts help_text.usage_string(wrap_width: terminal.width) Context.exit(1) end def add_help_flags(tool) flags = resolve_flags_spec(@help_flags, tool, DEFAULT_HELP_FLAGS) unless flags.empty? tool.add_flag( SHOW_HELP_KEY, flags, report_collisions: false, desc: "Display help for this tool", group: StandardMiddleware::COMMON_FLAG_GROUP ) end flags end def add_usage_flags(tool) flags = resolve_flags_spec(@usage_flags, tool, DEFAULT_USAGE_FLAGS) unless flags.empty? tool.add_flag( SHOW_USAGE_KEY, flags, report_collisions: false, desc: "Display a brief usage string for this tool", group: StandardMiddleware::COMMON_FLAG_GROUP ) end flags end def add_list_flags(tool) flags = resolve_flags_spec(@list_flags, tool, DEFAULT_LIST_FLAGS) unless flags.empty? tool.add_flag( SHOW_LIST_KEY, flags, report_collisions: false, desc: "List the subtools under this tool", group: StandardMiddleware::COMMON_FLAG_GROUP ) end flags end def add_recursive_flags(tool) flags = resolve_flags_spec(@recursive_flags, tool, DEFAULT_RECURSIVE_FLAGS) if flags.empty? tool.default_data[RECURSIVE_SUBTOOLS_KEY] = @default_recursive else tool.add_flag( RECURSIVE_SUBTOOLS_KEY, flags, report_collisions: false, default: @default_recursive, desc: "List all subtools recursively when displaying help" \ " (default is #{@default_recursive})", group: StandardMiddleware::COMMON_FLAG_GROUP ) end flags end def add_search_flags(tool) flags = resolve_flags_spec(@search_flags, tool, DEFAULT_SEARCH_FLAGS) unless flags.empty? tool.add_flag( SEARCH_STRING_KEY, flags, report_collisions: false, desc: "Search subtools for the given regular expression when displaying help", group: StandardMiddleware::COMMON_FLAG_GROUP ) end flags end def add_show_all_subtools_flags(tool) flags = resolve_flags_spec(@show_all_subtools_flags, tool, DEFAULT_SHOW_ALL_SUBTOOLS_FLAGS) if flags.empty? tool.default_data[SHOW_ALL_SUBTOOLS_KEY] = @default_show_all_subtools else tool.add_flag( SHOW_ALL_SUBTOOLS_KEY, flags, report_collisions: false, default: @default_show_all_subtools, desc: "List all subtools including hidden subtools and namespaces" \ " (default is #{@default_show_all_subtools})", group: StandardMiddleware::COMMON_FLAG_GROUP ) end flags end def resolve_flags_spec(flags, tool, defaults) flags = flags.call(tool) if flags.respond_to?(:call) case flags when true, :default Array(defaults) when ::String [flags] when ::Array flags else [] end end end end end
true
2ecd0f938e3010d1cae0a519c9de1904802bd730
Ruby
adaveniprashanth/MyData
/ruby_training/ver_1_file_copy.rb
UTF-8
948
3.703125
4
[]
no_license
#include <ruby.h> require 'fileutils' puts "Hello, World! me"; #opening the file and reading the contents file = File.open("clip_paths.txt") array = file.readlines.map(&:chomp) file.close #printing current working directory path = Dir.getwd puts path #creating the new directory in the current folder Dir.mkdir("MPEG2") #adding the MPEG2 folder to current path path1 = path.concat("/MPEG2") puts path1 dest_path = path1.concat("/") #puts6 Dir.exist?"dir_name" #array = ['one', 'two', 'three', 'four'] #copying the file from source to destination for i in array if i.length > 2 puts "clipname\n" clipname_split = i.split("\\") clipname = clipname_split[-1] puts clipname puts "clip path\n" puts dest_path full_path = dest_path+clipname puts full_path FileUtils.cp(i, full_path) end end puts "copy completed";
true
b8e796e16703297cd3700cef3bebb2229362b5cf
Ruby
Rianasoa/mini_jeu_poo
/app_2.rb
UTF-8
1,824
3.515625
4
[]
no_license
require 'bundler' Bundler.require require_relative 'lib/game' require_relative 'lib/player' puts "------------------------------------------------" puts "|Bienvenue sur 'ILS VEULENT TOUS MA POO' ! |" puts "|Le but du jeu est d'être le dernier survivant !|" puts "------------------------------------------------" puts "Quel est le nom de ton joueur ?" player3 = HumanPlayer.new(gets.chomp.to_s) player1 = Player.new("Josiane") player2 = Player.new("José") enemies = [player1, player2] user = player3 while user.life_points > 0 && (player1.life_points > 0 || player2.life_points > 0) puts "Voici l'état de santé de ton joueur #{user.name} :" puts "#{user.show_state}" puts "" puts "Que veux-tu faire ?" puts "a - chercher une meilleure arme" puts "s - chercher à se soigner" puts "" puts "Attaquer un autre joueur :" puts "0 - #{player1.name} -> #{player1.show_state} points de vie" puts "" puts "1 - #{player2.name} -> #{player2.show_state} points de vie" puts "" user_choice = gets.chomp if user_choice == "a" user.search_weapon elsif user_choice == "s" user.search_health_pack elsif user_choice == "0" user.attacks(player1) elsif user_choice == "1" user.attacks(player2) else puts "Choix non valide !" end puts "" # .all? vérifie si la condition est vraie pour TOUS les éléments de l'array # si oui, cela nous sort de la boucle break if enemies.all? { |enemie| enemie.life_points <= 0 } puts "Les autres joueurs attaquent !" enemies.each do |enemie| enemie.attacks(user) if user.life_points > 0 && enemie.life_points > 0 end end if player3.life_points > 0 puts "La partie est finie" puts "WAOUHHHH Tu As Fait un bon MATCH !" else puts "OUHHH ! Tu as perdu !" end
true
a68b9aba47280fa48aef3e59097c73ef49862c9a
Ruby
paulentine/slack-cli
/specs/workspace_spec.rb
UTF-8
4,316
2.625
3
[]
no_license
require 'minitest' require_relative 'test_helper.rb' describe "Workspace" do before do VCR.use_cassette("load_workspace") do response = SlackAPI::User.load response2 = SlackAPI::Channel.load @workspace = SlackAPI::Workspace.new(users: response, channels: response2) end end describe "select_user" do it "selects a user when name is provided" do @workspace.select_user(id_or_name:"slackbot") expect(@workspace.selected).must_be_kind_of SlackAPI::User expect(@workspace.selected.name).must_equal "slackbot" end it "selects a user when id is provided" do @workspace.select_user(id_or_name:"USLACKBOT") expect(@workspace.selected).must_be_kind_of SlackAPI::User expect(@workspace.selected.slack_id).must_equal "USLACKBOT" end end describe "select_channel" do it "returns nil if no user / channel is selected" do expect(@workspace.selected).must_be_nil end it "selects a channel when id is provided" do @workspace.select_channel(id_or_name:"CH2SBU69Y") expect(@workspace.selected).must_be_kind_of SlackAPI::Channel expect(@workspace.selected.slack_id).must_equal "CH2SBU69Y" end it "selects a channel when name is provided" do @workspace.select_channel(id_or_name:"everyone") expect(@workspace.selected).must_be_kind_of SlackAPI::Channel expect(@workspace.selected.name).must_equal "everyone" end it "returns nil if channel is not found" do @workspace.select_channel(id_or_name:"madeup_channel") expect(@workspace.selected).must_be_nil end end describe "show_details" do it "shows details for a selected user" do @workspace.select_user(id_or_name:"slackbot") expect(@workspace.show_details).must_be_kind_of String end it "shows details for a selected channel" do @workspace.select_channel(id_or_name:"everyone") expect(@workspace.show_details).must_be_kind_of String end end describe "send_message" do it "will raise an error when given an invalid channel" do bad_channel = SlackAPI::Channel.new(slack_id: "123", name: "bad", topic: "bad", member_count: "1") @workspace.channels.push(bad_channel) @workspace.select_channel(id_or_name:"bad") VCR.use_cassette("send_message_bad_channel") do exception = expect { @workspace.send_message(text:"This post should not work") }.must_raise SlackAPI::SlackApiError end @workspace.channels.pop end it "will raise an error when given an invalid user" do bad_user = SlackAPI::User.new(real_name: "baddie", slack_id: "123", name: "baddie") @workspace.users.push(bad_user) @workspace.select_user(id_or_name:"baddie") VCR.use_cassette("send_message_bad_user") do exception = expect { @workspace.send_message(text:"This post should not work") }.must_raise SlackAPI::SlackApiError end @workspace.users.pop end it "will send a message to a channel" do channel = @workspace.channels[0].name @workspace.select_channel(id_or_name: channel) VCR.use_cassette("send_message_to_channel") do response = @workspace.send_message(text:"message to channel!") expect(response).must_equal true end end it "will send a message to a user" do user = @workspace.users[0].name @workspace.select_user(id_or_name: user) VCR.use_cassette("send_message_to_user") do response = @workspace.send_message(text:"message to user!") expect(response).must_equal true end end it "will send rasie an error for empty text" do user = @workspace.users[0].name @workspace.select_user(id_or_name: user) VCR.use_cassette("send_empty_message_user") do exception = expect { @workspace.send_message(text:"") }.must_raise SlackAPI::SlackApiError end end it "it sends message with digits for text" do channel = @workspace.channels[0].name @workspace.select_channel(id_or_name: channel) VCR.use_cassette("send_digit_message_to_channel") do response = @workspace.send_message(text: 123) expect(response).must_equal true end end end end
true
d8a687b38b55f9476226f379cfd6514021133f1d
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/a752921c14494e47b5916bfc9c7cacb1.rb
UTF-8
261
3.40625
3
[]
no_license
class Hamming def self.compute(strand, other_strand) strand = strand.scan(/\w/) other_strand = other_strand.scan(/\w/) strand.each.with_index.inject(0) do |memo, (char, index)| char == other_strand[index] ? memo : memo +=1 end end end
true
4fa48c02b64336aeb43378d74053224df52fc68c
Ruby
RetynaGirl/enigma
/lib/key_applier.rb
UTF-8
524
3.078125
3
[]
no_license
# frozen_string_literal: true # Applies key hashes to incoming messages class KeyApplier @@ordered_characters = (97..122).map(&:chr).push(' ') def self.apply_key(message, key) message.downcase.split('').map.with_index do |character, idx| wrap_apply(character, key[idx % 4]) end.join end def self.wrap_apply(character, offset) if @@ordered_characters.include?(character) @@ordered_characters[(@@ordered_characters.index(character) + offset) % 27] else character end end end
true
f5152569ddc80f85e51c8ba140799a310a026cf1
Ruby
sa2taka/rootine
/vendor/bundle/ruby/2.6.0/gems/rspec-expectations-3.8.3/lib/rspec/matchers/built_in/be_kind_of.rb
UTF-8
930
2.703125
3
[ "MIT" ]
permissive
module RSpec module Matchers module BuiltIn # @api private # Provides the implementation for `be_a_kind_of`. # Not intended to be instantiated directly. class BeAKindOf < BaseMatcher private def match(expected, actual) if actual_object_respond_to?(actual, :kind_of?) actual.kind_of?(expected) elsif actual_object_respond_to?(actual, :is_a?) actual.is_a?(expected) else raise ::ArgumentError, "The #{matcher_name} matcher requires that " \ "the actual object responds to either #kind_of? or #is_a? methods "\ "but it responds to neigher of two methods." end end def actual_object_respond_to?(actual, method) ::Kernel.instance_method(:respond_to?).bind(actual).call(method) end end end end end
true
3eae9a3bc084e847801d606730c4147f5eee426a
Ruby
marlbones/CFA-Temperature-Project
/temp.rb
UTF-8
2,185
3.796875
4
[]
no_license
#Access the following files and gems require './progressbarsingle' require 'paint' require 'terminal-table' #Questioner class class Questioner def initialize @questions = [ "What was the temperature on Monday?", "What was the temperature on Tuesday?", "What was the temperature on Wednesday?", "What was the temperature on Thursday?", "What was the temperature on Friday?", "What was the temperature on Saturday?", "What was the temperature on Sunday?", ] end attr_accessor :questions #ask method within Questioner class. Carries the logic of progressing through questions/displaying def ask(progress_bar) answers = [] fahs = [] @questions.each do |question| #.each specific to arrays. Looks over arrays. the "do portin creates a function, and "question" is just a placeholder" system("clear") #clears screen puts "#{progress_bar.title}: #{progress_bar.current_step}" puts question answer= gets.chomp.to_i fah = (answer * 9) / 5 + 32 #colour logic if answer >= 30 answer = Paint[answer, :red] else answer = Paint[answer, :blue] end #fah colour logic if fah >= 86 fah = Paint[fah, :red] else fah = Paint[fah, :blue] end answers << answer #adds to the end of array/variable "answers" fahs << fah progress_bar.current_step = progress_bar.current_step + 1 end if progress_bar.current_step == @questions.length + 1 rows = [] rows << ['Monday', answers[0], fahs[0]] rows << ['Tuesday', answers[1], fahs[1]] rows << ['Wednesday', answers[2], fahs[2]] rows << ['Thursday', answers[3], fahs[3]] rows << ['Friday', answers[4], fahs[4]] rows << ['Saturday', answers[5], fahs[5]] rows << ['Sunday', answers[6], fahs[6]] table = Terminal::Table.new :rows => rows table = Terminal::Table.new :title => "Tempertaure Chart", :headings => ['Day', 'Celsius', 'Fahrenheit'], :rows => rows puts table end end end my_questioner = Questioner.new progress_bar = ProgressBar.new("Question Progress") my_questioner.ask(progress_bar)
true
7d96b8cc1c8e8733cfcab5ecc0bedd5f2784c5be
Ruby
marcrowindo/SECURA
/db/seeds.rb
UTF-8
1,384
2.515625
3
[]
no_license
puts "Destroying all the quotes." Quote.destroy_all quote_attributes = [ { supplier_name: 'Securitas', supplier_address: 'Potsdamer Straße 88 10785 Berlin', phone_number: '030 5010000', price: nil, token: nil, request_id: nil }, { supplier_name: 'Kötter Security', supplier_address: 'Friedrichstraße 95, 10117 Berlin', phone_number: '030 28509011', price: nil, token: nil, request_id: nil }, { supplier_name: 'GRAEF Information Technology', supplier_address: 'Eiswerderstrasse 20, 13585 Berlin', phone_number: '030 69202294', price: nil, token: nil, request_id: nil }, { supplier_name: 'Protection One', supplier_address: 'Holzhauser Str. 177, 13509 Berlin', phone_number: '030 27004970', price: nil, token: nil, request_id: nil }, { supplier_name: 'SOSCOM', supplier_address: 'Scharnweberstrasse 113, 13405 Berlin', phone_number: '030 410300', price: nil, token: nil, request_id: nil } ] Quote.create!(quote_attributes) puts "Finished"
true
7413e4cd03fbd017296161eae0ea9dc118285162
Ruby
emilyjf/rspec_testing
/calculator.rb
UTF-8
1,799
3.84375
4
[]
no_license
# require 'rspec' # class Calculator # def add(number_one, number_two) # return number_one + number_two # end # def subtract(number_one, number_two) # return number_one - number_two # end # def multiply(number_one, number_two) # return number_one * number_two # end # def divide(dividend, divisor) # return dividend / divisor # end # def square(number) # return number * number # end # def power(number, exponent) # return number ** exponent # end # end # #third sentence always begins with "it should" (describe and it are methods taking in a constant) # RSpec.describe Calculator do # describe '#add' do # it 'should return the sum of two numbers' do # calculator = Calculator.new # expect(calculator.add(1,3)).to eq(4) # end # end # describe '#subtract' do # it 'should return the difference between two numbers' do # calculator = Calculator.new # expect(calculator.subtract(8,6)).to eq(2) # end # end # describe '#multiply' do # it 'should return the product of two numbers' do # calculator = Calculator.new # expect(calculator.multiply(5,2)).to eq(10) # end # end # describe '#divide' do # it 'should return the quotient of two numbers' do # calculator = Calculator.new # expect(calculator.divide(6,3)).to eq(2) # end # end # describe '#square' do # it 'should return the product of a number times itself' do # calculator = Calculator.new # expect(calculator.square(2)).to eq(4) # end # end # describe '#power' do # it 'should return the product of a number times itself a number of times' do # calculator = Calculator.new # expect(calculator.power(2,3)).to eq(8) # end # end # end
true
907aaacd3e7ed5a48fdd74f746f9fc67211200fe
Ruby
payload-code/payload-ruby
/lib/payload/arm/session.rb
UTF-8
1,293
2.75
3
[ "MIT" ]
permissive
require 'payload/arm/request' module Payload class Session attr_accessor :api_key, :api_url def initialize(api_key, api_url=nil) @api_key = api_key @api_url = api_url || Payload.URL Payload.constants.each do |c| val = Payload.const_get(c) if val.is_a?(Class) && val < Payload::ARMObject define_singleton_method(c) { Payload::ARMObjectWrapper.new(val, self) } end end end def _get_request(cls = nil) return Payload::ARMRequest.new(cls, self) end def query(cls) return self._get_request(cls) end def create(objects) return self._get_request().create(objects) end def update(objects) return self._get_request().update_all(objects) end def delete(objects) return self._get_request().delete_all(objects) end def ==(other) return false unless other.is_a?(Session) # Compare the attributes for equality api_key == other.api_key && api_url == other.api_url end def to_s "#{api_key} @ #{api_url}" end end end
true
71c24a39e9f12d5c865cbfb3dd7d9f209969d24c
Ruby
bkoski/each_with_context
/test/test_each_with_context.rb
UTF-8
6,123
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require File.dirname(__FILE__) + '/test_helper' class TestEachWithContext < Test::Unit::TestCase context "first?" do setup do @collection = [1,2,3,4] end should "return true on last element" do @collection.each_with_context do |num,c| assert c.first? if num == 1 end end should "return false for all other elements" do @collection.each_with_context do |num,c| assert !c.first?, "first? should be false for #{num}" if num != 1 end end end context "last?" do setup do @collection = [1,2,3,4] end should "return true on last element" do @collection.each_with_context do |num,c| assert c.last? if num == 4 end end should "return false for all other elements" do @collection.each_with_context do |num,c| assert !c.last?, "last? should be false for #{num}" if num != 4 end end end context "edge" do setup do @collection = [1,2,3] end should "return :first for first element" do @collection.each_with_context do |num,c| assert_equal :first, c.edge if c == 1 end end should "return :last for last element" do @collection.each_with_context do |num,c| assert_equal :last, c.edge if c == 3 end end should "return nil for an element in the middle" do @collection.each_with_context do |num,c| assert_nil c.edge if c == 2 end end end context "index" do should "return the zero-based index as index" do [0,1,2,3].each_with_context do |num,c| assert_equal num, c.index end end end context "next" do setup do @collection = ['a','b','c','d'] end should "return the next element" do @collection.each_with_context do |element, c| assert_equal(@collection[c.index + 1], c.next) unless c.last? end end should "return nil if there is no next element" do @collection.each_with_context do |element, c| assert_nil c.next if c.last? end end end context "previous" do setup do @collection = ['a','b','c','d'] end should "return the previous element" do @collection.each_with_context do |element, c| assert_equal(@collection[c.index - 1], c.previous) unless c.first? end end should "return nil if there is no previous element" do @collection.each_with_context do |element, c| assert_nil c.previous if c.first? end end end context "next_differs_on?" do setup do @collection = [Date.today, Date.today + 1, Date.today + 2] end should "return true if next element doesn't have same value for specified method" do [Date.today, Date.today + 1, Date.today + 2].each_with_context do |date,c| assert c.next_differs_on?(:day) unless c.last? end end should "return false if next element doesn't have same value for specified method" do [Date.today, Date.today, Date.today].each_with_context do |date,c| assert !c.next_differs_on?(:day) unless c.last? end end should "return nil if there is no next element" do [Date.today, Date.today, Date.today].each_with_context do |date,c| assert_nil c.next_differs_on?(:day) if c.last? end end end context "previous_differs_on?" do setup do @collection = [Date.today, Date.today + 1, Date.today + 2] end should "return true if next element doesn't have same value for specified method" do [Date.today, Date.today + 1, Date.today + 2].each_with_context do |date,c| assert c.previous_differs_on?(:day) unless c.first? end end should "return false if next element doesn't have same value for specified method" do [Date.today, Date.today, Date.today].each_with_context do |date,c| assert !c.previous_differs_on?(:day) unless c.first? end end should "return nil if there is no next element" do [Date.today, Date.today, Date.today].each_with_context do |date,c| assert_nil c.previous_differs_on?(:day) if c.first? end end end context "next_is?" do setup do @collection = [1,2,3,4] end should "yield block with element as first parameter" do @collection.each_with_context do |element, c| unless c.last? c.next_is? { |e,n| assert_equal(element, e) } end end end should "yield block with next element as second parameter" do @collection.each_with_context do |element, c| unless c.last? c.next_is? { |e,n| assert_equal(c.next, n) } end end end should "return nil if there is no next element" do @collection.each_with_context do |element, c| assert_nil(c.next_is? { |e,n| 29 }) if c.last? end end should "return value returned by block" do @collection.each_with_context do |element, c| assert_equal(49, c.next_is? { |e,n| 49 }) unless c.last? end end end context "previous_is?" do setup do @collection = [1,2,3,4] end should "yield block with element as first parameter" do @collection.each_with_context do |element, c| unless c.first? c.previous_is? { |e,p| assert_equal(element, e) } end end end should "yield block with previous element as second parameter" do @collection.each_with_context do |element, c| unless c.first? c.previous_is? { |e,p| assert_equal(c.previous, p) } end end end should "return nil if there is no previous element" do @collection.each_with_context do |element, c| assert_nil(c.previous_is? { |e,p| 'test-value' }) if c.first? end end should "return value returned by block" do @collection.each_with_context do |element, c| assert_equal('test-value', c.previous_is? { |e,p| 'test-value' }) unless c.first? end end end end
true
c9383bb2c1c83c94bf05931332b81ab6f1870e43
Ruby
somethinrother/bitmaker_lessons
/inheritance_3/moon.rb
UTF-8
353
3.453125
3
[]
no_license
class Moon < Body attr_accessor(:name, :mass, :month, :planet) def initialize(name, mass, month, planet) super(name, mass) @month = month @planet = planet end def moon_stats puts "I am #{name}, my mass is #{mass.round(2)}kg, and I am in orbit around #{planet.name}, which it takes me #{month} earth days to orbit." end end
true
f6261dcf34cc07e481069099f7a6deebab1beafd
Ruby
chonnessey/burger_week_api
/db/seeds.rb
UTF-8
1,480
2.78125
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 bin/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) Burger.destroy_all Review.destroy_all class Seed def self.begin seed = Seed.new seed.generate_burgers seed.generate_reviews end def generate_burgers 37.times do |i| burger = Burger.create!( name: Faker::Food.dish, description: Faker::Food.description, inspiration: Faker::Fantasy::Tolkien.poem, drink_special: Faker::Beer.name, address: Faker::Address.street_address, hours_of_availability: "#{Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :long)} - #{Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :long)}" ) puts "#{burger.name} burger created!" end end def generate_reviews @burgers = Burger.all @burgers.each do |burger| rand(0..5).times do Review.create!( author: Faker::Name.name, rating: rand(1..5), content: Faker::Hipster.sentences(number: 3).join(" "), burger_id: burger.id, ) end end p "Created #{Review.count} Reviews for #{Burger.count} burgers." end end Seed.begin
true
5498ecc3d18c7dd97794ffe25cd96e4c77a48c4c
Ruby
mattgellert/regex-lab-immersive-alum
/lib/regex_lab.rb
UTF-8
452
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def starts_with_a_vowel?(word) !!word.match(/\A[aeiouAEIOU]/) end def words_starting_with_un_and_ending_with_ing(text) text.split(" ").grep(/\Aun.+ing\z/) end def words_five_letters_long(text) text.split(" ").select{|x| x.length == 5} end def first_word_capitalized_and_ends_with_punctuation?(text) !!text.match(/\A[A-Z](\w|\W)*[.!]/) end def valid_phone_number?(phone) !!phone.match(/\W{0,1}\d{3}\W{0,2}\d{3}\W{0,1}\d{4}/) end
true