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
4d154ebf26e79a66771692291e3c4ff0a050f5ea
Ruby
Waynexiee/My_leetcode
/spiral_matrix.rb
UTF-8
1,049
3.65625
4
[]
no_license
def spiral_order(matrix) return [] if matrix.empty? || matrix[0].empty? ceiling = 0 botton = matrix.size - 1 left = 0 right = matrix[0].size - 1 i = 0 j = 0 res = [] while left <= right && ceiling <= botton break if j > right while j <= right res << matrix[i][j] break unless j + 1 <= right j += 1 end ceiling += 1 i = ceiling break if i > botton while i <= botton res << matrix[i][j] break unless i + 1 <= botton i += 1 end right -= 1 j = right break if j < left while j >= left res << matrix[i][j] break unless j - 1 >= left j -= 1 end botton -= 1 i = botton break if i < ceiling while i >= ceiling res << matrix[i][j] break unless i - 1 >= ceiling i -= 1 end left += 1 j = left puts j end res end matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]] p spiral_order(matrix)
true
18c268a5893c44839ccfccee851ceb8f26eca2f6
Ruby
sweinstein27/operators-v-000
/lib/operations.rb
UTF-8
129
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def unsafe?(speed) speed.between?(40,60) ? false : true end def not_safe?(speed) speed.between?(40,60) ? false : true end
true
19961167969bd8233ecd1eee428df3bd1d6f7992
Ruby
AddisonDean/PuttPutt
/objects/gauge.rb
UTF-8
577
2.9375
3
[ "MIT" ]
permissive
class Gauge def initialize(x, y) @x, @y = x, y @image = Gosu::Image.new('resources/images/gauge/gauge_00.png') end def determine_power(power_level) power_level = ((power_level / 10) / 1.67).round(0) if power_level < 10 power_level = "0#{power_level}" end pic_name = "resources/images/gauge/gauge_#{power_level}.png" @image = Gosu::Image.new(pic_name) end def go_invisible @image = Gosu::Image.new('resources/images/blank.png') end def draw @image.draw(@x, @y, 0, 0.5, 0.5) end end
true
3dbd4469037a745927aadea910f690358de289f2
Ruby
sporkmonger/addressable
/benchmark/unicode_normalize.rb
UTF-8
1,338
2.609375
3
[ "Apache-2.0" ]
permissive
# /usr/bin/env ruby # frozen_string_literal: true. require "benchmark" require_relative "../lib/addressable/idna/pure.rb" require "idn" value = "fiᆵリ宠퐱卄.com" expected = "fiᆵリ宠퐱卄.com" N = 100_000 fail "ruby does not match" unless expected == value.unicode_normalize(:nfkc) fail "libidn does not match" unless expected == IDN::Stringprep.nfkc_normalize(value) fail "addressable does not match" unless expected == Addressable::IDNA.unicode_normalize_kc(value) Benchmark.bmbm do |x| x.report("pure") { N.times { Addressable::IDNA.unicode_normalize_kc(value) } } x.report("libidn") { N.times { IDN::Stringprep.nfkc_normalize(value) } } x.report("ruby") { N.times { value.unicode_normalize(:nfkc) } } end # February 14th 2023, before replacing the legacy pure normalize code: # > ruby benchmark/unicode_normalize.rb # Rehearsal ------------------------------------------ # pure 1.335230 0.000315 1.335545 ( 1.335657) # libidn 0.058568 0.000000 0.058568 ( 0.058570) # ruby 0.326008 0.000014 0.326022 ( 0.326026) # --------------------------------- total: 1.720135sec # user system total real # pure 1.325948 0.000000 1.325948 ( 1.326054) # libidn 0.058067 0.000000 0.058067 ( 0.058069) # ruby 0.325062 0.000000 0.325062 ( 0.325115)
true
10f51b065151e4afec98f93d7994983fd5b9799f
Ruby
jkim10132/procore_rails_tutorial
/01_Ruby_FizzBuzz/spec/fizz_buzz_spec.rb
UTF-8
1,541
3.734375
4
[]
no_license
require_relative "../lib/fizz_buzz.rb" describe "fizzbuzz_helper()" do it 'returns "Fizz" when the number is divisible by 3' do fizz_3 = fizzbuzz_helper(3) expect(fizz_3).to eq("Fizz") end it 'returns "Buzz" when the number is divisible by 5' do fizz_5 = fizzbuzz_helper(5) expect(fizz_5).to eq("Buzz") end it 'returns "FizzBuzz" when the number is divisible by 3 and 5' do fizz_15 = fizzbuzz_helper(15) expect(fizz_15).to eq("FizzBuzz") end it 'returns the number when the number is not divisible by 3 or 5' do fizz_4 = fizzbuzz_helper(4) expect(fizz_4).to eq(4) end end describe "fizz_buzz" do it 'returns the correct array when range is 100' do correct = [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz", 31, 32, "Fizz", 34, "Buzz", "Fizz", 37, 38, "Fizz", "Buzz", 41, "Fizz", 43, 44, "FizzBuzz", 46, 47, "Fizz", 49, "Buzz", "Fizz", 52, 53, "Fizz", "Buzz", 56, "Fizz", 58, 59, "FizzBuzz", 61, 62, "Fizz", 64, "Buzz", "Fizz", 67, 68, "Fizz", "Buzz", 71, "Fizz", 73, 74, "FizzBuzz", 76, 77, "Fizz", 79, "Buzz", "Fizz", 82, 83, "Fizz", "Buzz", 86, "Fizz", 88, 89, "FizzBuzz", 91, 92, "Fizz", 94, "Buzz", "Fizz", 97, 98, "Fizz", "Buzz"] expect(fizz_buzz(100)).to eq correct end it 'returns the correct array when max is 10' do correct = [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz"] expect(fizz_buzz(10)).to eq correct end end
true
65495799fdd7633278f503dbc7bd6eecf7a142f2
Ruby
bmordan/photogrid
/lib/db.rb
UTF-8
2,236
3.03125
3
[]
no_license
require "sqlite3" require_relative "./gallery" require_relative "./search" class DB include Search def initialize @db = SQLite3::Database.new ("./db") @db.execute "CREATE TABLE IF NOT EXISTS galleries(id INTEGER PRIMARY KEY, title TEXT);" @db.execute "CREATE TABLE IF NOT EXISTS keywords(id INTEGER PRIMARY KEY, keyword TEXT, gallery_id INTEGER);" @db.execute <<-SQL CREATE TABLE IF NOT EXISTS images( id INTEGER PRIMARY KEY, gallery_id INTEGER, src TEXT, photographer TEXT, photographer_avatar TEXT, likes INTEGER, tags TEXT ); SQL end def get_galleries galleries = [] @db.execute("SELECT * FROM galleries;") { |gallery| id, title = gallery keywords = get_keywords(id) images = get_images(id) galleries << Gallery.new(id, title, keywords, images) } return galleries end def get_keywords(id) @db.execute("SELECT * FROM keywords WHERE gallery_id IS ?;", id) .reduce([]) { |memo, row| memo << row[1] } end def get_gallery(id) @db.execute("SELECT * FROM galleries WHERE id IS ?;", id) { |gallery| id, title = gallery keywords = get_keywords(id) images = get_images(id) return Gallery.new(id, title, keywords, images) } end def create_gallery(title) @db.execute("INSERT INTO galleries (title) VALUES (?)", title) @db.last_insert_row_id end def add_keyword(gallery_id, keyword) @db.execute("INSERT INTO keywords (keyword, gallery_id) VALUES (?, ?);", [keyword, gallery_id]) count = @db.execute("SELECT COUNT(id) AS result FROM keywords WHERE gallery_id IS ?;", gallery_id) count.first.last end def get_images(gallery_id) @db.execute("SELECT * FROM images WHERE gallery_id IS ?;", gallery_id).reduce([]) { |memo, image| memo << Image.new(gallery_id, image) } end def add_images(gallery_id) gallery = get_gallery(gallery_id) gallery.images = fetch_images(gallery.id, gallery.keywords) gallery.images.each { |image| @db.execute("INSERT INTO images (gallery_id, src, photographer, photographer_avatar, likes, tags) VALUES (?, ?, ?, ?, ?, ?);", image.props) } return gallery end end
true
fd8fbccede45d9b17016188e6f1e9156c461f63f
Ruby
noku/university
/PAD/Lab#2/tcp_server.rb
UTF-8
1,462
3.140625
3
[]
no_license
class TcpServer BLOCK_SIZE = 1024 attr_reader :host, :port, :tcp_server, :data, :neighbors def initialize host, port, data, neighbors @host = host @port = port @data = data @neighbors = neighbors @tcp_server = TCPServer.open(host, port.to_i) end def listener loop do Thread.start(@tcp_server.accept) do |client| while true do request = client.gets.chomp send_all_data(client) if request == "*all*node*data*" send_node_data(client) if request == "*node*data*" end end end end private def send_all_data client puts "send all data" json_data = gather_data << get_node_data client.puts(format_data(json_data)) end def send_node_data client puts "send node data" client.puts get_node_data << "**%" end def get_node_data data[port]["employers"].join(",") end def gather_data neighbors.map do |neighbour_port| socket = TCPSocket.open(host, neighbour_port) socket.puts "*node*data*" receive_neighbour_data socket end end def receive_neighbour_data tcp_socket line_regex = /.*\*\*%/ data = '' while line = tcp_socket.recv(BLOCK_SIZE) data += (line =~ line_regex) ? line.split("**%").first : line # add break to the first if statement break if line =~ line_regex end data end def format_data data "[#{data.join(",").gsub("=>", ":")}]**%" end end
true
78b07da9f23568ca660132f3c65d078a77b245dc
Ruby
amb8l/tictactoe-ruby-core
/spec/tictactoe/game_engine_spec.rb
UTF-8
1,603
2.796875
3
[]
no_license
require 'tictactoe/mock_game_ui' require 'tictactoe/game_engine' require 'tictactoe/mock_player' module TicTacToe RSpec.describe GameEngine do before(:each) do @ui = MockGameUI.new @engine = GameEngine.new(@ui) end it "ends a game when the game is won" do p1 = MockPlayer.new('X', 1, 2, 3) p2 = MockPlayer.new('O', 4, 5) @engine.start(p1, p2) expect(@ui.show_game_state_called).to eq 6 expect(@ui.get_move_called).to eq 5 expect(@ui.show_game_result_called). to eq 1 end it "ends a game when the game is tied" do p1 = MockPlayer.new('X', 5, 3, 4, 2, 9) p2 = MockPlayer.new('O', 1, 7, 6, 8) @engine.start(p1, p2) expect(@ui.show_game_state_called).to eq 10 expect(@ui.get_move_called).to eq 9 expect(@ui.show_game_result_called). to eq 1 end it "runs a game on a custom sized board" do p1 = MockPlayer.new('X', 1, 2, 3, 4) p2 = MockPlayer.new('O', 5, 6, 7) @engine = GameEngine.new(@ui, 4) @engine.start(p1, p2) expect(@ui.show_game_state_called).to eq 8 expect(@ui.get_move_called).to eq 7 expect(@ui.show_game_result_called). to eq 1 end it "does not change player until a valid move has been made" do p1 = MockPlayer.new('X', 1, 4, 2, 3) p2 = MockPlayer.new('O', 4, 5) @engine.start(p1, p2) expect(@ui.show_game_state_called).to eq 6 expect(@ui.get_move_called).to eq 6 expect(@ui.show_invalid_position_message_called).to eq 1 expect(@ui.show_game_result_called). to eq 1 end end end
true
c58fcf38886fbbaabfb609cbba1b0f61b08ddb0f
Ruby
prrrnd/rails_language_select
/lib/rails_language_select/data_source.rb
UTF-8
446
2.53125
3
[ "MIT" ]
permissive
module RailsLanguageSelect DATA_SOURCE = {} DATA_SOURCE[:default] = lambda do |code_or_name = nil| languages = I18nData.languages(I18n.locale.to_s) if code_or_name.nil? languages.keys else if (language = languages[code_or_name.to_s.upcase]) code = code_or_name elsif (code = I18nData.language_code(code_or_name)) language = languages[code] end return language, code end end end
true
a6bee69373d407a41fa3f5e1662e5f886d4f8630
Ruby
practicingruby/compleat-testing
/lib/compleat/testing.rb
UTF-8
1,826
2.828125
3
[]
no_license
module Compleat module Testing extend self def targets @targets ||= [] end def each_test_case targets.each do |test_class| test_class.instance_methods.grep(/^test_/).each do |test_method| yield test_class, test_method end end end def run_tests tests_executed, tests_failed, tests_error = 0,0,0 each_test_case do |test_class, test_method| tests_executed += 1 begin test_obj = test_class.new test_obj.send(:setup) test_obj.send(test_method) rescue Compleat::Testing::FailedAssertion => e puts "Failure in #{test_class}##{test_method}:" puts " #{e.message}" tests_failed += 1 rescue Exception => e puts "Error in #{test_class}##{test_method}:\n" puts " #{e.message}" tests_error += 1 end end puts "\n#{tests_executed} tests ran, #{tests_failed} failed, " + "#{tests_error} errors" end FailedAssertion = Class.new(StandardError) module Helpers def self.included(base) base.extend(ClassMethods) Compleat::Testing.targets << base end module ClassMethods # code stolen from citrusbyte/contest, edited for brevity def test(name, &block) tname = "test_#{name.gsub(/\W+/, ' ').strip.gsub(/\s+/,'_')}".to_sym define_method(tname, &block) end end def setup # just a stub for extension end def assert(msg="Things did not go as expected") yield || raise(FailedAssertion, msg) end def assert_equal(a,b) assert("Expected #{a.inspect}, but got #{b.inspect}") { a == b } end end end end at_exit do Compleat::Testing.run_tests end
true
89049593dbcdd2293bd4faf0affd4cc90129f191
Ruby
OpenBEL/bel_parser
/lib/bel_parser/language/version2_0/relationships/has_members.rb
UTF-8
1,847
3
3
[ "Apache-2.0" ]
permissive
require_relative '../../version2_0' require_relative '../../relationship' module BELParser module Language module Version2_0 module Relationships # HasMembers: +A hasMembers (B, C, D)+ - The hasMembers # relationship is a special form which enables the assignment of # multiple member classes in a single statement where the object # of the statement is a set of abundance terms. A statement # using hasMembers is exactly equivalent to multiple hasMember # statements. A term may not appear in both the subject and # object of a of the same hasMembers statement. For the abundance # terms A, B, C and D, +A hasMembers B, C, D+ indicates that A # is defined by its member abundance classes B, C and D. class HasMembers extend Relationship SHORT = :hasMembers LONG = :hasMembers DESCRIPTION = <<-DOC HasMembers: +A hasMembers (B, C, D)+ - The hasMembers relationship is a special form which enables the assignment of multiple member classes in a single statement where the object of the statement is a set of abundance terms. A statement using hasMembers is exactly equivalent to multiple hasMember statements. A term may not appear in both the subject and object of a of the same hasMembers statement. For the abundance terms A, B, C and D, +A hasMembers B, C, D+ indicates that A is defined by its member abundance classes B, C and D. DOC def self.short SHORT end def self.long LONG end def self.description DESCRIPTION end def self.directed? true end def self.listable? true end end end end end end
true
41c759ec702bc25f25544ef85a3b72ce0cd9e688
Ruby
wangjoc/betsy
/test/models/order_item_test.rb
UTF-8
4,535
2.59375
3
[]
no_license
require "test_helper" describe OrderItem do let (:new_order) { Order.new( buyer_name: "Huang Shaotian", email_address: "troublingrain@glory.com", mail_address: "City Blue Rain", zip_code: "33333", cc_num: "************1111", cc_exp: 1230, cc_cvv: "***", ) } let (:order_item) { OrderItem.new( quantity: 10, product: products(:diaper), order: new_order, is_shipped: false, ) } before do @item_one = order_items(:item_one) @item_two = order_items(:item_two) @order_one = orders(:order_one) @order_two = orders(:order_two) @merchant_faker = merchants(:faker) @product_lion = products(:lion) @product_toilet = products(:toilet) end describe "instantiation" do it "can be instantiated" do expect(order_item.valid?).must_equal true expect(@item_one.valid?).must_equal true expect(@item_two.valid?).must_equal true end it "will have the required fields" do order_item.save new_order_item = OrderItem.last [:quantity, :product_id, :order_id, :is_shipped].each do |field| expect(new_order_item).must_respond_to field expect(@item_one).must_respond_to field end end end describe "relationships" do it "must have one order and product" do expect(@item_one.product).must_be_kind_of Product expect(@item_one.order).must_be_kind_of Order end it "cannot not have a order" do order_item.order = nil order_item.save expect(order_item.save).must_equal false end it "cannot not have a product" do order_item.product = nil order_item.save expect(order_item.save).must_equal false end end describe "validations" do it "must an order" do order_item.order = nil expect(order_item.valid?).must_equal false expect(order_item.errors.messages).must_include :order expect(order_item.errors.messages[:order]).must_equal ["must exist", "can't be blank"] end it "must have a product" do order_item.product = nil expect(order_item.valid?).must_equal false expect(order_item.errors.messages).must_include :product expect(order_item.errors.messages[:product]).must_equal ["must exist", "can't be blank"] end it "must have a quantity" do order_item.quantity = nil expect(order_item.valid?).must_equal false expect(order_item.errors.messages).must_include :quantity expect(order_item.errors.messages[:quantity]).must_equal ["can't be blank", "is not a number"] end it "must have a quantity > 0" do order_item.quantity = 0 expect(order_item.valid?).must_equal false expect(order_item.errors.messages).must_include :quantity expect(order_item.errors.messages[:quantity]).must_equal ["must be greater than 0"] end it "must have a quantity that is a number" do order_item.quantity = "a" expect(order_item.valid?).must_equal false expect(order_item.errors.messages).must_include :quantity expect(order_item.errors.messages[:quantity]).must_equal ["is not a number"] end end describe "custom tests" do describe "items_by_order_merchant" do it "get order items by order and merchant" do order_items_faker = OrderItem.items_by_order_merchant(@order_one.id, @merchant_faker.id) order_items_faker.each do |order_item| expect(order_item).must_be_kind_of OrderItem expect(order_item.order).must_equal @order_one end end it "return empty array if no order items by order and merchant" do order_items_faker = OrderItem.items_by_order_merchant(@order_two.id, @merchant_faker.id) expect(order_items_faker).must_be_empty end end describe "order_revenue" do it "calculate order revenue by order and merchant" do order_items_faker = OrderItem.items_by_order_merchant(@order_one.id, @merchant_faker.id) check_revenue = 0 order_items_faker.each do |order_item| check_revenue = order_item.quantity * order_item.product.price end order_rev_faker = OrderItem.order_revenue(@order_one.id, @merchant_faker.id) expect(order_rev_faker).must_equal check_revenue end it "return 0 if no combination of that order and merchant" do order_rev_faker = OrderItem.order_revenue(@order_two.id, @merchant_faker.id) expect(order_rev_faker).must_equal 0 end end end end
true
b29086a467416af867020002244c254ad200a489
Ruby
mame/ruby-minisat
/examples/lonely7.rb
UTF-8
6,379
3.203125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # ruby-minisat example -- lonely7.rb require "minisat" require File.dirname($0) + "/compat18" if RUBY_VERSION < "1.9.0" ############################################################################### class Digit def initialize @vars = (0..9).map { $solver.new_var } $solver << vars vars.combination(2) {|v1, v2| $solver << [-v1, -v2] } end attr_reader :vars def is(n) case n when Digit vars.zip(n.vars) {|v1, v2| $solver << [v1, -v2] << [-v1, v2] } when Numeric $solver << vars[n] else raise TypeError end end def is_not(n) case n when Digit vars.zip(n.vars) {|v1, v2| $solver << [-v1, -v2] } when Numeric $solver << -vars[n] else raise TypeError end end def sum(a, b, f = nil) sumdiff(a, b, f) {|na, nb| na + nb } end def diff(a, b, f = nil) sumdiff(a, b, f) {|na, nb| na - nb } end def sumdiff(a, b, f = nil) c = f ? Digit.new : self f2 = pair(a, b, c) {|na, nb| n = yield(na, nb); [n % 10, n % 10 != n] } f ? flag(c, f, f2) {|n| n = yield(n, 1); [n % 10, n % 10 != n] } : f2 end def prod(a, b, d) if b.is_a?(Numeric) b2 = Digit.new b2.is b b = b2 end a.vars.each_with_index do |va, na| b.vars.each_with_index do |vb, nb| nd, nc = (na * nb).divmod(10) $solver << [-va, -vb, vars[nc]] << [-va, -vb, d.vars[nd]] end end end def less(b, f) fs = (0..9).map { $solver.new_var } fr = $solver.new_var b.vars.each_with_index do |vb, nb| va = vars[nb] vf = fs[nb] $solver << [-f, -vb] + vars[0..nb] $solver << [-vb, -va, vf] << [-vf, va] << [-vf, vb] << [-vf, fr] end $solver << [-fr, f] << [-fr] + fs fr end def pair(a, b, c) f = $solver.new_var a.vars.each_with_index do |va, na| b.vars.each_with_index do |vb, nb| nc, f2 = yield(na, nb) $solver << [-va, -vb, c.vars[nc]] << [-va, -vb, f2 ? f : -f] end end f end def flag(a, f0, f1) f2 = $solver.new_var $solver << [f0, -f2] a.vars.each_with_index do |v, n| $solver << [-v, f0, vars[n]] n2, f = yield n $solver << [-v, -f0, vars[n2]] << [-v, -f0, f ? f2 : -f2] end f3 = $solver.new_var $solver << [-f1, f3] << [-f2, f3] << [-f3, f1, f2] f3 end def to_i (0..9).find {|n| $solver[vars[n]] }.to_i end end class Digits def initialize(n) @digits = n.is_a?(Numeric) ? (0...n).map { Digit.new } : n end attr_reader :digits def is(num) case num when Adder, Subtracter f = nil z = zero ms = [num.left, num.right, self]. max {|x, y| x.digits.size <=> y.digits.size } as = ms.extend(num.left.digits, z) bs = ms.extend(num.right.digits, z) cs = ms.extend(digits, z) as.zip(bs, cs) do |a, b, c| f = num.is_a?(Adder) ? c.sum(a, b, f) : c.diff(a, b, f) end $solver << -f when Multiplier f = d = nil b = num.right as = extend(num.left.digits, zero) as.zip(digits) do |a, c| c2 = d ? Digit.new : c d2 = Digit.new c2.prod(a, b, d2) f = c.sum(c2, d, f) if d d = d2 end $solver << -f d.is 0 end end def less(b) z = zero bs = extend(b.digits, z) as = b.extend(digits, z) f = $solver.new_var $solver << f as.reverse.zip(bs.reverse).each do |a, b| f = a.less(b, f) end $solver << -f end def extend(as, z) digits.size > as.size ? as + [z] * (digits.size - as.size) : as end def top digits.last end def *(d); Multiplier.new(self, d); end def -(d); Subtracter.new(self, d); end def +(d); Adder.new(self, d); end def [](*arg) case arg.size when 1 then digits.reverse[arg.first] when 2 then Digits.new(digits.reverse[arg.first, arg.last].reverse) end end def to_i digits.map {|v| v.to_i }.reverse.inject(0) {|z, x| z * 10 + x } end Adder = Struct.new(:left, :right) Subtracter = Struct.new(:left, :right) Multiplier = Struct.new(:left, :right) end def zero d = Digit.new d.is 0 d end ############################################################################### $solver = MiniSat::Solver.new str = <<END x7yzw --------- aaa )bbbbbbbb cccc ----- ddd eee ---- ffff ggg ----- hhhh hhhh ---- 0 END puts "problem:" puts str.gsub(/[a-z]/m, "#") a = Digits.new(3); a.top.is_not 0 b = Digits.new(8); b.top.is_not 0 c = Digits.new(4); c.top.is_not 0 d = Digits.new(3); d.top.is_not 0 e = Digits.new(3); e.top.is_not 0 f = Digits.new(4); f.top.is_not 0 g = Digits.new(3); g.top.is_not 0 h = Digits.new(4); h.top.is_not 0 i = Digits.new(3) j = Digits.new(4) x, y, z, w = (0..3).map { Digit.new } x.is_not 0 c.is a * x; d[0, 2].is b[0, 4] - c; d[0, 2].less a e.is a * 7; d[2].is b[4]; f[0, 3].is d - e; f[0, 3].less a g.is a * y; f[3].is b[5]; h[0, 2].is f - g; h[0, 2].less a z.is 0; h[0, 3].less a h.is a * w; h[2].is b[6]; h[3].is b[7] $solver.solve puts "answer:" puts str. gsub(/a+/, a.to_i.to_s). gsub(/b+/, b.to_i.to_s). gsub(/c+/, c.to_i.to_s). gsub(/d+/, d.to_i.to_s). gsub(/e+/, e.to_i.to_s). gsub(/f+/, f.to_i.to_s). gsub(/g+/, g.to_i.to_s). gsub(/h+/, h.to_i.to_s). gsub(/x+/, x.to_i.to_s). gsub(/y+/, y.to_i.to_s). gsub(/z+/, z.to_i.to_s). gsub(/w+/, w.to_i.to_s) puts puts ############################################################################### $solver = MiniSat::Solver.new str = <<END send + more ------ money END puts "problem:" puts str puts as = Digits.new(4); as.top.is_not 0 bs = Digits.new(4); bs.top.is_not 0 cs = Digits.new(5); cs.top.is_not 0 h = {} as.digits.reverse.zip(%w(s e n d)) {|d, c| (h[c] ||= []) << d } bs.digits.reverse.zip(%w(m o r e)) {|d, c| (h[c] ||= []) << d } cs.digits.reverse.zip(%w(m o n e y)) {|d, c| (h[c] ||= []) << d } cs.is as + bs h.each do |c, ds| ds[1..-1].each {|d| ds.first.is d } h.each do |c2, ds2| next if c == c2 ds2.each {|d2| ds.first.is_not d2 } end end $solver.solve puts "answer:" h.each {|c, d| str = str.gsub(c) { d.first.to_i } } puts str puts puts
true
dddaedece9a96355471318c3114a25d0bd22e8e1
Ruby
bigtiger/let-it-be
/lib/let_it_be.rb
UTF-8
422
2.515625
3
[ "WTFPL" ]
permissive
module LetItBe extend self def let(name, &block) define_method name do @__resources__ ||= {} @__resources__[name] ||= if block_given? instance_eval(&block) else __class_for__(name).find(params["#{name}_id"] || params['id']) end end helper_method name hide_action name end private def __class_for__(name) name.to_s.classify.constantize end end
true
3db76dd1ce8ddb15dbf93b27a438c622464dedd1
Ruby
twyststar/Ruby_palindrome
/lib/palindrome.rb
UTF-8
207
3.171875
3
[]
no_license
class String define_method(:palindrome?) do word = self word.gsub!(/\s+/, '') word.downcase!() if word == word.reverse() "That's a palindrome" else "Nope" end end end
true
ae50ad90a80a7ad3ccc13ac1150ac2ed9c027c58
Ruby
jyoder/ultra-robo-blasters
/src/level/space/gun.rb
UTF-8
957
2.921875
3
[ "Unlicense" ]
permissive
require 'geometry/rectangle' require 'physics/body' require 'timing/timer' module Level module Space class Gun attr_reader :fired def self.make(sound) Gun.new(Timing::Timer.new(0, 0.1), nil, sound) end def initialize(timer, fired, sound) @timer = timer @fired = fired @sound = sound end def fire(now, point) if @timer.expired?(now) @sound.play Gun.new(@timer.reset(now), _make_bullet(point), @sound) else Gun.new(@timer, nil, @sound) end end private def _make_bullet(point) Physics::Body.make_stationary( Geometry::Rectangle.make(point.x, point.y, _bullet_width, _bullet_height) ).push_right(_bullet_thrust) end def _bullet_width 15 end def _bullet_height 3 end def _bullet_thrust 1000 end end end end
true
948cc65472b0ad4c66fa8cae4f182503d6b15549
Ruby
dry-rb/dry-core
/spec/dry/core/constants_spec.rb
UTF-8
3,491
2.828125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true require "dry/core/constants" RSpec.describe Dry::Core::Constants do before do class ClassWithConstants include Dry::Core::Constants def empty_array EMPTY_ARRAY end def empty_hash EMPTY_HASH end def empty_set EMPTY_SET end def empty_string EMPTY_STRING end def empty_opts EMPTY_OPTS end def undefined Undefined end end end after do Object.send(:remove_const, :ClassWithConstants) end subject { ClassWithConstants.new } it "makes constants available in your class" do expect(subject.empty_array).to be Dry::Core::Constants::EMPTY_ARRAY expect(subject.empty_array).to eql([]) expect(subject.empty_hash).to be Dry::Core::Constants::EMPTY_HASH expect(subject.empty_hash).to eql({}) expect(subject.empty_set).to be Dry::Core::Constants::EMPTY_SET expect(subject.empty_set).to eql(Set.new) expect(subject.empty_string).to be Dry::Core::Constants::EMPTY_STRING expect(subject.empty_string).to eql("") expect(subject.empty_opts).to be Dry::Core::Constants::EMPTY_OPTS expect(subject.empty_opts).to eql({}) expect(subject.undefined).to be Dry::Core::Constants::Undefined end describe "nested" do before do class ClassWithConstants class Nested def empty_array EMPTY_ARRAY end end end end subject { ClassWithConstants::Nested.new } example "constants available in lexical scope" do expect(subject.empty_array).to be Dry::Core::Constants::EMPTY_ARRAY end end describe "Undefined" do subject(:undefined) { Dry::Core::Constants::Undefined } describe ".inspect" do it 'returns "Undefined"' do expect(subject.inspect).to eql("Undefined") end end describe ".to_s" do it 'returns "Undefined"' do expect(subject.to_s).to eql("Undefined") end end describe ".default" do it "returns the first arg if it's not Undefined" do expect(subject.default(:first, :second)).to eql(:first) end it "returns the second arg if the first one is Undefined" do expect(subject.default(subject, :second)).to eql(:second) end it "yields a block" do expect(subject.default(subject) { :second }).to eql(:second) end end describe ".map" do it "maps non-undefined value" do expect(subject.map("foo", &:to_sym)).to be(:foo) expect(subject.map(subject, &:to_sym)).to be(subject) end end describe ".dup" do subject { undefined.dup } it { is_expected.to be(undefined) } end describe ".clone" do subject { undefined.clone } it { is_expected.to be(undefined) } end describe ".coalesce" do it "returns first non-undefined value in a list" do expect(undefined.coalesce(1, 2)).to be(1) expect(undefined.coalesce(undefined, 1, 2)).to be(1) expect(undefined.coalesce(undefined, undefined, 1, 2)).to be(1) expect(undefined.coalesce(undefined, undefined)).to be(undefined) expect(undefined.coalesce(nil)).to be(nil) expect(undefined.coalesce(undefined, nil)).to be(nil) expect(undefined.coalesce(undefined, nil, false)).to be(nil) expect(undefined.coalesce(undefined, false, nil)).to be(false) end end end end
true
0ac9531a8534c692e802010ae82171e67078e779
Ruby
robertjlooby/Tic-Tac-Toe
/tests/player_tests.rb
UTF-8
2,270
3.28125
3
[]
no_license
require 'test/unit' require 'stringio' require_relative '../src/player' require_relative '../src/board' class PlayerTests < Test::Unit::TestCase def setup @reader = MockReader.new @writer = MockWriter.new @p1 = Player.new(:X) @p2 = Player.new(:O) end def test_player_initialization assert_equal(:X, @p1.sym) assert_equal(:O, @p2.sym) end def test_player_get_move_good_move b = Board.new @reader.responses = ["0"] r, c = @p1.get_move(b.board_state, @reader, @writer) assert_equal(r, 0) assert_equal(c, 0) assert_equal(1, @reader.times_read) assert_equal(1, @writer.times_asked_for_cell) assert_equal(0, @writer.times_notified_invalid_cell) end def test_player_get_move_move_with_bad_input b = Board.new @reader.responses = ["junk", "1still junk", "7"] r, c = @p1.get_move(b.board_state, @reader, @writer) assert_equal(r, 2) assert_equal(c, 1) assert_equal(3, @reader.times_read) assert_equal(3, @writer.times_asked_for_cell) assert_equal(2, @writer.times_notified_invalid_cell) end def test_player_get_move_move_with_taken_cells b = Board.new([[:X, :X, :O], [:X, :O, nil], [nil, :O, nil]], :X) @reader.responses = ["0", "1", "2", "7", "8"] r, c = @p1.get_move(b.board_state, @reader, @writer) assert_equal(r, 2) assert_equal(c, 2) assert_equal(5, @reader.times_read) assert_equal(5, @writer.times_asked_for_cell) assert_equal(4, @writer.times_notified_invalid_cell) end class MockWriter attr_accessor :times_asked_for_cell, :times_notified_invalid_cell def initialize @times_asked_for_cell = @times_notified_invalid_cell = 0 end def ask_for_cell(sym) @times_asked_for_cell += 1 end def notify_invalid_cell @times_notified_invalid_cell += 1 end end class MockReader attr_accessor :times_read, :responses def initialize @times_read = 0 end def read_cell @times_read += 1 @responses.shift end end end
true
b18e2525e88e886795fd7eeeabaa6b82016a36ef
Ruby
lpile/backend_prework
/day_3/ex30.rb
UTF-8
892
4.25
4
[]
no_license
people = 10 cars = 25 trucks = 25 # if there is more cars than people then output "take cars" if cars > people puts "We should take the cars." # if not, check if cars is least than people then output "don't take cars" elsif cars < people puts "We should not take the cars." # else then cars = people then output "cant decide" else puts "We can't decide." end # if theres more trucks than cars, then output "too many trucks" if trucks > cars puts "That's too many trucks." # if trucks less than cars, then output "maybe take trucks" elsif trucks < cars && trucks == cars puts "Maybe we could take the trucks." # if trucks = cars, output "cant decide" else puts "We still can't decide." end # if more people than trucks, ouput "take trucks" if people > trucks puts "Alright, let's just take the trucks." # if not, output stay home else puts "Fine, let's stay home then." end
true
8609eaabe6fc77840f80364120cdd14482ba1604
Ruby
silverhammermba/scripts
/stpeter.rb
UTF-8
8,276
2.890625
3
[]
no_license
#!/usr/bin/env ruby # if you want to get into heaven, you need to go through this guy require 'find' require 'taglib' require 'set' require 'fileutils' # for suggesting existing artist/album names def edit_distance(s, t) m = s.length n = t.length return m if n == 0 return n if m == 0 d = Array.new(m+1) {Array.new(n+1)} (0..m).each {|i| d[i][0] = i} (0..n).each {|j| d[0][j] = j} (1..n).each do |j| (1..m).each do |i| d[i][j] = if s[i-1] == t[j-1] # adjust index into string d[i-1][j-1] # no operation required else [ d[i-1][j]+1, # deletion d[i][j-1]+1, # insertion d[i-1][j-1]+1, # substitution ].min end end end d[m][n] end # how library files are organized def dest artist, album # ensure we only use primary artist, replace forward slashes with unicode equivalent artist = artist.split(" / ")[0].gsub("/", "∕") if album album = album.gsub("/", "∕") else album = '' end File.join($heaven, artist, album) end $copy = false $copy = true if ARGV.delete('--copy') or ARGV.delete('-c') if ARGV.length != 2 STDERR.puts "usage: #$0 EARTH HEAVEN" exit 1 end $earth = File.expand_path(ARGV[0]) $heaven = File.expand_path(ARGV[1]) known_exts = Set.new [ '.mp3', '.m4a', '.ogg', '.flac' ] sinners = [] # collect files with known extensions Find.find($earth) do |path| next if File.directory? path sinners << path if known_exts.include? File.extname(path).downcase end exit if sinners.empty? # get existing library info $library = {} Find.find($heaven) do |path| next if File.directory? path TagLib::FileRef.open(path) do |f| raise "DEMONS IN HEAVEN: #{path}" unless f.tag.artist artists = f.tag.artist.split(' / ') artists.each { |artist| $library[artist] ||= Set.new } $library[artists.first] << f.tag.album end end # try to correct artist names not in library def check_artists artists # collect all artist names all = artists.map(&:last).reduce(:+).uniq new_name = {} # check each artist all.each do |artist| # if this is a new artist unless $library[artist] # look for similar existing artist names STDERR.puts "Unrecognized artist: #{artist}" distances = $library.keys.map { |a| [a, edit_distance(a, artist)] } min = distances.min_by(&:last) matches = distances.select { |a, d| d == min[1] }.map(&:first) unless matches.empty? STDERR.puts "Closest matches:" matches.each { |a| puts "\t#{a}" } end # prompt for new one STDERR.print "Change artist name? " new = STDIN.gets.strip # if new name set if not new.empty? and new != artist new_name[artist] = new artist = new end # add library record $library[artist] ||= Set.new end end changes = {} # update songs artists.each do |path, a| # skip if we didn't change anything next unless a.any? { |artist| new_name[artist] } changes[path] = a.map { |artist| new_name[artist] || artist }.join(' / ') end primary = artists[0][1][0] # return primary artist name and changes to make return [new_name[primary] || primary, new_name, changes] end # check and correct duplicate/incorrect album names def check_album artist, album, paths changes = {} # if this is a new album unless $library[artist].include? album # look for similar existing album names STDERR.puts "New album: #{album}" distances = $library[artist].map { |a| [a, edit_distance(a || '', album || '')] } min = distances.min_by(&:last) matches = distances.select { |a, d| d == min[1] }.map(&:first) unless matches.empty? STDERR.puts "Closest matches:" matches.each { |a| puts "\t#{a}" } end # prompt for new one STDERR.print "Change album name? " new = STDIN.gets.strip # if new name set if not new.empty? and new != album album = new # update songs paths.each do |path| changes[path] = album end end end if $library[artist].include? album STDOUT.puts "ERROR: CONFLICT: Duplicate album: #{album}" paths.each { |path| STDOUT.puts "ERROR: SRC: #{path}" } Find.find(dest(artist, album)) { |path| STDOUT.puts "ERROR: DST: #{path}" unless File.directory? path } return [nil, changes] end $library[artist] << album return [album, changes] end def update path, artist_changes, album_changes if (artist_changes and artist_changes[path]) or (album_changes and album_changes[path]) TagLib::FileRef.open(path) do |f| f.tag.artist = artist_changes[path] if (artist_changes and artist_changes[path]) f.tag.album = album_changes[path] if (album_changes and album_changes[path]) f.save end end end # handle songs by directory sinners.group_by { |path| File.dirname(path) }.each do |dir, paths| # handle stray songs individually if dir == $earth STDOUT.puts "LOG: Processing #{dir}" paths.each do |path| artists, album = TagLib::FileRef.open(path) { |f| [(f.null? || f.tag.artist.nil?) ? [] : f.tag.artist.split(' / '), f.null? ? nil : f.tag.album] } if artists.empty? STDOUT.puts "ERROR: No artist information for #{path}" next end STDOUT.puts "LOG: Processing #{path}" # try to fix artist/album artist, new_artists, artist_changes = check_artists([[path, artists]]) if album album, album_changes = check_album(artist, album, [path]) next unless album dst = dest(artist, album) else STDOUT.puts "LOG: No album information for #{path}" dst = dest(artist, '') end # show new values unless new_artists.empty? STDOUT.puts "ACTION: Updating artists:" new_artists.each { |o, n| puts "ACTION:\t#{o} -> #{n}" } end if album_changes and not album_changes.empty? STDOUT.puts "ACTION: Updating album to: #{album}" end # allow bailout STDERR.print "Continue? [Yn] " next if STDIN.gets.strip =~ /^no?$/ # good to go now update(path, artist_changes, album_changes) STDOUT.puts "ACTION: Moving #{path} to #{dst}" FileUtils.mkdir_p(dst) FileUtils.mv(path, dst) end else # only import if we get one artist, one album artists = paths.map { |path| TagLib::FileRef.open(path) { |f| [path, (f.null? || f.tag.artist.nil?) ? [] : f.tag.artist.split(' / ')] } } if artists.map { |path, a| a.first }.uniq.size > 1 STDOUT.puts "ERROR: Multiple primary artists in #{dir}" next elsif artists[0][1].empty? STDOUT.puts "ERROR: No artist information for #{dir}" next end albums = paths.group_by { |path| TagLib::FileRef.open(path) { |f| f.null? ? nil : f.tag.album } } if albums.size == 1 and albums[nil] STDOUT.puts "ERROR: No album information for #{dir}" next end STDOUT.puts "LOG: Processing #{dir}" # try to fix artist artist, new_artists, artist_changes = check_artists(artists) albums.each do |album, paths| # try to fix album album, album_changes = check_album(artist, album, paths) next unless album # show new values unless new_artists.empty? STDOUT.puts "ACTION: Updating artists:" new_artists.each { |o, n| puts "ACTION:\t#{o} -> #{n}" } end unless album_changes.empty? STDOUT.puts "ACTION: Updating album to: #{album}" end # allow bailout STDERR.print "Continue? [Yn] " next if STDIN.gets.strip =~ /^no?$/ # go, go, go! paths.each { |path| update(path, artist_changes, album_changes) } dst = dest(artist, album) STDOUT.puts "ACTION: Moving #{dir} tracks to #{dst}" FileUtils.mkdir_p(dst) paths.each { |path| FileUtils.mv(path, dst) } end # look for leftover crap if Dir.entries(dir).size > 2 STDOUT.puts "WARNING: Leftover files in #{dir}" end end end empty = 1 while empty > 0 empty = 0 Find.find($earth) do |path| next unless File.directory? path FileUtils.rmdir path unless File.exists? path STDOUT.puts "ACTION: Removing empty dir #{path}" empty += 1 end end end
true
c5bbb7fc99ccbd0f5dbb0801f7549f39497de8ed
Ruby
EpicDream/shopelia
/lib/parsers/descriptions/amazon/formatter.rb
UTF-8
6,726
2.578125
3
[]
no_license
# -*- encoding : utf-8 -*- module Descriptions module Amazon class KeyCleaner SKIP = /commentaires? client|Politique de retour|Votre avis/ def self.clean key return nil if key =~ SKIP || key.blank? key end end class ContentCleaner SKIP = /commentaires? client|meilleures ventes d'Amazon/ def self.clean value return nil if value =~ SKIP || value.strip.length <= 1 value.gsub(/\n|\t/, '').strip end end class TextFormatter #<node>/text() DEFAULT_KEY = "Informations" def initialize node @text = node end def representation ContentCleaner.clean @text.text end def key KeyCleaner.clean(header_of(@text)) || DEFAULT_KEY end private def header_of div xpath = (1..5).map { |n| ".//preceding::h#{n}" } xpath += [".//preceding::div[@class='secHeader']//text()[normalize-space()]"] xpath = xpath.join(" | ") @text.xpath(xpath).map(&:text).last || DEFAULT_KEY end end class PFormatter DEFAULT_KEY = nil def initialize node @paragraph = node end def representation #!inside_table? && ContentCleaner.clean(@paragraph.text) end def key KeyCleaner.clean header_of(@paragraph) end private def inside_table? @paragraph.xpath(".//ancestor::table").any? end def header_of paragraph xpath = (1..5).map { |n| ".//preceding-sibling::h#{n}" }.join(" | ") @paragraph.xpath(xpath).map(&:text).last || DEFAULT_KEY end end class DivTableFormatter DEFAULT_KEY = "Informations" attr_reader :key def initialize node @table = node end def representation table_to_hash end def key xpath = (1..5).map { |n| ".//preceding-sibling::h#{n}" } xpath += [".//preceding::div[@class='tsSectionHeader']//text()[normalize-space()]"] xpath = xpath.join(" | ") @table.xpath(xpath).map(&:text).last || DEFAULT_KEY end def table_to_hash @table.xpath(".//div[@class='tsRow']").inject({}) { |hash, tr| key, value = tr.xpath(".//span/text()").map(&:text) next hash if key.blank? || value.blank? hash[key] = ContentCleaner.clean(value) hash } end end class TableFormatter DEFAULT_KEY = "Informations" attr_reader :key def initialize node @table = node end def representation return if skip? if simple_table? table_to_hash() else #@table.to_s end end def skip? @table.xpath(".//tr").count <= 1 #table for layout end def key xpath = (1..5).map { |n| ".//preceding-sibling::h#{n}" } xpath += [".//preceding::div[@class='secHeader']//text()[normalize-space()]"] xpath = xpath.join(" | ") @table.xpath(xpath).map(&:text).last || DEFAULT_KEY end def table_to_hash @table.xpath(".//tr").inject({}) { |hash, tr| key, value = tr.xpath(".//td/text()").map(&:text) next hash if key.blank? || value.blank? hash[key] = ContentCleaner.clean(value) hash } end def simple_table? @table.xpath(".//tr").first.xpath(".//td").count <= 2 rescue false end end class UlFormatter DEFAULT_KEY = "Summary" def initialize node @ul = node @lis = @ul.xpath(".//li") end def representation @lis.map {|li| li.xpath(".//script").map(&:remove) ContentCleaner.clean li.text }.compact end def key xpath = (1..5).map { |n| ".//preceding-sibling::h#{n}" }.join(" | ") KeyCleaner.clean(@ul.xpath(xpath).map(&:text).last || DEFAULT_KEY) end end class FormatterDetector NODES = ['table', 'ul', 'p'] TEXT_NODES = ['/', '/p/', '/p/font/', '/b/'].map { |node| "div#{node}text()[normalize-space()]" } DIV_TABLE = ['div[@class="tsTable"]'] def initialize nodeset @nodeset = nodeset.dup end def formatters # ./ and .// cause on max version of libxml of debian 6 .// does not work NODES.map { |node| @nodeset.xpath("./#{node} | .//#{node}").map { |xnode| node = 'div_table' if node == klass = "Descriptions::Amazon::#{node.camelize}Formatter" formatter = klass.constantize.new(xnode) } }.flatten + TEXT_NODES.map { |node| @nodeset.xpath("./#{node} | .//#{node}").map { |xnode| node = 'text' klass = "Descriptions::Amazon::#{node.camelize}Formatter" formatter = klass.constantize.new(xnode) } }.flatten + DIV_TABLE.map { |node| @nodeset.xpath("./#{node} | .//#{node}").map { |xnode| node = 'div_table' klass = "Descriptions::Amazon::#{node.camelize}Formatter" formatter = klass.constantize.new(xnode) } }.flatten end end class Formatter DEFAULT_KEY = "BLOCK" BLOCKS_SEPARATOR = "<!-- SHOPELIA-END-BLOCK -->" def initialize html, block_key=nil @html = html @fragment = Nokogiri::HTML.fragment html @key = key() || block_key end def self.format html_blocks return {} if html_blocks.nil? index = 0 blocks = html_blocks.split(BLOCKS_SEPARATOR).delete_if { |block| block.blank? } blocks.inject({}) { |hash, html| hash.merge!(new(html, "#{DEFAULT_KEY}-#{index += 1}").representation) } end def representation content = merged_representations content.empty? ? {} : { @key => content } end def merged_representations formatters.inject({}) { |hash, formatter| key, content = formatter.key, formatter.representation next hash if content.blank? || key.blank? hash[key] ||= [] hash[key] << content hash } end def key @fragment.xpath(".//*[self::h1 or self::h2]").map(&:text).first end def formatters FormatterDetector.new(@fragment).formatters end end end end
true
ed22687fbf0fc92c83729c8bf59cc5b510fbc13d
Ruby
Rim-777/CuteExchange
/spec/cute_exchange/money_spec.rb
UTF-8
5,602
3.171875
3
[ "MIT" ]
permissive
require 'spec_helper' RSpec.describe Money do let(:fifty_eur) {Money.new(50, 'EUR')} let(:fifty_five_dollars_fifty_cent) {Money.new(55.5, 'USD')} before do Money.conversion_rates('EUR', 'USD' => 1.11, 'RUB' => 70) end describe '.conversion_rates' do it 'assigns right values' do expect(Money.base).to eq 'EUR' expect(Money.rates).to eq 'USD' => 1.11, 'RUB' => 70 end end describe '#attr_readers' do describe '#amount' do it 'returns 50' do expect(fifty_eur.amount).to eq 50 end end describe '#currency' do it 'returns EUR' do expect(fifty_eur.currency).to eq 'EUR' end end end describe '#inspect' do it 'precents the money instance with default precision' do expect(fifty_eur.inspect).to eq '50.00 EUR' end it 'precents the money instance with the given precision' do expect(Money.new(0.1234567, 'Bitcoin').inspect(precision: 4)).to eq '0.1235 Bitcoin' end end describe '#convert_to' do context 'convert the base currency to other currency' do it 'returns the Money instans with currency: USD and amount: 50*1.11' do expect(fifty_eur.convert_to('USD')).to eq Money.new(55.5, 'USD') end it 'receives the method convert_to_base for the Money instance' do expect(fifty_eur).to receive(:convert_to_base).and_call_original fifty_eur.convert_to('USD') end it 'receives the method rate_by for the Money instance with USD as an argument' do expect(fifty_eur).to receive(:rate_by).with('USD').and_call_original fifty_eur.convert_to('USD') end end context 'convert an other currency to the base currency' do it 'returns the Money instance with the currency: EUR and amount 50' do expect(fifty_five_dollars_fifty_cent.convert_to('EUR')).to eq Money.new(50, 'EUR') end it 'receives the method convert_to_base for the Money instance' do expect(fifty_five_dollars_fifty_cent).to receive(:convert_to_base).and_call_original fifty_five_dollars_fifty_cent.convert_to('EUR') end end context 'convert an other currency to another currency' do it 'returns the Money instance with the currency:RUB and amount 3500' do expect(fifty_five_dollars_fifty_cent.convert_to('RUB')).to eq Money.new(3500, 'RUB') end it 'receives the method convert_to_base for the Money instance' do expect(fifty_five_dollars_fifty_cent).to receive(:convert_to_base).and_call_original fifty_five_dollars_fifty_cent.convert_to('RUB') end it 'receives the method rate_by for the Money instance with USD as an argument' do expect(fifty_five_dollars_fifty_cent).to receive(:rate_by).with('RUB').and_call_original fifty_five_dollars_fifty_cent.convert_to('RUB') end end end describe '#convert_to_base' do it 'returns a BigDecimal instance' do expect(fifty_five_dollars_fifty_cent.send(:convert_to_base)).to be_a(BigDecimal) end context 'the method is called for the base currency' do it 'returns the ammount of the base currency' do expect(fifty_eur.send(:convert_to_base)).to eq fifty_eur.amount end end context 'the method is called for the other currency' do it 'returns the converted ammount of the currency' do expect(fifty_five_dollars_fifty_cent.send(:convert_to_base)).to eq 50 end end end describe '#rate_by(currency)' do it 'returns the rate of the given currency from the established rates' do expect(fifty_eur.send(:rate_by, 'USD')).to eq 1.11 expect(fifty_eur.send(:rate_by, 'RUB')).to eq 70 end end describe '#perform_arithmetic' do context 'the number as an argument' do it 'gets an operation and number as an argument and performs the operation' do expect(fifty_eur.send(:perform_arithmetic, :+, 50)).to eq Money.new(100, 'EUR') expect(fifty_eur.send(:perform_arithmetic, :-, 30)).to eq Money.new(20, 'EUR') expect(fifty_eur.send(:perform_arithmetic, :/, 2)).to eq Money.new(25, 'EUR') expect(fifty_eur.send(:perform_arithmetic, :*, 2)).to eq Money.new(100, 'EUR') end it_behaves_like 'Unchangeble' do let(:argument) {100} end end context 'the Money instance as an arument' do it 'gets an operation and a money instanse and performs the operation' do expect(fifty_eur.send(:perform_arithmetic, :+, Money.new(100, 'EUR'))) .to eq Money.new(150, 'EUR') expect(fifty_eur.send(:perform_arithmetic, :-, Money.new(33.3, 'USD'))) .to eq Money.new(20, 'EUR') end it_behaves_like 'Unchangeble' do let(:argument) {Money.new(100, 'EUR')} end end end describe '#arithmetic methods :+,:-,:/, :*' do context 'the number as an argument' do it_behaves_like 'Arithmeticable' do let(:argument) {50} end end context 'the Money instance as an argument' do it_behaves_like 'Arithmeticable' do let(:argument) {Money.new(50, 'USD')} end end end describe '#comparisons' do let(:twenty_dollars) {Money.new(20, 'USD')} it 'makes the right comparisons' do expect(twenty_dollars < fifty_eur).to be_truthy expect(twenty_dollars != fifty_eur).to be_truthy expect(twenty_dollars >= fifty_eur).to be_falsey expect(fifty_eur == fifty_eur).to be_truthy expect(fifty_five_dollars_fifty_cent == fifty_eur).to be_truthy end end end
true
923fa5cb3cb09ed33bce39acfb23e8551aecac9b
Ruby
elainapolson/oo-animal-sorter-web-0615-public
/lib/animal_sorter.rb
UTF-8
923
4.25
4
[]
no_license
# Build a class AnimalSorter # Make sure there are two constants that AnimalSorter knows about, # SEA_ANIMALS and LAND_ANIMALS # AnimalSorter should be able to accept an array of animals on # initialization. # Define a to_a method to account for the species in the test suite. # Return an array that contains two arrays, the first one # should include the sea creatures, the second, land animals. # Read the test suite for an example of a nested array. class AnimalSorter SEA_ANIMALS = ["fish", "marlin", "octopus"] LAND_ANIMALS = ["cat", "elephant", "aardvark"] attr_accessor :animals def initialize(animal_array) @animals = animal_array end def sea_animals @animals.select do |animal| SEA_ANIMALS.include?(animal) end end def land_animals @animals.select do |animal| LAND_ANIMALS.include?(animal) end end def to_a [sea_animals, land_animals] end end
true
adad844ca412397e4542d590634e3dd8e5f12bc8
Ruby
KoKumagai/idioms-in-Ruby
/nil_guards2.rb
UTF-8
141
2.78125
3
[]
no_license
params = {} # nil guards Array(params[:items]).each do |item| # ... end # equivalent to (params[:items] || []).each do |item| # ... end
true
d7d1a84a7b2400c2979c9d5cc5b094ccba2c8b44
Ruby
StanTarnev/Week-2-Weekend-Homowork
/specs/song_spec.rb
UTF-8
432
2.796875
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../Guest.rb") require_relative("../Room.rb") require_relative("../Song.rb") class TestSong < MiniTest::Test def setup() @song1 = Song.new("Jesus Built My Hotrod") @song2 = Song.new("O Fortuna") @song3 = Song.new("Jump Around") @songs = [@song1, @song2, @song3] end def test_name() assert_equal("O Fortuna", @song2.name()) end end
true
ca15c5ac547a977099d0f0c36a1f89dd7d2b48c6
Ruby
revjatto/stock-trader
/app/models/stock.rb
UTF-8
623
2.921875
3
[]
no_license
class Stock < ActiveRecord::Base def self.find_by_ticker(ticker_symbol) where(ticker: ticker_symbol).first end def self.new_from_lookup(ticker_symbol) looked_up_stock = StockQuote::Stock.quote(ticker_symbol) return nil unless looked_up_stock.name new_stock = new(ticker: looked_up_stock.symbol, name: looked_up_stock.name) new_stock.last_price = new_stock.price new_stock end def price closing_price = StockQuote::Stock.quote(ticker).close return "#{closing_price} (Closing)" if closing_price opening_price = StockQuote::Stock.quote(ticker).open return "#{opening_price} (Opening)" if opening_price 'Unavailable' end end
true
b07714bb1e1fc146e182e34c8fc210fde30bb427
Ruby
rezaf/DataStructures_and_Algorithms
/int_hash_set.rb
UTF-8
1,053
3.359375
3
[]
no_license
class IntHashSet DEFAULT_SIZE = 8 MAX_LOAD = 1.00 attr_reader :count def initialize self.buckets = Array.new(DEFAULT_SIZE) { [] } self.count = 0 end def include?(value) bucket_for(value).include?(value) end def insert(value) return false if include?(value) self.resize! if (count + 1).fdiv(buckets.length) > MAX_LOAD bucket_for(value) << value self.count += 1 true end def remove(value) return unless include?(value) bucket_for(value).delete(value) self.count -= 1 end protected attr_accessor :buckets attr_writer :count def bucket_for(value, buckets = self.buckets) buckets[value_hash(value) % buckets.length] end # Modify this hash function to adapt IntHashSet for other data types. def value_hash(value) value end def resize! new_buckets = Array.new(buckets.length * 2) { [] } buckets.each do |bucket| bucket.each do |item| bucket_for(item, new_buckets) << item end end self.buckets = new_buckets end end
true
5222b3399d3931a0e4ac931a8d5d41308dbe731d
Ruby
DarkWater666/ruby_test
/task9.rb
UTF-8
198
3.078125
3
[]
no_license
class String def palindrome? return false if size == 0 self.downcase!.gsub! /\W+/, '' self == reverse end end module Enumerable def palindrome? to_a == to_a.reverse end end
true
69ba3b496766f93dbb08538972a9e6652ff80b5f
Ruby
alestar/Ruby-Code
/Rock Paper Siccors/public/lib/dessert.rb
UTF-8
443
3.34375
3
[]
no_license
class Dessert def initialize(name, calories) @name=name @calories=calories end attr_accessor :name,:calories def healthy? calories < 200 end def delicious? return true end end class JellyBean < Dessert def initialize(flavor) @flavor=flavor @calories=5 @name= flavor + " jelly bean" end attr_accessor :flavor def delicious? flavor== "licorice"? false:true end end
true
c7f592ee24e494db5b5e9f84eb0b6a8c4fab42f0
Ruby
smcommits/CodeAnalyzer
/lib/helpers/parser.rb
UTF-8
1,044
2.546875
3
[ "MIT" ]
permissive
class SourceHandler attr_reader :buffer, :ast, :tokens, :diagnostics def initialize(buffer, ast, tokens, diagnostics, comments) @buffer = buffer @ast = ast @comments = comments @tokens = tokens @diagnostics = diagnostics end end class ParseCode def initialize_parser parser = Parser::CurrentRuby.new parser.diagnostics.all_errors_are_fatal = false parser.diagnostics.ignore_warnings = false parser end def parse(string, name = '(string)') source_buffer = Parser::Source::Buffer.new(name, 1) source_buffer.source = string parser = initialize_parser diagnostics = [] parser.diagnostics.consumer = lambda do |diagnosed_error| diagnostics << diagnosed_error end begin ast, comments, tokens = parser.tokenize(source_buffer) rescue Parser::SyntaxError # rubocop:disable Lint/SuppressedException end SourceHandler.new(source_buffer, ast, tokens, diagnostics, comments) end def parse_file(path) parse(File.read(path), path) end end
true
ebde51c9cc6c2afb04fa993953ee6e506903e686
Ruby
bartezic/discounts_dictionary_wrong
/spec/lib/word_combinations/dictionary_spec.rb
UTF-8
825
2.65625
3
[]
no_license
require 'spec_helper' require 'word_combinations/dictionary' describe WordCombinations::Dictionary do before do @dictionary = WordCombinations::Dictionary.new @dictionary.add_dictionary_entries(%w(aa aab abc bce a)) end describe 'words prefixes' do def prefixes(word) @dictionary.prefixes_for(word).sort end it 'should return empty prefixes' do expect(prefixes('cde')).to eq(%w()) end it 'should not return reversed prefix' do expect(prefixes('cba')).to eq(%w()) end it 'should return single prefix' do expect(prefixes('bcef')).to eq(%w(bce)) end it 'should return word as prefix' do expect(prefixes('bce')).to eq(%w(bce)) end it 'should return all prefixex' do expect(prefixes('aabc')).to eq(%w(a aa aab)) end end end
true
cd7fd64f52275fe432e0f60575e99e91e8cb1519
Ruby
iteloo/tautology
/tautology/app/models/term.rb
UTF-8
481
3.4375
3
[ "MIT" ]
permissive
class Term def initialize(words_array) @words = words_array @string = @words.join ' ' end def is_singular? if @string.pluralize == @string return false else return true end end def is_plural? return !self.is_singular? end def opposite_pluralization if self.is_singular? return @string.pluralize else return @string.singularize end end def to_s @string end def inspect return self.to_json end end
true
c0517d9f38923c49ad199f38566d598c181427ce
Ruby
patjab/OO-mini-project-dumbo-web-051418
/app/models/User.rb
UTF-8
1,937
3.828125
4
[]
no_license
# USER # Build the following methods on the User class # ### User.all should return all of the user instances ### User#recipes should return all of the recipes this user has recipe cards for ### User#add_recipe_card should accept a recipe instance as an argument, as well as a date and rating, and create a new recipe card for this user and the given recipe ### User#declare_allergen should accept an ingredient instance as an argument, and create a new allergen instance for this user and the given ingredient # ###User#allergens should return all of the ingredients this user is allergic to #### User#top_three_recipes should return the top three highest rated recipes for this user. ### User#most_recent_recipe should return the recipe most recently added to the user's cookbook. class User attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end #helper def recipe_cards RecipeCard.all.select do |rc| rc.user == self end end def recipes self.recipe_cards.map do |rc| rc.recipe end end def add_recipe_card(recipe, date, rating) # and create a new recipe card for this user and the given recipe RecipeCard.new(self, recipe, date, rating) end def declare_allergen(ingredient) # create a new allergen instance for this user and the given ingredient Allergen.new(self, ingredient) end def allergens Allergen.all.select do |allergen| allergen.user == self end end def top_three_recipes sorted_rc = self.recipe_cards.sort_by {|rc| rc.rating} sorted_rc.map do |rc| rc.recipe end.reverse[0..2] end def most_recent_recipe #should return the recipe most recently added to the user's cookbook sorted_rc = self.recipe_cards.sort_by {|rc| rc.date} sorted_rc.map do |rc| rc.recipe end.reverse[0] end end
true
809980b6113254f4c2d103ccc9aac0dcef7b3e07
Ruby
stuart32/fxrates
/lib/fxrates.rb
UTF-8
2,225
3.359375
3
[]
no_license
require 'bundler/setup' require "fxrates/version" require 'open_uri_redirections' require 'crack' require 'crack/xml' require 'date' require 'json' class ExchangeRate #Stores fx data from ECB to db/rates.json def getRates response = Crack::XML.parse(File.read(open("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml"))) File.open(Dir.pwd + "/db/rates.json","w") do |f| f.write(JSON.pretty_generate(response)) end end #Returns the FX data for the date given in @date. def getRatesFromDate(date) file = File.read('../db/rates.json') data = JSON.parse(file)['gesmes:Envelope']['Cube']['Cube'] found = false for t in data d1 = Date.parse(t['time']) d2 = Date.parse(date) if d1 == d2 found = true return t['Cube'] end end if found == false raise "No data on #{d2}" end end #Returns the exchange rate for the curency given in @currency from the data given in @data. def getRate(currency, data) if currency == 'EUR' return 1.to_f end found = false for t in data if t['currency'].to_s == currency found = true return t['rate'].to_f else found = false end end if found == false raise "#{currency} is not a valid currency" end end #Returns each curreny three letter refrence for a given date with 'EUR' added. def getCurrenciesFromDate( date) cur = Array.new cur[1] = 'EUR'; data = getRatesFromDate(date) for t in data cur.push(t['currency'].to_s) end return cur end #Returns the exchange rate from @base to @counter on @date. def at(date,base,counter) data = getRatesFromDate(date) rate = getRate(counter,data) b = getRate(base, data) if b==nil || rate == nil puts "Not a valid currency pair" else if base == 'EUR' return rate elsif counter.to_s == 'EUR' return 1/b else return getRate(counter,data)/getRate(base,data) end end end #Converts @amount in @base into its eqivelent in @counter on @date. def calcTotal(date,amount,base,counter) return amount * at(date,base,counter) end end r = ExchangeRate.new s = r.calcTotal("2018-01-26", 100, "GBP", "HUF") puts s t = r.getCurrenciesFromDate("2018-01-26") puts t
true
f14c1e4e931b42d8852997d63d3cfb2c57d71d46
Ruby
m1neral/ororo-search-app
/app/services/logging/add_log.rb
UTF-8
531
2.5625
3
[]
no_license
module Logging class AddLog attr_reader :params, :results_count, :is_client_log def initialize(params, results_count, is_client_log: false) @params = params @results_count = results_count @is_client_log = is_client_log end def perform log = {} if is_client_log log[:client_log] = ClientLog.new(params) else log[:server_log] = ServerLog.new(params) end search = Search.new(results_count: results_count, **log) search.save! end end end
true
c8f1b63ea785507e1605cc97f2d6daef0dfa7558
Ruby
mrchenliang/math-game
/player.rb
UTF-8
154
2.625
3
[]
no_license
module MathGame class Player attr_accessor :lives def initialize @lives = 3 end def wrong @lives -= 1 end end end
true
1d26ced4afe6b52a5f5ef247351fad74a55d0201
Ruby
fatum/vips
/lib/vips/divider.rb
UTF-8
3,442
3
3
[ "MIT" ]
permissive
# -*- encoding : utf-8 -*- require 'vips/dom/element' require 'vips/block/element' require 'vips/block/pool' module Vips class Divider PDOC = 10 ROUNDS = 50 PAGE_SIZE = 1024 * 768 attr_accessor :dom, :signals, :current_signal, :block_pool def self.divided @@divided end def initialize(signals) @signals, @@divided = signals, [] @block_pool, @current_round = Vips::Block::Pool.new, 1 end def divide!(dom) page_block = add_to_block_pool(dom) split(page_block) end # Executed at each round def split(block) puts "Divide block: #{block}" puts "Current round at #{@current_round}".red # 1. extract blocks block.el.children.each do |el| divide(el, 0, block) end # 2. find separators separators = []#find_separators(block) # 3. construct page construct_blocks(block, separators) @current_round += 1 # После текущего раунда block.children содержит список # определившихся блоков. Если мы не прeвысили лимит раундов – # для каждого из них текущего уровня повторяем раунд split if ROUNDS >= @current_round block.children.each do |block| if block.leaf_node? && !granularity? split(block) end end end block end def find_separators(block) Separator::Manager.new.process(block.children) end def construct_blocks(block, separators) end private def signal_matched?(el, level) @current_signal = signals.find do |signal| log "checking #{signal.inspect}".blue, level signal.match?(el, level) end log "MATCHED! #{current_signal.inspect}".green, level if @current_signal @current_signal end def divide(el, level = 0, current_block = nil) log = ("-" * level) + "processing (#{level}): #{el.xpath}" debug el, level if signal_matched?(el, level) if current_signal.dividable == :dividable puts "divide!" @@divided << el puts log.red el.children.each { |child| divide(child, level + 1, current_block) } elsif current_signal.dividable == :undividable puts log.yellow block = add_to_block_pool(el, level, current_block) puts "create block! #{block}" end end end def add_to_block_pool(el, level = 0, current_block = nil) block = Block::Element.new(el, current_block) block.doc = current_signal.get_doc(el) if current_signal block.doc ||= Signal::Base::DEFAULT_DOC current_block.add_child(block) if current_block block end def granularity? @block_pool.find do |block| block.leaf_node? && block.doc >= PDOC end != nil end def log(msg, level) puts (" " * (level + 1)) + msg end def debug(el, level) log "text? - #{Signal::Color.text_node?(el)}", level log "valid? - #{Signal::Color.valid_node?(el)}", level log "inline? - #{Signal::Color.inline_node?(el)}", level log "has_valid_children? - #{Signal::Color.has_valid_children?(el)}", level log "width - #{el.width}", level log "height - #{el.height}", level log "visible - #{el.visible?}", level end end end
true
7ec653b13d86e94d85fc1de725cee18b6ea03704
Ruby
jstorimer/sprout
/lib/sprout/stream.rb
UTF-8
776
2.75
3
[ "MIT" ]
permissive
require 'events' module Sprout class Stream attr_accessor :io def initialize(io) @io = io @write_buffer = "" end include Events::Emitter CHUNK_SIZE = 8 * 1024 def handle_read begin data = io.read_nonblock(CHUNK_SIZE) emit(:data, data) rescue IO::WaitReadable rescue EOFError close if io.closed? end end def handle_write return if @write_buffer.empty? write(@write_buffer) end def write(data) begin bytes = io.write_nonblock(data) @write_buffer = data.slice(bytes, data.size) rescue Errno::EAGAIN, Errno::EPIPE end end def close emit(:close) io.close end def to_io io end end end
true
c6e6ab1a7e10cfec4323244308aa286968bf5083
Ruby
whtouche/wdi_2_ruby_lab_rspec_geometry
/spec/rectangle_spec.rb
UTF-8
629
3.21875
3
[]
no_license
require_relative '../lib/rectangle' describe Rectangle do let(:rectangle) { Rectangle.new(7, 5) } # Before every test, assign a local variable called rectangle whose value is the return value of the block describe 'attributes' do it 'has a length and width' do expect(rectangle.length).to eq 7 expect(rectangle.width).to eq 5 end end describe '#area' do it 'calculates the area' do expect(rectangle.area).to eq 35 end end describe '#perimeter' do it 'calculates the perimter' do expect(rectangle.perimeter).to eq 24 end end end # Existence is implicitly tested
true
250ed6372f2884a339c92aeda00d6cd84ca9f313
Ruby
noto81/Homeworks
/W4D3/Simon_skeleton/lib/simon.rb
UTF-8
1,268
3.609375
4
[]
no_license
class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @seq = [] @sequence_length = 1 @game_over = false end def play until @game_over take_turn end game_over_message reset_game end def take_turn show_sequence require_sequence unless @game_over round_success_message @sequence_length += 1 end end def show_sequence add_random_color @seq.each do |color| puts color sleep 2 system("clear") sleep 1 end end def require_sequence puts "Repeat the sequence" # repeat back the new sequence that was just shown to users, one color at a time @seq.each do |color| user_color = gets.chomp if color[0] != user_color @game_over = true break end end sleep 0.25 end def add_random_color @seq = COLORS.shuffle end def round_success_message puts "CONGRATULATIONS!" end def game_over_message puts "Game over!" end def reset_game @sequence_length = 1 @game_over = false @seq = [] end end s = Simon.new s.play
true
f8b2ed68600f45f1f1304049af6e61097d6e0d3e
Ruby
bingxie/code-questions
/lib/leetcode/124_binary-tree-maximum-path-sum.rb
UTF-8
656
3.453125
3
[ "MIT" ]
permissive
# class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} root # @return {Integer} def max_path_sum(root) @max = -Float::INFINITY max_path_recursive(root) @max end def max_path_recursive(node) return 0 if node.nil? # possibilities # 1. self # 2. left + self # 3. right + self # 4 self + left + right left = max_path_recursive(node.left) right = max_path_recursive(node.right) max_path = [node.val, node.val + left, node.val + right].max @max = [max_path, @max, node.val + left + right].max max_path end
true
f9ab6975f40d88fe9633e67374f257e0fd6a2655
Ruby
neeruram1/weather-bop
/app/models/user.rb
UTF-8
600
2.578125
3
[]
no_license
class User < ApplicationRecord def self.update_or_create(auth) user = User.find_by(spotify_id: auth['info']['id']) || User.new user.attributes = { spotify_id: auth['info']['id'], name: auth['info']['display_name'], access_token: auth['credentials']['token'], refresh_token: auth['credentials']['refresh_token'], email: auth['info']['email'] } user.save! user end def access_token_expired? (Time.current - updated_at) > 3300 end def token if access_token_expired? refresh_token else access_token end end end
true
6b47263a78756b7762a8c6fa908c1aee415b7c75
Ruby
jystewart/grand-rapids-wifi
/vendor/plugins/ym4r_mapstraction/lib/mapstraction_plugin/mapstraction.rb
UTF-8
9,725
2.515625
3
[ "MIT" ]
permissive
module Ym4r module MapstractionPlugin #Map types of the map class MapType ROAD = Variable.new("Mapstraction.ROAD") SATELLITE = Variable.new("Mapstraction.SATELLITE") HYBRID = Variable.new("Mapstraction.HYBRID") end #Represents a Mapstracted map. class Mapstraction include MappingObject #The id of the DIV that will contain the map in the HTML page. attr_reader :container, :map_type #A constant containing the declaration of the VML namespace, necessary to display polylines in google maps under IE. VML_NAMESPACE = "xmlns:v=\"urn:schemas-microsoft-com:vml\"" #By default the map in the HTML page will be globally accessible with the name +map+. +map_type+ is one of three choices: <tt>:google</tt>, <tt>:yahoo</tt> or <tt>microsoft</tt>. def initialize(container, map_type, variable = "map") @container = container @map_type = map_type @variable = variable @init = [] @init_begin = [] @init_end = [] @global_init = [] end def self.header(types,options = {}) a = "" Array(types).each do |type| if type == :google options[:with_vml] = true unless options.has_key?(:with_vml) if options.has_key?(:key) api_key = options[:key] elsif GMAPS_API_KEY.is_a?(Hash) #For this environment, multiple hosts are possible. #:host must have been passed as option if options.has_key?(:host) api_key = GMAPS_API_KEY[options[:host]] else raise AmbiguousGMapsAPIKeyException.new(GMAPS_API_KEY.keys.join(",")) end else #Only one possible key: take it api_key = GMAPS_API_KEY end a << "<script src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;key=#{api_key}\" type=\"text/javascript\"></script>\n" a << "<style type=\"text/css\">\n v\:* { behavior:url(#default#VML);}\n</style>" if options[:with_vml] elsif type == :yahoo a << "<script type=\"text/javascript\" src=\"http://api.maps.yahoo.com/ajaxymap?v=3.4&amp;appid=YellowMasp4R\"></script>\n" elsif type == :microsoft a << "<script src=\"http://dev.virtualearth.net/mapcontrol/v3/mapcontrol.js\"></script>\n" end end a << "<script src=\"/javascripts/mapstraction.js\" type=\"text/javascript\"></script>\n" a << "<script src=\"/javascripts/ym4r-mapstraction.js\" type=\"text/javascript\"></script>\n" a end #Outputs the <div id=...></div> which has been configured to contain the map. You can pass <tt>:width</tt> and <tt>:height</tt> as options to output this in the style attribute of the DIV element (you could also achieve the same effect by putting the dimension info into a CSS or using the instance method Mapstraction#header_width_height) def div(options = {}) attributes = "id=\"#{@container}\" " if options.has_key?(:height) && options.has_key?(:width) attributes += "style=\"width:#{options[:width]}px;height:#{options[:height]}px\"" end "<div #{attributes}></div>" end #Outputs a style declaration setting the dimensions of the DIV container of the map. This info can also be set manually in a CSS. def header_width_height(width,height) "<style type=\"text/css\">\n##{@container} { height: #{height}px;\n width: #{width}px;\n}\n</style>" end #Records arbitrary JavaScript code and outputs it during initialization inside the +load+ function. def record_init(code) @init << code end #Initializes the controls: you can pass a hash with key <tt>:small</tt> (only one for now) and a boolean value as the value (usually true, since the control is not displayed by default). Also in later version, you can be a bit more precise, with the following keys: pan (boolean), zoom (:large or :small), overview (boolean), scale (boolean), map_type (boolean) def control_init(controls = {}) if controls[:small] @init << add_small_controls() elsif controls[:large] @init << add_large_controls() else @init << add_controls(controls) end end #Initializes the initial center and zoom of the map. +center+ can be both a GLatLng object or a 2-float array. def center_zoom_init(center, zoom) if center.is_a?(LatLonPoint) @init_begin << set_center_and_zoom(center,zoom) else @init_begin << set_center_and_zoom(LatLonPoint.new(center),zoom) end end #Center and zoom based on the bbox corners. Pass a GLatLngBounds object, an array of 2D coordinates (sw and ne) or an array of GLatLng objects (sw and ne). def center_zoom_on_bounds_init(bounds) if bounds.is_a?(Array) if bounds[0].is_a?(Array) bounds = BoundingBox.new(bounds[0][0],bounds[0][1],bounds[1][0],bounds[1][1]) elsif bounds[0].is_a?(LatLonPoint) bounds = BoundingBox.new(bounds[0].lat,bounds[0].lon,bounds[1].lat,bounds[1].lon) end end #else it is already a latlngbounds object @init_begin << set_bounds(bounds) end #Initializes the map by adding a marker def marker_init(marker, options = {}) if options[:open_bubble] @init << add_marker_and_open(marker) else @init << add_marker(marker) end end def marker_group_init(marker_group) @init << add_marker_group(marker_group) end def clusterer_init(clusterer) @init << add_clusterer(clusterer) end def polyline_init(polyline) @init << add_polyline(polyline) end #Sets the map type displayed by default after the map is loaded. def set_map_type_init(map_type) @init << set_map_type(map_type) end #Locally declare a MappingObject with variable name "name" def declare_init(variable, name) @init << variable.declare(name) end #Records arbitrary JavaScript code and outputs it during initialization outside the +load+ function (ie globally). def record_global_init(code) @global_init << code end #Declares the marker globally with name +name+ def marker_global_init(marker,name, options = {}) declare_global_init(marker,name) marker_init(marker,options) end #Declares the marker group globally with name +name+ def marker_group_global_init(marker_group,name) declare_global_init(marker_group,name) marker_group_init(marker_group) end def clusterer_global_init(clusterer,name) declare_global_init(clusterer,name) clusterer_init(clusterer) end def polyline_global_init(polyline, name) declare_global_init(polyline,name) polyline_init(clusterer) end #Globally declare a MappingObject with variable name "name" def declare_global_init(variable,name) @global_init << variable.declare(name) end #Outputs the initialization code for the map. By default, it outputs the script tags, performs the initialization in response to the onload event of the window and makes the map globally available. You can pass the <tt>:full => true</tt> option to setup fullscreen for the map. def to_html(options = {}) no_load = options[:no_load] no_script_tag = options[:no_script_tag] no_declare = options[:no_declare] no_global = options[:no_global] fullscreen = options[:full] html = "" html << "<script type=\"text/javascript\">\n" if !no_script_tag #put the functions in a separate javascript file to be included in the page html << @global_init * "\n" html << "var #{@variable};\n" if !no_declare and !no_global html << "window.onload = addCodeToFunction(window.onload,function() {\n" if !no_load if fullscreen #Adding the initial resizing and setting up the event handler for #future resizes html << "setWindowDims($('#{@container}'));\n" html << "if (window.attachEvent) { window.attachEvent(\"onresize\", function() {setWindowDims($('#{@container}'));})} else {window.addEventListener(\"resize\", function() {setWindowDims($('#{@container}')); } , false);}\n" end if !no_declare and no_global html << "#{declare(@variable)}\n" else html << "#{assign_to(@variable)}\n" end html << @init_begin * "\n" html << @init * "\n" html << @init_end * "\n" html << "\n});\n" if !no_load html << "</script>" if !no_script_tag if fullscreen #setting up the style in case of full screen html << "<style>html, body {width: 100%; height: 100%} body {margin:0} ##{@container} {margin:0} </style>" end html end #Outputs in JavaScript the creation of a Mapstraction object def create "new Mapstraction(\"#{@container}\",\"#{@map_type.to_s}\")" end end class AmbiguousGMapsAPIKeyException < StandardError end end end
true
29f2e5d92442ac2c062138364973b13264d45a8d
Ruby
ctoa/monitoring-scripts
/puppet/check_puppet.rb
UTF-8
4,121
2.625
3
[]
no_license
#!/usr/bin/ruby # A simple nagios check that should be run as root # perhaps under the mcollective NRPE plugin and # can check when the last run was done of puppet. # It can also check fail counts and skip machines # that are not enabled # # The script will use the puppet last_run-summar.yaml # file to determine when last Puppet ran else the age # of the statefile. require 'optparse' require 'yaml' lockfile = "/var/lib/puppet/state/puppetdlock" statefile = "/var/lib/puppet/state/state.yaml" summaryfile = "/var/lib/puppet/state/last_run_summary.yaml" enabled = true enabled_message = "" running = false lastrun_failed = false lastrun = 0 failcount = 0 warn = 1 crit = 5 warn_time = 1900 crit_time = 3700 total_failure = false enabled_only = false opt = OptionParser.new opt.on("--critical_time [CRIT]", "-x", Integer, "Critical threshold for time last run") do |f| crit_time = f.to_i end opt.on("--warn_time [WARN]", "-u", Integer, "Warning thresold for time last run") do |f| warn_time = f.to_i end opt.on("--critical [CRIT]", "-c", Integer, "Critical threshold, time or failed resources") do |f| crit = f.to_i end opt.on("--warn [WARN]", "-w", Integer, "Warning thresold, time of failed resources") do |f| warn = f.to_i end opt.on("--only-enabled", "-e", "Only alert if Puppet is enabled") do |f| enabled_only = true end opt.on("--lock-file [FILE]", "-l", "Location of the lock file, default #{lockfile}") do |f| lockfile = f end opt.on("--state-file [FILE]", "-t", "Location of the state file, default #{statefile}") do |f| statefile = f end opt.on("--summary-file [FILE]", "-s", "Location of the summary file, default #{summaryfile}") do |f| summaryfile = f end opt.parse! if File.exists?(lockfile) if File::Stat.new(lockfile).zero? enabled = false enabled_message = "Puppet disabled. " else running = true end end lastrun = File.stat(statefile).mtime.to_i if File.exists?(statefile) if File.exists?(summaryfile) begin summary = YAML.load_file(summaryfile) lastrun = summary["time"]["last_run"] # machines that outright failed to run like on missing dependencies # are treated as huge failures. The yaml file will be valid but # it wont have anything but last_run in it unless summary.include?("events") failcount = 99 total_failure = true else # and unless there are failures, the events hash just wont have the failure count failcount = 0 + summary["events"]["failure"] + summary["resources"]["failed"] end rescue failcount = 0 summary = nil end end time_since_last_run = Time.now.to_i - lastrun if enabled_only && enabled == false puts "OK: #{enabled_message}Not alerting due to -e flag. Last run #{time_since_last_run} seconds ago with #{failcount} failures" exit 0 end if total_failure puts "CRITICAL: FAILED - Puppet failed to run. Missing dependencies? Catalog compilation failed? Puppet last ran #{time_since_last_run} seconds ago" exit 2 elsif failcount >= crit puts "CRITICAL: #{enabled_message}Puppet last ran had #{failcount} failures, expected < #{crit}. Puppet last ran #{time_since_last_run} seconds ago" exit 2 elsif failcount >= warn puts "WARNING: #{enabled_message}Puppet last ran had #{failcount} failures, expected < #{warn}. Puppet last ran #{time_since_last_run} seconds ago" exit 1 elsif time_since_last_run >= crit_time puts "CRITICAL: #{enabled_message}Puppet last ran #{time_since_last_run} seconds ago, expected < #{crit_time} seconds" exit 2 elsif time_since_last_run >= warn_time puts "WARNING: #{enabled_message}Puppet last ran #{time_since_last_run} seconds ago, expected < #{warn_time} seconds" exit 1 else if enabled puts "OK: #{enabled_message}Puppet last ran #{time_since_last_run} seconds ago with #{failcount} failures" else puts "WARNING: #{enabled_message}Puppet last ran #{time_since_last_run} seconds ago with #{failcount} failures" exit 1 end exit 0 end
true
3329b0500665cb07ba2004bb26c3190397cdca54
Ruby
dmaes/monitoring-plugins
/check_oom-killer.rb
UTF-8
2,496
2.71875
3
[ "Apache-2.0" ]
permissive
#! /usr/bin/env ruby # ----------------------- # Author: Andreas Paul (xorpaul) <xorpaul@gmail.com> # striped down to only contain oom killer check by # Yornik Heyl<yornik@yornik.nl> from https://github.com/xorpaul/check_linux/blob/master/check_linux.rb # Date: 2013-12-02 10:57 # Version: 0.1.2 # ----------------------- require 'date' require 'optparse' require 'yaml' def check_oom() oom_cmd = "dmesg | awk '/invoked oom-killer:/ || /Killed process/'" oom_data = `#{oom_cmd}` lines_count = oom_data.split("\n").size oom_result = {'perfdata' => "oom_killer_lines=#{lines_count}"} if lines_count == 2 oom_result['returncode'] = 1 invoked_line, killed_line = oom_data.split("\n") killed_pid = killed_line.split(" ")[3] killed_cmd = "dmesg | grep #{killed_pid}]" killed_data = `#{killed_cmd}` killed_pid_rss = killed_data.split(" ")[-5].to_i oom_result['text'] = "WARNING: #{invoked_line.split(" ")[1]} invoked oom-killer: #{killed_line.split(" ")[1..4].join(" ")} to free #{killed_pid_rss / 1024}MB - reset with dmesg -c when finished" elsif lines_count > 3 # we can't match this with reasonable effort, so just scream for help oom_result['returncode'] = 1 oom_result['text'] = "WARNING: oom-killer was invoked and went on a killing spree (dmesg | awk '/invoked oom-killer:/ || /Killed process/) - reset with dmesg -c when finished" else oom_result['returncode'] = 0 oom_result['text'] = "OK: No OOM killer activity found in dmesg output" oom_result['perfdata'] = '' end return oom_result end results = [] results << check_oom() puts "\n\nresult array: #{results}\n\n" if $debug # Aggregate check results output = {} output['returncode'] = 0 output['text'] = '' output['multiline'] = '' output['perfdata'] = '' results.each do |result| output['perfdata'] += "#{result['perfdata']} " if result['perfdata'] != '' if result['returncode'] >= 1 output['text'] += "#{result['text']} " case result['returncode'] when 3 output['returncode'] = 3 if result['returncode'] > output['returncode'] when 2 output['returncode'] = 2 if result['returncode'] > output['returncode'] when 1 output['returncode'] = 1 if result['returncode'] > output['returncode'] end else output['multiline'] += "#{result['text']}</br>\n" end end if output['text'] == '' output['text'] = 'OK - everything looks okay' end puts "#{output['text']}|#{output['perfdata']}\n#{output['multiline'].chomp()}" exit output['returncode']
true
37cf89bbf461cefd59511fc46a9af2d49fb00cef
Ruby
flapjack/flapjack
/lib/flapjack/cli/purge.rb
UTF-8
2,441
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'hiredis' require 'flapjack/configuration' module Flapjack module CLI class Purge def initialize(global_options, options) @global_options = global_options @options = options if @global_options[:'force-utf8'] Encoding.default_external = 'UTF-8' Encoding.default_internal = 'UTF-8' end config = Flapjack::Configuration.new config.load(global_options[:config]) @config_env = config.all if @config_env.nil? || @config_env.empty? exit_now! "No config data found in '#{global_options[:config]}'" end Flapjack::RedisProxy.config = config.for_redis Zermelo.redis = Flapjack.redis end def check_history # find all checks, or the check given # purge old data for check options = {} if @options[:days] options[:older_than] = @options[:days].to_i * 24 * 60 * 60 raise "days must be resolvable to an integer" unless @options[:days].to_i.to_s == @options[:days] end checks = if @options[:check] [Flapjack::Data::Check.find_by_id(options[:check])].compact else Flapjack::Data::Check.all end purge_before = Time.now - options[:older_than] purge_range = Zermelo::Filters::IndexRange.new(nil, purge_before, :by_score => true) purged = checks.inject(0) do |memo, check| purgees = check.states.intersect(:created_at => purge_range) num = purgees.count if num > 0 purgees.destroy_all memo += num end memo end if purged == 0 puts "Nothing to do" else puts "Purged #{purged.reduce(:+) || 0} historical check states over #{purged.length} checks." end end end end end desc "Purge data from Flapjack's database" command :purge do |purge| purge.desc 'Purge check history' purge.command :check_history do |check_history| check_history.flag [:d, 'days'], :desc => "purge check history older than DAYS days ago", :default_value => 90 check_history.flag [:c, 'check'], :desc => "affect history of only the CHECK with the provided id" check_history.action do |global_options,options,args| purge = Flapjack::CLI::Purge.new(global_options, options) purge.check_history end end end
true
d38353d8d75fb7f9e273ccd12645e4e407cce639
Ruby
iknow/phraseapp_updater
/lib/phraseapp_updater/differ.rb
UTF-8
5,385
2.765625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'set' require 'hashdiff' require 'deep_merge' class PhraseAppUpdater class Differ SEPARATOR = '~~~' using IndexBy def initialize(verbose: false) @verbose = verbose end # Resolution strategy is that primary always wins in the event of a conflict def resolve_diffs(primary:, secondary:, secondary_deleted_prefixes:) primary = primary.index_by { |op, path, from, to| path } secondary = secondary.index_by { |op, path, from, to| path } # As well as explicit conflicts, we want to make sure that deletions or # incompatible type changes to a `primary` key prevent addition of child # keys in `secondary`. Because input hashes are flattened, it's never # possible for a given path and its prefix to be in the same input. # For example, in: # # primary = [["+", "a", 1]] # secondary = [["+", "a.b", 2]] # # the secondary change is impossible to perform on top of the primary, and # must be blocked. # # This applies in reverse: prefixes of paths in `p` need to be available # as hashes, so must not appear as terminals in `s`: # # primary = [["+", "a.b", 2]] # secondary = [["+", "a", 1]] primary_prefixes = primary.keys.flat_map { |p| path_prefixes(p) }.to_set # Remove conflicting entries from secondary, recording incompatible # changes. path_conflicts = [] secondary.delete_if do |path, diff| if primary_prefixes.include?(path) || primary.keys.any? { |pk| path.start_with?(pk) } path_conflicts << path unless primary.has_key?(path) && diff == primary[path] true else false end end # For all path conflicts matching secondary_deleted_prefixes, additionally # remove other changes with the same prefix. prefix_conflicts = secondary_deleted_prefixes.select do |prefix| path_conflicts.any? { |path| path.start_with?(prefix) } end secondary.delete_if do |path, diff| prefix_conflicts.any? { |prefix| path.start_with?(prefix) } end primary.values + secondary.values end def apply_diffs(hash, diffs) deep_compact!(Hashdiff.patch!(hash, diffs)) end def resolve!(original:, primary:, secondary:) # To appropriately cope with type changes on either sides, flatten the # trees before calculating the difference and then expand afterwards. f_original = flatten(original) f_primary = flatten(primary) f_secondary = flatten(secondary) primary_diffs = Hashdiff.diff(f_original, f_primary) secondary_diffs = Hashdiff.diff(f_original, f_secondary) # However, flattening discards one critical piece of information: when we # have deleted or clobbered an entire prefix (subtree) from the original, # we want to consider this deletion atomic. If any of the changes is # cancelled, they must all be. Motivating example: # # original: { word: { one: "..", "many": ".." } } # primary: { word: { one: "..", "many": "..", "zero": ".." } } # secondary: { word: ".." } # would unexpectedly result in { word: { zero: ".." } }. # # Additionally calculate subtree prefixes that were deleted in `secondary`: secondary_deleted_prefixes = Hashdiff.diff(original, secondary, delimiter: SEPARATOR).lazy .select { |op, path, from, to| (op == "-" || op == "~") && from.is_a?(Hash) && !to.is_a?(Hash) } .map { |op, path, from, to| path } .to_a resolved_diffs = resolve_diffs(primary: primary_diffs, secondary: secondary_diffs, secondary_deleted_prefixes: secondary_deleted_prefixes) if @verbose STDERR.puts('Primary diffs:') primary_diffs.each { |d| STDERR.puts(d.inspect) } STDERR.puts('Secondary diffs:') secondary_diffs.each { |d| STDERR.puts(d.inspect) } STDERR.puts('Resolution:') resolved_diffs.each { |d| STDERR.puts(d.inspect) } end Hashdiff.patch!(f_original, resolved_diffs) expand(f_original) end # Prefer everything in current except deletions, # which are restored from previous if available def restore_deletions(current, previous) current.deep_merge(previous) end private def flatten(hash, prefix = nil, acc = {}) hash.each do |k, v| k = "#{prefix}#{SEPARATOR}#{k}" if prefix if v.is_a?(Hash) flatten(v, k, acc) else acc[k] = v end end acc end def expand(flat_hash) flat_hash.each_with_object({}) do |(key, value), root| path = key.split(SEPARATOR) leaf_key = path.pop leaf = path.inject(root) do |node, path_key| node[path_key] ||= {} end raise ArgumentError.new("Type conflict in flattened hash expand: expected no key at #{key}") if leaf.has_key?(leaf_key) leaf[leaf_key] = value end end def path_prefixes(path_string) path = path_string.split(SEPARATOR) parents = [] path.inject do |acc, el| parents << acc "#{acc}#{SEPARATOR}#{el}" end parents end end end
true
45f592074ab6b21182356332b3610c6e3bc720ea
Ruby
kh45/Algorithms
/Codewars/find_the_outlier.rb
UTF-8
926
4.1875
4
[]
no_license
# You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N. ## Examples # [2, 4, 0, 100, 4, 11, 2602, 36] # Should return: 11 (the only odd number) # [160, 3, 1719, 19, 11, 13, -21] # Should return: 160 (the only even number) #test ##Past terrible solution # def find_outlier(integers) # even = 0 # integers.each{|item| # if item.even? # even += 1 # end} # integers.each{|item| # if even > 1 # return item if item.odd? # else # return item if item.even? # end} # end def find_outlier(integers) integers.one?{|num| num.odd?} ? integers.find{|num| num.odd?} : integers.find{|num| num.even?} end
true
085210b1c698517211e9d283c5257d0c228bcf46
Ruby
tnandate/ruby_toy
/spec/factory_method/id_card_spec.rb
UTF-8
416
2.5625
3
[]
no_license
require './spec/spec_helper' require './lib/factory_method/id_card' RSpec.describe IdCard do before do @id_card = IdCard.new("John") end describe '#use' do it 'return use message' do expect{ @id_card.use }.to output("use John's card.\n").to_stdout end end describe '#get_owner' do it 'return the owner of id card' do expect(@id_card.get_owner).to eq 'John' end end end
true
ff7d11be68e69cd931c0d25cb910cb7604ebacf8
Ruby
ping-n/Fast-track-Gem
/lib/Class.rb
UTF-8
499
3.28125
3
[ "MIT" ]
permissive
# frozen_string_literal: true class Employee attr_accessor :first_name, :last_name, :age, :gender def initialize(f_name, l_name, age, gender) @first_name = f_name @last_name = l_name @age = age @gender = gender end def to_a [@first_name, @last_name, @age, @gender] end end class Shift attr_accessor :day, :name, :s_time, :e_time def initialize(day, name, s_time, e_time) @day = day @name = name @start_time = s_time @end_time = e_time end end
true
2cbc31795af95b7136ceb8362eb804a3be98b62f
Ruby
edelgado/code-challenge-parsing-and-sorting
/lib/registrar/importers/comma_importer.rb
UTF-8
340
2.546875
3
[]
no_license
module Registrar class CommaImporter < Importer def self.mapping(row) { first_name: row[1], middle_initial: nil, last_name: row[0], campus: row[2], date_of_birth: row[4], favorite_color: row[3] } end def self.delimiter ',' end end end
true
597c7ac221afd7d56e4e6122771513e464bb6615
Ruby
wjue/Empo
/models.rb
UTF-8
4,970
3.3125
3
[]
no_license
# encoding: utf-8 # Auhtor WANG Jue aka wjue, Copyright 2014. wjue@outlook.com # License GPL v2 # =============================================================================================== # The primary goal of this project is to create an application that assist Chinese classical poem # learner to practice the specific rules of compisition, to check conformity, etc... # Empo name is derivated from "poem" :-) # =============================================================================================== # Empo Models, defaut encoding is utf-8 $LOAD_PATH << '.' require 'empo_module.rb' include Empo class Hzshi # we use 'Hz' prefix for 漢字 objet attr_reader "text" def author # getter method (@author == nil) ? '不詳' : @author end def author=(value) return @author = '不詳' if (value == nil) @author = (value != '') ? value : '不詳' end def yyunsystem # getter method @yyunsystem end def yyunsystem=(value) # setter method @yyunsystem = (['平水韻','中古韻','上古韻','新韻'].include?(value)) ? value : '平水韻' end def initialize(input) # input should be pre-sanitized: a string with only chinese characters and "," "。" ponctuation symboles if input.include?(",") @text = input else @text = 'Error: the input text is not suitable, tips: 至少一聯兩句,上句與下句用逗號(“,”)分開,聯以句號(“。”)分開,換行可自由。' end @yyunsystem = '平水韻' end def shengdiaos(poem) # 聲調,給出全詩每字的平上去入 s = poem @rsds = [] s.each_char {|x| ( [',','。'].include?(x) ) ? @rsds << x : @rsds << Empo.shengdiao(x) } @rsds end def pingzes(poem) # 平仄,給出平仄 #[平 ,仄] ar = shengdiaos(poem) @rpzs = [] ar.each {|x| ( [',','。'].include?(x) )? @rpzs << x : @rpzs << Empo.pingze(x) } @rpzs end def yinyuns # 音韻,給出字的韻母 end end # Testing Models # ============== # init for Character property tables $聲調表 = Hash.new("") # set the default value returned by $聲調表 to an empty string $聲調表 = {'平'=>['平','東','童','中','同'], '上'=>['上','董','動','孔','總','同'], '去'=>['去','送','夢','鳳','洞'], '入'=>['入','屋','木','竹','目','爵'] } #testshi = "长安白日照春空, 绿杨结烟垂袅风 。 披香殿前花始红空,流芳发色绣户中。" testshi = "東童孔送童東同, 送孔平東夢屋中。  " testshi = Empo.sanitize(testshi) myshi = Hzshi.new(testshi) #create a Hzshi instance puts "詩文: " << myshi.text myshi.author= '李白' myshi.yyunsystem='中古韻' puts "作者: " << myshi.author puts "音韻體系: " << myshi.yyunsystem # testing Hzshi::shengdiaos str = "聲調: " myshi.shengdiaos(testshi).each {|x| case when (x.class == String) then str << x when (x.class == Array)&& (x.size == 1) then str << x[0] else str << '[' x.each { |y| str << y } str << ']' end } puts str # ====== # testing Hzshi::pingzes str = "平仄: " myshi.pingzes(testshi).each { |x| case when (x.class == String) then str << x when (x.class == Array)&& (x.size == 1) then str << x[0] else str << '[' x.each { |y| str << y } str << ']' end } puts str # ===== #puts Empo.pingzes() puts Empo.shengdiao('爵') puts "OK" =begin # We define a chinese classical poem strophe "詩句" as a list of (n,n) pair, where n is the number of chinese characters. # Generally we have n=5, or n=7. we will consider it as a 2n length unicode string class Empostrophe # define "詩句" class, 應用: 上句,下句, 一般一聯有多句 attr_accessor "phrase" attr_reader "type" # type=5 五言 , type=7 七言 etc. def initialize(text) if text.length % 2 == 1 #in text there should be only single “,” sign as non chinese character @type = (text.length/2).to_s @phrase = text.split(/,/) else begin raise "Expected empo-strophe to be of even length" rescue => expc puts "#{expc.class}: #{expc.message}" end end end end class Empo # Empo: 漢語古詩,律詩 def initialize(text) # split the input text into strophes 聯, 每聯以句號 “。”分開 tab = Filter(text).split(/\s*。\s*/) empo_s = Array.new tab.each {|x| empo_s << x} @strophes = empo_s end def strophes @strophes end end # Control code comes here shi = Empo.new('长安白日照春空, 绿杨结烟垂袅风 。 披香殿前花始红空,流芳发色绣户中。') shi.strophes.each do |x| strophe = Empostrophe.new(x) puts strophe.phrase puts "#{strophe.type}言" end =end
true
c67f1633afabcf7b1c7d07f553f4595245624be9
Ruby
8geonirt/github-contributions
/app/models/github/github_repository.rb
UTF-8
429
2.515625
3
[]
no_license
# frozen_string_literal: true module Github # Class that stores a Github Repository returned by the Github Graphql Server class GithubRepository attr_reader :name_with_owner, :url, :created_at, :updated_at def initialize(repository) @name_with_owner = repository.name_with_owner @url = repository.url @created_at = repository.created_at @updated_at = repository.updated_at end end end
true
106a9ac8396c260a154a38e8970cde7c005611ce
Ruby
HLuning/Launch-School-Core-Curriculum
/RB101_Programming_Foundations/small_problems/retirement.rb
UTF-8
432
4.0625
4
[]
no_license
# age puts "What's your age? " age = gets.to_i # age of retirement puts "At what age would you like to retire? " age_retirement = gets.to_i # current year current_year = Time.now.year # working years left years_left = age_retirement - age # year of retirement year_retirement = current_year + years_left puts "It's #{current_year}. You will retire in #{year_retirement}." puts "You only have #{years_left} years of work to go!"
true
b1107f0ae7e7c0b49bfa4ef8aa9278d4af1f80c2
Ruby
lwlsns/claim-additional-payments-for-teaching
/app/models/payroll/payment_csv_row.rb
UTF-8
2,787
2.640625
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
# frozen_string_literal: true require "delegate" require "csv" require "excel_utils" module Payroll class PaymentCsvRow < SimpleDelegator DATE_FORMAT = "%Y%m%d" UNITED_KINGDOM = "United Kingdom" BASIC_RATE_TAX_CODE = "BR" CUMULATIVE_TAX_BASIS = "0" NOT_EMPLOYEES_ONLY_JOB = "3" NI_CATEGORY_FOR_ALL_EMPLOYEES = "A" HAS_STUDENT_LOAN = "T" STUDENT_LOAN_PLAN_1 = "1" STUDENT_LOAN_PLAN_2 = "2" def to_s CSV.generate_line(data) end private def data Payroll::PaymentsCsv::FIELDS_WITH_HEADERS.keys.map do |f| field = send(f) ExcelUtils.escape_formulas(field) end end def title # Hardcoded as HMRC require it, but we don't collect it. As HMRC will already hold # a record for teachers, they will be able to match to their existing record based # on other fields such as name, dob, NI number "Captain" end def payroll_gender model.payroll_gender.chr.upcase end def start_date second_monday_of_month.strftime(DATE_FORMAT) end def end_date second_monday_of_month.end_of_week.strftime(DATE_FORMAT) end def second_monday_of_month day = Date.today.at_beginning_of_month day += 1.days until day.monday? day.next_week end def date_of_birth model.date_of_birth.strftime(DATE_FORMAT) end def address_lines @address_lines ||= [ model.address_line_1, model.address_line_2, model.address_line_3, model.address_line_4, model.postcode ].compact end def address_line_1 address_lines[0] end def address_line_2 address_lines[1] end def address_line_3 address_lines[2] end def address_line_4 address_lines[3] end def address_line_5 address_lines[4] end def address_line_6 end def country UNITED_KINGDOM end def tax_code BASIC_RATE_TAX_CODE end def tax_basis CUMULATIVE_TAX_BASIS end def new_employee NOT_EMPLOYEES_ONLY_JOB end def ni_category NI_CATEGORY_FOR_ALL_EMPLOYEES end def has_student_loan HAS_STUDENT_LOAN if model.has_student_loan end def student_loan_plan if model.student_loan_plan == "plan_1" || model.student_loan_plan == "plan_1_and_2" STUDENT_LOAN_PLAN_1 elsif model.student_loan_plan == "plan_2" STUDENT_LOAN_PLAN_2 end end def banking_name model.banking_name end def scheme_amount model.award_amount.to_s end def roll_number model.building_society_roll_number end def payment_id model.id end def model __getobj__ end end end
true
7fac01a4f8eeac262dc22b5a0118e8f176c93ea9
Ruby
trvslhlt/TextDig
/ContactsGateway.rb
UTF-8
2,342
3.0625
3
[]
no_license
#!/usr/bin/ruby require 'sqlite3' require_relative './MessagesGateway' class ContactsGateway FIRST = "First" LAST = "Last" CONTACT_ID = "ContactID" attr_accessor :contacts def initialize(source_db_url) @contacts = self.get_contacts(source_db_url) end def get_contacts(source_db_url) begin db = SQLite3::Database.open source_db_url stm = db.prepare "SELECT First, Last, ROWID, value FROM ABMultiValue, ABPerson WHERE record_id = ROWID AND value is not null" results = stm.execute # implicit return temp_contacts_hashes = {} results.each do |contact| new_contact_hash = {} new_contact_hash[FIRST] = contact[0] new_contact_hash[LAST] = contact[1] new_contact_hash[CONTACT_ID] = contact[2] dirty_unique_id = contact[3] unique_id = self.class.normalize_unique_id(dirty_unique_id) new_contact_hash[MessagesGateway::UNIQUE_ID] = unique_id temp_contacts_hashes[unique_id] = new_contact_hash if unique_id end odd_contacts = knownContactsWithUniqueIDs() contacts_hashes = temp_contacts_hashes.merge(odd_contacts) return contacts_hashes rescue SQLite3::Exception => e puts 'Exception occured' puts e end end def contact_id_to_readable_name( contact_id ) name = contact_id contact_hash = @contacts[contact_id] if !contact_hash.nil? first = contact_hash[FIRST] last = contact_hash[LAST] n = first.nil? ? "" : first n = last.nil? ? n : n + last if (n != "") then name = n end end return name end def self.normalize_unique_id( dirty_unique_id) if dirty_unique_id.nil? then return nil end if dirty_unique_id.include? "@" then return dirty_unique_id end inter = dirty_unique_id.gsub(/( |\+|\(|\)|\-|\.)/,"") clean_unique_id = inter.sub(/^1/, "") clean_unique_id end def knownContactsWithUniqueIDs() contacts = {} raw_contacts = {} contact_id_generator = 10000 raw_contacts['ki'] = ['4046555562','falcorkle@gmail.com', '7708919910', 'mmccorkie2@student.gsu.edu', '61405738298'] raw_contacts.each do |name, unique_ids| contact_id = contact_id_generator contact_id_generator += 1 unique_ids.each do |unique_id| contact = {} contact[FIRST] = name contact[MessagesGateway::UNIQUE_ID] = unique_id contact[CONTACT_ID] = contact_id contacts[unique_id] = contact end end return contacts end end
true
15feea50856de5d0d0468c888c5d6cb80c3c14be
Ruby
jamesreck/lesson_2
/lesson_2/rock_paper_scissors.rb
UTF-8
2,442
3.875
4
[]
no_license
# Ask the user to choose rock, paper or scissors # The computer will then choose. # The program will decide who won and display the winner # The program will ask if the user wants to play again COMBATANTS = %w(rock paper scissors lizard spock) VALID_CHOICES = %w(rock r paper p scissors sc lizard l spock sp) SCISSORS_BEATS = %w(paper lizard) PAPER_BEATS = %w(rock spock) ROCK_BEATS = %w(scissors lizard) LIZARD_BEATS = %w(spock paper) SPOCK_BEATS = %w(rock scissors) win_conditions = { scissors: SCISSORS_BEATS, paper: ["rock", "spock"], rock: ["scissors", "lizard"], lizard: %w(spock paper), spock: %w(rock scissors) } def prompt(message) puts "=> #{message}" end =begin def win?(first, second) first_sym = first.to_sym win_conditions[first_sym].include?(second) end =end =begin def display_results(player, computer) if win?(player, computer) prompt "You won!" elsif win?(computer, player) prompt "Computer won!" else prompt "It's a tie!" end end =end still_playing = true player_score = 0 computer_score = 0 while still_playing choice = '' loop do prompt "Choose one: #{COMBATANTS.join(', ')}" choice = gets.chomp.downcase if VALID_CHOICES.include?(choice) break else prompt "That is not a valid choice. Please try again." end end case choice when "sc" choice = "scissors" when "r" choice = "rock" when "p" choice = "paper" when "l" choice = "lizard" when "sp" choice = "spock" else choice end computer_choice = COMBATANTS.sample prompt "You chose: #{choice}. The computer chose: #{computer_choice}." if win_conditions[choice.to_sym].include?(computer_choice) player_score += 1 prompt "You win!" elsif win_conditions[computer_choice.to_sym].include?(choice) prompt "Computer wins!" computer_score += 1 else prompt "It's a tie!" end prompt "The score is: Player: #{player_score}, Computer: #{computer_score}." if player_score == 5 prompt "You win the match!" prompt "Goodbye!" still_playing = false elsif computer_score == 5 prompt "The computer wins the match!" prompt "Goodbye!" still_playing = false end prompt "Do you want to play again?" answer = gets.chomp.downcase if answer != "y" still_playing = false end end
true
450953e8974a0a00c636a16890a39d8c28f2137e
Ruby
emanon001/atcoder-ruby
/abc036/c/main.rb
UTF-8
277
2.890625
3
[]
no_license
N = gets.to_i a_list = N.times.map.with_index { |i| [gets.to_i, i] } sorted = a_list.sort_by { |a, _| a } b_list = Array.new(N) max = -1 current = nil sorted.each do |(a, i)| if a != current current = a max += 1 end b_list[i] = max end b_list.each { |b| puts b }
true
9fba748a688c6df52b729b54fae4c8318e8661d7
Ruby
ministryofjustice/laa-apply-for-legal-aid
/spec/mock_objects/mock_queued_job.rb
UTF-8
170
2.5625
3
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
class MockQueuedJob attr_reader :item, :score def initialize(klass, at) @item = { "queue" => "default", "wrapped" => klass.to_s } @score = at.to_i end end
true
1ec8b5999018db4d0f68fc7536bde3e530b47a75
Ruby
costagavras/week_3-multiclass
/product.rb
UTF-8
983
4.1875
4
[]
no_license
# Each product has a name, base price, and tax rate. There should also be a method to calculate and return the product's total price based on the base price # and tax rate. class Product def initialize(name, base_price, quantity, category) @name = name @base_price = base_price @quantity = quantity # Stretch #3. tax classification system if category == "full" @sales_tax = 0.15 elsif category == "redux" @sales_tax = 0.05 elsif category == "exempt" @sales_tax = 0 end end def full_price @full_price = @base_price * (1 + @sales_tax) end def base_price @base_price end def name @name end # Stretch 2. Associate quantity def quantity @quantity end end # banana = Product.new("banana", 0.57, "exempt") # candy = Product.new("candy", 1.50, "full") # book = Product.new("book", 18.00, "redux") # puts banana.full_price.round(2) # puts candy.full_price.round(2) # puts book.full_price.round(2)
true
bcf510a85e998c5a1112b81ba5fcf33e14589e80
Ruby
jimjeffers/EquipmentBookingSystem
/app/models/category.rb
UTF-8
1,863
2.546875
3
[]
no_license
class Category < ActiveRecord::Base # Plugins has_guid :name # Relationships has_many :categories has_many :items belongs_to :category # Validations validates_presence_of :name validates_uniqueness_of :name # Scopes default_scope :order => 'position ASC, created_at DESC' named_scope :root_level, :conditions => ['category_id IS ?',nil], :include => {:categories => :categories} # Returns parent categories of the current instance in an array. def parents parents = [] current = category_id while current parents << (parent = Category.find(current)) current = parent.category_id end return parents.reverse! end # Returns item count including counts the current instances immediate children. def item_count count = items.count categories(:include => :items).each do |child| count += child.items.count end return count end # Returns all items in the current category and it's children's items. def items_and_nested_items Item.all_in_given_categories([self]+categories) end # Get all of the root level categories for a set of items. There has to be a better way to do this. # TODO: Refactor this so that it's less convoluted and uses less queries. def self.top_level_categories_for_items(items) if items.length > 0 item_ids_string = items.map { |i| i.id }.join(',') parents = self.find(:all, :conditions => ["id IN (#{item_ids_string}) AND category_id IS ?", nil], :include => :categories) children = self.find(:all, :conditions => ["id IN (#{item_ids_string}) AND category_id IS NOT ?", nil], :include => :category) if children.length > 0 for child in children parents << child.category unless parents.include?(child.category) end end end return parents || [] end end
true
746f9d0869c11b2311784a21836eff39597f60ca
Ruby
remind101/request_signing
/lib/request_signing/ssm.rb
UTF-8
3,168
2.5625
3
[ "MIT" ]
permissive
require "aws-sdk-ssm" require "request_signing" module RequestSigning module KeyStores # AWS SSM-backed key store implementation # @see RequestSigning::Signer # @see RequestSigning::Verifier # @see http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html class SSM ## # Makes a new instance of {RequestSigning::KeyStores::SSM} # # @param ssm_client [Aws::SSM::Client] an instance of configured SSM client # @param path [String] path prefix for SSM GetParametersByPath operation # # @return [RequestSigning::KeyStores::SSM] # # @see http://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SSM/Client.html#get_parameters_by_path-instance_method ## def self.with_ssm_path(ssm_client:, path:) ssm_options = { path: path, recursive: false, with_decryption: true } new(ssm_client: ssm_client, ssm_options: ssm_options) end ## # Makes a new instance of {RequestSigning::KeyStores::SSM} # # @param ssm_client [Aws::SSM::Client] an instance of configured SSM client # @param ssm_options [Hash] custom parameters for SSM GetParametersByPath operation # # @return [RequestSigning::KeyStores::SSM] # # @see http://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SSM/Client.html#get_parameters_by_path-instance_method ## def self.with_ssm_options(ssm_client:, ssm_options:) new(ssm_client: ssm_client, ssm_options: ssm_options) end def initialize(ssm_client:, ssm_options:) @ssm_client = ssm_client @ssm_options = ssm_options @loaded = false @keys = {} end # @param key_id [String] id of the key to retrieve # # @return [String] key contents # # @raise [RequestSigning::KeyNotFound] when requested key is not found # @raise [Aws::SSM::Errors::ServiceError] when keys were not eager loaded and loading fails def fetch(key_id) load! unless loaded? @keys.fetch(key_id) rescue KeyError raise KeyNotFound, key_id: key_id end # @param key_id [String] id of the key # # @return true if store knows this key # @return false if store does not recognize the key # # @raise [Aws::SSM::Errors::ServiceError] when keys were not eager loaded and loading fails def key?(key_id) load! unless loaded? @keys.key?(key_id) end # Eager loads the keys # # @raise [Aws::SSM::Errors::ServiceError] def load! return if loaded? keys = {} next_token = nil loop do params = @ssm_options.merge(next_token: next_token) response = @ssm_client.get_parameters_by_path(params) response.parameters.each do |p| keys[p.name] = p.value end next_token = String(response.next_token) break if next_token.empty? end @keys = keys @loaded = true end def loaded? !!@loaded end end end end
true
928b958d54e1688dcc19cc93afcbb9810269c895
Ruby
ShomaFujii/furima-34532
/app/models/purchaser_address.rb
UTF-8
1,041
2.609375
3
[]
no_license
class PurchaserAddress include ActiveModel::Model attr_accessor :zip_code, :prefecture_id, :city, :street_number, :building, :phone_number,:user_id,:item_id,:token with_options presence: true do validates :user_id validates :item_id validates :city validates :street_number validates :token validates :zip_code, format: {with: /\A\d{3}[-]\d{4}\z/, message: "is invalid. Include hyphen(-)"} validates :phone_number, format: {with: /\A\d{,11}\z/, message: "is invalid. without hyphen(-)"} end validates :prefecture_id, numericality: {other_than: 0, message: "can't be blank"} def save # 寄付情報を保存し、変数donationに代入する purchaser = Purchaser.create( user_id: user_id ,item_id: item_id) # 住所を保存する # donation_idには、変数donationのidと指定する Address.create(zip_code: zip_code, prefecture_id: prefecture_id, city: city, street_number: street_number, building: building,phone_number: phone_number, purchaser_id: purchaser.id) end end
true
b49625f5d3cd7d3cef43c38f6706d1e740ceca75
Ruby
Gothu/fremar
/spec/models/user_spec.rb
UTF-8
6,358
2.734375
3
[]
no_license
require 'rails_helper' describe User do describe '#create' do it "全て入力すると登録できる" do user = create(:user) expect(user).to be_valid end it "nicknameが空だと登録できない" do user = build(:user, nickname: "") user.valid? expect(user.errors[:nickname]).to include("can't be blank") end it "nicknameが40文字を超えると登録できない" do user = build(:user, nickname: "a" * 41) user.valid? expect(user.errors[:nickname]).to include("is too long (maximum is 40 characters)") end it "nicknameが40文字以内だと登録できる" do user = create(:user, nickname: "a" * 40) expect(user).to be_valid end it "first_nameが空だと登録できない" do user = build(:user, first_name: "") user.valid? expect(user.errors[:first_name]).to include("can't be blank") end it "last_nameが空だと登録できない" do user = build(:user, last_name: "") user.valid? expect(user.errors[:last_name]).to include("can't be blank") end it "first_nameに「ひらがな、カタカナ、漢字」以外は登録できない" do user = build(:user, first_name: ['A', '1', '@']) user.valid? expect(user.errors[:first_name]).to include("no") end it "first_nameが「ひらがな、カタカナ、漢字」だと登録できる" do user = create(:user, first_name: "亜あア") expect(user).to be_valid end it "last_nameに「ひらがな、カタカナ、漢字」以外は登録できない" do user = build(:user, last_name: ['A', '1', '@']) user.valid? expect(user.errors[:last_name]).to include("no") end it "last_nameが「ひらがな、カタカナ、漢字」だと登録できる" do user = create(:user, last_name: "亜あア") expect(user).to be_valid end it "first_name_hiraganaが空だと登録できない" do user = build(:user, first_name_hiragana: "") user.valid? expect(user.errors[:first_name_hiragana]).to include("can't be blank") end it "last_name_hiraganaが空だと登録できない" do user = build(:user, last_name_hiragana: "") user.valid? expect(user.errors[:last_name_hiragana]).to include("can't be blank") end it "first_name_hiraganaに「ひらがな」以外は登録できない" do user = build(:user, first_name_hiragana: ['A', '1', '@', 'ア', '亜']) user.valid? expect(user.errors[:first_name_hiragana]).to include("is must NOT contain any other characters than alphanumerics.") end it "first_name_hiraganaが「ひらがな」だと登録できる" do user = build(:user, first_name_hiragana: "あいうえお") expect(user).to be_valid end it "last_name_hiraganaに「ひらがな」以外は登録できない" do user = build(:user, first_name_hiragana: ['A', '1', '@', 'ア', '亜']) user.valid? expect(user.errors[:first_name_hiragana]).to include("is must NOT contain any other characters than alphanumerics.") end it "last_name_hiraganaが「ひらがな」だと登録できる" do user = build(:user, last_name_hiragana: "あいうえお") expect(user).to be_valid end it "birth_yearが空だと登録できない" do user = build(:user, birth_year: "") user.valid? expect(user.errors[:birth_year]).to include("can't be blank") end it "birth_yearが4桁以外は登録できない" do user = build(:user, birth_year: [1, 11, 111, 11111]) user.valid? expect(user.errors[:birth_year]).to include("no") end it "birth_yearが4桁のみ登録できる" do user = build(:user, birth_year: 1111) expect(user).to be_valid end it "birth_monthが空だと登録できない" do user = build(:user, birth_month: "") user.valid? expect(user.errors[:birth_month]).to include("can't be blank") end it "birth_monthが2桁以外は登録できない" do user = build(:user, birth_month: [1, 111, 1111]) user.valid? expect(user.errors[:birth_month]).to include("no") end it "birth_monthが2桁のみ登録できる" do user = build(:user, birth_month: 11) expect(user).to be_valid end it "birth_dayが空だと登録できない" do user = build(:user, birth_day: "") user.valid? expect(user.errors[:birth_day]).to include("can't be blank") end it "birth_dayが2桁以外は登録できない" do user = build(:user, birth_day: [1, 111, 1111]) user.valid? expect(user.errors[:birth_day]).to include("no") end it "birth_dayが2桁のみ登録できる" do user = build(:user, birth_day: 11) expect(user).to be_valid end it "passwordが空だと登録できない" do user = build(:user, password: "") user.valid? expect(user.errors[:password]).to include("can't be blank") end it "passwordが7桁以下だと登録できない" do user = build(:user, password: "a" * 6, password_confirmation: "a" * 6) user.valid? expect(user.errors[:password]).to include("is too short (minimum is 7 characters)") end it "passwordが7桁以上だと登録できる" do user = create(:user, password: "a" * 7, password_confirmation: "a" * 7) expect(user).to be_valid end it "password_confirmationが空だと登録できない" do user = build(:user, password_confirmation: "") user.valid? expect(user.errors[:password_confirmation]).to include("doesn't match Password") end it "emailが空だと登録できない" do user = build(:user, email: "") user.valid? expect(user.errors[:email]).to include("can't be blank") end it "emailに一意性制約がかかっているか" do user = create(:user) another_user = build(:user, email: user.email) another_user.valid? expect(another_user.errors[:email]).to include("has already been taken") end it "statusが空だと登録できない" do user = build(:user, status: "") user.valid? expect(user.errors[:status]).to include("can't be blank") end end end
true
b657457a1fde00f3d0d7318d23dfd8b82949c07e
Ruby
Aprekek/DegreezeRuby
/spec/input_target_temperature_spec.rb
UTF-8
2,090
3.03125
3
[]
no_license
require_relative '../src/scenarious/input_target_temperature' require_relative '../src/io_adapter' require_relative '../src/scenarious/convert_temperature' RSpec.describe States::InputTargetTemperature do type_of_degrees = 'k', temperature_amount = '34.0' state = States::InputTargetTemperature.new(type_of_degrees, temperature_amount) let(:io_mock) { instance_double IOAdapter } before do allow(IOAdapter).to receive(:instance).and_return(io_mock) allow(io_mock).to receive(:write) end it '#initialize' do expect(state.type_of_degrees).to eq(type_of_degrees) expect(state.temperature_amount).to eq(temperature_amount) expect(state.final_state).to eq(false) end it '#render' do state.render expect(io_mock).to have_received(:write).with('Convert to (F, C, K): ') end context '#next' do let(:temperature_handler_mock) { instance_double TemperatureHandler } before do allow(TemperatureHandler).to receive(:instance).and_return(temperature_handler_mock) end it 'with correct conversation type' do to_type = 'C' allow(io_mock).to receive(:read).and_return(to_type) allow(temperature_handler_mock).to receive(:correct_temperature_type?).and_return true actual_state = state.next expected_state = States::ConvertTemperature.new(type_of_degrees, temperature_amount, to_type) expect(temperature_handler_mock).to have_received(:correct_temperature_type?).with(to_type) expect(actual_state.type_of_degrees).to eq(expected_state.type_of_degrees) expect(actual_state.temperature_amount).to eq(expected_state.temperature_amount) expect(to_type).to eq(expected_state.to_type) end it 'with incorrect conversation type' do to_type = 'Hohma' allow(io_mock).to receive(:read).and_return(to_type) allow(temperature_handler_mock).to receive(:correct_temperature_type?).and_return false expect(state.next).to eq(state) expect(io_mock).to have_received(:write).with('Incorrect input') end end end
true
5492d43d951c502abde52da2c81f323e1609bb1b
Ruby
jaycdave88/Hisser
/spec/model_spec.rb
UTF-8
1,666
2.6875
3
[]
no_license
require_relative "./spec_helper" describe User do #tests that the model has attributes it { should respond_to(:first_name) } it { should respond_to(:last_name) } it { should respond_to(:snake_name) } it { should respond_to(:email) } it { should respond_to(:password) } it { should respond_to(:avatar) } #swag tests - should pass eventually it { should respond_to(:password_confirmation) } it { should respond_to(:authentication) } end describe "Snakes in the model" do #arrange some test data to work with before :all do @user1 = User.create( snake_name: "Left", first_name: "Hairy", last_name: "Nut", email: "Left@testes.com", password: "qwerty", avatar: "http://i.imgur.com/Y4S7Bx9.gif" ) @user2 = User.create( snake_name: "Right", first_name: "Smooth", last_name: "Nut", email: "Right@testes.com", password: "qwerty", avatar: "http://i.imgur.com/Y4S7Bx9.gif" ) @test_hiss = "I like your ball bro" @user1.relationships.create(person_id:2) @user1_follower_array = @user1.relationships.pluck(:person_id) end it "can identify their own hisses" do @user1.hisses.create(hiss: @test_hiss) expect(@user1.hisses.pluck(:hiss).first).to eq(@test_hiss) end it "can identify their followers" do expect(@user1_follower_array.first).to eq(2) end it "can identify who they're following" do @user2_is_following = @user2.relationships.pluck(:person_id).first expect(@user2_is_following).to equal(1) end it "can identify hisses from snakes they follow" do expect(@user2_is_following.first.hisses).to equal(@test_hiss) end end
true
b872d1e8de400d7c2898736a9574cafc088611ad
Ruby
mako1997/Ruby_sample
/02_08.rb
UTF-8
312
2.859375
3
[]
no_license
programming_languages = %w(ruby php python javascript) # コードを追加 programming_languages.map! { |item| item.capitalize } upper_case_programming_languages = programming_languages.map { |item| item.upcase } # 以下は変更しないで下さい p programming_languages p upper_case_programming_languages
true
bfff5148d9317b9456cf27ce230d592b403d0520
Ruby
adwinsky/skyscraper
/spec/skyscraper/skyscraper/path_spec.rb
UTF-8
3,713
2.65625
3
[ "MIT" ]
permissive
require "spec_helper" describe Skyscraper::Path do describe "when path is REMOTE" do before(:each) do @path = Skyscraper::Path.factory("http://google.com/index.php?q=e") end it "local? method should returns false" do @path.local?.should == false end it "remote? method should returns true" do @path.remote?.should == true end it "should returns domain" do @path.domain.should == "http://google.com" end it "should returns domain with no scheme" do @path = Skyscraper::Path.factory("google.com/index.php?q=e") @path.full_path.should == "google.com/index.php?q=e" end it "should returns path" do @path.path.should == "/index.php" end it "should returns query" do @path.query.should == "?q=e" end it "should returns base" do @path.base.should == "http://google.com/" end it "should returns full path" do @path.full_path.should == "http://google.com/index.php?q=e" end it "should be converted to string" do @path.to_s.should == @path.full_path end it "should returns full path for full different" do path = Skyscraper::Path.factory("http://google.com/a/index.php") path.full_path_for("http://yahoo.com/b.html").should == "http://yahoo.com/b.html" end it "should returns full path for relative" do path = Skyscraper::Path.factory("http://google.com/a/index.php") path.full_path_for("b.html").should == "http://google.com/a/b.html" end it "should returns full path for absolute" do path = Skyscraper::Path.factory("http://google.com/a/index.php") path.full_path_for("/b.html").should == "http://google.com/b.html" end it "should returns file name" do path = Skyscraper::Path.factory("http://google.com/a/index.php") path.file_name.should == "index.php" end end describe "when path is LOCAL" do before(:each) do @path = Skyscraper::Path.factory("/var/www/files/file.ext") end it "should returns folder" do @path.folder.should == "/var/www/files/" end it "local? method should returns true" do @path.local?.should == true end it "remote? method should returns false" do @path.remote?.should == false end it "should returns file name" do @path.file_name.should == "file.ext" end it "should returns full path" do @path.full_path.should == "/var/www/files/file.ext" end it "should returns base" do @path.base.should == "/var/www/files/" end it "should returns full path for relative" do path = Skyscraper::Path.factory("/var/www/public/index.html") path.full_path_for("../b.html").should == "/var/www/public/../b.html" path.full_path_for("b.html").should == "/var/www/public/b.html" end it "should returns full path for absolute full" do path = Skyscraper::Path.factory("/var/www/public/index.html") path.full_path_for("/var/www/test.html").should == "/var/www/test.html" end end it "should detect if string is remote " do Skyscraper::Path.remote?("http://google.com").should == true Skyscraper::Path.remote?("google.com").should == true end it "should detect if string is not remote " do Skyscraper::Path.remote?("/var/www/projects").should == false Skyscraper::Path.remote?("/var/www/projects/file.ext").should == false end it "should check if is absolute address" do Skyscraper::Path.absolute?("/some/relative/path").should == true end it "should returns nil for wrong path" do path = Skyscraper::Path.factory("/var/www/files/") path.file_name.should == nil end end
true
990cbb123ee2a88680785b57be94594e85be2575
Ruby
james-wallace-nz/ls_rb109
/lesson_4/additional_practice.rb
UTF-8
4,199
4.5625
5
[]
no_license
# 1. # Given the array below flintstones = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"] # Turn this array into a hash where the names are the keys and the values are the positions in the array. hash = {} flintstones.each_with_index do |name, index| hash[name] = index end p hash # 2. # Add up all of the ages from the Munster family hash: ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } puts ages.reduce(0) { |num, (key, value)| num + value } total_age = 0 ages.each { |name, age| total_age += age } p total_age p ages.values.inject(&:+) # 3. # In the age hash: ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } # remove people with age 100 and greater. ages.delete_if { |k, v| v >= 100 } p ages # 4. # Pick out the minimum age from our current Munster family hash: ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } min_age = ages.values.first ages.each do |name, age| min_age = age if age < min_age end puts min_age p ages.values.min # 5. # In the array: flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles) # Find the index of the first name that starts with "Be" p flintstones.index { |name| name.start_with?('Be') } # 6. # Amend this array so that the names are all shortened to just the first three characters: flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles) flintstones.map! { |name| name[0..2] } p flintstones # 7. # Create a hash that expresses the frequency with which each letter occurs in this string: statement = "The Flintstones Rock" # ex: # { "F"=>1, "R"=>1, "T"=>1, "c"=>1, "e"=>2, ... } frequency = Hash.new(0) statement.chars.each do |char| frequency[char] += 1 end p frequency # 8. # What happens when we modify an array while we are iterating over it? What would be output by this code? numbers = [1, 2, 3, 4] numbers.each do |number| p number numbers.shift(1) end # If we modify an array while iterating then some elements in the array will be skipped as elements are added or removed while iteration takes place # 1 # 3 # What would be output by this code? numbers = [1, 2, 3, 4] numbers.each do |number| p number numbers.pop(1) end # 1 # 2 # 9. # As we have seen previously we can use some built-in string methods to change the case of a string. A notably missing method is something provided in Rails, but not in Ruby itself...titleize. This method in Ruby on Rails creates a string that has each word capitalized as it would be in a title. For example, the string: words = "the flintstones rock" # would be: # words = "The Flintstones Rock" # Write your own version of the rails titleize implementation. def titelize(string) words = string.split words.each do |word| word.capitalize! end words.join(' ') end p titelized = titelize(words) # 10. # Given the munsters hash below munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } # Modify the hash such that each member of the Munster family has an additional "age_group" key that has one of three values describing the age group the family member is in (kid, adult, or senior). Your solution should produce the hash below # { "Herman" => { "age" => 32, "gender" => "male", "age_group" => "adult" }, # "Lily" => {"age" => 30, "gender" => "female", "age_group" => "adult" }, # "Grandpa" => { "age" => 402, "gender" => "male", "age_group" => "senior" }, # "Eddie" => { "age" => 10, "gender" => "male", "age_group" => "kid" }, # "Marilyn" => { "age" => 23, "gender" => "female", "age_group" => "adult" } } # Note: a kid is in the age range 0 - 17, an adult is in the range 18 - 64 and a senior is aged 65+. def age_group(age) if age.between?(0,17) 'kid' elsif age.between?(18,64) 'adult' else 'senior' end end munsters.each do |name, details| age_group = age_group(details['age']) details['age_group'] = age_group end pp munsters
true
93df3cae3abc4be72669555a4186f3e9a869e856
Ruby
jhh/net-denon-gem
/lib/net/denon/state.rb
UTF-8
2,973
2.984375
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
require 'net/denon/constants' require 'net/denon/loggable' module Net ; module Denon class State include Constants include Loggable attr_reader :master_volume attr_reader :master_volume_max attr_reader :input_source attr_reader :channel_volume attr_reader :record_source def initialize @channel_volume = Hash.new @standby = nil @mute = nil end def standby? debug {"@standby = #{@standby}"} @standby end def on? ! @standby end def mute? @mute end def main_zone_on? @main_zone end def update(response) debug {"response = #{response}"} response.each("\r") do |r| case command(r) when POWER update_power(r) when MASTER_VOLUME update_master_volume(r) when CHANNEL_VOLUME update_channel_volume(r) when MUTE update_mute(r) when INPUT_SOURCE update_input_source(r) when MAIN_ZONE update_main_zone(r) when RECORD_SOURCE update_record_source(r) end end end private def update_power(r) @standby = (parameter(r) == "STANDBY") end def update_master_volume(r) p = parameter(r) if p.length == 2 then @master_volume = p.to_i else @master_volume_max = p[-2..-1].to_i end end def update_channel_volume(r) re = /^([A-Z]+) (\d\d)(\d?)$/ md = re.match(parameter(r)) vol = md[2].to_i case (md[1]) when "FL" @channel_volume[:front_left] = vol when "FR" @channel_volume[:front_right] = vol when "C" @channel_volume[:center] = vol when "SW" @channel_volume[:subwoofer] = vol when "SL" @channel_volume[:surround_left] = vol when "SR" @channel_volume[:surround_right] = vol when "SBL" @channel_volume[:surround_back_left] = vol when "SBR" @channel_volume[:surround_back_right] = vol when "SB" @channel_volume[:surround_back] = vol end end def update_mute(r) @mute = (parameter(r) == "ON") end def update_input_source(r) @input_source = parameter(r) end def update_main_zone(r) @main_zone = (parameter(r) == "ON") end def update_record_source(r) @record_source = parameter(r) end def command(r) r[0, 2] end def parameter(r) r[2, r.length-3] end def to_s string = '' string += "standby: #{@standby}\n" string += "mute: #{@mute}\n" string += "master volume: #{@master_volume}\n" string += "master max volume: #{@master_max_volume}\n" string += "input source: #{@input_source}\n" string += "main zone: #{@main_zone}\n" string += "record source: #{record_source}\n" end end end ; end
true
022eb39ecd861693401c845290d1256610cde9db
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/triangle/9e871778d02d4cacb7333a1cd839144c.rb
UTF-8
414
3.40625
3
[]
no_license
class Triangle def initialize(side1, side2, side3) @a = side1 @b = side2 @c = side3 end def kind raise TriangleError if [@a, @b, @c].min <= 0 x, y, z = [@a, @b, @c].sort raise TriangleError if x + y <= z return :scalene if @a != @b && @b != @c && @a != @c return :equilateral if @a == @b && @b == @c return :isosceles if @a == @b || @b == @c || @a == @c end end
true
97d635783c25c93e367f7d0939abe7e2b154c405
Ruby
sul-dlss/content_management_scripts
/add_donor_tag.rb
UTF-8
1,605
2.796875
3
[]
no_license
# Spotlight workaround to use the otherwise unused "Donor tags" field as a specialized facet # Usage: ruby add_donor_tag.rb input_dir/ output_dir/ mapfile.txt ## input_dir contains MODS files with "druid:" prefix in filename ## mapfile.txt is two tab-delimited columns: first column is druid, second column is term to add require 'nokogiri' input_dir = ARGV[0] output_dir = ARGV[1] mapfile = ARGV[2] # Create output directory if not existing unless Dir.exist?("#{output_dir}") Dir.mkdir("#{output_dir}") end # Create hash for druids and new terms mapping = {} File.foreach("#{mapfile}") do |line| fields = line.strip.split("\t") mapping[fields[0]] = fields[1] end # Iterate through druid-term hash and open MODS file with druid in filename mapping.each do |druid, note| # Skip if no term given for druid in mapping next if note == "" # Open input MODS file # NOTE: will fail if there is a druid in the mapping that doesn't have a corresponding file doc = Nokogiri::XML(File.open(File.join("#{input_dir}", "druid:#{druid}.xml"))) # Create donor tags note node note_node = doc.create_element("note") note_node["displayLabel"] = "Donor tags" # Set value as term from mapping note_node.content = "#{note}" # Add note before first subject node # NOTE: will fail if MODS record does not have any subject nodes subject = doc.at_xpath("//xmlns:subject") subject.previous = note_node # Open file in output directory with same filename and write updated MODS record outfile = File.open(File.join("#{output_dir}", "druid:#{druid}.xml"), 'w') outfile.write(doc.to_s) end
true
c7591c35e5b988eaad199374c6e9d315d99da26f
Ruby
nehagrg/rubys1
/practice/p3.rb
UTF-8
231
3.046875
3
[]
no_license
puts "enter n number" n=gets n=n.to_i for i in 1..n for j in 1..n-i print " " end for k in 1..i print "#{k}" end for m in 1..i if m<i h=i while h>1 do print "#{h-1}" h=h-1 end break end end puts end
true
97ea87bfd8c11ffa9ee2b3b59ba92fa894fa3ab8
Ruby
jeremyjaybaker/blockcypher-ethereum
/lib/blockcypher/ethereum/api.rb
UTF-8
1,296
2.546875
3
[ "MIT" ]
permissive
module Blockcypher module Ethereum class API include APIState # The primary class through which most API interaction will occur through. # Each instance of this class has initializers for all defined API objects # which can then call the various actions associated with those objects. # # For example, # ```api = Blockcypher::Ethereum::API.new(use_testnet: true) # api.faucet.add_wei(amount: 100)``` # # Will automatically configure the API class with your API key and version # and provide quick access to testnet API objects. DEFAULT_VERSION = 1.freeze def initialize(use_testnet: false, api_token: ENV['BLOCKCYPHER_API_KEY'], version: DEFAULT_VERSION) @use_testnet = use_testnet @api_token = api_token @version = version end Blockcypher::Ethereum::APIDefinitions.versions.each do |number| "Blockcypher::Ethereum::V#{number}::OBJECTS".constantize.each do |name, _| define_method name do |**args| class_name = "Blockcypher::Ethereum::V#{version}::#{name.to_s.titleize.gsub(' ','')}" class_name.constantize.new(args.merge(api_state)) end end end end end end
true
c5feb2335688e2e21f022679ad5923061f50360d
Ruby
versality/GildedRose-challenge
/lib/gilded_rose/item_collection.rb
UTF-8
273
2.609375
3
[]
no_license
module GildedRose class ItemCollection def initialize(items) @items = items end def update_quality @items.each do |item| item_behavior = ItemBehavior::ItemBehavior.new(item) item_behavior.update_quality end end end end
true
1ef07defa86133c8b35b275d8861ce9e84af0ac2
Ruby
j-eaves/params-game
/app/controllers/input_parameters_controller.rb
UTF-8
2,447
2.78125
3
[]
no_license
class InputParametersController < ApplicationController #Ruby logic should always be here - none in the view page def parameter_input #/test_page (page) #p params[:name] @param_value = params[:name].upcase if @name[0]=='A' @message = "Hey your name starts with an A!" end render 'query_params_view.html.erb' end def query_name #/say_name (page) #Make a counter @counter = params[:count].to_i render 'name_of_query.html.erb' end def guess_number #Page needs to be made, yet @guess = params[:guess].to_i if @guess != 0 and @guess != "0" if @guess.to_i>50 @message = "You guessed too high." elsif @guess.to_i<50 @message = "You guessed too low." else @message = "You got it!" end end render 'guess_a_num.html.erb' end def url_segment_parameter_method @my_input = params[:this_is_a_variable] render 'url_seg_param_view.html.erb' end def guessing_game_form #/guess_the_number (page) #This online form prompts a user to guess a number render 'guessing_game_form.html.erb' end def guessing_game #/submit_guess and /guessing_game (pages) #this method takes in a number from a form and #returns a response (/submit_guess page), based on whether #the number matches a randomly generated number @message = "You guessed too " #@guess is assigned the number entered in the input box @guess = params[:guessed_number].to_i @num = rand(0...100)+1 if @guess != 0 and @guess != "0" if @guess.to_i > @num @message += "high." elsif @guess.to_i < @num @message += "low." elsif @guess == @num @message = "You got it!" end else @message = "Type a number, not a word, or 0.." end render 'guessing_game_submit_page.html.erb' end def form_params #/form (page) #my first and last names become the keys #to the params from this form, which are #passed to the submit-button method #@form_1 = params[:first_name] #@form_2 = params[:last_name] render 'form_params.html.erb' end def submit_button #/submit_form (page) #Use the form input to render it on the submit page @form_1 = params[:first_name] @form_2 = params[:last_name] render 'form_submitted.html.erb' end #def form_goes_here # render 'form_result.html.erb' #end end
true
97fddaa04d0d33c9765044f1a48a2be9ae9b9986
Ruby
lei7dover/NotesAPI
/app/models/note.rb
UTF-8
375
2.703125
3
[]
no_license
class Note < ActiveRecord::Base has_and_belongs_to_many :tags validates_presence_of :title, :body belongs_to :user def tag_names=(tags) tags.split(",").collect{|t| t.strip}.each do |tag| this_tag=Tag.find_or_create_by(name: Tag.clean_name(tag)) self.tags << this_tag end end def tag_names self.tags.collect{|t| t.name} .join (",") end end
true
5d9706afaf08a3120bccaea614718d2aa4d477b2
Ruby
Camsbury/caesar-cipher-ruby
/cipher.rb
UTF-8
827
3.359375
3
[]
no_license
def caesar_cipher(statement,num) statement=statement.split("") for index in 0..statement.length-1 do if statement[index] =~ /[A-Z]/ if statement[index].ord+num>90 add=num%26 if add>(90-statement[index].ord) add=add+statement[index].ord-90 statement[index]=(64+add).chr else statement[index]=(statement[index].ord+add).chr end else statement[index]=(statement[index].ord+num).chr end elsif statement[index] =~ /[a-z]/ if statement[index].ord+num>122 add=num%26 if add>(122-statement[index].ord) add=add+statement[index].ord-122 statement[index]=(96+add).chr else statement[index]=(statement[index].ord+add).chr end else statement[index]=(statement[index].ord+num).chr end end end statement=statement.join("") return statement end
true
6fc2fc8ef8738ef63be5f4c4854c5268407129f6
Ruby
barkingiguana/compound
/lib/barking_iguana/compound/host_manager.rb
UTF-8
1,839
2.546875
3
[]
no_license
module BarkingIguana module Compound class HostManager attr_accessor :hosts private :hosts= attr_accessor :implementation private :implementation=, :implementation include BarkingIguana::Logging::Helper include BarkingIguana::Benchmark def initialize hosts = [], implementation_options = {} self.hosts = hosts self.implementation = Vagrant.new self, implementation_options implementation.prepare end def destroy_all destroy *hosts.map { |h| h.name } end def active all.select { |h| h.state == 'running' } end def all refresh_status hosts end def refresh_status benchmark "refreshing host status" do implementation.refresh_status end end { launch: "up", shutdown: "halt", destroy: "destroy", }.each do |interface, command| define_method interface do |*host_names| if host_names.empty? logger.debug { "Not running anything because the hosts list is empty" } else host_names.sort! benchmark "running #{interface} for #{host_names.join(', ')}" do implementation.public_send command, *host_names end end end end def find_all_by_name names logger.debug { "Finding hosts with names #{names.sort}" } all.select { |h| names.include? h.inventory_name }.tap do |hosts| logger.debug { "Result: #{hosts.inspect}" } end end def find_by_name name logger.debug { "Finding host with name #{name}" } all.detect { |h| h.inventory_name == name }.tap do |h| logger.debug { "Result: #{h.inspect}" } end end end end end
true
301294bf72764906f418e901ff948eb961661c6e
Ruby
keisuke07/RubyStudy2016
/submit/ishigaki/RubyQ13-20161008/post_initial.rb
UTF-8
1,195
2.96875
3
[]
no_license
require 'sqlite3' require 'csv' class Post_initial CSV_COLUMN = {code: 2, pref_kana: 3, city_kana: 4, addr_kana: 5, pref: 6, city: 7, addr: 8} def initialize(dbfile) @dbfile = dbfile end def create(zipfile) begin return if File.exist?(@dbfile) SQLite3::Database.open(@dbfile) do |db| db.execute(<<-SQL) CREATE TABLE IF NOT EXISTS zip_codes (code TEXT, pref_kana TEXT, city_kana TEXT, addr_kana TEXT, pref TEXT, city TEXT, addr TEXT, alladdr TEXT) SQL db.execute("BEGIN TRANSACTION") CSV.open(zipfile, "r:Shift_JIS:UTF-8") do |csv| csv.each do |rec| data = Hash.new CSV_COLUMN.each{ |key, index| data[key] = rec[index] } data[:alladdr] = data[:pref] + data[:city] + data[:addr] db.execute(<<-SQL, data) INSERT INTO zip_codes VALUES (:code, :pref_kana, :city_kana, :addr_kana, :pref, :city, :addr, :alladdr) SQL end end db.execute("COMMIT TRANSACTION") end return true rescue Exception => e print "#{e}" return e end end end test = Post_initial.new("address.db") flg = test.create("KEN_ALL.CSV") if flg == true p "success" else p "failued" end
true
ab4dd5fe6bc661950fdabb5cad370d85fdc757e1
Ruby
Samthedriver/pokemon-scraper-dc-web-082718
/lib/pokemon.rb
UTF-8
685
3.34375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Pokemon attr_accessor :id, :name, :type, :db def initialize(hash) @id = hash[:id] @name = hash[:name] @type = hash[:type] @db = hash[:db] end def self.save(name, type, db) db.execute("INSERT INTO pokemon (name, type) VALUES (?, ?)", name, type) end def self.find(id, db) pokemon_data = db.execute("SELECT * FROM pokemon WHERE id = ?", id).flatten hash = Hash.new hash[:id] = pokemon_data[0] hash[:name] = pokemon_data[1] hash[:type] = pokemon_data[2] hash[:db] = pokemon_data[3] Pokemon.new(hash) end def alter_hp(new_hp, db) db.execute("UPDATE pokemon SET hp = ? WHERE id = ?", new_hp, self.id) end end
true
ebd8343cabe4daa6a42129c55bfce31f99034aa7
Ruby
vmendi/ListenAndRepeat
/IdxLeecher/main.rb
UTF-8
1,263
3.4375
3
[]
no_license
require 'net/http' require 'uri' require 'CGI' class Main def run_all_letters words = [] 97.upto(122) { |chr_idx| char = chr_idx.chr.upcase puts "Fetching #{char}..." char_uri = URI.parse("http://education.yahoo.com/reference/dictionary/entry_index?letter=#{char}") char_web_page = Net::HTTP.get(char_uri) char_web_page = CGI::unescapeHTML char_web_page matches = char_web_page.scan(/entry_index\?letter=#{Regexp.quote(char)}\&key=(\S+)\"/) matches.each { |capture| puts "Fetching #{char} #{CGI::unescape capture[0]}..." entries_uri = "http://education.yahoo.com/reference/dictionary/entry_index?letter=#{char}&key=#{capture[0]}" entries_web_page = Net::HTTP.get(URI.parse(entries_uri)) entries_web_page = CGI::unescapeHTML entries_web_page # We need the text inside the anchor: <a href="/reference/dictionary/entry/Abigail">Abigail</a> entries_matches = entries_web_page.scan(/entry\/\S+\">(\S+)<\/a>/) entries_matches.each { |entry| words.push entry[0] } } } words.uniq! words.sort! File.open("words2.txt", "w") { |the_file| words.each { |word| the_file.puts word } } end end Main.new().run_all_letters()
true
5678d161fef61ed0088c1f926c4b51a1102dff12
Ruby
cshomaker/skillcrush-ruby
/blog.rb
UTF-8
895
3.625
4
[]
no_license
class Page attr_accessor :title, :blog_posts, :total_posts, :created_date, :author, :content def initialize @blog_posts = {} @total_posts = 0 end def show_posts return @blog_posts.sort_by {@created_date} end end class Blog_post < Page attr_accessor :title, :blog_posts, :total_posts, :created_date, :author, :content def create_post puts "What is your author name?" @author = gets.chomp puts "What is the title of your post?" @title = gets.chomp @created_date = Time.now puts "Add your post content:" @content = gets.chomp @total_posts += 1 end def publish(blog_posts) blog_posts.each do |post| puts post.title puts post.created_date puts post.content end end end new_post = Blog_post.new post1 = new_post.create_post blog_posts = new_post.show_posts puts new_post.inspect new_post.publish(blog_posts)
true
cc79699b74ee3a994cfd6c2dd470ef6ac1891f1e
Ruby
dcadizm/Ruby_learning
/Comparator.rb
UTF-8
798
4.03125
4
[]
no_license
############################################################# =begin Objetivo Encontrar el minimo de tres numeros Tareas 1.- preguntar los 3 numeros al usuario 2.- llamar a la clase comparadora 3.- presentar el resultado del proceso =end ############################################################# # 1.- Recuperar los numeros del usuario puts "Ingresa cáda número y presiona ENTER cada vez" puts ">primer número" uno = 1000 puts ">segundo número" dos = 200 puts ">tercer número" tres = 3000 ############################################################# # 2-. shamar a la clase comparadora require "./Clases/claseComparacion.rb" #instancio mi clase obj = Cual_es.new #llamo al metodo dentro de la clase obj.el_mayor(uno,dos,tres) obj.el_menor(uno,dos,tres)
true
0799d0bfd2a64bff0e4101c9b74660641897be3c
Ruby
humawork/wardrobe
/lib/wardrobe/plugins/merge.rb
UTF-8
1,133
2.53125
3
[ "MIT" ]
permissive
module Wardrobe module Plugins module Merge extend Wardrobe::Plugin module MergeRefinements refine Object do def merge(other) other.dup end def deep_merge(other) merge(other) end end refine Hash do def deep_merge(other) dup.tap do |h| other.each do |k,v| h[k] = h[k].deep_merge(v) end end end end end module InstanceMethods using MergeRefinements def merge(other, deep: false) raise TypeError, "Class missmatch #{other.class} != #{self.class}" unless other.class == self.class merge_type = deep ? :merge : :deep_merge res = _attribute_store.inject({}) do |hash, atr| hash[atr.name] = send(atr.name).send(merge_type, other.send(atr.name)) hash end self.class.new(res) end def deep_merge(other) merge(other, deep: true) end end end end register_plugin(:merge, Plugins::Merge) end
true
e670161b92e58e2461fe6241a6f9fc0b348fa76b
Ruby
JackHowa/phase-0-tracks
/ruby/secret_agents-input.rb
UTF-8
859
3.875
4
[]
no_license
puts "Would you like to encrypt or decrypt a message?" crypt_choice = gets.chomp puts "What should I input into the encrypter/decrypter machine?" input = gets.chomp puts "What is the caesar shift for the message? (1 for +1)" shift = gets.to_i if crypt_choice == "decrypt" shift = -(shift) end def decrypt(input) input_length = input.length input_number = 0 current_index = 0 output_number = 0 output = "" alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" until input_length == current_index input_letter = input[current_index] input_number = alphabet.index(input_letter) output_number = input_number - shift output_letter = alphabet[output_number] current_index += 1 output_word = output_word + output_letter end puts output_word end decrypt(input) if choice == "encrypt" then
true
ed8419a659f65ab67b0404bb0b5d94ac642f9a3a
Ruby
jlaw90/truegrit
/blob.rb
UTF-8
448
2.703125
3
[]
no_license
require_relative 'util' module TrueGrit class Blob attr_reader :data def initialize(content,source=nil) @data = Util.crlf(content) @source = source end def self.from_file(path) return Blob.new(File.readlink(path), path) if File.symlink?(path) Blob.new(File.binread(path), path) end alias :lame_to_s :to_s def to_s return lame_to_s if @source.nil? "#{@source}" end end end
true
9e61b7ceef4a844ca403573197579beb6a2f1cb9
Ruby
learn-co-students/nyc-web-students-042219
/10-activerecord/db/migrate/20190503143114_create_squirrels.rb
UTF-8
565
2.953125
3
[]
no_license
class CreateSquirrels < ActiveRecord::Migration[5.2] def change create_table :squirrels do |t| t.string :name t.string :fur_color t.integer :height t.string :disposition end end end # rake db:migrate # CreateSquirrels.new.change # # def change(table_name) # # does some stuff # yield(TableBuilder.new) # end # def my_each(arr) # # puts "here" # counter = 0 # # while counter < arr.length # yield(arr[counter]) # counter += 1 # end # # # puts "at the bottom" # end # [1,2,3].each do |n| # puts n # end
true
7b99814d6d2d98d86b0e5c53846fb9adf3e1d905
Ruby
cebartling/certification-exam-quizzer-rails
/lib/seeds/exam_questions/exam_questions_seed.rb
UTF-8
1,257
2.703125
3
[ "MIT" ]
permissive
require 'csv' module Seeds module ExamQuestions class ExamQuestionsSeed def self.execute puts 'START: Seeding exam_questions table' csv_text = File.read(Rails.root.join('lib', 'seeds', 'exam_questions', 'exam_questions.csv')) csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1') csv.each do |row| exam = CertificationExam.find_by_name(row['exam_name']) if exam found = ExamQuestion.find_by_question_text(row['question_text']) unless found new_instance = ExamQuestion.create!({ certification_exam: exam, question_text: row['question_text'], single_answer: row['single_answer'], difficulty: row['difficulty'] }) puts "Created new ExamQuestion: #{new_instance.question_text}" end end end puts "There are now #{ExamQuestion.count} rows in the exam_questions table" puts 'FINISH: Seeding exam_questions table' end end end end
true
5a2b6faa2672fa7d80db08883944bc203b548b58
Ruby
godsent/trap
/lib/trap/concerns/eventable.rb
UTF-8
623
2.515625
3
[]
no_license
module Trap::Concerns::Eventable def on(event, object, method, *args) @listeners[event] ||= [] @listeners[event] << [object, method, args].flatten end def emit(event) (@listeners[event] || []).each { |a| a[0].send a[1], *a[2 .. -1] } end private def init_variables super @listeners = {} add_listeners_from_options end def add_listeners_from_options option_keys.each do |key| (@options[key] || {}).each do |event_id, c| on key, self, :disable_all_switches, event_id on key, self, :enable_switch, event_id, c unless c == 'OFF' end end end end
true
95c5f1e1b8c5ae857348e95de0ebe5333e825325
Ruby
pixelastic/tedtalks-audio-list
/lib/helper_path.rb
UTF-8
1,467
3.265625
3
[]
no_license
require 'uri' # Convenience methods for dealing with filepaths module HelperPath # Sanitize a filename so it can be written on disk without any risk. # Removes all special chars. # Args: # - filepath (String): Original filepath # Returns: # - String: Sanitized filepath def self.sanitize(filename) filename.gsub(%r{[^0-9A-Za-z.\-/]}, '_') end # Transform a string to camelCase # Args: # - string (String): A string in underscore_form # Returns: # String: The same string in camelCase form def self.camelize(underscore) camel = [] underscore.split('_').each_with_index do |string, index| if index == 0 camel << string next end string[0] = string[0].upcase camel << string end camel.join('') end # Returns the download path for any given url # Args: # - url (String): Input url # Returns: # - String: Download filepath def self.download(url) path = sanitize(URI(url).path) path = 'index.html' if path == '' path = File.expand_path(File.join('./data/html', path)) path += '.html' unless File.extname(path) == '.html' path end # Returns the record path for any given HTML file # Args: # - object_id (String): Unique object ID representing that record # Returns: # - String: JSON record filepath def self.record(object_id) File.expand_path(File.join('./data/records', "#{sanitize(object_id)}.json")) end end
true
d499040b31aa009a4a9997b8ce15be9bfd72e339
Ruby
melzreal/key-for-min-value-v-000
/key_for_min.rb
UTF-8
230
3.125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def key_for_min_value(name_hash) min = nil min_k = nil name_hash.each do |key, value| if min ==nil min = value min_k = key elsif min > value min = value min_k = key end end min_k end
true
2a25f832b1f2efe90e17c07cc62f774ff40b67f8
Ruby
jacksonlmp/Conta_Bancaria_Exercicio
/principal.rb
UTF-8
616
3.484375
3
[]
no_license
#principal.rb require "./classes/conta_bancaria" require "./classes/conta_com_taxa" conta_jack = ContaComtaxa.new "jack", 100 conta_pessoa2 = ContaBancaria.new "pessoa2", 200 conta_jack.transferir conta_pessoa2, 50 p "Conta JACK" p conta_jack.saldo p "Conta Pessoa" p conta_pessoa2.saldo #Caso de teste de conta sem saldo begin conta_jack.transferir(conta_pessoa2, 60) #Falhar rescue StandardError => meu_erro p "Não foi possivel transferir: #{meu_erro.message}" end #Codigo não executado, pois a linha acima gerou um erro p "Conta JACK" p conta_jack.saldo p "Conta Pessoa" p conta_pessoa2.saldo
true
de99df7bc0927826f06b302c4dbf10aa527fcf21
Ruby
karthickpdy/CP
/Codemonk/Searching/rip.rb
UTF-8
150
3.25
3
[]
no_license
t = gets.to_i t.times do s = gets.chomp puts s =~ /21.*/ || s.to_i % 21 == 0 ? "The streak is broken!" : "The streak lives still in our heart!" end
true
c2decba2a0cf1d2277e73749c701f3e47e2ac8b5
Ruby
digideskio/racing_on_rails
/app/models/category.rb
UTF-8
1,918
2.59375
3
[ "Ruby", "MIT" ]
permissive
# Senior Men, Pro/1/2, Novice Masters 45+ # # Categories are just a simple hierarchy of names # # Categories are basically labels and there is no complex hierarchy. In other words, Senior Men Pro/1/2 and # Pro/1/2 are two distinct categories. They are not combinations of Pro and Senior and Men and Cat 1 # # +friendly_param+ is used for friendly links on BAR pages. Example: senior_men class Category < ActiveRecord::Base acts_as_tree include ActsAsTree::Validation include Categories::Ability include Categories::Ages include Categories::Cleanup include Comparable include Categories::FriendlyParam include Categories::Gender include Categories::NameNormalization include Export::Categories acts_as_list has_many :results has_many :races before_validation :set_friendly_param validates_presence_of :name validates_presence_of :friendly_param # All categories with no parent (except root 'association' category) def self.find_all_unknowns Category.includes(:children).where(parent_id: nil).where("name != ?", RacingAssociation.current.short_name) end # Sr, Mst, Jr, Cat, Beg, Exp def self.short_name(name) return name if name.blank? name.gsub('Senior', 'Sr').gsub('Masters', 'Mst').gsub('Junior', 'Jr').gsub('Category', 'Cat').gsub('Beginner', 'Beg').gsub('Expert', 'Exp').gsub("Clydesdale", "Clyd") end def name=(value) self[:name] = Category.normalized_name(value) end def raw_name name end def raw_name=(value) self[:name] = value end # Sr, Mst, Jr, Cat, Beg, Exp def short_name Category.short_name name end # Compare by position, then by name def <=>(other) return 0 if self[:id] && self[:id] == other[:id] diff = (position <=> other.position) if diff == 0 name <=> other.name else diff end end def to_s "#<Category #{id} #{parent_id} #{position} #{name}>" end end
true
3f019cfd21224041d0658d7e9af6f170d2fc2361
Ruby
jirokun/shizuku
/sample/create_data.rb
UTF-8
1,612
2.90625
3
[]
no_license
require 'faker' Faker::Config.locale = :ja puts "making data..." open('create_table.sql', 'w') do |f| f.puts <<EOT drop table if exists transactions; drop table if exists users; create table users ( id varchar(10) primary key, sei varchar(20), mei varchar(20), age int, specialty varchar(5), employment varchar(100), employee_number int, last_login timestamp ); create table transactions ( id int primary key, user_id varchar(10) references users(id), amount bigint, created_date timestamp ); EOT end users = "0000000001".upto("0001000000").map {|i| i } specialties = 'A'.upto('Z').map do |c| '01'.upto('05').map { |num| c + num } end.flatten empolyments = 100.times.map { { :name => Faker::Company.name, :employee_number => rand(10000) } } open('users_data.sql', 'w') do |f| f.puts "COPY users (id, sei, mei, age, specialty, employment, employee_number, last_login) FROM stdin;" users.each do |user| employment = empolyments[rand(empolyments.size)] f.puts [user, Faker::Name.last_name, Faker::Name.first_name, rand(60), specialties[rand(specialties.size)], employment[:name], employment[:employee_number], Faker::Time.backward(1000, :evening).strftime('%Y-%m-%d %H:%M:%S')].join("\t") end end open('transaction_data.sql', 'w') do |f| f.puts "COPY transactions (id, user_id, amount, created_date) FROM stdin;" 1.upto(1000000) do |i| f.puts [i, users[rand(users.size)], rand(10000) + 100, Date.today - rand(1000)].join "\t" end end puts <<EOT psql <database> < create_table.sql psql <database> < users_data.sql psql <database> < transaction_data.sql EOT
true
67e43d859e04c0024cc172b3e56e0f6fd69a687b
Ruby
escoffon/fl-framework
/lib/fl/framework/service/nested.rb
UTF-8
8,909
2.796875
3
[ "MIT" ]
permissive
module Fl::Framework::Service # Base class for service objects that are "nested" inside others. # This class implements functionality used by objects that map to nested resources, like for example # comments associated with a commentable. class Nested < Base # Initializer. # # @param owner_class [Class] The class object of the owner. Since it is possible to nest objects # within different owners, we need to provide the class at the instance level, rather than at the # class level as we do fo the model class. An example of a nested object that takes multiple owner # types is a comment, which can be created in the context of multiple commentables. # @param actor [Object] The actor (typically an instance of {Fl::Core::Actor}, and more specifically # a {Fl::Core::User}) on whose behalf the service operates. It may be +nil+. # @param params [Hash, ActionController::Parameters] The processing parameters. If the value is +nil+, # the parameters are obtained from the `params` property of _controller_. If _controller_ is also # +nil+, the value is set to an empty hash. Hash values are converted to `ActionController::Parameters`. # @param controller [ActionController::Base] The controller (if any) that created the service object; # this parameter gives access to the request context. # @param cfg [Hash] Configuration options. # @option cfg [Boolean] :disable_access_checks Controls the access checks: set it to +true+ to # disable access checking. The default value is +false+. # @option cfg [Boolean] :disable_captcha Controls the CAPTCHA checks: set it to +true+ to # disable verification, even if the individual method options requested. # This is mainly used during testing. The default value is +false+. def initialize(owner_class, actor, params = nil, controller = nil, cfg = {}) @owner_class = owner_class super(actor, params, controller, cfg) end # @!attribute [r] owner_class # The owner class. # Wraps a call to {.owner_class}. # # @return [Class] Returns the owner class. def owner_class() @owner_class end # Look up an owner in the database, and check if the service's actor has permissions on it. # This method uses the owner id entry in the {#params} to look up the object in the database # (using the owner model class as the context for +find+, and the value of _idname_ as the lookup # key). # If it does not find the object, it sets the status to {Fl::Framework::Service::NOT_FOUND} and # returns +nil+. # If it finds the object, it then calls {Fl::Framework::Access::Access::InstanceMethods#permission?} to # confirm that the actor has _op_ access to the object. # If the permission call fails, it sets the status to {Fl::Framework::Service::FORBIDDEN} and returns the # object. # Otherwise, it sets the status to {Fl::Framework::Service::OK} and returns the object. # # @param [Symbol,nil] op The operation for which to request permission. # If +nil+, no access check is performed and the call is the equivalent of a simple database lookup. # @param [Symbol, Array<Symbol>] idname The name or names of the key in _params_ that contain the object # identifier for the owner. A +nil+ value defaults to +:owner_id+. # @param [Hash] params The parameters where to look up the +:id+ key used to fetch the object. # If +nil+, use the value returned by {#params}. # @option [Object] context The context to pass to the access checker method {#allow_op?}. # The special value +:params+ (a Symbol named +params+) indicates that the value of _params_ is to be # passed as the context. # Defaults to +nil+. # # @return [Object, nil] Returns an object, or +nil+. Note that a non-nil return value is not a guarantee # that the check operation succeded. The object class will be the value of the owner_class parameter # to {#initialize}. def get_and_check_owner(op, idname = nil, params = nil, context = nil) idname = idname || :owner_id idname = [ idname ] unless idname.is_a?(Array) params = params || self.params ctx = (:context == :params) ? params : context obj = nil idname.each do |idn| if params.has_key?(idn) begin obj = self.owner_class.find(params[idn]) break rescue ActiveRecord::RecordNotFound => ex obj = nil end end end if obj.nil? self.set_status(Fl::Framework::Service::NOT_FOUND, I18n.tx(localization_key('no_owner'), id: idname.join(','))) return nil end self.clear_status if allow_op?(obj, op, ctx) obj end # Create a model for a given owner. # This method is used for classes created within the "context" of another class, as is the case for # nested resources. For example, say we have a +Story+ object that is associated with a +User+ author, # and the story controller is nested inside the user context. # The resource URL for creating stories, then, looks like +/users/1234/stories+, where +1234+ is the # user's identifier; the route pattern is +/users/:user_id/stories+. # The story object has an attribute +:author+ that contains the story's author, which in this case is # set to the user that corresponds to +:user_id+. # With all that in mind, the value for *:owner_id_name* is +:user_id+, and for # *:owner_attribute_name* it is +:author+. # # The method attempts to create and save an instance of the model class; if either operation fails, # it sets the status to UNPROCESSABLE_ENTITY and loads a message and the *:details* key in the error status # from the object's errors. # # @param opts [Hash] Options to the method. This section describes the common options; subclasses may # define type-specific ones. # @option opts [Hash,ActionController::Parameters] :params The parameters to pass to the object's # initializer. If not present or +nil+, use the value returned by {#create_params}. # @option opts [Boolean,Hash] :captcha If this option is present and is either +true+ or a hash, # the method does a CAPTCHA validation using an appropriate subclass of {Fl::CAPTCHA::Base} # (typically {Fl::Google::RECAPTCHA}, which implements # {https://www.google.com/recaptcha/intro Google reCAPTCHA}). # If the value is a hash, it is passed to the initializer for {Fl::CAPTCHA::Base}. # @option opts [Symbol,String] :permission The name of the permission to request in order to # complete the operation. Defaults to {Fl::Framework::Access::Grants::CREATE}. # @option opts [Object] :context The context to pass to the access checker method {#class_allow_op?}. # The special value +:params+ (a Symbol named +params+) indicates that the create parameters are to be # passed as the context. # Defaults to +:params+. # @option opts [Symbol,String] :owner_id_name The name of the parameter in {#params} that # contains the object identifier for the owner. Defaults to +:owner_id+. # @option opts [Symbol,String] :owner_attribute_name The name of the attribute passed to the initializer # that contains the owner object. Defaults to +:owner+. # # @return [Object] Returns the created object on success, +nil+ on error. # Note that a non-nil return value does not indicate that the call was successful; for that, you should # call #success? or check if the instance is valid. def create_nested(opts = {}) idname = (opts.has_key?(:owner_id_name)) ? opts[:owner_id_name].to_sym : :owner_id attrname = (opts.has_key?(:owner_attribute_name)) ? opts[:owner_attribute_name].to_sym : :owner p = (opts[:params]) ? opts[:params].to_h : create_params(self.params).to_h op = (opts[:permission]) ? opts[:permission].to_sym : Cf::Core::User::ACCESS_BOOKMARK_CREATE ctx = if opts.has_key?(:context) (opts[:context] == :params) ? p : opts[:context] else # This is equivalent to setting the default to :params p end owner = get_and_check_owner(op, idname, nil, ctx) obj = nil if owner && success? rs = verify_captcha(opts[:captcha], p) if rs['success'] if allow_op?(owner, op, ctx) p[attrname] = owner obj = self.model_class.new(p) unless obj.save self.set_status(Fl::Framework::Service::UNPROCESSABLE_ENTITY, I18n.tx(localization_key('creation_failure'), owner: owner.fingerprint), (obj) ? obj.errors.messages : nil) end end end end obj end end end
true
055e5ec3d08493602461799af33c9849076b3f9f
Ruby
Heightened/backend
/model/Race.class.rb
UTF-8
974
3.21875
3
[]
no_license
# Character Race # # @author Tim van Dalen class Race < StatModifyingProperty end # Collection of defined [Race]s module Races # @returns [Race] A totally neutral race that does nothing def self.Neutral Races::get "neutral" end # Gets a race # # @param [String] race alias of the Race you want to get # @returns [Race] the requested race def self.get race ret = Race.first(:alias => race) if ret.nil? ret = make race end ret end # Makes a new Race # This should only be called when a Race doesn't exist yet, no further checks will be done # # @param [String] race alias of the Race you want to create (which should not yet exist in the database) # @param [Race] the race you wanted to create def make race case race when "neutral" ret = Race.make(race, "Neutral", "Nothing",Stats.create(:strength => 1,:speed => 1,:serenity => 1,:stamina => 1,:sorcery => 1)) end ret end private :make end
true
0b23445159c818c3b15d107a1b89fdf13e2da79f
Ruby
charrednewth/Succubus-Rhapsodia-ENG
/Scripts - manually insert these/018 - RPG-Ability(素質・設定用).rb
SHIFT_JIS
30,067
2.640625
3
[]
no_license
#============================================================================== # RPG::Ability #------------------------------------------------------------------------------ # @f̏B$data_ability[id]QƉ”\B #============================================================================== module RPG #-------------------------------------------------------------------------- # f̓o^ #-------------------------------------------------------------------------- class Ability_registration #-------------------------------------------------------------------------- # JCX^Xϐ #-------------------------------------------------------------------------- attr_accessor :id # id attr_accessor :name # O attr_accessor :UK_name # Engrish, go! attr_accessor :description # attr_accessor :icon_name # attr_accessor :hidden # \f #-------------------------------------------------------------------------- # IuWFNg #-------------------------------------------------------------------------- def initialize(ability_id) @id = ability_id @name = "" @UK_name = "" @description = "" @icon_name = "acce_003" @hidden = false setup(ability_id) end #-------------------------------------------------------------------------- # ZbgAbv #-------------------------------------------------------------------------- def setup(ability_id) # KfidŕԂ߁Al邱ƁB case ability_id # id [0..9] ʁȂŗDf when 0 @name = "j" # Y @UK_name = "Male" # Y @description = "A man. ith a attached." #jBʁAB" when 1 @name = "" # Y @UK_name = "Female" @description = "A woman. ith a . And all." #BʁAB" # id [10..29] e_(njɉe) # 10`17͒jp(nD)A19`30͏p()ƂȂ when 10 @name = "U߂Ɏア" # Y @UK_name = "Mouth Fetish" @description = "Oral and tongue techniques have a higher chance of doing critical damage to you." when 11 @name = "U߂Ɏア" # Y @UK_name = "Hand Fetish" @description = "Hand and finger techniques have a higher chance of doing critical damage to you." when 12 @name = "U߂Ɏア" # Y @UK_name = "Breast Fetish" @description = "Breast and nipple techniques have a higher chance of doing critical damage to you." when 13 @name = "AU߂Ɏア" # Y @UK_name = "Pussy Fetish" @description = "Vaginal techniques have a higher chance of doing critical damage to you." when 14 @name = "nsU߂Ɏア" @UK_name = "S Fetish" @description = "Sadistic attacks, such as foot techniques, have a higher chance of doing critical damage to you." when 15 @name = "ٌ`U߂Ɏア" @UK_name = "Monmusu Fetish" @description = "Unconventional techniques have a higher chance of doing critical damage to you." # vCɂĉ when 16 @name = "Ɏア" @UK_name = "Weak to Intercourse" @description = "When Inserted, you have a higher chance of suffering critical damage." when 17 @name = "sɎア" @UK_name = "Ass Fetish" @description = "Ass techniques have a higher chance of doing critical damage to you." # vCɂĉ when 19 @name = "" @UK_name = "Weak Mouth" @description = "Attacks to your mouth have a higher chance of doing critical damage." when 20 @name = "O" @UK_name = "Lewd Mouth" @description = "Attacks to your mouth have a very high chance of doing critical damage." when 21 @name = "" @UK_name = "Weak Chest" @description = "Attacks to your breasts have a higher chance of doing critical damage." when 22 @name = "" @UK_name = "Lewd Chest" @description = "Attacks to your breasts have a very high chance of doing critical damage." when 23 @name = "K" @UK_name = "Weak Ass" @description = "Attacks to your backside have a higher chance of doing critical damage." when 24 @name = "K" @UK_name = "Lewd Ass" @description = "Attacks to your backside have a very high chance of doing critical damage." when 25 @name = "e" @UK_name = "Weak Rosette" @description = "When anally Inserted, you have a higher chance of suffering critical damage." # vCɂĉ when 26 @name = "" @UK_name = "Lewd Rosette" @description = "When anally Inserted, you have a very high chance of suffering critical damage." # vCɂĉ when 27 @name = "Aj" @UK_name = "Weak Clit" @description = "Attacks to your crotch have a higher chance of doing critical damage." when 28 @name = "j" @UK_name = "Lewd Clit" @description = "Attacks to your crotch have a very high chance of doing critical damage." when 29 @name = "A" @UK_name = "Weak Pussy" @description = "When vaginally Inserted, you have a higher chance of suffering critical damage." when 30 @name = "" @UK_name = "Lewd Pussy" @description = "When vaginally Inserted, you have a very high chance of suffering critical damage." # id [31..49] Uf / attack damage bonuses # 31`37̓AN^[̒nj㏸ / multiple attack trigger # 40`46͒ljXL擾ƂȂ / new skill get when 31 @name = "LbXn" @UK_name = "Kiss Mastery" @description = "wKissx attack deals more damage and has a higher chance of dealing critical damage." when 32 @name = "oXgn" @UK_name = "Breast Mastery" @description = "wChestx attack deals more damage and has a higher chance of dealing critical damage." when 33 @name = "qbvn" @UK_name = "Ass Mastery" @description = "wHipsx attack deals more damage and has a higher chance of dealing critical damage." when 34 @name = "Nb`n" @UK_name = "Crotch Mastery" @description = "wCrotchx attack deals more damage and has a higher chance of deadling critical damage." when 35 @name = "CT[gn" @UK_name = "Insert Mastery" @description = "Insert-exclusive skills are more powerful and have a higher chance of dealing critical damage." # vCɂĉ when 36 @name = "z[hn" @UK_name = "Bondage Mastery" @description = "When using restrictive skills, the RESIST gauge difficulty is easier." # vCɂĉ when 40 @name = "Z̐S" @UK_name = "Hand Arts" @description = "You can now make full use of your hands through experience." when 41 @name = "Z̐S" @UK_name = "Tongue Arts" @description = "You're able to learn how to make good use of your tongue through experience." when 42 @name = "Z̐S" @UK_name = "Chest Arts" @description = "Through experience, you can now make full use of chest techniques." when 43 @name = "̐S" @UK_name = "Caress Arts" @description = "Through practice, you're now able to obtain mastery of caressing." when 44 @name = "s̐S" @UK_name = "Domme Arts" @description = "You can now master S skills." # vCɂĉ when 45 @name = "s̐S" @UK_name = "Sub Arts" @description = "You can now master M skills." # vCɂĉ when 46 @name = "̐S" @UK_name = "Sex Arts" @description = "You've learned to master the art of insertion through experience." when 47 @name = "ċz̐S" @UK_name = "Breath Mastery" @description = "Mastery of medication can now be obtained." # id [50..99] D\f when 50 @name = "ō̎p" @UK_name = "The Highest Form" @description = "This succubus is as strong as its fully evolved form." # NAbvO̖łA # ő僉N̏Ԃ̃Xe[^XƂČvZB when 51 @name = "" @UK_name = "Virgin" @description = "Still knows nothing of the taste of a woman." # vCɂĉ when 52 @name = "߂ĂD" @UK_name = "Ravished" @description = "You took the virginity of this succubus." when 53 @name = "" @UK_name = "Maiden" @description = "Has yet to become a woman." when 54 @name = "߂ĂDꂽ" @UK_name = "Virginity Taken" @description = "You gave your virginity to this succubus." # vCɂĉ when 55 @name = "V̏" @UK_name = "Heavenly Maiden" @description = "An eternal virgin." # t[[̑f when 56 @name = "L" @UK_name = "Futanari" @description = "A female that has parts." # vCɂĉ when 57 @name = "̎" @UK_name = "Motherly Bounty" @description = "Milk is flowing out of her breasts." # vCɂĉ when 60 @name = "" @UK_name = "Loving" @description = "This succubus really likes you..." when 61 @name = "؂Ȑl" @UK_name = "Trusting" @description = "There feels like something special between you and this succubus." when 70 @name = "z" # Y @UK_name = "Soul-sucking" @description = "When allowed to be on top, a small amount of hunger is satiated." when 71 @name = "TfBXg" @UK_name = "Sadist" @description = "Effects of S-attribute skills are increased." when 72 @name = "}]qXg" # Y @UK_name = "Masochist" @description = "Converts effects of incoming S-attribute skills to different effects." when 73 @name = "JX}" # Y @UK_name = "Charismatic" @description = "Have increased chances of being offered a contract after battle." when 74 @name = "V[Xgbv" @UK_name = "Stripteaser" @description = "When removing one's own clothes while the Mood is high, all enemies are rendered Horny." when 80 @name = "^tH[[" @UK_name = "Shapeshifter" @description = "Appears in battle disguised as a different succubus. Returns to original form when in CRISIS." # _[Cv̑fB̏ꍇAԌ̖̎pɂȂB when 81 @name = "̘Ag" # Y @UK_name = "Goblin Teamwork" @description = "During battle, can use yGoblin Leadershipz ith an ally." when 82 @name = "̓" # Y @UK_name = "Goblin Leadership" @description = "During battle, can use yGoblin Teamworkz ith an ally ith the same skill." when 83 @name = "d" # Y @UK_name = "Keen Eyes" @description = "Checks all enemies upon entering combat." when 91 @name = "ł̑̉t" # Y @UK_name = "Poisonous Fluids" @description = "Contact ith this succubus' fluids will produce an\n abnoral status effect." # lCWWfB when 92 @name = "" @description = "" # WFIfB when 93 @name = "mł鎩S" # Y @UK_name = "Unshakable Pride" @description = "Immune to status abnormalities." # trAfB when 94 @name = "ߕqȐg" # Y @UK_name = "Hypersensitive Body" @description = "Has become hypersensitive to pleasures of the flesh." # MS[fB when 95 @name = "" @description = "" # [KmbgfB when 96 @name = "ǂ" @UK_name = "Forereading" @description = "When having not yet acted yet this turn, become resistant to SS attacks." # VtFfB when 97 @name = "ώ" # Y @UK_name = "Obsession" @description = "This girl keeps looking at you..." # [~f # id [100..199] 퓬nf when 103 @name = "X^~i" @UK_name = "Stamina" @description = "The Weakened phase after climaxing is shorter." when 104 @name = "m" # Y @UK_name = "Cooking Knowledge" @description = "Can cook ingredients." when 105 @name = "@m" @UK_name = "Magic Knowledge" @description = "Magic consues less VP." when 106 @name = "G₷" # Y @UK_name = "Wet" @description = "Crotch gets wet easily. Increased lubrication rate." when 107 @name = "Gɂ" # Y @UK_name = "Prudish" @description = "Crotch lubrication rises slowly." when 108 @name = "" # Y @UK_name = "Calm Mind" @description = "Doesn't go Berserk easily." when 109 @name = "C" # Y @UK_name = "Vigorous" @description = "Doesn't becoe Lethargic easily." when 110 @name = "_" # Y @UK_name = "Courage" @description = "Doesn't becoe in Ae easily." when 111 # Ԉʒu @name = "" @description = "" when 112 @name = "_" # Y @UK_name = "Flexible" @description = "Doesn't get Paralyzed easily." when 113 @name = "S" # Y @UK_name = "Deterined" @description = "Doesn't become in Awe easily." when 114 @name = "S" # Y @UK_name = "Slimy Body" @description = "Well lubricated from the start of battle. Also easy to raise target's lubrication." # XCn̑fB when 115 @name = "veNV" # Y @UK_name = "Magic Ward" @description = "Iune to agical effects." # S[hXC̑fB when 116 @name = "ubLO" # Y @UK_name = "Blocking" @description = "When having not acted during turn, incoming pleasure is reduced." # K[SC̑fB when 117 @name = "" # Y @UK_name = "Thick Clothing" @description = "When still clothed, Agility falls but Endurance rises." # ^}̑fB when 118 @name = "Ɖu" # Y @UK_name = "Immunity" @description = "Immune to spore effects, and resistance to poison." when 120 @name = "g" # Y @UK_name = "Excited" @description = "Becoes Excited upon entering cobat." when 121 @name = "" # Y @UK_name = "Coposed" @description = "Becoes Coposed when entering cobat." when 122 @name = "y`" @UK_name = "Epicurian" @description = "Mood rises when attacked." when 123 @name = "}`Xg" # Y @UK_name = "Romantic" @description = "Deals even more damage when mood is high." when 124 @name = "n" # Y @UK_name = "Technique Mastery" @description = "Has a higher Sensual Stroke rate." when 125 @name = "Mߏ" @UK_name = "Superiority" @description = "Recovers from status abnormalities when this succubus makes the opposition climax." when 126 @name = "ŗ~" # Y @UK_name = "Greedy" @description = "When ally other than oneself climaxes, Charm and Vitality increase by 1 stage." when 127 @name = "XȍU" # Y @UK_name = "Relentless" @description = "Pleasure is not reduced as much from repeated use of the same skills." =begin when 128 @name = "b|" @description = "g[N̐オB" when 129 @name = "ۋC" @description = "܂ɑҋ@^[ɂȂB" =end when 130 @name = "@" # Y @UK_name = "Insight" @description = "Checks the target that one attacks." when 131 @name = "I" @UK_name = "Provocative" @description = "Upon entering cobat, 20 VP is consued to snatch the eneies' attention." when 132 @name = "{fBA}" @UK_name = "Seet Aroa" @description = "Upon entering cobat, 8 VP is consued, raising the ood by a little." when 133 @name = "fI" @UK_name = "Fascinating" @description = "When entering cobat, 40 VP is consued for a sall chance of rendering eneies Horny." when 134 @name = "T`FbN" # Y @UK_name = "Awesoe Presence" @description = "When entering cobat, 100 VP is consumed, rendering eneies in a Panicked state." when 135 @name = "̕ۏ" # Y @UK_name = "Peacekeeper" @description = "Recovery magic is more effective." when 136 @name = "obh`FC" # Y @UK_name = "Trick Chain" @description = "Lands attacks easier on targets ith 2 or more status abnoralities." when 140 @name = "ԕ" @UK_name = "Masturbator" @description = "Has a habit of masturbating a lot." when 141 @name = "t" @UK_name = "Cum addict" @description = "Has a copulsive habit of consuing semen." when 150 @name = "䖲" # Y @UK_name = "Desperado" @description = "Vitality rises when in CRISIS." when 151 @name = "΍RS" # Y @UK_name = "Copetitive" #rivalry? @description = "When there are less allies than eneies at the time of an ally's cliax, Vitality and Agility increases." when 152 @name = "S" @UK_name = "Self-control" @description = "Consumes 50 VP when made Horny - increasing Willpower adn removing the Horniness." when 153 @name = "̑̎" @UK_name = "Body of a Sex Deon" @description = "When Horny, recovers VP autoatically at the end of each turn." when 154 @name = "\" # Y @UK_name = "Berserker" @description = "When Berserk, Control and Spirit fall even ore, but Vitality rises substantially." when 160 @name = "LXXCb`" # Y @UK_name = "Kiss Sitch" @description = "Gets turned on when kissed." when 161 @name = "}]XCb`" @UK_name = "Masochist Sitch" @description = "Gets turned on when doinated." when 170 @name = "GNX^V[{" # Y @UK_name = "Ecstasy Bob" @description = "When cliaxing, render all allies except oneself into a Berserk state." when 171 @name = "̎" @UK_name = "Sealed" @description = "Cannot ove until pleasure is received, and is sealed again shortly afterwards even if seal was broken." # V[f[̑fB # id [100..199] Tnf when 210 @name = "doq[O" # Y @UK_name = "EP Recovery" @description = "Restores a sall amount of EP to the party after a victorious battle." when 211 @name = "uoq[O" # Y @UK_name = "VP Recovery" @description = "Restores all VP to the party after a victorious battle." when 212 @name = "񕜗" # Y @UK_name = "Resilient" @description = "EP Auto-regeneration is slightly increased." when 213 @name = "񕜗" # Y @UK_name = "Overfloing Resilience" @description = "EP Auto-regeneration is slightly increased for the whole party." when 214 @name = "" # Y @UK_name = "Energetic" @description = "VP Auto-regeneration is slightly increased." when 215 @name = "鐶" # Y @UK_name = "Overflowing Energy" @description = "VP Auto-regeneration is slightly increased for the whole party." when 220 @name = "op" # Y @UK_name = "Quick Learner" @description = "EXP gains are increased." when 221 @name = "NW" # Y @UK_name = "Collector" @description = "Item Drop chance is increased." when 222 @name = "^" # Y @UK_name = "Gold Digger" @description = "Increased Lps gains after battle." when 223 @name = "ւ̗" @UK_name = "Wind whispers" @description = "A dim marker is placed near hidden passages." when 224 @name = "_EWO" @UK_name = "Dowser" @description = "A marker appears on the map when you step over a hidden item." when 225 @name = "V[X^v" @UK_name = "Sealer" @description = "Reduces damage dealt to party from floor traps." when 226 @name = "_Eg" @UK_name = "Doubtful" @description = "Can detect Mimics beforehand." when 227 @name = "P̔" # Y @UK_name = "Ambusher" @description = "Increases chance of preeptive engagements when making\n contact ith an eney sprite." when 228 @name = "x̔" # Y @UK_name = "Sentry" @description = "Reduces the chance of the enemy getting a preemptive engagement on you." when 229 @name = "@" # Y @UK_name = "Dasher" @description = "Reduces chance of being preeptively engaged when\n contacting an eney while dashing." when 230 @name = "̋Ɉ" # Y @UK_name = "Escapist" @description = "Increased success rate of escape attempts." when 240 @name = "ۗǂ̎" # Y @UK_name = "Scavenger" @description = "Decreases the time it takes for collection." when 241 @name = "ڑ̎" # Y @UK_name = "Meticulous" @description = "Increases chance of rare items from collecting." when 300 @name = "\feXg" @UK_name = "Headhunter" @description = "\feXgłBhidden^̑f͕\܂" @hidden = true when 301 @name = "CT[g" # Y @UK_name = "Insert" @description = "z[hKς݊mFp" @hidden = true when 302 @name = "ANZvg" # Y @UK_name = "Accept" @description = "z[hKς݊mFp" @hidden = true when 303 @name = "VF}b`" # Y @UK_name = "Tribadism" @description = "z[hKς݊mFp" @hidden = true when 304 @name = "GLTCgr[" # Y @UK_name = "Facesit" @description = "z[hKς݊mFp" @hidden = true when 305 @name = "GuCX" # Y /z[h(Jr͏) @UK_name = "Embrace" @description = "z[hKς݊mFp" @hidden = true when 306 @name = "I[ZbNX" # Y /tF{Njp @UK_name = "Oral sex" @description = "z[hKς݊mFp" @hidden = true when 307 @name = "yXR[v" # Y /pCYz[h @UK_name = "Breast sex" @description = "z[hKς݊mFp" @hidden = true when 308 @name = "wu[tB[" # Y /ςӂςӃz[h @UK_name = "Heaven's feel" @description = "z[hKς݊mFp" @hidden = true when 309 @name = "tb^iCY" # Y /LbXz[h @UK_name = "Lock lips" @description = "z[hKς݊mFp" @hidden = true when 310 @name = "gChz[" # Y /Kgpn @UK_name = "Valley of the Gange" @description = "z[hKς݊mFp" @hidden = true when 311 @name = "AhMkX" # Y /yjXgpn @UK_name = "Androgynous" @description = "z[hKς݊mFp" @hidden = true when 312 @name = "eC}X^[" # Y /Kgpn @UK_name = "Tail Mastery" @description = "z[hKς݊mFp" @hidden = true when 313 @name = "e^N}X^[" # Y /Ggpn @UK_name = "Feeler Mastery" @description = "z[hKς݊mFp" @hidden = true when 314 @name = "CNCbvfBh" # Y /fBhn @UK_name = "Strapon Mastery" @description = "z[hKς݊mFp" @hidden = true when 315 @name = "ACB}X^[" # Y /ӎgpn @UK_name = "Vine Mastery" @description = "z[hKς݊mFp" @hidden = true when 320 @name = "AkX}[LO" # Y /K_ @UK_name = "Anal Marking" @description = "Can aim for the anus through Insertion hold." @hidden = true when 321 @name = "oCh}X^[" # Y /SZ @UK_name = "Restraint Mastery" @description = "Sz[h" @hidden = true when 332 @name = "s" # Y / @UK_name = "Awful Cook" @description = "̖͗łȂB" @hidden = true end end end #-------------------------------------------------------------------------- # f܂Ƃ #-------------------------------------------------------------------------- class Ability #-------------------------------------------------------------------------- # JCX^Xϐ #-------------------------------------------------------------------------- attr_accessor :data #-------------------------------------------------------------------------- # IuWFNg #-------------------------------------------------------------------------- def initialize @data = [] @max = 400 #f̓o^ for i in 0..@max @data[i] = Ability_registration.new(i) end end #-------------------------------------------------------------------------- # f̎擾 #-------------------------------------------------------------------------- def [](ability_id) return @data[ability_id] end #-------------------------------------------------------------------------- # f̌ # type : w variable : #-------------------------------------------------------------------------- def search(type, variable) case type when 0 # Ołhc for data in @data if data.name == variable n = data.id break end end end if n == nil text = "Ήhc܂łB" text += "\nȉ̂ƂmFĂB" text += "\nE뎚EiXNvgGfB^Sj" text += "\nEyztČĂȂ" text += "\nEf̏fID̐ȉłȂ" text += "\n[hF#{variable}" print text end return n end end end
true
7ea0c51f11f2326979086659500eb78f069572b2
Ruby
Mfbeeck/votersim
/lib/test_voter2.rb
UTF-8
2,044
3.828125
4
[]
no_license
class Politician attr_accessor :name, :party def initialize(name, party) @name = name @party = party end end # This version uses a "Campaign" class to hold the pieces. class Campaign # Instead of having separate runner code, the user prompts # are coded into the class. def display_main_menu puts "What would you like to do?" puts "Create, List, Update, or Vote" end def create puts "What would you like to create?" puts "Politician or Person" end def create_politician puts "Name?" # This rescue trick allows this code to run in SublimeText. name = gets.chomp rescue "Ed" puts "Party?" puts "Democrat or Republican" party = gets.chomp rescue "Democrat" politician = Politician.new(name, party) # This line is a bug we never got around to fixing. @politicians = [] @politicians << politician end def list_of_politicians @politicians end end # require 'minitest/autorun' # class TestVoterSim < Minitest::Test # def test_main_menu # votersim = Campaign.new # # You can assert that your code outputs the correct prompts. # assert_output("What would you like to do?\nCreate, List, Update, or Vote\n") do # votersim.display_main_menu # end # end # def test_create # votersim = Campaign.new # assert_output("What would you like to create?\nPolitician or Person\n") do # votersim.create # end # end # def test_create_politician # votersim = Campaign.new # assert_output("Name?\nParty?\nDemocrat or Republican\n") do # votersim.create_politician # end # politicians = votersim.list_of_politicians # assert_equal 1, politicians.length # politician = politicians.first # assert_equal "Ed", politician.name # assert_equal "Democrat", politician.party # end # end # Because we implement the prompts in the class, the # simulation runner code is very simple. campaign = Campaign.new campaign.display_main_menu campaign.create_politician
true