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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
af49eadc9a7701507261838d1e30af72b9389098 | Ruby | mitsu9/study_programming | /src/ALDS1/bubble_sort.rb | UTF-8 | 516 | 4.25 | 4 | [] | no_license | # バブルソート
def bubble_sort(ary, len)
swp = 0
len = len - 1
(0...len).each { |n|
(0...len-n).each { |j|
if ary[j] > ary[j+1]
ary[j], ary[j+1] = ary[j+1], ary[j] # swapの書き方
swp += 1
end
}
}
return ary, swp
end
# main
len = gets.to_i
ary = gets.split(' ').map(&:to_i) # 半角スペース区切りでintになおして配列に詰め込む
sorted_ary, swp = bubble_sort(ary, len)
puts sorted_ary.join(' ') # 半角スペース区切りで出力
puts swp
| true |
28d196b096a315f0acbe4c39d6cf0a9aea0c5647 | Ruby | eminnett/sample-shopping-cart | /lib/shopping_cart.rb | UTF-8 | 1,642 | 3.265625 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'validations'
require_relative 'basket'
require_relative 'catalogue'
require_relative 'delivery_cost_schedule'
require_relative 'offer'
# The core shopping cart entity that has a catalogue, set of delivery charges, available offers.
# Products can be added and put in a basket. The shopping cart calulates the total cost of an order
# taking both available offers and delivery into account.
class ShoppingCart
CURRENCY = '£'
attr_reader :catalogue, :delivery_cost_schedule, :offers, :basket
def initialize(catalogue:, delivery_cost_schedule:, offers: [])
@catalogue = catalogue
@delivery_cost_schedule = delivery_cost_schedule
@offers = offers
@basket = Basket.new
validate_parameters
end
def add(product_code)
message = 'Only products in the catalogue can be added to the shopping cart.'
Validations.ensure_argument(catalogue.includes_code?(product_code), message)
basket.add catalogue.product_by_code product_code
end
def empty!
basket.empty!
end
alias << add
def total
basket_total = basket.total(offers: offers)
shipping = delivery_cost_schedule.delivery_cost(amount_spent: basket_total)
# Round down to the nearest penny.
total_cost = format('%.2f', ((basket_total + shipping) * 100).floor / 100.0)
"#{CURRENCY}#{total_cost}"
end
private
def validate_parameters
Validations.ensure_is_a(catalogue, 'catalogue', Catalogue)
Validations.ensure_is_a(delivery_cost_schedule, 'delivery_cost_schedule', DeliveryCostSchedule)
Validations.ensure_is_an_array_of(offers, 'offers', Offer)
end
end
| true |
05cd8600f5f94e876ad4cf6b84bb121dc65f3649 | Ruby | victorvitalino/platform | /components/brb/app/models/brb/barcode.rb | UTF-8 | 3,579 | 2.640625 | 3 | [
"MIT"
] | permissive | module Brb
class Barcode
include ActiveModel::Model
# capitulo 1 - composição da chave
#váriveis bancárias
attr_accessor :bank, :bank_agency, :bank_account, :bank_wallet
#variaveis de execução
attr_accessor :sequential, :due, :value
#variaveis de calculo
attr_accessor :key_digit_one, :key_digit_two
#variaveis de configuração
attr_accessor :coin
DATE_CORRECTION = "03/07/2000" #Essa data é para criação do fator vencimento, capitulo 7
def initialize(options = {})
#valores padrão do manual
@bank_wallet = options[:bank_wallet] ||= '1'
@sequential = options[:sequential] ||= '1'
@bank = options[:bank] ||= '070'
@bank_agency = options[:bank_agency] ||= '058'
@bank_account = options[:bank_account] ||= '6002006'
@due = options[:due] ||= '0'
@coin = options[:coin] ||= '9'
@value = options[:value] ||= 100
end
#agência / código do beneficário
def agency_and_benefict_code_formated
"000 - #{@bank_agency} - #{@bank_account}"
end
def agency_and_benefict_code
"000#{@bank_agency}#{@bank_account}"
end
# nosso número
def our_number
#carteira direta com registro NOSSO NUMERO = 2
set_key_digits
"#{@bank_wallet}#{self.formated_sequential}#{@bank}#{@key_digit_one}#{@key_digit_two}"
end
def document_number
"#{self.formated_sequential}"
end
def key
"#{agency_and_benefict_code}#{our_number}"
end
def barcode_without_digit
"#{@bank}#{@coin}#{self.due_factor}#{self.value_factor}#{self.key}"
end
def barcode_with_digit
"#{@bank}#{@coin}#{self.barcode_digit}#{self.due_factor}#{self.value_factor}#{self.key}"
end
def barcode_without_format
"#{self.group_one}#{self.group_one.to_s.module_10}" \
"#{self.group_two}#{self.group_two.to_s.module_10}" \
"#{self.group_three}#{self.group_three.to_s.module_10}" \
"#{self.barcode_digit}#{self.due_factor}" \
"#{self.value_factor}"
end
def barcode_with_format
"#{self.barcode_without_format[0..4]}.#{self.barcode_without_format[5..9]} " \
"#{self.barcode_without_format[10..14]}.#{self.barcode_without_format[15..20]} " \
"#{self.barcode_without_format[21..25]}.#{self.barcode_without_format[26..31]} " \
"#{self.barcode_without_format[32]} " \
"#{self.barcode_without_format[33..46]}"
end
def group_one
"#{@bank}#{@coin}#{self.key[0..4]}"
end
def group_two
"#{self.key[5..14]}"
end
def group_three
"#{self.key[15..25]}"
end
def group_four
"#{@due_factor}#{@value_factor}"
end
#formating variables
def formated_sequential
"#{'%06d' % @sequential.to_i}"
end
private
def set_key_digits
digit = "#{self.agency_and_benefict_code}#{@bank_wallet}#{self.formated_sequential}#{@bank}".calculate!
@key_digit_one = digit[:digit_one]
@key_digit_two = digit[:digit_two]
end
protected
def barcode_digit
barcode = self.barcode_without_digit
barcode.module_11({multiplier: [2,3,4,5,6,7,8,9]})
end
def due_factor
if @due.class == Date
(@due - Date.parse(DATE_CORRECTION)).to_i + 1000
else
"0000"
end
end
def value_factor
value = sprintf('%.2f', @value)
"#{'%010d' % value.to_s.gsub('.','').to_i}"
end
end
end | true |
eda9cd5788e972f9bc5012f2d32dbd858058f646 | Ruby | DarkBones/Stishly | /test/system/users_test.rb | UTF-8 | 3,787 | 2.546875 | 3 | [] | no_license | require 'application_system_test_case'
class UsersTest < ApplicationSystemTestCase
test 'visit the index' do
"""
Go the the root path
Expected result:
- See welcome screen
- See link to sign up
- See link to sign in
"""
visit root_path
assert_selector 'h1', text: "Sign Up"
assert_selector '.navbar-nav', text: I18n.t('views.devise.shared.buttons.sign_up.text')
assert_selector '.navbar-nav', text: I18n.t('views.devise.shared.buttons.sign_in.text')
end
test 'create user account' do
"""
Create a user account
Expected result:
- Not able to create the account when not filling in the form completely
- Abe to create the account after filling in the form completely
"""
# form fields to be filled in
form_fields = [
{
type: 'text',
name: I18n.t('helpers.label.user.first_name'),
value: 'System'
},
{
type: 'text',
name: I18n.t('helpers.label.user.last_name'),
value: 'Test'
},
{
type: 'text',
name: I18n.t('helpers.label.user.email'),
value: 'system_test@example.com'
},
{
type: 'text',
name: I18n.t('helpers.label.user.password'),
value: 'Fallout76IsAGem^!'
},
{
type: 'text',
name: I18n.t('helpers.label.user.password_confirmation'),
value: 'Fallout76IsAGem^!'
}
]
# Fill in the registration form, ommitting one field each time. On the final run, it will fill in all the details
for i in 0..form_fields.length do
visit root_path
all('a', :text => I18n.t('views.devise.shared.buttons.sign_up.text'))[0].click
form_fields.each_with_index do |f, idx|
if idx != i
if f[:type] == 'text'
fill_in f[:name], with: f[:value]
else
select f[:value], from: f[:name]
end
end
end
find('button[type="submit"]').click
if i < form_fields.length
assert_selector 'h2', text: I18n.t('views.shared.errors.form')
else
assert_selector '#flash_notice', text: I18n.t('devise.registrations.signed_up')
end
end
end
test 'log in as blank' do
"""
Login as a user, then log out again
Expected result:
- See notification that sign in was successful
- See notification that the logout was successful
- See welcome screen
- See sign up / sign in links
"""
login_user(users(:bas), 'SomePassword123^!')
assert_selector '#flash_notice', text: I18n.t('devise.sessions.signed_in')
assert_selector '.navbar-nav', text: I18n.t('views.devise.shared.buttons.sign_up.text') == false
assert_selector '.navbar-nav', text: I18n.t('views.devise.shared.buttons.sign_in.text') == false
page.find('.navbar-gear').click
click_on 'Sign Out'
assert_selector '#flash_notice', text: I18n.t('devise.sessions.signed_out')
assert_selector '.navbar-nav', text: I18n.t('views.devise.shared.buttons.sign_up.text')
assert_selector '.navbar-nav', text: I18n.t('views.devise.shared.buttons.sign_in.text')
end
test 'destroy account' do
"""
Login as a user, and delete the account
Expected result:
- See notification that sign in was successful
- See notification that account was cancelled
- See welcome screen
- See sign up / sign in links
- Get an error when trying to log in again
"""
login_user(users(:destroy), 'SomePassword123^!')
page.find('.navbar-gear').click
click_on "Edit Account"
click_on "Delete My Account"
page.driver.browser.switch_to.alert.accept
assert_selector '#flash_notice', text: I18n.t('devise.registrations.destroyed')
login_user(users(:destroy), 'SomePassword123^!')
assert_selector '#flash_alert', text: I18n.t('devise.failure.not_found_in_database')
end
end | true |
25f36e6d446f9580fc7d38a073981e7b2a956f85 | Ruby | barunecka/advent_of_code_2018 | /day_2/calculate_checksum_for_box_ids.rb | UTF-8 | 764 | 3.453125 | 3 | [] | no_license | class CalculateChecksumForBoxIds
def initialize(list_of_ids)
@list_of_ids = list_of_ids
@two_letter_id_boxes = Array.new
@three_letter_id_boxes = Array.new
end
def call
sort_boxes_by_id
print_checksum(calculate_checksum)
end
private
attr_accessor :list_of_ids, :two_letter_id_boxes, :three_letter_id_boxes
def sort_boxes_by_id
list_of_ids.each do |word|
box_id = BoxId.new(word)
three_letter_id_boxes << word if box_id.contains_threes?
two_letter_id_boxes << word if box_id.contains_twos?
end
end
def calculate_checksum
three_letter_id_boxes.count * two_letter_id_boxes.count
end
def print_checksum(checksum)
puts "Checksum for current list of box IDs is: #{checksum}"
end
end
| true |
375081cce6d277d63b7f840a3b78d2bce9985295 | Ruby | matus-tomlein/ics_parser | /lib/event_parser.rb | UTF-8 | 3,273 | 3.296875 | 3 | [] | no_license | require 'ostruct'
require 'time'
class EventParser
def initialize(calendar_content)
@calendar_content = calendar_content
end
def events
events = []
get_events_in_calendar.each do |event|
summary = parse_summary event
starts_at = parse_starts_at event
ends_at = parse_ends_at event
if recurring_event? event
recurring_dates = parse_recurring_dates(event)
recurring_dates.each do |recurring_starts_at, recurring_ends_at|
events << new_event(summary,
recurring_starts_at,
recurring_ends_at)
end
else
events << new_event(summary,
starts_at,
ends_at)
end
end
events
end
private
def new_event(summary, starts_at, ends_at)
OpenStruct.new(summary: summary,
starts_at: starts_at,
ends_at: ends_at)
end
def get_events_in_calendar
beginnings = @calendar_content.split('BEGIN:VEVENT')
events = []
beginnings.each do |event_beginning|
next unless event_beginning.include? 'END:VEVENT'
events << event_beginning.split('END:VEVENT').first
end
events
end
def parse_summary(event)
/SUMMARY:(.*)/.match(event)[1].strip
end
def parse_starts_at(event)
Time.parse(/DTSTART[\w\/=;\s]*:(\d+T\d+)/.match(event)[1])
end
def parse_ends_at(event)
Time.parse(/DTEND[\w\/=;\s]*:(\d+T\d+)/.match(event)[1])
end
def recurring_event?(event)
event.include? 'RRULE:FREQ=WEEKLY;'
end
def parse_recurring_dates(event)
recurring_dates = {}
starts_at = parse_starts_at event
ends_at = parse_ends_at event
summary = parse_summary event
if event.include? 'RRULE:FREQ=WEEKLY;COUNT='
count = /RRULE:FREQ=WEEKLY;COUNT=(\d+)/.match(event)[1].to_i
count.times do |i|
recurring_starts_at = add_days_to_time(starts_at, i * 7)
recurring_ends_at = add_days_to_time(ends_at, i * 7)
unless is_date_excluded?(recurring_starts_at, event)
recurring_dates[recurring_starts_at] = recurring_ends_at
end
end
elsif event.include? 'RRULE:FREQ=WEEKLY;UNTIL='
until_time = Time.parse(/RRULE:FREQ=WEEKLY;UNTIL=(\d+T\d+)/.match(event)[1])
last_starts_at = starts_at
last_ends_at = ends_at
while last_starts_at <= until_time
unless is_date_excluded?(last_starts_at, event)
recurring_dates[last_starts_at] = last_ends_at
end
last_starts_at = add_days_to_time(last_starts_at, 7)
last_ends_at = add_days_to_time(last_ends_at, 7)
end
else
raise "Unsupported recurring event type: #{summary}"
end
recurring_dates
end
def is_date_excluded?(date, event)
date_str = date.strftime '%Y%m%dT%I%M%S'
not_excluded = /EXDATE[\w\/=;]*:#{date_str}/.match(event).nil?
!not_excluded
end
def add_days_to_time(time, days)
new_time = time + (days * 24 * 60 * 60)
# required to keep the same hour after summer/winter time change
if time.hour > new_time.hour
new_time + 60 * 60
elsif time.hour < new_time.hour
new_time - 60 * 60
else
new_time
end
end
end
| true |
02502a33412f5db6d544b1503afa1c04eedeaada | Ruby | deniseyu/FAAST-challenge | /spec/passenger_spec.rb | UTF-8 | 818 | 2.890625 | 3 | [] | no_license | require './lib/spec_helper'
require './lib/passenger'
require './lib/station'
describe Passenger do
let(:passenger) { Passenger.new }
let(:station) { double :station }
it "should have balance in his wallet" do
expect(passenger.wallet_balance).to_not eq 0
end
it "should be able to pay for a trip when tapping in" do
expect{ passenger.tap_in }.to change{passenger.wallet_balance}.by -2
end
it "should be able to know when it has paid for a trip" do
expect{ passenger.tap_in }.to change{passenger.paid?}.to eq true
end
it "should be able to tap out of a station" do
passenger.tap_in
expect{ passenger.tap_out }.to change{passenger.paid?}.to eq false
end
it "should be able to add balance to wallet" do
expect{ passenger.top_up(10) }.to change{passenger.wallet_balance}.by 10
end
end
| true |
0519166eb6b8526fa0cfc6349bcff08fbf980dd0 | Ruby | afshinator/playground | /Ruby-BuildingBlocks/building_blocks_spec.rb | UTF-8 | 2,474 | 3.6875 | 4 | [] | no_license | # # Odin Project - Ruby >> Basic Ruby >> Project: Building Blocks & Advanced Building Blocks
#
# http://www.theodinproject.com/curriculum/ruby/basic_ruby/project_building_blocks.md
#
# Afshin Mokhtari
#
require "building_blocks"
describe "==>Building Blocks Warmup: Word Counter" do
describe "#Given example" do
it "deals with given case" do
histogram("the rain in Spain falls mainly on the plain").should == [["the", 2], ["falls",1], ["mainly", 1], ["on", 1], ["Spain", 1], ["in", 1], ["rain", 1], ["plain", 1]]
end
end
describe "#My tests" do
it "deals with 3 instances" do
histogram("my pain pain pain my reframe").should == [["pain", 3], ["my", 2], ["reframe", 1]]
end
end
end
describe "==>Building Blocks Project 1: Caesar Cipher" do
describe "#Given example" do
it "deals with given case" do
caesar_cipher("What a string!", 5).should == "Bmfy f xywnsl!"
end
end
describe "#My tests" do
it "deals with shift of nothing!" do
caesar_cipher("What a string!", 0).should == "What a string!"
end
it "deals with backward shift" do
caesar_cipher("What a string!", -1).should == "Vgzs z rsqhmf!"
end
end
end
describe "==>Building Blocks Project 2: Stock Picker" do
describe "#Given example" do
it "deals with given case" do
stock_picker([17,3,6,9,15,8,6,1,10]) == [1,4]
end
it "deals with edge case: lowest day is last day" do
stock_picker([3,6,7,15,2]) == [0,3]
end
it "deals with edge case: highest day is first day" do
stock_picker([15,3,6,7,4]) == [1,3]
end
end
describe "#My tests" do
it "deals with no gain periods" do
stock_picker([5,4,3,2,1]).should == [0,0]
end
it "deals with constant gain periods" do
stock_picker([5, 10, 15, 20, 25]).should == [0,4]
end
it "deals with the only gain period in the range" do
stock_picker([1,1,1,1,1,2,1,1,1]).should == [0,5]
end
end
end
describe "==>Building Blocks Project 3: Substrings" do
describe "#Given example" do
it "deals with given case" do
dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"]
substrings("below", dictionary).should == {"below"=>1, "low"=>1}
end
end
describe "#My tests" do
it "deals with small dictionary" do
dictionary = ["below"]
substrings("below", dictionary).should == { "below" => 1 }
end
it "deals with empty dictionary" do
dictionary = []
substrings("below", dictionary).should == { }
end
end
end
| true |
0c8e4f71ce97fe1ac77b72cec50f2d2034c60df3 | Ruby | Jakintero/sinatra-intro | /challenges/1-CRUD/sinatra-mvc-skeleton/app/controllers/notes_controller.rb | UTF-8 | 851 | 2.671875 | 3 | [] | no_license |
#Index
get '/' do
@notes = Note.all
erb :index
end
#New
get '/notes/new' do
erb :new
end
#Show
get '/notes/:id' do
@note = Note.find_by(id: params[:id])
erb :show
end
#Create
post '/notes' do
@note = Note.new(name: params[:name], description: params[:description], quantity: params[:quantity])
if @note.save
redirect "/notes/#{@note.id}"
else
erb :new
end
end
#Edit
get '/notes/:id/edit' do
@note = Note.find_by(id: params[:id])
erb :edit
end
#Update
patch '/notes/:id' do
note = Note.find_by(id: params[:id])
note.update(name: params[:name], description: params[:description], quantity: params[:quantity])
redirect "/notes/#{note.id}" #Por qué funciona si le quito el @
end
#Destroy
get '/notes/:id/delete' do
@note = Note.find_by(id: params[:id])
@note.destroy
redirect '/'
end
| true |
dec4620ec570b2a219f0fe9c0938dd6d6870545b | Ruby | viditn91/vinsol-training | /Ruby_exercise/Interest_Difference/main/main.rb | UTF-8 | 275 | 3.109375 | 3 | [] | no_license | require_relative '../lib/interest.rb'
puts "enter principal_"
principal = gets.chomp
puts "enter time period_"
time = gets.chomp
interests = Interest.new { [principal.to_i, time.to_i ] }
p "The difference between Simple and Compound Interest is #{ interests.get_difference }" | true |
1af5ba0fbcb02f7a5a49367459a6e39b4a60744c | Ruby | anamsoomro/my-collect-houston-web-012720 | /lib/my_collect.rb | UTF-8 | 501 | 3.84375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def my_collect(array)
#collect modifies the given array
i = 0
result = []
while i < array.length do
# yield (array[i])
# result << array[i]
# this is shoveling in the unoperated element
# I need to shovel in the operated element
# whatever I shovel needs to have yield called on it
result << yield(array[i])
i += 1
end
result
end
# array = [4,4,6]
# puts my_collect(array) {|iteration| iteration + 2 } | true |
e0acfc34c2e2c43e267d54acb85d7d47ffbe2278 | Ruby | AndersonNguyen1/CodeEval | /armstrong_numbers.rb | UTF-8 | 224 | 3.28125 | 3 | [] | no_license | File.open(ARGV[0]).each_line do |line|
a = line.strip.split ''
sum = 0
a.each do |character|
sum += character.to_i ** a.length
end
if sum.to_s == line.strip
puts 'True'
else
puts 'False'
end
end
| true |
1726052c737ac15215526ac93ad83baac9225b33 | Ruby | tilo/smarter_logging | /lib/smarter_logging/anomaly_logger.rb | UTF-8 | 390 | 2.65625 | 3 | [
"MIT"
] | permissive | module SmarterLogging
class AnomalyLogger < BaseLogger
def log(unique_identifier, data, &block)
data = {:anomaly => unique_identifier}.merge( data )
_log_wrapper(data, &block)
end
def _log(data)
# If activity logging broke, make sure we log it as an anomaly:
data[:anomaly] = data.delete(:activity) if data[:activity]
super
end
end
end
| true |
967696a4908534b7d82a9487d9e513a2c90b6be4 | Ruby | voke/payson_api | /lib/payson_api/shipping_address.rb | UTF-8 | 1,146 | 2.921875 | 3 | [
"MIT"
] | permissive | require 'cgi'
module PaysonAPI
class ShippingAddress
FORMAT_STRING = "shippingAddress.%s"
attr_accessor :name, :street_address, :postal_code, :city, :country
def initialize(name, street_address, postal_code, city, country)
@name = name
@street_address = street_address
@postal_code = postal_code
@city = city
@country = country
end
def to_hash
{}.tap do |hash|
hash[FORMAT_STRING % 'name'] = @name
hash[FORMAT_STRING % 'streetAddress'] = @street_address
hash[FORMAT_STRING % 'postalCode'] = @postal_code
hash[FORMAT_STRING % 'city'] = @city
hash[FORMAT_STRING % 'country'] = @country
end
end
def self.parse(data)
return unless data[FORMAT_STRING % 'name']
name = CGI.unescape(data[FORMAT_STRING % 'name'].to_s)
street_address = CGI.unescape(data[FORMAT_STRING % 'streetAddress'].to_s)
postal_code = CGI.unescape(data[FORMAT_STRING % 'postalCode'].to_s)
city = CGI.unescape(data[FORMAT_STRING % 'city'].to_s)
country = CGI.unescape(data[FORMAT_STRING % 'country'].to_s)
self.new(name, street_address, postal_code, city, country)
end
end
end
| true |
2c9bd2a56bf948e872c59270638c996efeafdf5e | Ruby | oumiya/click_rpg | /scripts/Scene_Box.rb | UTF-8 | 8,675 | 2.84375 | 3 | [] | no_license | require_relative 'Scene_Base.rb'
require_relative 'Scene_Home.rb'
require_relative 'Message_Box.rb'
require_relative 'Wave_Result.rb'
require_relative 'Paper_Snow.rb'
# 戦闘結果シーンクラス
class Scene_Box < Scene_Base
def initialize(result)
@result = result
# 背景画像読み込み
@background = nil
case $dungeon_id
when 1
@background = Image.load("image/background/cave.jpg")
when 2
@background = Image.load("image/background/forest.jpg")
when 3
@background = Image.load("image/background/mansion.jpg")
when 4
@background = Image.load("image/background/volcano.jpg")
when 5
@background = Image.load("image/background/ice_world.jpg")
when 6
@background = Image.load("image/background/castle.jpg")
else
# 一応、入れておく
@background = Image.load("image/background/cave.jpg")
end
# 宝箱画像
@box_image = Image.load("image/enemy/box.png")
# 紙吹雪
@paper_snow = Paper_Snow.new
# You're Winner!画像
@youre_winner = Image.load("image/system/yourewinner.png")
@font = Font.new(18)
@next_scene = nil
@show_message_box = false
end
# ループ前処理 例えばインスタンス変数の初期化などを行う
def start()
$bgm.each{|bgm_name, bgm_ayame|
bgm_ayame.stop(1)
}
$sounds["box"].play(1, 0)
if @result.result then
$sounds["wave_win"].play(1, 0)
end
@wait_frame = 180
if $player.cleared then
@result.exp *= 2
@result.gold *= 2
end
@message = @result.exp.to_s + "の経験値を獲得!<br>"
$player.exp += @result.exp
if $player.level_up? then
@message += "レベルが上がった!<br>"
end
@message += @result.gold.to_s + "ゴールドを獲得!<br>"
$player.gold += @result.gold
@item_name = ""
if @result.result == true then
item_drop() # 必ず1個は当たる
end
if $player.cleared == true then
for i in 0..@result.battle_count do
item_drop()
end
else
for i in 0..@result.battle_count do
if rand(8) == 0 then
item_drop()
end
end
end
@message += @item_name
# 街づくり収入
if $player.income > 0 then
income = $player.income * @result.battle_count
$player.gold += income
@message += income.to_s + "ゴールドの税収を獲得!<br>"
end
end
# 画面描画処理
def draw()
# 背景画像の描画
Window.draw(0, 0, @background)
# 宝箱画像の描画
Window.draw(230, 70, @box_image)
if @result.result then
# 紙吹雪の描画
@paper_snow.draw
# You're Winner!の描画
Window.draw(320, 18, @youre_winner)
end
Message_Box.show(@message, -1, -1, @font)
if @show_message_box then
Message_Box.show("街へ戻る", -1, 415, @font)
end
end
# フレーム更新処理
def update()
@paper_snow.update
# 指定のフレーム数ウェイト
if @wait_frame > 0 then
@wait_frame -= 1
return
end
@show_message_box = true
# キー入力待ち
if Input.mouse_push?(M_LBUTTON) || Input.pad_push?($attack_button) then
@next_scene = Scene_Home.new
end
end
# ループ後処理
def terminate()
end
# 次のシーンに遷移
# 遷移しない場合は nil を返す
def get_next_scene()
return @next_scene
end
def item_drop()
# 武器か防具の抽選
drop_item = rand(2) # 0 なら武器 1 なら防具
# ゴミ、ノーマル、レア、スーパレアの抽選
idx = rand(100)
if idx < 40
idx = 0
elsif idx < 70
idx = 1
elsif idx < 90
idx = 2
else
idx = 3
end
idx = ($dungeon_id - 1) * 4 + idx
# ボーナスの抽選
# まずボーナスがつくかどうか(ボーナスは50%の確率で付与)
lottery = rand(100)
bonus = 0
if lottery < 50 then
# ボーナス値の抽選
lottery = rand(100) + 1
if lottery >= 96
bonus = 10
elsif lottery >= 91
bonus = 9
elsif lottery >= 85
bonus = 8
elsif lottery >= 78
bonus = 7
elsif lottery >= 70
bonus = 6
elsif lottery >= 61
bonus = 5
elsif lottery >= 51
bonus = 4
elsif lottery >= 40
bonus = 3
elsif lottery >= 29
bonus = 2
else
bonus = 1
end
end
# 属性の抽選
# 属性について 0:無は空文字 1:火属性 2:氷属性 3:土属性 4:風属性 5:光属性 6:闇属性
# まず属性がつくかどうか(属性は65%の確率で付与)
lottery = rand(100)
element = ""
if drop_item == 0 then
element = $weapondata.get_weapon_data(idx)[:element]
else
element = $armordata.get_armor_data(idx)[:element]
end
if lottery < 65 then
# 属性が無属性の時は属性を付与する
if element.empty? then
lottery = rand(6) + 1
if lottery == 1 then
element = "火"
end
if lottery == 2 then
element = "氷"
end
if lottery == 3 then
element = "土"
end
if lottery == 4 then
element = "風"
end
if lottery == 5 then
element = "光"
end
if lottery == 6 then
element = "闇"
end
end
end
# 武器の場合のみスキルの抽選
skill = -1
skill = $weapondata.get_weapon_data(idx)[:skill]
if drop_item == 0 && skill < 0 then
# スキルの付与は 40%
lottery = rand(100)
if lottery < 40 then
lottery = rand(100)
if lottery < 11 then
skill = 0
elsif lottery < 22 then
skill = 1
elsif lottery < 33 then
skill = 2
elsif lottery < 44 then
skill = 3
elsif lottery < 55 then
skill = 4
elsif lottery < 66 then
skill = 5
elsif lottery < 77 then
skill = 6
elsif lottery < 88 then
skill = 7
else
skill = 8
end
end
end
# 防具の場合のみ自動回復の抽選
heal = 0
heal = $armordata.get_armor_data(idx)[:heal]
if drop_item == 1 && heal < 1 then
# 防具の自動回復は10%の確率で付与 戦闘毎10% ~ 戦闘毎100% まで
lottery = rand(100)
if lottery < 10 then
lottery = rand(100) + 1
if lottery >= 96
heal = 10
elsif lottery >= 91
heal = 9
elsif lottery >= 85
heal = 8
elsif lottery >= 78
heal = 7
elsif lottery >= 70
heal = 6
elsif lottery >= 61
heal = 5
elsif lottery >= 51
heal = 4
elsif lottery >= 40
heal = 3
elsif lottery >= 29
heal = 2
else
heal = 1
end
end
end
if drop_item == 0 then
# ドロップ武器の名前生成
reward_name = $weapondata.get_weapon_data(idx)[:name]
if bonus > 0 then
reward_name += "+" + bonus.to_s
end
if element != "" then
reward_name = reward_name + "(" + element + ")"
end
# 実攻撃力の計算
value = $weapondata.get_weapon_data(idx)[:value]
if bonus > 0 then
value_bonus = value / 10
value += value_bonus * bonus
end
# 所持品を追加
$player.add_weapon(idx, reward_name, element, bonus, value, skill)
@item_name += reward_name + "を手に入れた!<br>"
else
# ドロップ防具の名前を生成
reward_name = $armordata.get_armor_data(idx)[:name]
if bonus > 0 then
reward_name += "+" + bonus.to_s
end
if element != "" then
reward_name = reward_name + "(" + element + ")"
end
if heal > 0 then
reward_name = reward_name + "H" + heal.to_s
end
# 実防御力の計算
value = $armordata.get_armor_data(idx)[:value]
if bonus > 0 then
value_bonus = value / 10
value += value_bonus * bonus
end
# 所持品にドロップ防具を追加
$player.add_armor(idx, reward_name, element, bonus, heal, value)
@item_name += reward_name + "を手に入れた!<br>"
end
end
end
| true |
ddd20e6dfb1f086b8324b5d3d35cd99d059cd20d | Ruby | ericzhonghou/fa15-hw2 | /app/controllers/pages_controller.rb | UTF-8 | 575 | 2.796875 | 3 | [] | no_license | class PagesController < ApplicationController
def home
foo = Foobar.new "baz"
@baz = foo.bar :cat, sat: :dat, dat: :sat
end
def stringify
@text = "You are nothing!"
name = params[:name]
adj = params[:adjective]
@string = @text
if !(name.empty? or adj.empty?)
@string = "#{name} is so #{adj}"
end
end
def age
puts age
end
def person
name = params[:name]
age = params[:age]
a = Person.new(name, age)
@introduce = a.introduce
@birth = a.birthyear
@nick = a.nickname
puts "person"
end
end
| true |
c50e06d3a22b96ae2f3a88b427f7ee772116b099 | Ruby | timtan93/week-1-group-review-london-web-121018 | /review-question-3.rb | UTF-8 | 1,097 | 3.46875 | 3 | [] | no_license | # begin to build a simple program that models Instagram
# you should have a User class, a Photo class and a comment class
class User
attr_accessor :name, :photos
def initialize(name)
@name = name
@photos = []
end
def photos
@photos
end
end
class Photo
attr_accessor :user
def initialize
end
def user
@user.photos << self
@user
end
def make_comment (comment)
@comment = Comment.new(comment)
Comment.all << @comment
end
def comments
@comment
end
end
class Comment
attr_accessor :comment, :photo
@@all = []
def self.all
@@all
end
def initialize(comment)
@comment = comment
end
end
sandwich_photo = Photo.new
sophie = User.new("Sophie")
sandwich_photo.user = sophie
sandwich_photo.user.name
# => "Sophie"
user.photos
# => [#<Photo:0x00007fae2880b370>]
sandwich_photo.comments
# => []
sandwich_photo.make_comment("this is such a beautiful photo of your lunch!! I love photos of other people's lunch")
sandwich_photo.comments
# => [#<Comment:0x00007fae28043700>]
Comment.all
#=> [#<Comment:0x00007fae28043700>]
| true |
c47b8da8556ae351b748385c9c1235af6f1a5039 | Ruby | joshnevius/orlando-tech-meetups-cli-gem | /lib/orlando_tech_meetups/cli.rb | UTF-8 | 1,073 | 3.25 | 3 | [
"MIT"
] | permissive | class OrlandoTechMeetups::CLI
def call
list_meetups
menu
end
def menu
input = nil
while input != "exit"
input = gets.strip.downcase
if input.to_i > 0
the_group = @meetups[input.to_i-1]
puts "#{the_group.name}"
puts "The next meetup is: #{the_group.next_meetup}"
puts "To create a new meetup group, copy and paste the link below into Chrome or Firefox..."
puts "Internet Explorer is not a browser. It's a mistake."
puts "#{the_group.url}"
puts "To go back to the menu, enter 'menu'. To exit, type 'exit'."
elsif input == "menu"
meetup
else
puts "Hope to see you soon!"
end
end
end
def list_meetups
puts "Hello and Welcome to the Orlando Tech Scene!"
puts "Loading meetups"
meetup
puts "Enter the number of the meetup group you're interested in going to:"
end
def meetup
@meetups = OrlandoTechMeetups::Meetups.all
@meetups.each.with_index(1) do |meetup, i|
puts "#{i}. #{meetup.name}"
end
end
end | true |
383e96340ac802d53e563272cadbcca22f49cc9e | Ruby | johnkchow/cached_record | /lib/cached_record/store/block_collection.rb | UTF-8 | 7,921 | 2.640625 | 3 | [
"MIT"
] | permissive | class CachedRecord
class Store
class BlockCollection
include Util::Assertion
attr_reader :header, :store_adapter, :order, :block_size, :data_fetcher
def initialize(header_key,
store_adapter:,
data_fetcher:,
order:,
block_size: CachedRecord.config.block_size)
@store_adapter = store_adapter
@data_fetcher = data_fetcher
@block_size = block_size
@order = order.to_sym
@header_key = header_key
@header = get_header(header_key)
end
def total_count
@header.total_count
end
def items(offset:, limit:)
block_keys, start_index = header.block_keys_for_offset_limit(offset, limit)
blocks = get_blocks(block_keys)
# TODO: instead of concat, let's precalculate the returned
# size from the meta data in the header block
items = []
items_left = limit
first_block = blocks.first
items.concat(first_block.values[start_index, items_left])
items_left = limit - (first_block.count - start_index)
blocks[1..-1].each do |block|
items.concat(block.values[0, items_left])
items_left -= block.count
end
items
end
def insert(meta_key, key, value)
found_meta_block = nil
if header.empty_blocks?
found_meta_block, block = create_new_block(meta_key, key, value)
item_index = 0
persist_block!(block)
else
meta_blocks = header.meta_blocks
if meta_blocks.first.can_insert_before?(key)
found_meta_block, block = create_new_block(meta_key, key, value)
item_index = 0
persist_block!(block)
else
# NOTE: do binary search instead of linear
meta_blocks.each_with_index do |meta_block, i|
next_meta_block = meta_blocks[i + 1]
if meta_block.include_key?(key)
found_meta_block, block, item_index = insert_within_block!(meta_block, meta_key, key, value)
break
elsif !meta_block.full? && (!next_meta_block || next_meta_block.can_insert_before?(key))
found_meta_block, block, item_index = insert_within_block!(meta_block, meta_key, key, value)
break
elsif !next_meta_block || meta_block.can_insert_between?(key, next_meta_block)
found_meta_block, block = create_new_block(meta_key, key, value)
item_index = 0
persist_block!(block)
break
end
end
end
end
persist_header!
assert("found_meta_block is not nil") { !found_meta_block.nil? }
assert("meta_block and block have same keys") { found_meta_block.key == block.key }
CachedRecord::Store::ManagedItem.new(
store: self,
meta_block: found_meta_block,
block: block,
index: item_index,
)
end
def find_by_meta(&block)
found_block = nil
found_index = nil
found_meta_block = nil
header.meta_blocks.each do |meta_block|
if index = meta_block.find_by_meta(&block)
found_meta_block = meta_block
found_block = get_block(meta_block.key)
found_index = index
end
end
if found_block
CachedRecord::Store::ManagedItem.new(
store: self,
meta_block: found_meta_block,
block: found_block,
index: found_index,
)
end
end
# Takes a block that must take in a value and return a boolean value
def remove
raise NotImplementedError, "todo"
# loop through all the meta blocks
# fetch the block
# loop through all items in the block
# if the conditional returns true, remove the item
#
# NOTE: should we compact here? This is probably the easiest to do, since
# compacting is only necessary when removing items, as keys may be unbalanced
#
# rebalance keys/items if necessary with surrounding blocks
end
def persist_block!(block)
store_adapter.write(block.key, block.to_hash)
end
def persist_header!
store_adapter.write(header.key, header.to_hash)
end
protected
attr_reader :header_key
def create_new_block(meta_key, key, value)
block = build_block(nil, keys: [key], values: [value])
meta_block = header.create_block(
block_key: block.key,
key: key,
meta_key: meta_key,
size: block_size,
)
[meta_block, block]
end
def insert_within_block!(meta_block, meta_key, key, value)
block = get_block(meta_block.key)
found_meta_block = nil
if meta_block.should_resize?
split_meta_blocks = header.split_meta_block(meta_block.key)
blocks = split_block(block)
inserted = false
blocks.each_with_index do |b, index|
meta_block = split_meta_blocks[index]
meta_block.key = b.key
if !inserted && b.key_within_range?(key)
index = b.insert(key, value)
meta_block.insert(meta_key, key, index)
found_meta_block = meta_block
block = b
inserted = true
end
persist_block!(b)
end
else
index = block.insert(key, value)
meta_block.insert(meta_key, key, index)
found_meta_block = meta_block
persist_block!(block)
end
[found_meta_block, block, index]
end
def split_block(block)
min_key, max_key = build_block_key, build_block_key
block.split(min_key, max_key)
end
def get_block(key)
get_blocks([key]).first
end
def get_blocks(keys)
ordered_blocks = Array.new(keys.length)
keys_to_index = {}
keys.each_with_index do |k, i|
keys_to_index[k] = i
end
raw_blocks = store_adapter.read_multi(*keys)
if raw_blocks.any? {|k,v| v.nil? }
unfound_block_keys = raw_blocks.inject([]) do |arr, (k, v)|
arr << k if v.nil?
arr
end
unfound_block_keys.each do |block_key|
meta_keys = header.meta_keys_for_block_key(block_key)
block_keys, block_values = data_fetcher.fetch_key_values(meta_keys)
block = build_block(block_key, keys: block_keys, values: block_values)
persist_block!(block)
ordered_blocks[keys_to_index[block_key]] = block
end
end
raw_blocks.each do |key, raw_block|
if raw_block
block = build_block(key, raw_block)
ordered_blocks[keys_to_index[key]] = block
end
end
ordered_blocks
end
def build_block(key, raw_block)
data = {order: order, size: block_size}.merge(raw_block)
key ||= build_block_key
Block.new(key, data)
end
def build_block_key
"#{header_key}:block:#{SecureRandom.uuid}"
end
def get_header(key)
header_data = store_adapter.read(key) || fetch_header_attributes
Header.new(header_data.merge(key: key, block_size: block_size))
end
def fetch_header_attributes
meta_keys = data_fetcher.fetch_meta_keys
blocks = meta_keys.each_slice(block_size).inject([]) do |arr, keys_data|
arr << {
key: build_block_key,
size: block_size,
keys_data: keys_data
}
end
{
order: order,
blocks: blocks,
}
end
end
end
end
| true |
0cb1fc601b5eb52ba9c334afa219a40072266b50 | Ruby | thisirs/event_scraper | /lib/event_scraper/scrapers/tvrage/tvrage.rb | UTF-8 | 5,481 | 2.546875 | 3 | [] | no_license | module EventScraper
class TVRageOrgFormatter
conf "TVRage/OrgFormatter"
def format(events)
body = events.map do |e|
time_format = (e.option("time_format") ||
option("time_format") ||
"%Y-%m-%d %H:%M")
template = (e.option("org_template") ||
option("org_template") ||
"*** <%U> %N S%SE%E %T")
list = e.eps_list
list << e.next_eps if e.next_eps
line = list.map do |l|
time_str = l.air_date.strftime(time_format)
template.gsub("%N", e.alt_name || e.name)
.gsub("%U", time_str)
.gsub("%T", l.title)
.gsub("%S", "%02d" % l.season)
.gsub("%E", "%02d" % l.episode)
end.join("\n")
head = e.option("head") || option("sub_head") || "** %N"
head = head.sub("%N", e.alt_name || e.name)
head ? head + "\n" + line : line
end.join("\n")
if option("head")
option("head") + "\n" + body
else
body
end
end
end
class TVRageScraper
conf "TVRage/Scraper"
include Scraper
def add(event_name)
@events << TVRageEvent.new(event_name)
end
def format
EventScraper.const_get(option("formatter")).new.format(active_events)
end
end
class Episode
attr_accessor :title, :air_date, :season, :episode
end
class InvalidEpisode < StandardError
end
class TVRageEvent < Event
conf 'TVRage/Scraper/events/#{name}', 'TVRage/Event'
BASE_URL="http://services.tvrage.com/feeds/search.php?show=%s"
SEARCH_URL="http://services.tvrage.com/feeds/episodeinfo.php?sid=%d"
attr_accessor :name, :alt_name, :id, :next_eps, :eps_list, :last_check
def initialize(name)
@name = name
@eps_list = []
@id = nil
@last_check = nil
end
# Update next air date if needed. Depends on last check and next air
# date if any.
def update
Logging.logger.debug("Update next episode for show #{@name}")
Logging.logger.debug("Last check date is #{@last_check || "nil"}")
now = DateTime.now
Logging.logger.debug("Now is #{now}")
if @next_eps
Logging.logger.debug("Next episode present")
if @next_eps.air_date < now
Logging.logger.debug("Next episode is past")
@eps_list << @next_eps
@last_check = now
begin
eps = retrieve_next_episode
@next_eps = eps
rescue InvalidEpisode => e
Logging.logger.error(e.message)
@next_eps = nil
end
else
if @last_check and @next_eps.air_date - now < now - @last_check \
and @next_eps.air_date > now + option("days_preceding")
Logging.logger.debug("Mid date reached or not too close to next air date")
begin
@last_check = now
@next_eps = retrieve_next_episode
rescue InvalidEpisode => e
Logging.logger.error(e.message)
end
else
Logging.logger.debug("Not at mid date or show in less than %d days" %
option("days_preceding"))
end
end
else
Logging.logger.debug("No next episode")
if not @last_check or now - @last_check > option("days_until_next_check")
Logging.logger.debug("More than #{option("days_until_next_check")} days since last check or no last check")
begin
@last_check = now
@next_eps = retrieve_next_episode
rescue InvalidEpisode => e
Logging.logger.error(e.message)
end
else
Logging.logger.debug("No need to check again")
end
end
end
private
def retrieve_next_episode
Logging.logger.debug("Retrieving next \"#{name}\" episode data")
unless @id
Logging.logger.debug("No ID, retrieving...")
begin
doc = Nokogiri::XML(open(BASE_URL % CGI::escape(name)))
@id = doc.xpath("/Results/show[1]/showid").text.to_i
rescue Exception => e
puts e
raise InvalidEpisode.new("Unable to retrieve id")
end
end
Logging.logger.debug("Id is #{@id}")
eps = Episode.new
begin
doc = Nokogiri::XML(open(SEARCH_URL % @id))
sec = doc.xpath("/show/nextepisode/airtime[@format='GMT+0 NODST']").text.to_i
rescue
raise InvalidEpisode.new("Unable to parse date")
end
eps.air_date = Time.at(sec).to_datetime
Logging.logger.debug("Air date is #{eps.air_date || "nil"}")
if eps.air_date.nil? or eps.air_date < DateTime.now
raise InvalidEpisode.new("Invalid date")
end
begin
eps.title = doc.xpath("/show/nextepisode/title").text
rescue
raise InvalidEpisode.new("Unable to parse title")
end
Logging.logger.debug("Title is \"#{eps.title || "nil"}\"")
begin
number = doc.xpath("/show/nextepisode/number").text
rescue
raise InvalidEpisode.new("Unable to parse episode number")
end
if number =~ /(\d+)x(\d+)/
eps.season = $1.to_i
eps.episode = $2.to_i
else
raise InvalidEpisode.new("Invalid episode number")
end
Logging.logger.debug("Season is #{eps.season}")
Logging.logger.debug("Episode is #{eps.episode}")
eps
end
end
end
| true |
d585db6eb1f87043a5152609775af61c881bfc32 | Ruby | shaneoston72/bank_tech_test | /lib/account.rb | UTF-8 | 874 | 3.265625 | 3 | [] | no_license | class Account
attr_reader :statement
def initialize(transaction_klass: Transaction, statement_klass: Statement)
@balance = 0
@account_history = []
@transaction = transaction_klass
@statement = statement_klass
end
def transaction(type: type, amount: amount)
complete_transaction(type, amount)
end
def print_statement
print_statement
end
attr_accessor :balance, :account_history
def complete_transaction(type, amount)
self.balance += amount
transaction_record(type, amount)
end
def transaction_record(type, amount)
@activity = create_transaction(type, amount)
self.account_history << @activity
end
def create_transaction(type, amount)
@transaction.new(type, amount)
end
def print_statement(account_history)
statement.prepare_statement(account_history)
end
end
| true |
ae418f09f61e776f62ec001daf1b343963fd2db0 | Ruby | udaltsova-nastya/ruby | /lesson3/rail_road_interface.rb | UTF-8 | 10,756 | 3.140625 | 3 | [] | no_license | # frozen_string_literal: true
# Интерфейс для управления железной дорогой
class RailRoadInterface
attr_reader :rail_road
def initialize(rail_road)
@rail_road = rail_road
end
def run
loop do
action = main_menu_action
break if action.zero?
main_menu_process(action)
end
end
private
# отображаем главное меню и возвращаем выбор пользователя
def main_menu_action
puts "Выберите действие:"
puts "0 - завершить работу с программой"
puts "1 - управление поездами"
puts "2 - управление станциями"
puts "3 - управление маршрутами"
gets.chomp.to_i
end
# rubocop:disable Metrics/MethodLength
# Ну, вот такое у нас большое меню...
def train_menu_action
puts "Управление поездами:"
puts "0 - вернуться в главное меню"
puts "1 - создать поезд"
puts "2 - добавить вагон к поезду"
puts "3 - отцепить вагон от поезда"
puts "4 - назначить маршрут поезду"
puts "5 - переместить поезд по маршруту вперед"
puts "6 - переместить поезд по маршруту назад"
puts "7 - занять место в вагоне"
puts "8 - список поездов"
puts "9 - список вагонов в поезде"
gets.chomp.to_i
end
# rubocop:enable Metrics/MethodLength
def station_menu_action
puts "Управление станциями:"
puts "0 - вернуться в главное меню"
puts "1 - создать станцию"
puts "2 - вывести список станций"
puts "3 - получить список поездов на станции"
gets.chomp.to_i
end
def route_menu_action
puts "Управление маршрутами:"
puts "0 - вернуться в главное меню"
puts "1 - создать маршрут"
puts "2 - добавить станцию в маршрут"
puts "3 - удалить станцию из маршрута"
gets.chomp.to_i
end
def main_menu_process(action)
case action
when 1
train_menu_process(train_menu_action)
when 2
station_menu_process(station_menu_action)
when 3
route_menu_process(route_menu_action)
end
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength
# Ну, вот такое у нас большое меню...
def train_menu_process(action)
case action
when 1
create_train
when 2
add_wagon_to_train
when 3
remove_wagon_from_train
when 4
assign_route_to_train
when 5
move_train_forward
when 6
move_train_backward
when 7
occupy_wagon
when 8
show_trains_list
when 9
show_train_wagons_list
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/MethodLength
def station_menu_process(action)
case action
when 1
create_station(ask_station_name)
when 2
show_stations_list
when 3
show_trains_list_on_station(find_station)
end
end
def route_menu_process(action)
case action
when 1
create_route
when 2
add_station_to_route
when 3
remove_station_from_route
end
end
def ask_station_name
puts "Введите название станции:"
gets.chomp
end
def find_or_create_station
rail_road.find_or_create_station(ask_station_name)
end
def show_stations_list
puts "Список станций:"
rail_road.stations.each.with_index(1) do |station, index|
puts "#{index} - #{station.name}"
end
end
def show_routes_list
puts "Список маршрутов:"
rail_road.routes.each.with_index(1) do |route, index|
puts "#{index} - #{route.name}"
end
end
def find_station
rail_road.find_station(ask_station_name)
end
def show_trains_list_on_station(station)
if station
puts "Список поездов на станции #{station.name}:"
show_trains_list(station.trains)
else
puts "Станция не найдена"
end
end
# Отображаем переданный список поездов
# Если список поездов не передан, то отображаем список всех поездов на железной дороге
def show_trains_list(trains = rail_road.trains)
trains.each.with_index(1) do |train, index|
# print -- чтобы не было лишнего перевода на новую строку
print "#{index}. Поезд #{train.human_readable_type} № #{train.number}, вагонов #{train.wagons_count}"
print ", занято #{train.taken_space} "
puts ", доступно : #{train.free_space} "
end
end
def show_train_wagons_list
train = select_train
if train
train.iterate_wagons do |wagon, wagon_number|
print "#{wagon_number}. Вагон #{wagon.human_readable_type}"
print ", занятo: #{wagon.taken_space}"
puts ", свободнo: #{wagon.free_space}"
end
else
puts "Поезд не найден"
end
end
def create_station(station_name)
rail_road.create_station(station_name)
end
def create_route
first_station_name = ask_station_name
last_station_name = ask_station_name
rail_road.create_route(first_station_name, last_station_name)
end
def add_station_to_route
route = select_route
if route
station = find_or_create_station
puts "Введите порядковый номер станции в маршруте"
station_index = gets.chomp.to_i
route.add_station(station_index, station)
else
puts "Маршрут не найден"
end
end
def remove_station_from_route
route = select_route
if route
station = find_station
route.remove_station(station)
else
puts "Маршрут не найден"
end
end
def ask_train_type
puts "Введите тип поезда:"
puts "1 - пассажирский (по умолчанию)"
puts "2 - грузовой"
train_type = gets.chomp.to_i
case train_type
when 1
:passenger
when 2
:cargo
end
end
def ask_train_number
puts "Введите номер поезда"
gets.chomp
end
def create_train
train_type = ask_train_type
train_number = ask_train_number
train = rail_road.create_train(train_type, train_number)
puts "Создан #{train}"
rescue ArgumentError => e
puts "Не удалось создать поезд:"
puts e.message
retry
end
def select_train
puts "Выберите поезд:"
show_trains_list
train_index = gets.chomp.to_i - 1
rail_road.trains[train_index]
end
def select_route
puts "Выберите маршрут:"
show_routes_list
route_index = gets.chomp.to_i - 1
rail_road.routes[route_index]
end
def add_wagon_to_train
train = select_train
if train
wagon_attributes = ask_wagon_attributes(train)
rail_road.add_wagon_to_train(train, wagon_attributes)
else
puts "Поезд не найден"
end
puts "Вагон добавлен к поезду №#{train.number}"
puts "Общее количество вагонов в поезде: #{train.wagons_count}"
end
def ask_wagon_attributes(train)
case train.type
when :cargo
ask_cargo_wagon_attributes
when :passenger
ask_passenger_wagon_attributes
end
end
def ask_passenger_wagon_attributes
puts "Укажите кол-во мест в вагоне"
puts "По умолчанию #{rail_road.passenger_wagon_default_seats_count} мест"
seats_count = gets.chomp.to_i
seats_count = nil if seats_count.zero?
seats_count
end
def ask_cargo_wagon_attributes
puts "Укажите вместимость вагона (в тоннах)"
puts "По умолчанию #{rail_road.cargo_wagon_default_volume} тонн"
volume = gets.chomp.to_i
volume = nil if volume.zero?
volume
end
def occupy_wagon
train = select_train
puts "Поезд не найден" && return unless train
wagon = select_wagon(train)
puts "Вагон не найден" && return unless wagon
occupy_wagon_by_type(wagon)
end
def occupy_wagon_by_type(wagon)
case wagon.type
when :passenger
occupy_passenger_wagon(wagon)
when :cargo
occupy_cargo_wagon(wagon)
else
puts "Невозможно загрузить или занять место в данном типе вагона"
end
end
def occupy_passenger_wagon(wagon)
if wagon.take_space
puts "Место в вагоне успешно занято"
puts "Осталось свободных мест: #{wagon.free_space}"
else
puts "Не удалось занять место в вагоне"
end
end
def occupy_cargo_wagon(wagon)
puts "Доступно для загрузки #{wagon.free_space} тонн"
puts "Укажите объем загрузки (в тоннах):"
space = gets.chomp.to_i
if wagon.take_space(space)
puts "Вагон успешно загружен"
puts "Осталось свободного места для загрузки: #{wagon.free_space}"
else
puts "Не удалось загрузить вагон"
end
end
def select_wagon(train)
return nil if train.wagons_count.zero?
puts "Выберите вагон: от 1 до #{train.wagons_count}"
wagon_index = gets.chomp.to_i - 1
train.wagons[wagon_index]
end
def remove_wagon_from_train
train = select_train
if train
train.remove_wagon
else
puts "Поезд не найден"
end
end
def assign_route_to_train
train = select_train
puts "Поезд не найден" && return unless train
route = select_route
puts "Маршрут не найден" && return unless route
train.assign_route(route)
end
def move_train_forward
train = select_train
if train
train.move_forward
else
puts "Поезд не найден"
end
end
def move_train_backward
train = select_train
if train
train.move_backward
else
puts "Поезд не найден"
end
end
end
| true |
fd169b7519a192c7ed55584144dc61142b86e132 | Ruby | Iaox/IaoxRubyWebServer | /models/rs/clientHandler.rb | UTF-8 | 597 | 2.796875 | 3 | [] | no_license | class ClientHandler
@clients
@active_rs_accounts
def initialize
@clients = Array.new
@active_rs_accounts = Array.new
end
def add(client)
@clients.push(client)
end
def remove(client)
if @clients.include?(client)
if !client.get_rs_account.nil?
client.get_rs_account.update(:available => true)
end
@clients.delete(client)
end
end
def get_clients
return @clients
end
def get_client_by_name(name)
@clients.each do |client|
if client.get_name == name
return client
end
end
return nil
end
end | true |
3e2cad1975c631372fbd281a0bef502f0e9e8879 | Ruby | wxq92109/JOB | /第五次任务/《Ruby基础教程》示例程序/case_class.rb | UTF-8 | 252 | 3.75 | 4 | [] | no_license |
class Case_class
array = ["a",1,nil]
array.each do |item|
case item
when String
puts item," is a string"
when Numeric
puts item,"item is a numeric"
else
puts item,"item is something"
end
end
end | true |
ef74ec292ae6f550f02d8bc02d12546fc14aa638 | Ruby | jm96441n/phase-0 | /week-4/add-it-up/my_solution.rb | UTF-8 | 1,405 | 4.15625 | 4 | [
"MIT"
] | permissive | # Add it up!
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# I worked on this challenge [with: Ivy Vetor].
# 0. total Pseudocode
# make sure all pseudocode is commented out!
=begin
def total(array)
sum equals 0
while a number of the index is less than the array length
add sum to the number at index n
increase n by 1 each time you loop through this
end
return the new sum
=end
# Input:
# Output:
# Steps to solve the problem.
# 1. total initial solution
def total (array)
n = 0
sum = 0
while n < array.length
sum += array[n]
n+=1
end
return sum
end
3. total refactored solution
def total (array)
sum = 0
array.each {|x| sum+=x}
end
# 4. sentence_maker pseudocode
# make sure all pseudocode is commented out!
# Input:parts of the sentence
# Output: a full sentence (one string)
# Steps to solve the problem.
# take each part of the string and concate it with the other sentence parts.
# 5. sentence_maker initial solution
def sentence_maker(array)
n = 1
sentence = array[0].capitalize
while n < array.length
sentence = sentence + ' ' + array[n].to_s
n+=1
end
return sentence + '.'
end
# 6. sentence_maker refactored solution
def sentence_maker(array)
sentence = array[0]
array.each {|n| sentence= sentence + ' ' + array[n].to_s}
end | true |
3ecb32966a5b166baa98035796443faad1cf476e | Ruby | citygent/W4D2-BikeHire | /spec/bike_spec.rb | UTF-8 | 533 | 2.921875 | 3 | [] | no_license | require_relative './spec_helper.rb'
require_relative '../lib/bike.rb'
#describing functionlity of the specific bike class
describe Bike do
let(:bike) {Bike.new} #instantiate an instance of the Bike Class every test.
it 'should not be broken after we create it' do
expect(bike.broken?).to be false
end
it 'should be able to break down' do
bike.break
expect(bike.broken?).to be true
end
it 'should be able to be fixed' do
bike.break
bike.fix
expect(bike.broken?).to be false
end
end
| true |
37fd1d39ad853410c3547a2e1b60c44aa7a32233 | Ruby | gracexinran/sorting-string-manipulation | /lib/reverse_sentence.rb | UTF-8 | 1,152 | 4.125 | 4 | [] | no_license | # A method to reverse the words in a sentence, in place.
# Time complexity: O(n2)
# Space complexity: O(1)
require 'pry'
def reverse_sentence(my_sentence)
# raise NotImplementedError
return nil if my_sentence.nil?
i = 0
j = my_sentence.length - 1
until i >= j
temp = my_sentence[i]
my_sentence[i] = my_sentence[j]
my_sentence[j] = temp
i += 1
j -= 1
end
m = 0
start_index = m
while m < my_sentence.length
# binding.pry
if my_sentence[start_index] != " " && my_sentence[m] == " "
my_sentence[start_index..m-1] = reverse_helper(my_sentence[start_index..m-1])
start_index = m
elsif my_sentence[start_index] != " " && m == my_sentence.length - 1
my_sentence[start_index..m] = reverse_helper(my_sentence[start_index..m])
elsif my_sentence[start_index] == " " && my_sentence[m] != " "
start_index = m
end
m += 1
end
return my_sentence
end
def reverse_helper(my_sentence)
i = 0
j = my_sentence.length - 1
until i >= j
temp = my_sentence[i]
my_sentence[i] = my_sentence[j]
my_sentence[j] = temp
i += 1
j -= 1
end
return my_sentence
end | true |
807b6333dd60e4eafcbca94a29003136b1651916 | Ruby | therichey/PlusPlus-Analytics | /categorizer_test.rb | UTF-8 | 5,693 | 2.734375 | 3 | [] | no_license | require './categorizer'
require 'minitest/autorun'
class TestCategorizer < MiniTest::Unit::TestCase
def test_single_upc_is_returned
assert_equal 'single-upc', Categorizer.categorize('/search/?q=06250003')
assert_equal 'single-upc', Categorizer.categorize('/search/?q= 07358210')
assert_equal 'single-upc', Categorizer.categorize('/search/?q=07358210 ')
assert_equal 'single-upc', Categorizer.categorize('/search/?q=+07358210')
assert_equal 'single-upc', Categorizer.categorize('/search/?q=07358210+')
end
def test_unclassified_is_returned_for_things_that_cannot_be_categorized
assert_equal 'unclassified', Categorizer.categorize('/DGJKHGKSDFJHSDFH')
end
def test_blank_search_is_returned_for_blank_searches
assert_equal 'blank-search', Categorizer.categorize('/search/?q=')
end
def test_single_tcode_is_returned
assert_equal 'single-tcode', Categorizer.categorize('/search/?q=t579057')
assert_equal 'single-tcode', Categorizer.categorize('/search/?q=T747304J')
assert_equal 'single-tcode', Categorizer.categorize('/search/?q=+t579057')
assert_equal 'single-tcode', Categorizer.categorize('/search/?q= t579057')
assert_equal 'single-tcode', Categorizer.categorize('/search/?q=+T747304J+')
end
def test_generic_search_is_returned
assert_equal 'generic-search', Categorizer.categorize('/search/?q=bouquets')
assert_equal 'generic-search', Categorizer.categorize('/search/?q=2+pack+hold+ups')
assert_equal 'generic-search', Categorizer.categorize('/search/?q= bouquets')
end
def test_pcode_is_returned
assert_equal 'single-pcode', Categorizer.categorize('/search/?q=p22320758')
end
def test_customer_search_is_returned
assert_equal 'customer-search', Categorizer.categorize('/customer-search?search_type=blarrgh')
end
def test_customer_search_phone_number
assert_equal 'phone-number', Categorizer.categorize('/customer-search?search_type=phoneNumber')
end
def test_customer_search_email
assert_equal 'email', Categorizer.categorize('/customer-search?search_type=email')
end
def test_customer_search_first_last_name
assert_equal 'firstname-lastname', Categorizer.categorize('/customer-search?search_type=firstName_lastName')
assert_equal 'firstname-lastname', Categorizer.categorize('/customer-search?search_type=first-name,last-name')
end
def test_lastname_postcode
assert_equal 'lastname-postcode', Categorizer.categorize('/customer-search?search_type=lastName_postcode')
assert_equal 'lastname-postcode', Categorizer.categorize('/customer-search?search_type=last-name,postcode')
end
def test_first_last_postcode
assert_equal 'first-last-postcode', Categorizer.categorize( '/customer-search?search_type=first-name,last-name,postcode')
end
def test_postcode_only
assert_equal 'postcode', Categorizer.categorize('/customer-search?search_type=postcode')
end
def test_lastname_only
assert_equal 'lastname', Categorizer.categorize('/customer-search?search_type=last-name')
end
def test_can_recognize_order_number
assert_equal 'ordernumber', Categorizer.categorize('/customer-search?search_type=orderNumber')
end
def test_successful_customer_search_is_returned
assert_equal 'enacted-customer', Categorizer.categorize('/search/')
end
def test_can_recognize_when_the_path_contains_categories
assert Categorizer.contains_category?('/search/?q=flowers&category=97114')
refute Categorizer.contains_category?('/search/?q=flowers')
end
def test_can_recognize_when_the_path_contains_page
assert Categorizer.contains_page?('/search/?q=bouquets&page=2')
refute Categorizer.contains_page?('/search/?q=flowers')
end
def test_can_recognize_when_the_path_contains_category_and_page
assert Categorizer.contains_page?('/search/?q=wool mix trousers&page=2&category=98212')
assert Categorizer.contains_category?('/search/?q=wool mix trousers&page=2&category=98212')
end
def test_can_recognize_when_path_contains_filter
assert Categorizer.contains_price_filter?('/search/?q=blue+trousers&price_filter_min=20&price_filter_max=20')
assert Categorizer.contains_price_filter?('/search/?q=red+shirt&price_filter_min=2&price_filter_max=')
assert Categorizer.contains_price_filter?('/search/?q=black+trousers&price_filter_min=&price_filter_max=300')
end
def test_can_recognize_the_min_price
assert_equal '20', Categorizer.min_price_filtering('/search/?q=blue+trousers&price_filter_min=20&price_filter_max=20')
end
def test_can_recognize_the_max_price
assert_equal '300', Categorizer.max_price_filtering('/search/?q=black+trousers&price_filter_min=&price_filter_max=300')
end
def test_multi_code_search_is_returned
assert_equal 'multi-code', Categorizer.categorize('/search/?q=05396696+05795635+20553708')
assert_equal 'multi-code', Categorizer.categorize('/search/?q=T825634+T038568')
assert_equal 'multi-code', Categorizer.categorize('/search/?q=T825634+05795635+20553708')
end
def test_generic_with_code_is_returned
assert_equal 'generic-and-code', Categorizer.categorize('/search/?q=t862681+anti+bobble')
assert_equal 'generic-and-code', Categorizer.categorize('/search/?q=T743631B+black+trousers+T743631B')
assert_equal 'generic-and-code', Categorizer.categorize('/search/?q=05396696+black+trousers+T743631B')
assert_equal 'generic-and-code', Categorizer.categorize('/search/?q=05396696+black+trousers+05396696+05795635+20553708')
end
def test_can_handle_pound_sign
assert_equal 'generic-search', Categorizer.categorize('/search/?q=orchid+£15')
end
end
| true |
61638404f7ef293118088f88fb03128458337436 | Ruby | nikosd/roodi | /lib/roodi/checks/npath_complexity_check.rb | UTF-8 | 1,629 | 2.859375 | 3 | [
"MIT"
] | permissive | require 'roodi/checks/check'
module Roodi
module Checks
class NpathComplexityCheck < Check
# , :when, :and, :or
MULTIPLYING_NODE_TYPES = [:if, :while, :until, :for, :case]
ADDING_NODE_TYPES = [:rescue]
COMPLEXITY_NODE_TYPES = MULTIPLYING_NODE_TYPES + ADDING_NODE_TYPES
def initialize(complexity)
super()
@complexity = complexity
@value_stack = []
@current_value = 1
end
def evalute_start_if(node)
push_value
end
def evalute_start_while(node)
push_value
end
def evalute_start_until(node)
push_value
end
def evalute_start_for(node)
push_value
end
def evalute_start_case(node)
push_value
end
def evalute_start_rescue(node)
push_value
end
MULTIPLYING_NODE_TYPES.each do |type|
define_method "evaluate_end_#{type}" do |node|
leave_multiplying_conditional
end
end
ADDING_NODE_TYPES.each do |type|
define_method "evaluate_end_#{type}" do |node|
leave_multiplying_conditional
end
end
protected
def push_value
@value_stack.push @current_value
@current_value = 1
end
def leave_multiplying_conditional
pop = @value_stack.pop
@current_value = (@current_value + 1) * pop
end
def leave_adding_conditional
pop = @value_stack.pop
puts "#{type}, so adding #{pop}"
@current_value = @current_value - 1 + pop
end
end
end
end
| true |
d8558d284a6ffdfb452c672fa23abbd9b46e1b41 | Ruby | didiermarques/tests-ruby | /lib/01_temperature.rb | UTF-8 | 91 | 3.28125 | 3 | [] | no_license | def ftoc(f)
return (f - 32) * 5/9.0
end
def ctof (c)
return (c * 9.0/5) + 32
end | true |
cb734dd55224ba4421e9cfff8b818e8d9539f8ef | Ruby | matthewbillienyc/postgres-lukather | /lukather_csv_writer.rb | UTF-8 | 2,037 | 3.65625 | 4 | [] | no_license | require 'nokogiri'
require 'open-uri'
require 'csv'
require 'pry'
years = 1977..2016
class Artist
@@artists = []
def self.all
@@artists
end
def self.find_by_name(name)
all.find { |a| a.name == name }
end
attr_accessor :name
def initialize(name)
Artist.all << self unless Artist.find_by_name(name)
@name = name
end
end
class Year
@@years = []
def self.all
@@years
end
def self.find(year)
all.find { |y| y.year = year }
end
attr_accessor :year
def initialize(year)
Year.all << self
@year = year
end
end
class Title
@@titles = []
def self.all
@@titles
end
def self.find_by_title(title)
all.find { |t| t.title = title }
end
def self.find_by_year(year)
Title.all.select { |t| t.year == year }
end
attr_accessor :artist, :year, :title
def initialize(title, artist, year)
Title.all << self
@title = title
@artist = artist
@year = year
end
end
years.each do |y|
html = Nokogiri::HTML(open("http://www.stevelukather.com/music/discography/#{y}.aspx"))
albums = html.css('.discography-title').map { |album| album.inner_text.gsub("\t", "").gsub("\n", "") }
artists = html.css('.discography-artist').map { |artist| artist.inner_text }
year = Year.new(y)
albums.each_with_index do |album, i|
artist = Artist.new(artists[i])
tutke = Title.new(album, artist, year)
end
end
years = File.open('years.csv', 'w')
CSV.open(years, 'w') do |csv|
Year.all.each do |y|
csv << [y.year]
end
end
years.close
artists = File.open('artists.csv', 'w')
CSV.open(artists, 'w', force_quotes: true) do |csv|
Artist.all.uniq.each do |a|
csv << [a.name.to_s]
end
end
artists.close
titles = File.open('titles.csv', 'w')
CSV.open(titles, 'w', force_quotes: true) do |csv|
Title.all.each do |t|
csv << [t.title.to_s, t.artist.name.to_s, t.year.year]
end
end
titles.close
puts "Finished writing #{Year.all.length} years, #{Artist.all.uniq.length} artists, and #{Title.all.length} titles to CSV!"
| true |
98cbaa14a3dcf9761ff840a668924c08b017a110 | Ruby | Matevito/Chess | /lib/pieces/knight.rb | UTF-8 | 1,687 | 3.453125 | 3 | [] | no_license | require_relative "../board"
require_relative "../player"
require_relative "../game_methods"
class Knight < Board
include GameMethods
def possible_moves(player, position, board)
color = player.color
possible_moves = []
current_board = board.board
current_position = position.dup.map(&:dup)
possible_moves.concat([current_position[0]-2, current_position[1]+1])
possible_moves.concat([current_position[0]-1, current_position[1]+2])
possible_moves.concat([current_position[0]+1, current_position[1]+2])
possible_moves.concat([current_position[0]+2, current_position[1]+1])
possible_moves.concat([current_position[0]+2, current_position[1]-1])
possible_moves.concat([current_position[0]+1, current_position[1]-2])
possible_moves.concat([current_position[0]-1, current_position[1]-2])
possible_moves.concat([current_position[0]-2, current_position[1]-1])
possible_moves = correct_path(possible_moves)
knight_valid_moves = []
possible_moves.each do |cell|
if move_in_board?(cell)
row = cell[0]
column = cell[1]
board_cell = current_board[row][column]
if board_cell == " "
knight_valid_moves.concat([cell])
elsif color == "white"
knight_valid_moves.concat([cell]) if board_cell == board_cell.downcase
elsif color == "black"
knight_valid_moves.concat([cell]) if board_cell == board_cell.upcase
end
end
end
return knight_valid_moves
end
end | true |
5a915e6bbb01e45f471afa1c2b044c4c9fa403c1 | Ruby | andyw8/codeclimate-engine-rb | /lib/cc_engine/issue.rb | UTF-8 | 1,398 | 2.5625 | 3 | [
"MIT"
] | permissive | require "json"
module CCEngine
class Issue
def initialize(
check_name:,
description:,
categories:,
location:,
remediation_points:,
content:,
fingerprint:
)
@check_name = check_name
@description = description
@categories = categories
@location = location
@remediation_points = remediation_points
@content = content
@fingerprint = fingerprint
end
def render
to_hash.to_json + "\0"
end
def to_json
to_hash.to_json
end
def to_hash
{
type: "issue",
check_name: check_name,
description: description,
categories: categories,
location: location.to_hash
}.merge(remediation_points_hash).merge(content_hash).merge(fingerprint_hash)
end
private
def remediation_points_hash
return {} unless remediation_points
{
remediation_points: remediation_points
}
end
def content_hash
return {} unless content
{
content: {
body: content
}
}
end
def fingerprint_hash
return {} unless fingerprint
{
fingerprint: fingerprint
}
end
private
attr_reader :check_name,
:description,
:categories,
:location,
:remediation_points,
:content,
:fingerprint
end
end
| true |
5b07334f7bfe053071856ce6217194136e8d79d1 | Ruby | ept/invoicing_generator | /lib/invoicing_generator/name_tools.rb | UTF-8 | 4,518 | 2.921875 | 3 | [
"MIT"
] | permissive | # Tools for dealing with names of controllers or models, passed to us by the user
# from the command line when invoking the generator. Designed to be included into
# a subclass of Rails::Generator::NamedBase.
#
# This code is inspired by the generator in restful_authentication.
module InvoicingGenerator
module NameTools
# Analyses a name provided by the user on the command line, and returns a hash
# of useful bits of string based on that name:
# extract_name_details 'MegaBlurb/foo/BAR_BLOBS', :kind => :controller, :extension => '.rb'
# => {
# :underscore_base => 'bar_blobs', # last part of the name, underscored
# :camel_base => 'BarBlobs', # last part of the name, camelized
# :underscore_singular => 'bar_blob', # underscore_base forced to singular form
# :camel_singular => 'BarBlob', # camel_base forced to singular form
# :underscore_plural => 'bar_blobs', # underscore_base forced to plural form
# :camel_plural => 'BarBlobs', # camel_base forced to plural form
# :class_path_array => ['mega_blurb', 'foo'], # array of lowercase, underscored directory names
# :class_path => 'mega_blurb/foo', # class_path_array joined by filesystem separator
# :class_nesting_array => ['MegaBlurb', 'Foo'], # array of camelized module names
# :class_nesting => 'MegaBlurb::Foo', # class_nesting_array joined by double colon
# :nesting_depth => 2, # length of class_path array
#
# # The following depend on the given :kind
# :file_path_base => 'bar_blobs_controller.rb' # based on underscore_*
# :file_path_full => 'app/controllers/mega_blurb/foo/bar_blobs_controller.rb', # full file path
# :class_name_base => 'BarBlobsController', # file_path_base.camelize
# :class_name_full => 'MegaBlurb::Foo::BarBlobsController', # = class_nesting + class_name_base
# }
#
# Recognised options:
# :kind => :model -- use conventions for creating a model object from the name
# :kind => :controller -- use conventions for creating a controller from the name
def extract_name_details(user_specified_name, options={})
result = {}
# See Rails::Generator::NamedBase#extract_modules
modules = extract_modules(user_specified_name)
base_name = modules.shift
result[:class_path_array] = modules.shift
file_path = modules.shift
result[:class_nesting] = modules.shift
result[:nesting_depth] = modules.shift
result[:class_path] = File.join(result[:class_path_array])
result[:class_nesting_array] = result[:class_nesting].split('::')
result[:underscore_base] = base_name.underscore
result[:camel_base] = result[:underscore_base].camelize
result[:underscore_singular] = result[:underscore_base].singularize
result[:camel_singular] = result[:underscore_singular].camelize
result[:underscore_plural] = result[:underscore_singular].pluralize
result[:camel_plural] = result[:underscore_plural].camelize
if options[:kind] == :controller
result[:file_path_base] = "#{result[:underscore_base]}_controller"
path_prefix = File.join('app', 'controllers')
elsif options[:kind] == :model
result[:file_path_base] = result[:underscore_singular]
path_prefix = File.join('app', 'models')
else
raise 'unknown kind of name'
end
result[:class_name_base] = result[:file_path_base].camelize
result[:file_path_base] += (options[:extension] || ".rb")
if result[:nesting_depth] == 0
result[:file_path_full] = File.join(path_prefix, result[:file_path_base])
result[:class_name_full] = result[:class_name_base]
else
result[:file_path_full] = File.join(path_prefix, result[:class_path], result[:file_path_base])
result[:class_name_full] = "#{result[:class_nesting]}::#{result[:class_name_base]}"
end
#result[:routing_name] = result[:singular_name]
#result[:routing_path] = result[:file_path].singularize
#result[:controller_name] = result[:plural_name]
result
end
end
end
| true |
32702cfdce62232e6259f101d5cfeb17c0ceb2a5 | Ruby | WeilerWebServices/Hulu | /vfl2objc/vfl2objc.rb | UTF-8 | 14,373 | 3.3125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
class UIView
# r means right, b means bottom
# xref means reference object for x. e.g. [v1]-10-[v2] makes v2.xref=v1, v2.x=10 if v1's size is unknown
attr_accessor :name, :x, :y, :r, :b, :w, :h, :xref, :yref, :rref, :bref, :added_to_list, :centerx, :centery
def code_for_x
return "#{self.xref.to_s.length>0 ? "CGRectGetMaxX(#{self.xref}.frame) + " : ""}#{self.x}"
end
def code_for_right
return "#{self.rref.to_s.length>0 ? "CGRectGetMinX(#{self.rref}.frame)" : "superview.bounds.size.width"} - (#{self.r})"
end
def code_for_y
return "#{self.yref.to_s.length>0 ? "CGRectGetMaxY(#{self.yref}.frame) + " : ""}#{self.y}"
end
def code_for_bottom
return "#{self.bref.to_s.length>0 ? "CGRectGetMinY(#{self.bref}.frame)" : "superview.bounds.size.height"} - (#{self.b})"
end
end
PARAMS = {:VFL => ""}
HASH = {}
LIST = []
#common beginnings and endings of VFL block comment delimiters (ie // --- VFL... )
STARTS_AND_ENDS = [
["\/\/ \-\-\- VFL", "VFL \-\-\-\n"],
["\/\/ VFL begin", "\/\/ VFL end\n"],
["\/\/ begin VFL", "\/\/ end VFL\n"]
]
def get_or_create_view(name)
if HASH[name]
return HASH[name]
else
view = UIView.new
view.name = name
view.added_to_list = false
HASH[name] = view
return view
end
end
def exists(v)
unless v
return false
end
return v.length > 0
end
def parse(vfl)
simpler_vfl = vfl.strip
# make parsing simpler
simpler_vfl.gsub! "|[", "|-["
simpler_vfl.gsub! "][", "]-["
simpler_vfl.gsub! "]|", "]-|"
PARAMS[:VFL] = vfl
lines = simpler_vfl.split("\n")
lines.each do |line|
line.strip!
if line.index("V:")==0
orientation = :vertical
else
orientation = :horizontal
end
if line[/center\[([a-zA-Z0-9_\.]+)\s*(?:\(([a-zA-Z\d]+)[^\)]*\))?\]/]
view = get_or_create_view($1)
if orientation == :horizontal
view.centerx = true
view.w = $2 if $2
else
view.centery = true
view.h = $2 if $2
end
next
end
# puts orientation.to_s
line.gsub!(/^(H|V):/, "")
elements = line.split("-")
position = "" # positon=empty string means position is unknown. If it's unknown we don't allow any calculation on that
ref = ""
treat_element = lambda { |element,reversed|
# puts "element: #{element}"
if element == "|"
position = "0"
elsif element[/^([_a-zA-Z\d]+).*/]
# get number between elements
if exists(position)
position = position + " + " + $1
end
elsif element[/\[([a-zA-Z0-9_\.]+)\s*(?:\(([_a-zA-Z\d\>]+)[^\)]*\))?\]/]
# get element in brackets (possibly with number in paren)
view = get_or_create_view($1)
# puts "treatint #{view.name}"
if orientation == :horizontal
if reversed
view.r = position
view.rref = ref
# puts "setting the right of #{element} to #{position}, ref is #{ref}."
else
view.x = position
view.xref = ref
# puts "setting the left of #{element} to #{position}, ref is #{ref}."
end
if $2 and (not $2.index(">"))
view.w = $2
if exists(position)
position = position + " + " + view.w
end
# puts "#{element} does have a width: #{$2}, position becomes #{position}."
elsif (not $2) and exists(position)
ref = view.name
position = "0"
# puts "#{element} doesn't have a width, position becomes 0 and ref becomes #{ref}."
else
position = ""
# puts "#{element} has no width and can't determine the edge"
end
else # vertical
if reversed
view.b = position
view.bref = ref
else
view.y = position
view.yref = ref
end
if $2 and (not $2.index(">"))
view.h = $2
if exists(position)
position = position + " + " + $2
end
elsif (not $2) and exists(position)
ref = view.name
position = "0"
else
position = ""
end
end
end
# puts "position becomes #{position}"
}
# puts "regular direction (l->r or top->bottom)"
elements.each_with_index do |element, idx|
treat_element.call(element, false)
end
# puts "reversed direction (r->l or bottom->top)"
position = ""
ref = ""
elements.reverse.each_with_index do |element, idx|
treat_element.call(element, true)
end
end
# puts "hash:\n#{HASH}"
end
def add_to_list(position, view)
unless view
return
end
if view.added_to_list
return
end
LIST.insert(position, view)
view.added_to_list = true
if view.xref.to_s.length>0
v2 = HASH[view.xref]
# puts "#{view.name} depends on #{v2.name}, so before adding #{v2.name} before #{view.name}"
add_to_list(LIST.index(view), v2)
end
if view.yref.to_s.length>0
v2 = HASH[view.yref]
# puts "#{view.name} depends on #{v2.name}, so before adding #{v2.name} before #{view.name}"
add_to_list(LIST.index(view), v2)
end
if view.rref.to_s.length>0
v2 = HASH[view.rref]
# puts "#{view.name} depends on #{v2.name}, so before adding #{v2.name} before #{view.name}"
add_to_list(LIST.index(view), v2)
end
if view.bref.to_s.length>0
v2 = HASH[view.bref]
# puts "#{view.name} depends on #{v2.name}, so before adding #{v2.name} before #{view.name}"
add_to_list(LIST.index(view), v2)
end
end
def construct_list
HASH.each {|k, v|
# puts "adding #{k} currently it's #{LIST.collect{|v| v.name}.join("-")}"
add_to_list(LIST.length, v)
}
# puts LIST.collect{|v| v.name}
end
def objc_gen
code = "// --- VFL GENERATED CODE ---\n"
code << "/*\n"
code << PARAMS[:VFL].split("\n").collect{|l| " "+l.strip}.join("\n")
code << "\n */\n{\n"
code << " // You need to predefine superview before this.\n\n CGRect frame;\n\n"
arh = "" # horizontal autoresizing mask
arv = ""
LIST.each { |view|
code << " frame = #{view.name}.frame;\n" # in case user had predefined sizes, or autocalculated sizes
if view.centerx
code << (exists(view.w) ? " frame.size.width = #{view.w};\n" : " // You need to set frame.size.width before this\n")
code << " frame.origin.x = (superview.bounds.size.width - frame.size.width) / 2.0;\n"
arh = "UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin"
elsif exists(view.x) and exists(view.w)
code << " frame.origin.x = #{view.code_for_x};\n"
code << " frame.size.width = #{view.w};\n"
arh = "UIViewAutoresizingFlexibleRightMargin"
elsif exists(view.w) and exists(view.r)
code << " frame.origin.x = #{view.code_for_right} - (#{view.w});\n"
code << " frame.size.width = #{view.w};\n"
arh = "UIViewAutoresizingFlexibleLeftMargin"
elsif exists(view.x) and exists(view.r)
code << " frame.origin.x = #{view.code_for_x};\n"
code << " frame.size.width = #{view.code_for_right} - frame.origin.x;\n"
arh = "UIViewAutoresizingFlexibleWidth"
else
arh = ""
if exists(view.w)
code << " frame.size.width = #{view.w};\n // You need to set frame.origin.x\n"
arh = "?"
end
if exists(view.x)
code << " frame.origin.x = #{view.code_for_x};\n // You need to set frame.size.width\n"
arh = "UIViewAutoresizingFlexibleRightMargin"
end
if exists(view.r)
code << " // You need to set frame.size.width\n frame.origin.x = #{view.code_for_right} - frame.size.width;\n"
arh = "UIViewAutoresizingFlexibleLeftMargin"
end
if arh.length==0
code << " // You need to set frame.size.width\n // You need to set frame.origin.x\n"
arh = "?"
end
end
if view.centery
code << (exists(view.h) ? " frame.size.height = #{view.h};\n" : " // You need to set frame.size.height before this\n")
code << " frame.origin.y = (superview.bounds.size.height - frame.size.height) / 2.0;\n"
arv = "UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin"
elsif exists(view.y) and exists(view.h)
code << " frame.origin.y = #{view.code_for_y};\n"
code << " frame.size.height = #{view.h};\n"
arv = "UIViewAutoresizingFlexibleBottomMargin"
elsif exists(view.h) and exists(view.b)
code << " frame.origin.y = #{view.code_for_bottom} - #{view.h};\n"
code << " frame.size.height = #{view.h};\n"
arv = "UIViewAutoresizingFlexibleTopMargin"
elsif exists(view.y) and exists(view.b)
code << " frame.origin.y = #{view.code_for_y};\n"
code << " frame.size.height = #{view.code_for_bottom} - frame.origin.y;\n"
arv = "UIViewAutoresizingFlexibleHeight"
else
arv = ""
if exists(view.h)
code << " frame.size.height = #{view.h};\n // You need to set frame.origin.y\n"
arv = "?"
end
if exists(view.y)
code << " frame.origin.y = #{view.code_for_y};\n // You need to set frame.size.height\n"
arv = "UIViewAutoresizingFlexibleBottomMargin"
end
if exists(view.b)
code << " // You need to set frame.size.height\n frame.origin.y = #{view.code_for_bottom} - frame.size.height;\n"
arv = "UIViewAutoresizingFlexibleTopMargin"
end
if arv.length==0
code << " // You need to set frame.size.height\n // You need to set frame.origin.y\n"
arv = "?"
end
end
code << " #{view.name}.frame = frame;\n"
code << (arh=="?" ? " // You need to figure out the horizontal autoresizing mask\n" : " #{view.name}.autoresizingMask |= #{arh};\n")
code << (arv=="?" ? " // You need to figure out the vertical autoresizing mask\n" : " #{view.name}.autoresizingMask |= #{arv};\n")
code << " [superview addSubview:#{view.name}];\n"
code << "\n"
}
code << "}\n// --- END OF CODE GENERATED FROM VFL ---\n"
code
end
def transform_raw_code(vfl)
PARAMS[:VFL] = ""
HASH.clear
LIST.clear
parse(vfl)
construct_list
objc_gen
end
def transform_delimited_code(input)
code = input
vfl_start = "/*\n"
vfl_finish = "*/"
last_i_finish = 0
STARTS_AND_ENDS.each do |start, finish|
$stderr.puts "checking blocks between #{start} and #{finish}"
last_i_finish = 0
while true do
i_start = code.index(start, last_i_finish)
break unless i_start
i_finish = code.index(finish, i_start)
break unless i_finish
last_i_finish = i_finish
$stderr.puts "detected block: #{i_start} - #{i_finish}" if $stdout.isatty
i_vfl_start = code.index(vfl_start, i_start)
i_vfl_end = code.index(vfl_finish, i_vfl_start)
$stderr.puts "vfl: #{i_vfl_start} - #{i_vfl_end}" if $stdout.isatty
vfl = code[i_vfl_start+vfl_start.length..i_vfl_end-1]
newcode = transform_raw_code(vfl.strip)
# find indent
indent = ""
i = i_start - 1
while code[i..i]!="\n" do
indent = code[i..i] + indent
i = i - 1
end
lines = newcode.split("\n")
newcode = ""
lines.each_with_index {|line, idx|
if idx==0 or line.strip.length==0
newcode << line + "\n"
else
newcode << (indent + line) + "\n"
end
}
code[i_start..i_finish+finish.length-1] = newcode
end
end
code
end
def update_file(path)
# start = "\/\/ \-\-\- VFL"
# finish = "VFL \-\-\-\n"
File.open(path, "r") do |f|
code = f.read
code = transform_delimited_code(code)
File.open(path, "w") do |f|
f.write(code)
end
end
end
if __FILE__ == $0
if ARGV[0]=="-h"
$stderr.puts "Usage: #{$0} [-r|--raw]|[-f filename]"
$stderr.puts
$stderr.puts " -r, --raw Treat standard input as raw VFL without comment delimiters"
$stderr.puts " -f filename Transform a file IN PLACE"
$stderr.puts
$stderr.puts "With no file specified, will transform standard input and output to standard output"
elsif ARGV[0]=="-f"
update_file(ARGV[1])
else
if ARGV[0]=="--raw" or ARGV[0]=="-r"
mode = :raw
else
mode = :delimited
end
str = STDIN.read
if mode == :raw
puts transform_raw_code(str)
else
puts transform_delimited_code(str)
end
end
end
| true |
c6de6d2a9d115c12ead3f0d9ccfafb076980058e | Ruby | nono/unified-redis | /lib/unified_redis/core.rb | UTF-8 | 298 | 2.65625 | 3 | [
"MIT"
] | permissive | module UnifiedRedis
class Core
def initialize(redis)
@redis = redis
@adapter = Adapter.get_adapter(redis)
end
def method_missing(command, *args, &block)
#return unless @redis.respond_to?(command.to_sym)
@adapter.call(command, *args, &block)
end
end
end
| true |
8865c6d34f2426371503ce5ab0b3c00a00074869 | Ruby | DeveloperAlan/WDI_SYD_7_Work | /w01/d01/alan/hw_w01_d01.rb | UTF-8 | 4,915 | 4.65625 | 5 | [] | no_license | # Building Ruby Familiarity
# In this exercise you will take a first look at some common commands in Ruby
# The idea here is to build familiary with Ruby syntax
# This will likely be the first time you've seen some of these commands
# Just type them in and see the displayed output
# Steps:
# 1. Open up a new terminal window
# 2. Launch irb
# 3. Paste a line of code into irb
# 4. Press return
# 5. Write down the displayed output in a file in today's homework folder
# 6. Repeat steps 3-5 for all lines below in order
first_ans = 7 / 2
#The answer turns out to be 3 because it is an integer. Integers are whole numbers. first_ans is defined as 3 in the memory
puts first_ans
#the answer prints out as 3, the nil represent that there is no errors
print first_ans
#the answer prints out as 3 but with no new line seperator, the nil represents that there is no errors
first_ans = 7 / 2.to_f
#the answer prints out as 3.5
first_ans = 7.to_f / 2
#the answer prints out as 3.5
first_ans = 7 / 2.0
#the answer prints out as 3.5
first_ans = 7.0 / 2
#the answer prints out as 3.5
first_ans = first_ans.round * 4
#first_ans is 3.5, rounded up is 4. four times four is 16. first_ans is now 16.
def get_character(full_string, index)
full_string[index]
end
#=>get_character inputs the method/function and the instructions
message_string = "oicdlcwhejkeenoemrstuo"
#defines message_string to "oicdlcwhejkeenoemrstuo"
character_1 = get_character(message_string, 4)
#output is l because it is the 5th position in oicdlcwhejkeenoemrstuo
character_2 = get_character(message_string, 7)
#output is h because it is the 8th position in oicdlcwhejkeenoemrstuo
character_3 = get_character(message_string, 2)
#output is c because it is the 3rd position in oicdlcwhejkeenoemrstuo
message_array = [character_1, character_2]
#["l", "h"] is the character_1 and character_2
message_array.push(character_2)
#["h"] is added with ["l", "h"], message array is now ["h"]
message_array.pop()
#write the message_array, which is h
message_array.push(character_3)
#Adds["c"] to the current ["l", "h", "h"], as character_3 is c
message_array
#Depending on what is in memeory at the moment, it will show what is it is. At this point it is ["l", "h", "h", "c"]
puts message_array
#prints l , h , h , c each in different lines.
print message_array
#prints current message_array, which is ["l", "h", "h", "c"]
value_float_1 = Math.sin(Math::PI / 2)
#value_float_1 is defined as math.sin(Math::PI / 2) which equals to 1. Math is part of the Ruby API/one of the methods
value_float_2 = Math.cos(Math::PI)
#value_float_2 is defined as math.cos(math::PI) which is equals to -1.
value_float_3 = (value_float_1 + value_float_2)
#adds value_float_1 and value_float_2 which is 0
value_integer_1 = (value_float_1 + value_float_2).to_i
#changes the answer to value_integer_1 into a integer
value_float_1 = value_float_1 * 4
#the current value_float_1 times 4 makes the new value_float_1, which is 4.0
value_float_2 *= 5
#the current value_float_2 times 5 makes the new value_float_2, which is -5.0
value_float_2 = value_float_2.abs
#the currrent absolute sum of value_float_2, which is 5.0
value_integer_1 += 8
#adds 8 to the current value_integer_1 to create the new value_integer_1, which is 8
value_float_4 = value_integer_1 * 3
#value_float_4 is defined as 8(from the current value_integer_1) * 3, which is 24
value_float_3 -= 1
#value_float_3 is equal to the current value_float_3 - 1, which is -1.0
number_array = [value_float_1, value_float_2, value_float_3, value_float_4]
#defines the number array, using the numbers stored in the floats.
number_array.push(first_ans)
#puts first_ans as the 5th array in number_array, as 16
number_array.unshift(value_integer_1)
#unshift adds value_integer_1 to the beginning of the array, in this isntance is 8
number_array.push(value_integer_1)
#push value_integer_1 at the end of the array, in this instance is 8
number_array.unshift( Math.sqrt(36) )
#unshift adds the square root of 36 to the front of the array, which is 6
number_array.delete_at(5)
#deletes the 6th number in the array, which in this case is 24(as shown in the console)
number_array.push( [19, 21, 6, 3, 1] )
#adds the array of numbers into the number_array as it's own category
number_array.flatten!
#puts all existing array within number_array in the same level as number_array
number_array.each { |current_index| puts get_character(message_string, current_index) }
#number_array.each means that every number in the array gets used for the following method. |current_index| is an absolute value and every number
#an absolute value. puts prints out each number solution when it gets fed into the method, which the method decides which part of the string it
#would use using the number and the message_string "oicdlcwhejkeenoemrstuo". Prints out for every number in the number_array. Clever. | true |
2f336844246bc62582608748eb1f78f23fca26f3 | Ruby | kwatch/rubinius | /spec/ruby/1.8/core/numeric/div_spec.rb | UTF-8 | 1,173 | 3.03125 | 3 | [] | no_license | require File.dirname(__FILE__) + '/../../spec_helper'
# FIXME: this awful wording
describe "Numeric#div" do
it "div right integers" do
13.div(4).should == 3
4.div(13).should == 0
end
it "div right integers and floats" do
13.div(4.0).should == 3
4.div(13).should == 0
end
it "div right the integers and floats" do
13.div(4.0).should == 3
4.div(13).should == 0
end
it "div right floats" do
13.0.div(4.0).should == 3
4.0.div(13).should == 0
end
it "returns self divided by other" do
(3**33).div(100).should == 55590605665555
end
it "raises an ArgumentError if not passed one argument" do
lambda { 13.div }.should raise_error(ArgumentError)
lambda { 13.div(1, 2) }.should raise_error(ArgumentError)
end
it "raises a ZeroDivisionError if passed 0" do
lambda { 13.div(0) }.should raise_error(ZeroDivisionError)
end
it "raises a TypeError if not passed a Numeric type" do
lambda { 13.div(nil) }.should raise_error(TypeError)
lambda { 13.div('test') }.should raise_error(TypeError)
lambda { 13.div(true) }.should raise_error(TypeError)
end
end
| true |
081d0b0ca105555d2ba57e52b4de68d637774d24 | Ruby | lroberts77/GildedRose-Refactoring-Kata | /lib/gilded_rose.rb | UTF-8 | 3,084 | 3.375 | 3 | [
"MIT"
] | permissive | require_relative 'item'
class GildedRose
MAXIMUMQUALITY = 50
MINIMUMQUALITY = 0
MINIMUMSELLIN = 0
def initialize(items)
@items = items
end
def update_quality()
@items.each do |item|
#Generic item
if generic_item(item)
item.sell_in <= MINIMUMSELLIN ? item.quality -= 2 : item.quality -= 1 unless item.quality == MINIMUMQUALITY
end
#Conjured items
if item.name == "Conjured"
item.sell_in <= MINIMUMSELLIN ? item.quality -= 4 : item.quality -= 2 unless item.quality == MINIMUMQUALITY
end
#Aged Brie
if item.name == "Aged Brie"
item.sell_in <= MINIMUMSELLIN ? item.quality += 2 : item.quality += 1 unless item.quality == MAXIMUMQUALITY
end
# Backstage passes to a TAFKAL80ETC concert
if item.name == "Backstage passes to a TAFKAL80ETC concert"
item.sell_in <= 5 ? item.quality += 3 : item.quality += 2 unless item.quality == MAXIMUMQUALITY
if item.sell_in == MINIMUMSELLIN
item.quality = MINIMUMQUALITY
end
end
#Sulfuras, Hand of Ragnaros
if item.name == "Sulfuras, Hand of Ragnaros"
item.quality = 80
item.sell_in += 1
end
item.sell_in -= 1
end
end
end
def generic_item(item)
item.name != "Aged Brie" &&
item.name != "Backstage passes to a TAFKAL80ETC concert" &&
item.name != "Sulfuras, Hand of Ragnaros" &&
item.name != "Conjured"
end
# THIS IS THE ORIGINAL CODE WHICH I HAVE REFACTORED ABOVE
# if item.name != "Aged Brie" and item.name != "Backstage passes to a TAFKAL80ETC concert"
# if item.quality > 0
# if item.name != "Sulfuras, Hand of Ragnaros"
# item.quality = item.quality - 1
# end
# end
# else
# if item.quality < 50
# item.quality = item.quality + 1
# if item.name == "Backstage passes to a TAFKAL80ETC concert"
# if item.sell_in < 11
# if item.quality < 50
# item.quality = item.quality + 1
# end
# end
# if item.sell_in < 6
# if item.quality < 50
# item.quality = item.quality + 1
# end
# end
# end
# end
# end
# if item.name != "Sulfuras, Hand of Ragnaros"
# item.sell_in = item.sell_in - 1
# end
# if item.sell_in < 0
# if item.name != "Aged Brie"
# if item.name != "Backstage passes to a TAFKAL80ETC concert"
# if item.quality > 0
# if item.name != "Sulfuras, Hand of Ragnaros"
# item.quality = item.quality - 1
# end
# end
# else
# item.quality = item.quality - item.quality
# end
# else
# if item.quality < 50
# item.quality = item.quality + 1
# end
# end
# end
# end
# end
# end
| true |
72acbcf194c0ecd01b1dc5e992dd54e5996347ca | Ruby | breakliu/MatrixCalc | /matrix_calc.rb | UTF-8 | 2,366 | 3.765625 | 4 | [] | no_license | class MatrixCalc
attr_reader :foot_print
def initialize(array)
@array = array
end
def calc
if matrix?
result = 0
@row = 0
@col = 0
@foot_print = []
init_steps
# 超始方向是1(右:1, 下:2, 左:3, 上:4)
@direction = 1
begin
mark_step
result += @array[@row][@col]
end while next_step
result
else
'The array is not a matrix'
end
end
private
# 简单地对输入数据进行验证
def matrix?
if @array == [[]] or not @array.is_a?(Array) or not @array.first.is_a?(Array)
false
elsif @array.map { |row| row.size }.uniq.count > 1
false
else
true
end
end
# 记录走过的脚步,初始化为0
def init_steps
@rows = @array.size
@cols = @array.first.size
@steps = ([0] * @rows * @cols).each_slice(@cols).to_a
end
# 走过了标记为1
def mark_step
@steps[@row][@col] = 1
@foot_print << @array[@row][@col]
end
def next_step
# 如果不能前进, 最多尝试四次, 即四个方向, 也就是在结束点转一圈
4.times.each do
case @direction
when 1
right
when 2
down
when 3
left
when 4
up
end
if @steps[@row][@col] == 0
return true
else
if @direction == 4
@direction = 1
else
@direction += 1
end
end
end
# 到达这里,证明矩阵已经算完了
false
end
# 下面四个方法为判断能否往相应的方向前进
def right
#p "current: [#{@row}][#{@col}]. want to right [#{@row}][#{@col+1}]"
@col += 1 if @col+1 < @cols and @steps[@row][@col+1] == 0
end
def down
#p "current: [#{@row}][#{@col}]. want to down [#{@row+1}][#{@col}]"
@row += 1 if @row+1 < @rows and @steps[@row+1][@col] == 0
end
def left
#p "current: [#{@row}][#{@col}]. want to left [#{@row}][#{@col-1}]"
@col -= 1 if @col-1 >= 0 and @steps[@row][@col-1] == 0
end
def up
#p "current: [#{@row}][#{@col}]. want to up [#{@row-1}][#{@col}]"
@row -= 1 if @row-1 >= 0 and @steps[@row-1][@col] == 0
end
end
#matrix = MatrixCalc.new(
#[
#[12,32,9,11,34],
#[8,54,76,23,07],
#[27,18,25,9,43],
#[11,23,78,63,19],
#[9,22,56,31,05]
#]
#)
#p matrix.calc
| true |
b8eebd72d4393eeb9aae53992b3ab33d558070db | Ruby | kuraga/survey_rgnf | /populations/by_question_and_population_mapper_processor.rb | UTF-8 | 938 | 2.984375 | 3 | [] | no_license | require_relative '../lib/processors/by_question_and_group_mapper_processor'
module Populations
class ByQuestionAndPopulationMapperProcessor < ByQuestionAndGroupMapperProcessor
def initialize(data, population_question_name, populations = DEFAULT_POPULATIONS)
super data, population_question_name
@populations = populations
end
protected
DEFAULT_POPULATIONS = {
'1' => 'село, деревня',
'2' => 'небольшой город',
'3' => 'областной/краевой центр',
'4' => 'мегаполис (большой город)'
}
def get_group(unit)
if unit.has_key?(@group_question_name)
population_answer = unit[@group_question_name]
unless population_answer.nil?
population_answer.match(/_(\d+)$/) { |m| @populations[m[1]] }
else
nil
end
else
nil
end
end
end
end
| true |
dd01cd3c6c0d3dde3b11e1a929a36c837267f99e | Ruby | craighdunn/skillcrush-ruby-challenges | /pareent_classes.rb | UTF-8 | 782 | 3.796875 | 4 | [] | no_license | #I am not a gun nut. I thought really hard about an example to use. This was the best I could come up with for a group of things that had enough in common and different to be good practice.
class Weapon
attr_writer :name, :material
attr_reader :name, :material
end
class Pistol < Weapon
attr_accessor :ammo, :range
def about_pistol
return "The #{@name} is a pistol that is made of #{@material}. It can fire #{@ammo} caliber bullets and is accurate at a range of #{@range}"
end
end
class Sword < Weapon
attr_accessor :length, :hands
end
class Explosive < Weapon
attr_accessor :delivery, :radius
end
my_pistol = Pistol.new
my_pistol.name = "Mark 1 Desert Eagle"
my_pistol.material = "steel"
my_pistol.ammo = ".44 Magnum"
my_pistol.range = "200m"
puts my_pistol.about_pistol | true |
cf44b4738d345acd925eae4116499e8ecff4897b | Ruby | lishulongVI/leetcode | /ruby/685.Redundant Connection II(冗余连接 II).rb | UTF-8 | 4,955 | 3.6875 | 4 | [
"MIT"
] | permissive | =begin
<p>
In this problem, a rooted tree is a <b>directed</b> graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
</p><p>
The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, ..., N), with one additional directed edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
</p><p>
The resulting graph is given as a 2D-array of <code>edges</code>. Each element of <code>edges</code> is a pair <code>[u, v]</code> that represents a <b>directed</b> edge connecting nodes <code>u</code> and <code>v</code>, where <code>u</code> is a parent of child <code>v</code>.
</p><p>
Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.
</p><p><b>Example 1:</b><br />
<pre>
<b>Input:</b> [[1,2], [1,3], [2,3]]
<b>Output:</b> [2,3]
<b>Explanation:</b> The given directed graph will be like this:
1
/ \
v v
2-->3
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
<b>Input:</b> [[1,2], [2,3], [3,4], [4,1], [1,5]]
<b>Output:</b> [4,1]
<b>Explanation:</b> The given directed graph will be like this:
5 <- 1 -> 2
^ |
| v
4 <- 3
</pre>
</p>
<p><b>Note:</b><br />
<li>The size of the input 2D-array will be between 3 and 1000.</li>
<li>Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.</li>
</p><p>在本问题中,有根树指满足以下条件的<strong>有向</strong>图。该树只有一个根节点,所有其他节点都是该根节点的后继。每一个节点只有一个父节点,除了根节点没有父节点。</p>
<p>输入一个有向图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。</p>
<p>结果图是一个以<code>边</code>组成的二维数组。 每一个<code>边</code> 的元素是一对 <code>[u, v]</code>,用以表示<strong>有向</strong>图中连接顶点 <code>u</code> and <code>v</code>和顶点的边,其中父节点<code>u</code>是子节点<code>v</code>的一个父节点。</p>
<p>返回一条能删除的边,使得剩下的图是有N个节点的有根树。若有多个答案,返回最后出现在给定二维数组的答案。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> [[1,2], [1,3], [2,3]]
<strong>输出:</strong> [2,3]
<strong>解释:</strong> 给定的有向图如下:
1
/ \
v v
2-->3
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> [[1,2], [2,3], [3,4], [4,1], [1,5]]
<strong>输出:</strong> [4,1]
<strong>解释:</strong> 给定的有向图如下:
5 <- 1 -> 2
^ |
| v
4 <- 3
</pre>
<p><strong>注意:</strong></p>
<ul>
<li>二维数组大小的在3到1000范围内。</li>
<li>二维数组中的每个整数在1到N之间,其中 N 是二维数组的大小。</li>
</ul>
<p>在本问题中,有根树指满足以下条件的<strong>有向</strong>图。该树只有一个根节点,所有其他节点都是该根节点的后继。每一个节点只有一个父节点,除了根节点没有父节点。</p>
<p>输入一个有向图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。</p>
<p>结果图是一个以<code>边</code>组成的二维数组。 每一个<code>边</code> 的元素是一对 <code>[u, v]</code>,用以表示<strong>有向</strong>图中连接顶点 <code>u</code> and <code>v</code>和顶点的边,其中父节点<code>u</code>是子节点<code>v</code>的一个父节点。</p>
<p>返回一条能删除的边,使得剩下的图是有N个节点的有根树。若有多个答案,返回最后出现在给定二维数组的答案。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> [[1,2], [1,3], [2,3]]
<strong>输出:</strong> [2,3]
<strong>解释:</strong> 给定的有向图如下:
1
/ \
v v
2-->3
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> [[1,2], [2,3], [3,4], [4,1], [1,5]]
<strong>输出:</strong> [4,1]
<strong>解释:</strong> 给定的有向图如下:
5 <- 1 -> 2
^ |
| v
4 <- 3
</pre>
<p><strong>注意:</strong></p>
<ul>
<li>二维数组大小的在3到1000范围内。</li>
<li>二维数组中的每个整数在1到N之间,其中 N 是二维数组的大小。</li>
</ul>
=end
# @param {Integer[][]} edges
# @return {Integer[]}
def find_redundant_directed_connection(edges)
end | true |
511f6b496f8a3a70b8844eede04abcd5cd26000e | Ruby | postazure/Ruby-Practice | /CH8/ArrayNames.rb | UTF-8 | 197 | 3.5625 | 4 | [] | no_license | names = ["Ada", "Belle","Chris"]
puts names
puts
puts names[0]
puts names[1]
puts names[2]
puts names[3] # this is out of range
#this does not produce and error,
# in ruby its actually empty (nil) | true |
3cdd72b9b23e931e522444a024a46ccac353d485 | Ruby | lgreenberg23/ruby-collaborating-objects-lab-web-062617 | /lib/song.rb | UTF-8 | 823 | 3.46875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # The Song class will be responsible for creating songs given
# each filename and sending the artist's name (a string) to the Artist class
require 'pry'
class Song
attr_accessor :name, :artist
# attr_reader :artist
#@@song_array = []
def initialize(name)
@name = name
end
# def self.artist=(artist)
# self.artist = artist
# end
def self.new_by_filename(file_name)
song_array = file_name.split(" - ")
song = self.new(song_array[1])
#song.name = song_array[1]
artist = Artist.find_or_create_by_name(song_array[0])
artist.add_song(song)
song.artist = artist
# binding.pry
song
end
end
# song_array
# artist_name = song_array[0]
# array_part_2 = song_array[1].split(".")
# name = array_part_2[0]
# format = array_part_2[1]
# self.create_by_name(name, artist_name) | true |
8f0d11b6b6acbbc9430d72adf292932631e81da3 | Ruby | danliu277/project-euler-sum-square-difference-nyc-web-120919 | /lib/oo_sum_square_difference.rb | UTF-8 | 491 | 3.6875 | 4 | [] | no_license | # Implement your object-oriented solution here!
class SumSquareDifference
attr_accessor :difference
def initialize(input)
@difference = self.square_sum(input) - self.sum_square(input)
end
def sum_square(input)
sum = 0
(1..input).each do |x|
sum += (x * x)
end
return sum
end
def square_sum(input)
sum = 0
(1..input).each do |x|
sum += x
end
return sum * sum
end
end | true |
e0e03be48d7b9a4b3180b29be40fe74ad756f8fd | Ruby | ftomassetti/codemodels-javaparserwrapper | /test/test_parser.rb | UTF-8 | 3,031 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | require 'helper'
$CLASSPATH << 'test/dummyjavaparser/classes'
java_import 'it.codemodels.javaparserwrapper.ast.Project'
java_import 'it.codemodels.javaparserwrapper.ast.Todo'
java_import 'java.util.Date'
java_import 'java.util.GregorianCalendar'
class TestParser < Test::Unit::TestCase
include CodeModels::JavaParserWrapper
module Src
class A
attr_accessor :x
attr_accessor :y
end
end
module Dest
class A < RGen::MetamodelBuilder::MMBase
has_attr 'x',Integer
has_attr 'y',String
end
class Todo < RGen::MetamodelBuilder::MMBase
has_attr 'description',String
has_attr 'status',String
end
class Project < RGen::MetamodelBuilder::MMBase
has_attr 'name',String
contains_many_uni 'todos', Todo
end
end
class MyJavaObjectsToRgenTransformer < JavaObjectsToRgenTransformer
# include CodeModels::Javaparserwrapper::BasicTransformationFactory
def initialize
super
@factory.target_module = TestParser::Dest
end
end
def setup
@poli = Project.new('Poli')
@original_a = Src::A.new
@original_a.x = 1
@original_a.y = '2'
d1 = GregorianCalendar.new
@fill_report = Todo.new('fill report')
@have_a_party = Todo.new('have a party!')
@have_a_party.status = Todo::Status::WORKING_ON
@poli.addTodo(@fill_report)
@poli.addTodo(@have_a_party)
end
class MyBasicTransformationFactory < CodeModels::JavaParserWrapper::BasicTransformationFactory
# include CodeModels::Javaparserwrapper::BasicTransformationFactory
def initialize
self.target_module = TestParser::Dest
end
end
def test_basic_transformation_factory
tf = MyBasicTransformationFactory.new
transformed = tf.instantiate_transformed(@original_a)
assert transformed.is_a?(TestParser::Dest::A)
end
def test_node_to_model_simple_attr
j2rt = MyJavaObjectsToRgenTransformer.new
t = j2rt.node_to_model(@poli)
assert t.is_a?(Dest::Project)
assert_equal 'Poli',t.name
end
def test_node_to_model_enum_attr
j2rt = MyJavaObjectsToRgenTransformer.new
t = j2rt.node_to_model(@fill_report)
assert t.is_a?(Dest::Todo)
assert_equal 'fill report',t.description
assert_equal 'NOT_STARTED',t.status
t = j2rt.node_to_model(@have_a_party)
assert t.is_a?(Dest::Todo)
assert_equal 'have a party!',t.description
assert_equal 'WORKING_ON',t.status
end
def test_node_to_model_containment
j2rt = MyJavaObjectsToRgenTransformer.new
t = j2rt.node_to_model(@poli)
assert_equal 2,@poli.todos.count
assert_equal 'fill report',@poli.todos[0].description
assert_equal 'have a party!',@poli.todos[1].description
end
end | true |
a4f4565778092fe276106fc464dec9f9dea4acbf | Ruby | reqshark/commandlinetools | /sysadmin/backup/rubycookbook/21-ui/10 - Allowing Input Editing with Readline.rb | UTF-8 | 509 | 3.03125 | 3 | [] | no_license | #!/usr/bin/ruby -w
# readline.rb
require 'readline'
vegetable = Readline.readline("What's your favorite vegetable?> ")
puts "#{vegetable.capitalize}? Are you crazy?"
#---
$ ruby readline.rb
What's your favorite vegetable?> okra
Okra? Are you crazy?
#---
# readline_windows.rb
print "What's your favorite vegetable?> "
puts gets.chomp.capitalize + "? Are you crazy?"
#---
#!/usr/bin/ruby -w
# mini_irb.rb
require 'readline'
line = 0
loop do
eval Readline.readline('%.3d> ' % line, true)
line += 1
end
#---
| true |
f2326be8320388f42869322f276d19dfb00f53a2 | Ruby | rgo594/school-domain-nyc-web-career-040119 | /lib/school.rb | UTF-8 | 539 | 3.703125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class School
attr_accessor :grade
attr_reader :roster
def initialize(name)
@name = name
@grade
@roster = {}
end
def add_student(name, grade)
if roster[grade]
roster[grade] << name
else
roster[grade] = []
roster[grade] << name
end
end
def grade(grade)
roster.each do |key, value|
if key == grade
return value
end
end
end
def sort
hash = {}
roster.each do |key, value|
hash[key] = value.sort
end
hash
end
end
| true |
88a6b5fec1ef07fff4da621f55b9489bd7fcfe24 | Ruby | jdan/adventofcode | /2015/rb/2015/19a-medicine.rb | UTF-8 | 1,199 | 3.4375 | 3 | [] | no_license | # http://adventofcode.com/day/19
def index_all(haystack, needle)
offset = 0
indices = []
# Initial value
index = haystack.index(needle, offset)
until index.nil?
indices << index
# Move the offset
offset = index + 1
# Find the next index
index = haystack.index(needle, offset)
end
indices
end
substitutions = {}
original = ""
molecules = []
ARGF.each do |line|
if line =~ /=>/
find, replace = line.scan(/(\w+) => (\w+)/)[0]
if substitutions[find]
substitutions[find] << replace
else
substitutions[find] = [replace]
end
elsif line =~ /\w+/
original = line
end
end
# For each substitution rule
substitutions.each do |key, value|
# For each index of the substitution in the string
index_all(original, key).each do |index|
# For each replacement
value.each do |replacement|
# Build a new molecule
molecules << original[0...index] +
original[index..-1].sub(key, replacement)
end
end
end
puts molecules.uniq.count
| true |
9253d19e5b3ab9f10396b0f58af718849cda39d6 | Ruby | draffensperger/tt_demos | /lib/tt_demos/arg_checked_double/no_method_on_arg.rb | UTF-8 | 452 | 3.453125 | 3 | [
"MIT"
] | permissive | module NoMethodOnArg
class GreetingApp
def self.run
# give nil for default language
language = nil
Greeter.new.greet(language)
end
end
class Greeter
HELLOS = { english: 'Hello',
german: 'Hallo' }
def greet(language)
# language can be string or symbol
hello = HELLOS[language.to_sym]
puts("#{hello}!")
end
end
end
=begin
bundle console
NoMethodOnArg::GreetingApp.run
=end
| true |
db74a3595062bddfcdac6d94c4f0d1bb6d664756 | Ruby | jenpoole/rb-grade-avg | /user_input.rb | UTF-8 | 1,075 | 3.921875 | 4 | [] | no_license | require_relative("averages.rb")
class Input
attr_accessor :student_name, :score1, :score2, :score3, :students_and_scores
def user_input
@students_and_scores = {}
counter = 0
while counter < 25
puts "Enter student name: "
@student_name = gets.chomp
puts "Enter first test score: "
@score1 = gets.chomp.to_i
puts "Enter second test score: "
@score2 = gets.chomp.to_i
puts "Enter third test score: "
@score3 = gets.chomp.to_i
puts "Are you done entering student information?"
@exit_loop = gets.chomp.downcase
# add students and their scores to hash
@students_and_scores[@student_name] = [@score1, @score2, @score3]
break if @exit_loop == "yes"
counter += 1
end
end
end
x = Input.new
puts x.user_input
grade_calc = Calculator.new
grade_calc.average(x.students_and_scores) | true |
6e56d201cee01c55ccb621080d8e63a1496bac9a | Ruby | batizhevsky/puzzlenode-solutions | /1/trade.rb | UTF-8 | 1,748 | 3.1875 | 3 | [] | no_license | require 'rexml/document'
require 'csv'
require 'bigdecimal'
class Trade
def self.total item, currency
prices = Trade.get_item_price item
conv = Trade.convert prices, currency
total = conv.inject(BigDecimal.new(0)){|sum, pr| sum + pr}.round(2, :banker).to_s('F')
File.open('OUTPUT.txt', 'w') { |f| f.puts total }
end
def self.get_item_price item
stocks = []
CSV.foreach("TRANS.csv", headers: true) do |row|
stocks << row['amount'] if row['sku'] == item
end
stocks
end
def self.load_rates
rates = {}
file = File.new("RATES.xml")
doc = REXML::Document.new file
doc.elements.to_a('//rates/rate').each do |el|
from = el.elements["from"].first.to_s
to = el.elements["to"].first.to_s
rate = el.elements["conversion"].first.to_s
rates[from] = { to => rate }
end
rates
end
def self.find_path rates, search, path=[]
dist = []
rates.each_key do |k|
dist[k] = Float::INFINITY
end
end
def self.convert prices, currency
res = []
rates = Trade.load_rates
puts rates
rate = ""
prices.each do |pr|
cost, item_cur = pr.split(' ')
cost = BigDecimal.new cost
if item_cur != currency
exchange = rates[item_cur]
if exchange[currency]
rate = BigDecimal.new(exchange[currency]).round(2, :banker)
else
exchange.each_key do |val|
if rates[val] && rates[val][currency]
rate = BigDecimal.new(exchange[val]) * BigDecimal.new(rates[val][currency])
break
end
end
end
cost *= rate
end
res << cost.round(2, :banker)
end
res
end
end
Trade.total "DM1182", "USD"
| true |
f029033eb8a64d9c5a422e60139395911b5b8452 | Ruby | LukeRobertsonUK/pet_shop | /main.rb | UTF-8 | 3,062 | 3.21875 | 3 | [] | no_license | require 'pry'
require_relative 'client'
require_relative 'animal'
require_relative 'shelter'
#initialize existing objects
hq = Shelter.new("Headquarters", "55 Clapham High Street")
people = [
Client.new("Luke", 35, :male, 1),
Client.new("Fred", 22, :male, 1),
Client.new("Wilma", 45, :female, 0),
Client.new("Tracy", 37, :female, 0),
Client.new("Brian", 19, :male, 2),
Client.new("Betty", 25, :female, 1)
]
people.each do |person|
hq.clients[person.name.downcase] = person
end
hq.clients["luke"].pets["olaff"] = Animal.new("Olaff", "Poodle", 2, :male, "rubber duck")
hq.clients["betty"].pets["bernie"] = Animal.new("Bernie", "Bulldog", 3, :male, "toy sheep")
animals = [
Animal.new("Woofer", "German Shepheard", 3, :male, "rubber duck"),
Animal.new("Bilbo", "Parson Russell", 1, :male, "tennis ball"),
Animal.new("K-9", "Yorkshire Terrier", 2, :female, "fake bone"),
Animal.new("Fido", "Bull Terrier", 5, :male, "toy sheep"),
Animal.new("Arnold", "Sheep Dog", 7, :male, "toy sheep"),
Animal.new("Lassy", "Collie", 8, :female, "tennis ball"),
Animal.new("TheLittlestHobo", "German Shepheard", 5, :male, "fake bone"),
Animal.new("Mumrah The Ever Living", "Labradoodle", 1, :female, "tennis ball")
]
animals.each do |animal|
hq.inventory[animal.name.downcase] = animal
end
def add_dog(branch_or_client)
puts "What's the dog called?"
n = gets.chomp.downcase.to_s
puts "What breed is it?"
b = gets.chomp.downcase.to_s
puts "How old is it?"
a= gets.chomp.downcase.to_i
puts "What sex is it?"
s = gets.chomp.downcase.to_sym
puts "And what's it's favourite toy?"
t = gets.chomp.downcase.to_s
branch_or_client.dog_adder(Animal.new(n, b, a, s, t))
end
#run the app
condition = true
while condition
puts `clear`
puts "----------------------------------"
puts "ANIMAL SHELTER MANAGEMENT SYSTEM"
puts "----------------------------------"
puts "\nPlease select an option:"
puts "Get (c)lient information"
puts "(A)dd a new client"
puts "(D)isplay current inventory"
puts "Check-(o)ut a dog"
puts "Check-(i)n a dog"
puts "(V)iew dogs on file for a particular client"
puts "Add a new dog to (r)ecords"
response = gets.chomp.downcase
case response
when 'c'
hq.list_clients
when 'a'
hq.new_client_record
when 'd'
hq.display_inventory
when 'o'
hq.check_out
when 'i'
hq.list_clients
puts "\nWho is checking-in the animal?"
seller = hq.clients[gets.chomp.downcase.to_s]
seller.give_up(hq)
hq.display_inventory
when 'v'
hq.list_clients
puts "\nWhose pets would you like to see?"
hq.clients[gets.chomp.downcase.to_s].display_pets
when 'r'
puts "Add to (i)nventory or a (c)lient?"
response = gets.chomp.downcase
if response == "i"
add_dog(hq)
else
puts "\nOK, which client?"
hq.list_clients
add_dog(hq.clients[gets.chomp.downcase.to_s])
end
end
puts "\nWould you like to run the program again or (q)uit?"
condition = false if gets.chomp.downcase == "q"
end
| true |
0587d20d6b616422e0b683589d227ad014c687d6 | Ruby | npogodina/hotel | /lib/date_range.rb | UTF-8 | 780 | 3.265625 | 3 | [] | no_license | module Hotel
class DateRange
attr_reader :start_date, :end_date
def initialize(start_date:, end_date:)
#TODO: validate dates' input
#TODO: add defaults (for example, one year from/before Date.today)
@start_date = Date.parse(start_date)
@end_date = Date.parse(end_date)
raise ArgumentError.new("End date cannot be equal to or come before start date.") if @end_date <= @start_date
end
def overlap?(date_range)
raise ArgumentError.new("Must provide a date range.") unless date_range.is_a? DateRange
#TODO: efficient date checking (first compare years? months?)
start_date < date_range.end_date && end_date > date_range.start_date
end
def nights
(end_date - start_date).to_i
end
end
end | true |
b1df788d4b42253eda8e2f39b8a19be14fc8a21b | Ruby | puffsun/itebooks | /test/lib/itebooks/base_test.rb | UTF-8 | 1,179 | 2.625 | 3 | [
"MIT"
] | permissive | require_relative '../../test_helper.rb'
describe Itebooks::Base do
subject {Itebooks::Base}
describe "querying from www.it-ebooks.info website" do
it "must have the it-ebooks.info api base url" do
subject.base_uri.must_equal("http://it-ebooks-api.info/v1")
subject.request.wont_be_empty
subject.request.must_include("IT-eBooks")
end
it "must return error message for empty search keywords" do
errorMsg = "Please enter one or more search keywords, separated by space."
subject.search(nil).must_equal(errorMsg)
subject.search("").must_equal(errorMsg)
end
it "must return books info in json string with books that exist" do
subject.search("mysql").wont_be_empty
subject.search("mysql").code.must_equal(200)
subject.search("mysql").body.downcase.must_include("mysql")
end
it "must return error message for failed request" do
# Search without network connection
end
it "must return parsed result for successful search" do
result = subject.search_and_print("mysql")
result.must_be_instance_of(Hash)
result['Books'].must_be_instance_of(Array)
end
end
end
| true |
db52f1a78f71b877769cda42b44a4d99b815b708 | Ruby | sjv-vinsol/Learning | /advance_ruby/exercise_dynamic_method_calling/bin/main.rb | UTF-8 | 405 | 3.125 | 3 | [] | no_license | require_relative '../lib/derived'
require_relative '../lib/string'
extract_class_pattern = /(.*).new/
puts 'Create object : '
input_object = gets.chomp
extract_class_pattern.match(input_object)
klass = Object.const_get($1)
obj = klass.new
print 'Enter a method name :'
input_method = gets.chomp
parsed = input_method.get_method_and_params
method_name = parsed.shift
puts obj.send(method_name, *parsed) | true |
0e678e86cbbf138fa94702bdb9137fc69dca3f8e | Ruby | PayTrace/paytrace_ruby | /lib/paytrace/debug.rb | UTF-8 | 3,108 | 2.890625 | 3 | [
"MIT"
] | permissive | require 'paytrace'
require 'minitest/autorun'
module PayTrace
# Useful helper methods for debugging.
module Debug
#
# Helper that loops through the response values and dumps them out
#
def self.dump_transaction
puts "[REQUEST] #{PayTrace::API::Gateway.last_request}"
response = PayTrace::API::Gateway.last_response_object
if(response.has_errors?)
response.errors.each do |key, value|
puts "[RESPONSE] ERROR: #{key.ljust(20)}#{value}"
end
else
response.values.each do |key, value|
puts "[RESPONSE] #{key.ljust(20)}#{value}"
end
end
end
# Formatted output for a text message.
def self.log(msg)
puts ">>>>>> #{msg}"
end
# split a raw request string into an array of name-value tuples
def self.split_request_string(raw)
raw.split('|').map {|kv_pair| kv_pair.split('~')}
end
# Helper method to dump a request response pair. Usage:
# Usage:
# PayTrace::Debug.trace do
# # code the intiates a request/response pair
# end
# _Note:_ also includes exception handling to ensure responses are dumped even if an exception occurs
def self.trace(&block)
PayTrace::API::Gateway.debug = true
begin
yield
rescue PayTrace::Exceptions::ErrorResponse => e
puts "[REQUEST] #{PayTrace::API::Gateway.last_request}"
puts "[RESPONSE] #{PayTrace::API::Gateway.last_response}"
raise
else
dump_transaction
end
end
# Helper method to configure a default test environment. Accepts *username*, *password*, and *domain* parameters.
# domain defaults to "stage.paytrace.com" and the username/password default to the credentials for the sandbox account
def self.configure_test(un = "demo123", pw = "demo123", domain = "stage.paytrace.com")
PayTrace.configure do |config|
config.user_name = un
config.password = pw
config.domain = domain
end
end
# helper method to make CodeClimate happy
def self.split_tuples(raw, case_sensitive = false)
PayTrace::Debug.split_request_string(raw).map {|tuple| case_sensitive ? tuple : [tuple[0].upcase, tuple[1]]}
end
# verify whether two requests match
def self.diff_requests(expected_raw, actual_raw, case_sensitive = false)
whats_wrong = []
expected = PayTrace::Debug.split_tuples(expected_raw, case_sensitive)
actual = PayTrace::Debug.split_tuples(actual_raw, case_sensitive)
expected_remaining = []
actual_extra = actual.dup
expected.each do |tuple|
idx = actual_extra.find_index(tuple)
if idx.nil?
expected_remaining << tuple
else
actual_extra.delete_at(idx)
end
end
expected_remaining.each do |tuple|
whats_wrong << "Missing expected property #{tuple[0]}~#{tuple[1]}"
end
actual_extra.each do |tuple|
whats_wrong << "Extra unexpected property #{tuple[0]}~#{tuple[1]}"
end
whats_wrong
end
end
end | true |
b4dc60f5b460f6330ebc17b670bcee2352168039 | Ruby | blackeaglejs/BEWD_DC_JAN2015 | /class18/zoheb/cc_validator_luhn.rb | UTF-8 | 599 | 3.640625 | 4 | [] | no_license | require 'pry'
def sumDigits(num, base = 10)
num.to_s(base).split(//).inject(0) {|z, x| z + x.to_i(base)}
end
def valid(x)
cc_arr = x.to_s.chars.map.to_a
cc_arr_int = []
cc_arr.each do |x|
y = x.to_i
cc_arr_int.push(y)
end
cc_arr_doubl = cc_arr_int.map.with_index{|v,i| i % 2 == 0 ? v: v*2}
total = 0
cc_arr_doubl.each do |number|
if number < 10
total += number
elsif number >= 10
a = sumDigits(number)
total += a
end
end
if total % 10 == 0
puts "Valid Credit Card Number"
else
puts "Invalid Credit Card Number"
end
binding.pry
end
valid(4408041234567893) | true |
3e65493193e118f25a0e6c28b7aac88d42ec2a09 | Ruby | Richmj/rForRuby | /times.rb | UTF-8 | 146 | 3.421875 | 3 | [] | no_license | # Write a method that can ring the bell N times,
#where N is a parameter passed to the method.
def ring(bell, n)
n.times do
bell.ring
end
end | true |
d04551b395e6076c7abab879ddb2e85d5cd5cb1b | Ruby | BlackwingKakashi/fibonaccicalculator | /quadraticequationcalculator.rb | UTF-8 | 229 | 3.5 | 4 | [] | no_license | puts "What is the a value"
a = gets.to_f
puts "What is the b value"
b = gets.to_f
puts "What is the c value"
c = gets.to_f
x1 = ((-1)*b+((b**2-4*a*c)**0.5))/(2*a)
x2 = ((-1)*b-((b**2-4*a*c)**0.5))/(2*a)
puts "X ="
puts x1
puts x2 | true |
2a67e231afe6ce744716ab96e0910845e1333b1a | Ruby | Zainab-Omar/ruby-puppy-onl01-seng-pt-070620 | /lib/dog.rb | UTF-8 | 280 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Dog
attr_accessor :name
@@all=[]
def initialize (name)
@name=name
self.save
end
def self.all
@@all
end
def self.print_all
@@all.each do |dog_name|
puts dog_name.name
end
end
def save
@@all << self
end
def self.clear_all
@@all.clear
end
end | true |
f770034e489d5ba1805fd464dfe286d13c2db549 | Ruby | kalves-rally/automation_learning | /sample_module.rb | UTF-8 | 1,441 | 3.09375 | 3 | [] | no_license | #setting the argument equals something will use that value if you don't pass one
def adopt_puppies(num, pay_type, email="j@test.com",name, address)
view_details_button(num).click
adopt_me_button.click
complete_the_adoption_button.click
name(name)
address(address)
email(email)
pay_type(pay_type)
@browser.button(:value => 'Place Order').click
end
#in this way, it is not constrained to the order of the arguments
def adopt_puppies_new(args)
#boolean ? if_true : if_false
name = args[:name] ? args[:name] : 'Mark'
view_details_button(args[:number]).click
adopt_me_button.click
complete_the_adoption_button.click
name(name)
address(args[:address])
email(args[:email])
pay_type(args[:pay_type])
# @browser.button(:value => 'Place Order').click
end
def goto(url)
@browser.goto url
end
def close
@browser.close
end
def address(string)
@browser.text_field(:id => 'order_address').set string
end
def name(string)
@browser.text_field(:id => 'order_name').set string
end
def email(string)
@browser.text_field(:id => 'order_email').set string
end
def pay_type(string)
@browser.select_list(:id => 'order_pay_type').select string
end
def view_details_button(num)
@browser.button(:value => 'View Details', :index => (num - 1))
end
def adopt_me_button()
@browser.button(:value => 'Adopt Me!')
end
def complete_the_adoption_button()
@browser.button(:value => 'Complete the Adoption')
end | true |
05d648c5a19d253638a0ae1df26e88d91fca2bb3 | Ruby | jchappypig/kidcare | /app/pdf/weekly_program_printer.rb | UTF-8 | 4,368 | 2.609375 | 3 | [
"MIT"
] | permissive | class WeeklyProgramPrinter
include Prawn::View
include Printer
def initialize(weekly_program)
initialize_fonts
@weekly_program = weekly_program
if @weekly_program.instance_of? WeeklyProgram
write_header
write_title('Weekly Program from ' + @weekly_program.week_range)
write_indoor_programs
start_new_page
write_outdoor_programs
start_new_page
write_group_time_plannings
end
end
def document
@document ||= Prawn::Document.new(page_layout: :landscape)
end
private
def write_indoor_programs
write_category('Indoor Program')
write_weekly_program_property_group1
write_activities(@weekly_program.indoor_activities)
end
def write_outdoor_programs
write_category('Outdoor Program')
write_weekly_program_property_group1
write_activities(@weekly_program.outdoor_activities)
end
def write_group_time_plannings
write_category('Group Time Planning')
write_weekly_program_property_group2
write_group_activities(@weekly_program.group_time_plannings_sorted)
end
def write_category(category)
text "#{h3(category)}", inline_format: true
move_down 10
end
def write_weekly_program_property_group1
font('Courier', size: 11) do
text "Program Staff: #{@weekly_program.program_staff} Theme: #{@weekly_program.theme} Goal: #{@weekly_program.goals}"
end
move_down 10
end
def write_weekly_program_property_group2
font('Courier', size: 11) do
text "Letter: #{@weekly_program.letter} Number: #{@weekly_program.number} Colour: #{@weekly_program.colour} Shape: #{@weekly_program.shape}"
end
move_down 10
end
def write_activities(activities)
if activities.any?
data = []
days = [th('Broad Skill')]
column_widths = [80]
available_days = activities.map(&:day)
column_width = 640.0.to_f/available_days.size
available_days.each do |day|
days << th(day)
column_widths << column_width
end
data << days
cognitive_data = [row_th('Cognitive')]
cross_mentor_data = [row_th('Cross Mentor')]
social_data = [row_th('Social/Emotional')]
art_and_craft_data = [row_th('Fine motor Eye-hand co. Sensory Art and craft')]
language_data = [row_th('Language')]
activities.each do |activity|
cognitive_data << activity.cognitive
cross_mentor_data << activity.cross_mentor
social_data << activity.social
art_and_craft_data << activity.art_and_craft
language_data << activity.language
end
data << cognitive_data
data << cross_mentor_data
data << social_data
data << art_and_craft_data
data << language_data
table(data, position: :center, row_colors: %w(008CBA FFFFFF a0d3e8 FFFFFF a0d3e8 FFFFFF),
cell_style: {:inline_format => true,
size: 8},
column_widths: column_widths
)
move_down 20
end
end
def write_group_activities(activities)
if activities.any?
data = []
days = [th('Group Time')]
column_widths = [80]
available_days = activities.map(&:day)
column_width = 640.0.to_f/available_days.size
available_days.each do |day|
days << th(day)
column_widths << column_width
end
morning_data = [row_th('Transition song 9:00 AM')]
late_morning_data = [row_th('Show and tell 11:00 AM')]
afternoon_data = [row_th('Computer 2:45 PM')]
late_afternoon_data = [row_th('Story time 3:30 PM')]
finishing_up_data = [row_th('Game group time 5:15 PM')]
data << days
activities.each do |activity|
morning_data << activity.morning
late_morning_data << activity.late_morning
afternoon_data << activity.afternoon
late_afternoon_data << activity.late_afternoon
finishing_up_data << activity.finishing_up
end
data << morning_data
data << late_morning_data
data << afternoon_data
data << late_afternoon_data
data << finishing_up_data
table(data, position: :center, row_colors: %w(008CBA FFFFFF a0d3e8 FFFFFF a0d3e8 FFFFFF),
cell_style: {:inline_format => true,
size: 8},
column_widths: column_widths
)
move_down 20
end
end
end
| true |
dcc645c32eae218bbf4f2d85987054784e17a616 | Ruby | Michaelreforged/charts_hw | /app/models/product.rb | UTF-8 | 1,398 | 2.515625 | 3 | [] | no_license | class Product < ApplicationRecord
belongs_to :seller
# SELECT p.name, p.description, p.price, p.category, s.name AS sellers_name, s.email
# FROM products AS p
# LEFT JOIN sellers AS s
# ON p.seller_id = s.id
def self.w_seller
select('p.name, p.description, p.price, p.category, p.id as product_id , s.name AS sellers_name, s.email, p.seller_id')
.from('products AS p')
.joins('LEFT JOIN sellers AS s ON p.seller_id = s.id')
.order('p.price ASC')
end
# SELECT DISTINCT p.seller_id, s.name
# FROM products AS p
# INNER JOIN sellers AS s ON p.seller_id = s.id
def self.sellers
select('DISTINCT p.seller_id, s.name')
.from('products AS p')
.joins('INNER JOIN sellers AS s ON p.seller_id = s.id')
end
# SELECT DISTINCT p.seller_id, s.name AS seller_name, p.name, p.price, p.description, p.category
# FROM products AS p
# INNER JOIN sellers AS s ON p.seller_id = s.id
# WHERE LOWER(s.name) = 'jerry schowalter'
def self.by_sellers(seller)
select('DISTINCT p.seller_id, p.name, p.price, p.description, p.category')
.from('products AS p')
.joins('INNER JOIN sellers AS s ON p.seller_id = s.id')
.where('s.id = ? ', seller)
.order('p.price ASC')
end
end
# SELECT p.name, p.category, p.description, p.seller_id, p.id, p.price, s.name AS seller_name
# FROM products AS p
# INNER JOIN sellers AS s ON p.seller_id = s.id
# ORDER BY p.price ASC | true |
762e3391b4d6cb3e304462435128cfc6565d073c | Ruby | LittleCatBear/Question3 | /team.rb | UTF-8 | 2,135 | 3.53125 | 4 | [] | no_license | class Team
Member = Struct.new(:name)
def initialize
@members = []
end
def <<(name)
@members << Member.new(name)
end
def members_names
@members.map { |member| member.name }
end
def pro_print(limit = 10)
members_names.take(limit).each { |name| puts name.capitalize }
end
def reverse_print
members_names.reverse.each { |name| puts name.reverse.downcase }
end
# I assumed the purpose was to (in the end) be able to add as many options as possible,
# and to be qble to qpply several presentation options.
# I like this implementation because it offers more flexibility and you don't have to
# add new cases when you want to add a new presentation option.
# The obvious drawback is that it's a bit less readable. There is also less constraints:
# its possible to call presentation_print("shuffle", "sort"), which doesn't make much sense.
def presentation_print(*args)
list = members_names
args.each do |arg|
list = list.send(arg.to_sym) if members_names.respond_to?(arg.to_sym)
end
puts "Members:"
list.each { |name| puts "* #{name}" }
end
=begin
# This version is a bit more readable and also maybe more common as well.
# But it's necessary to add manually each new option behaviour manually,
# and if there are many of them in the end, you have a huge switch case and it doesn't look great.
# also because the function is expecting specific options, it would be better to add the expected options as comments
# Options expected:
# options["shuffle"]: true|false
# options["sort"]: true|false
# options["reverse"]: true|false
def presentation_print(options = {})
list = members_names
case options
when options["shuffle"]
list.shuffle!
when options["sort"]
list.sort!
when options["reverse"]
list.reverse!
end
puts "Members:"
list.each { |name| puts "* #{name}" }
end
=end
def funny_print
sunglasses_face="\u{1F60E}".encode('utf-8')
books="\u{1F4DA}".encode('utf-8')
members_names.each do |name|
puts "#{books} #{name} #{sunglasses_face}"
end
end
end
| true |
782e57bfb23a0f3410560e3919a4ea301b6cfb16 | Ruby | Justafigurehead/CodeClanWork | /week_1/day_3/loops/function_loops.rb | UTF-8 | 1,095 | 4.125 | 4 | [] | no_license | # chicken_hash = [
# {name: "Clucky", eggs: 0, age: 2},
# {name: "Maggie", eggs: 2, age: 3},
# {name: "June", eggs: 3, age: 2},
# {name: "Wilma", eggs: 4, age: 4},
# {name: "Betty", eggs: 1, age: 1}
# ]
# def count_eggs(array)
# total = 0
# for chicken in array
# total += chicken[:eggs]
# chicken[:eggs] = 0
# end
# return total.to_s + " eggs collected."
# end
# puts count_eggs(chicken_hash)
chicken_hash = [
{name: "Clucky", eggs: 0, age: 2},
{name: "Maggie", eggs: 2, age: 3},
{name: "June", eggs: 3, age: 2},
{name: "Wilma", eggs: 4, age: 4},
{name: "Betty", eggs: 1, age: 1}
]
# def count_eggs(array)
# total = 0
# for chicken in array
# total += chicken[:eggs]
# chicken[:eggs] = 0
# end
# return total.to_s + " eggs collected."
# end
# puts count_eggs(chicken_hash)
def find_chicken_by_name(array, name)
for chicken in array
if chicken[:name].downcase == name.downcase
return "I found #{chicken[:name]}."
end
end
return "No chicken found."
end
puts find_chicken_by_name(chicken_hash, "Henry")
| true |
3875b88d9045f3bf14c21a4c529410ef4a82518d | Ruby | jknight1725/payday | /deal_deck.rb | UTF-8 | 456 | 3.109375 | 3 | [] | no_license | # frozen_string_literal: true
class DealDeck
attr_accessor :cards, :deck
def initialize(args={})
@cards = args[:cards]
@deck = args[:deck]
end
def to_h
{
cards: self.cards.map{|k,v| [k.to_i, v.to_h]}.to_h,
deck: deck
}
end
def reset_deck
self.deck = cards.keys
end
def draw_card
reset_deck if deck.empty?
card_drawn = deck.sample
self.deck.delete(card_drawn)
cards[card_drawn]
end
end
| true |
0c6550151d38456c59bcdb19812ed2b9e09af9e9 | Ruby | Stono/migsql | /spec/migration_spec.rb | UTF-8 | 8,025 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
require 'yaml'
require 'fileutils'
describe 'Migration' do
after :each do
FileUtils.rm_rf './db'
end
before :each do
FileUtils.mkdir_p './db'
@migration = Migration.new './db/config.yml'
@test_server = get_test_server
end
# Helper Methods
def create_example_server
@migration.create_server(
@test_server['name'],
@test_server['address'],
@test_server['database'],
@test_server['username'],
@test_server['password']
)
end
it '#get_first_server_name should return the name of the first server' do
create_example_server
expect(@migration.get_first_server_name).to eq(@test_server['name'])
end
it '#new Should create a new instance of the Migration class' do
expect(@migration).to be_an_instance_of Migration
end
it '#create_server Should add a server to the list' do
create_example_server
server = @migration.get_server(@test_server['name'])
expect(server.address).to eq(@test_server['address'])
expect(server.database).to eq(@test_server['database'])
expect(server.username).to eq(@test_server['username'])
expect(server.password).to eq(@test_server['password'])
end
it '#save Should write the settings to a yaml file' do
create_example_server
@migration.save
expect(File.file?('./db/config.yml')).to eq(true)
file = File.open('./db/config.yml')
expect(file.read.length).to eq(147)
end
it '#load Should load settings from a yaml file' do
example = {}
example['example'] = {
:address => '127.0.0.1',
:database => 'example_db',
:username => 'username',
:password => 'password'
}
File.open('./db/config.yml', 'w') { |f| f.write example.to_yaml }
@migration.load
server = @migration.get_server('example')
expect(server[:address]).to eq('127.0.0.1')
expect(server[:database]).to eq('example_db')
expect(server[:username]).to eq('username')
expect(server[:password]).to eq('password')
end
it '#create_migration should create up/down sql scripts' do
create_example_server
@migration.create_migration @test_server['name'], 'test_migration'
expect(File.directory?("./db/#{@test_server['name']}")).to eq(true)
expect(Dir["./db/#{@test_server['name']}/*.sql"].length).to eq(2)
end
it '#create_migration should force unique names' do
create_example_server
@migration.create_migration @test_server['name'], 'test_migration'
result = capture_stdout { @migration.create_migration @test_server['name'], 'test_migration' }
expect(result).to include('Error: migration name already in use')
end
it '#get_latest_migration should return the latest migration' do
create_example_server
@migration.create_migration @test_server['name'], 'test_migration'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration2'
result = @migration.get_latest_migration @test_server['name']
expect(result).to include('test_migration2')
end
it '#get_migration_plan should return all migrations when new db' do
create_example_server
@migration.create_migration @test_server['name'], 'test_migration'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration2'
result = @migration.get_migration_plan @test_server['name'], nil, '0'
expect(result.length).to eq(2)
expect(result[0]).to include('test_migration_up.sql')
expect(result[1]).to include('test_migration2_up.sql')
end
it '#get_migration_plan should return only the difference in migrations when going up' do
create_example_server
@migration.create_migration @test_server['name'], 'test_migration'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration2'
current_migration = @migration.get_migration_by_name @test_server['name'], 'test_migration'
result = @migration.get_migration_plan @test_server['name'], nil, current_migration
expect(result.length).to eq(1)
expect(result[0]).to include('test_migration2_up.sql')
end
it '#get_migration_plan should return the correct migrations when going down' do
create_example_server
@migration.create_migration @test_server['name'], 'test_migration'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration2'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration3'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration4'
target_migration = @migration.get_migration_by_name @test_server['name'], 'test_migration2'
current_migration = @migration.get_migration_by_name @test_server['name'], 'test_migration4'
result = @migration.get_migration_plan @test_server['name'], target_migration, current_migration
expect(result.length).to eq(2)
expect(result[0]).to include('test_migration4_down.sql')
expect(result[1]).to include('test_migration3_down.sql')
end
it '#apply_migration_plan should run the migrations against the database' do
create_example_server
server = SqlServer.new(
@test_server['name'],
@test_server['address'],
@test_server['database'],
@test_server['username'],
@test_server['password']
)
server.remove_migration
@migration.create_migration @test_server['name'], 'test_migration'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration2'
sleep 0.1
# Update these migrations to actually do something...
first_migration = @migration.get_migration_by_name @test_server['name'], 'test_migration'
first_migration_path = "./db/#{@test_server['name']}/#{first_migration}_up.sql"
second_migration = @migration.get_migration_by_name @test_server['name'], 'test_migration2'
second_migration_path = "./db/#{@test_server['name']}/#{second_migration}_up.sql"
tmp_server = @migration.get_server(@test_server['name'])
sql1 = tmp_server.get_sql('create_test_table')
sql2 = tmp_server.get_sql('populate_test_table')
File.open(first_migration_path, 'w') { |f| f.write sql1 }
File.open(second_migration_path, 'w') { |f| f.write sql2 }
migration_plan = @migration.get_migration_plan @test_server['name'], nil, '0'
@migration.apply_migration_plan @test_server['name'], migration_plan, second_migration
expect(second_migration).to eq(@migration.get_migration_status(@test_server['name']))
end
it '#apply_migration_plan should set the migration to be the last sucessful' do
create_example_server
server = SqlServer.new(
@test_server['name'],
@test_server['address'],
@test_server['database'],
@test_server['username'],
@test_server['password']
)
server.remove_migration
@migration.create_migration @test_server['name'], 'test_migration'
sleep 0.1
@migration.create_migration @test_server['name'], 'test_migration2'
sleep 0.1
# Update these migrations to actually do something...
first_migration = @migration.get_migration_by_name @test_server['name'], 'test_migration'
first_migration_path = "./db/#{@test_server['name']}/#{first_migration}_up.sql"
second_migration = @migration.get_migration_by_name @test_server['name'], 'test_migration2'
second_migration_path = "./db/#{@test_server['name']}/#{second_migration}_up.sql"
tmp_server = @migration.get_server(@test_server['name'])
sql1 = tmp_server.get_sql('create_test_table')
sql2 = 'THIS SQL WILL BOMB OUT'
File.open(first_migration_path, 'w') { |f| f.write sql1 }
File.open(second_migration_path, 'w') { |f| f.write sql2 }
migration_plan = @migration.get_migration_plan @test_server['name'], nil, '0'
begin
@migration.apply_migration_plan @test_server['name'], migration_plan, second_migration
rescue ArgumentError
puts 'SqlServer.rb correctly threw exception'
ensure
expect(first_migration).to eq(@migration.get_migration_status(@test_server['name']))
end
end
end
| true |
384014a6cbdba6ab4e16d38bb7a598b95b8ba266 | Ruby | ricecakemonster/BankAccounts | /specs/money_market_spec.rb | UTF-8 | 2,763 | 2.6875 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/reporters'
require 'minitest/skip_dsl'
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
# TODO: uncomment the next line once you start wave 3 and add lib/checking_account.rb
require_relative '../lib/money_market'
describe "MoneyMarket" do
describe "#initialize" do
it "Is a kind of Account" do
# Check that a MoneyMarket is in fact a kind of account
account = Bank::MoneyMarket.new(12345, 15000.00)
account.must_be_kind_of Bank::Account
end
it "Requires an initial balance of at least $10000" do
proc {
Bank::MoneyMarket.new(1337, 9999)
}.must_raise ArgumentError
end
end
describe "#withdraw" do
it "Applies a $100 fee when the balance goes below $10000" do
account = Bank::MoneyMarket.new(1337, 15000.0)
account.withdraw(5001)
account.balance.must_equal 9899
end
it "No more transactions allowed after 6 transactions" do
account = Bank::MoneyMarket.new(1337, 15000.0)
account.withdraw(10)
account.withdraw(10)
account.withdraw(10)
account.withdraw(10)
account.withdraw(10)
account.withdraw(10)
account.withdraw(10)
account.balance.must_equal 14940
end
end
describe "#deposit" do
it "The deposit transaction made to push balance over 0 is not counted in max 6 transactions per month " do
account = Bank::MoneyMarket.new(12345, 10000)
account.deposit(10)
account.deposit(10)
account.deposit(10)
account.deposit(10)
account.withdraw(30)
account.withdraw(30)
account.deposit(200)
account.balance.must_equal 10080
end
end
describe "#add_interest" do
it "Returns the interest calculated" do
account = Bank::MoneyMarket.new(12345, 15000.0)
interest = account.add_interest(0.25)
interest.must_equal 3750
end
it "Updates the balance with calculated interest" do
account = Bank::MoneyMarket.new(12345, 15000.0)
account.add_interest(0.25)
account.balance.must_equal 18750
end
it "Requires a positive rate" do
account = Bank::MoneyMarket.new(12345, 15000.0)
proc {
account.add_interest(-0.25)
}.must_output (/.+/)
end
end
describe "#reset_transactions" do
it "Setting the number of transactions to 0" do
account = Bank::MoneyMarket.new(12345, 10000.0)
account.deposit(10)
account.deposit(10)
account.deposit(10)
account.deposit(10)
account.withdraw(30)
account.withdraw(30)
account.deposit(200) #10080
account.deposit(20)
account.reset_transactions
account.deposit(20)
account.balance.must_equal 10100
end
end
end
| true |
b43fc15c5aa9986dd589ae3cf272241941fb6604 | Ruby | DanielJPark/phase-0-tracks | /Ruby/hashes.rb | UTF-8 | 2,738 | 3.625 | 4 | [] | no_license | =begin
pseudocode
initialzie empty hash
Greet the new client and ask them to answer questions
prompt user for name, age, marital status, decor theme
return all information to client and ask if it is correct.
allow for corrections.
ask again until all info is correct
return upated information with message saying client will be contacted shortly.
=end
p "Hello! Please answer the following questions"
new_client = {}
p "What is your name?"
new_client[:name] = gets.chomp.capitalize
p "How old are you?"
new_client[:age] = gets.chop.to_i
p "What is your marital status? (married/single)"
new_client[:married] = gets.chomp.downcase
if new_client[:married] == "married"
new_client[:married] = true
puts "What is your spouse's name?"
new_client[:spouse] = gets.chomp.capitalize
else new_client[:married] = false
new_client[:spouse] = nil
end
p "Do you have any children? (y/n)"
new_client[:children] = gets.chomp.downcase
if new_client[:children] == "y"
new_client[:children] = true
puts "How many?"
new_client[:number_of_children] = gets.chomp.to_i
else new_client[:children] == "n"
new_client[:children] = false
new_client[:number_of_children] = nil
end
p "Please enter your email address"
new_client[:email] = gets.chomp.to_s
correct = "n"
while correct == "n"
p new_client
p "Is all of your information correct?(y/n)"
correct = gets.chomp.downcase
if correct == "n"
p "what item needs correction? (name, age, marital status, children, email)"
correction = gets.chomp.downcase
if correction == "name"
p "What is your name?"
new_client[:name] = gets.chomp.capitalize
elsif correction == "age"
p "How old are you?"
new_client[:age] = gets.chop.to_i
elsif correction == "marital status"
p "What is your marital status? (married/single)"
new_client[:married] = gets.chomp.downcase
if new_client[:married] == "married"
new_client[:married] = true
puts "What is your spouse's name?"
new_client[:spouse] = gets.chomp.capitalize
else new_client[:married] = false
new_client[:spouse] = nil
end
elsif correction == "children"
p "Do you have any children? (y/n)"
new_client[:children] = gets.chomp.downcase
if new_client[:children] == "y"
new_client[:children] = true
puts "How many?"
new_client[:number_of_children] = gets.chomp.to_i
else new_client[:children] == "n"
new_client[:children] = false
new_client[:number_of_children] = nil
end
elsif correction == "email"
p "Please enter your email address"
new_client[:email] = gets.chomp.to_s
end
end
end
p "Thank you #{new_client[:name]}, we will contact you shortly via email."
| true |
130f1ff042c73b876ff3cee22274f14c16c05972 | Ruby | caachz/backend_module_0_capstone | /day_4/exercises/methods.rb | UTF-8 | 1,172 | 4.625 | 5 | [] | no_license | # In the exercises below, write your own code where indicated
# to achieve the desired result. You should be able to run this
# file from your terminal with the command `ruby day_4/exercises/methods.rb`
# example: Write a method below that, when called will print your name
def print_name
p "Severus Snape"
end
print_name
# Write a method that takes an argument of your name and prints your name
def print_name(name)
p name
end
print_name("Albus Dumbledore")
# Write a method that takes in 2 numbers and prints their sum, then call that
# method.
# YOUR CODE HERE
def addition(number1, number2)
puts number1 + number2
end
addition(3,6)
# Write a method that takes in two strings and prints a concatenation
# of those two strings, for example the arguments could be (man, woman) and
# the end result might be "When Harry Met Sally". Then, call that method.
puts "What is your favorite animal?"
fav_animal = gets.chomp
puts "what is your super duper extra favorite animal?"
extra_fav_animal = gets.chomp
def animals(favorite_animal,extra_favorite_animal)
puts "I LOVE #{favorite_animal} BUT I love #{extra_favorite_animal} more!!!"
end
puts animals(fav_animal, extra_fav_animal)
| true |
21b459152dc3d77af4272c9e49083a6e6f8e0529 | Ruby | bbatsov/ruby-lint | /lib/ruby-lint/analysis/undefined_variables.rb | UTF-8 | 1,493 | 2.828125 | 3 | [
"MIT"
] | permissive | module RubyLint
module Analysis
##
# The UndefinedVariables class checks for the use of undefined variables
# (such as instance variables and constants). The order of definition and
# use of a variable does not matter.
#
# This analysis class does *not* check for undefined local variables. Ruby
# treats these as method calls and as result they are handled by
# {RubyLint::Analysis::UndefinedMethods} instead.
#
class UndefinedVariables < Base
register 'undefined_variables'
##
# Hash containing the various variable types to add errors for whenever
# they are used but not defined.
#
# @return [Hash]
#
VARIABLE_TYPES = {
:gvar => 'global variable',
:ivar => 'instance variable',
:cvar => 'class variable'
}
VARIABLE_TYPES.each do |type, label|
define_method("on_#{type}") do |node|
unless current_scope.has_definition?(type, node.name)
error("undefined #{label} #{node.name}", node)
end
end
end
##
# Handles regular constants as well as constant paths.
#
# @param [RubyLint::AST::Node] node
#
def on_const(node)
path = ConstantPath.new(node)
variable = path.resolve(current_scope)
name = path.to_s
error("undefined constant #{name}", node) unless variable
end
end # UndefinedVariables
end # Analysis
end # RubyLint
| true |
888f43a19ed9da13374402e5631877a2cb6723e9 | Ruby | barrettclark/AdventOfCode | /2016/day07/abba.rb | UTF-8 | 1,734 | 2.921875 | 3 | [] | no_license | class Abba
attr_reader :ip_address
# create 2 capture groups and match against each one
ABBA_PATTERN = /(.)(.)\2\1/
# http://stackoverflow.com/a/2403148/2100028
HYPERNET_PATTERN = /\[([^\]]+)\]/
def initialize(ip_address)
@ip_address = ip_address
end
def supports_tls?
has_abba? && abba_valid?
end
private
def abba_matches
@abba_match ||= @ip_address.scan(ABBA_PATTERN)
end
def abba_in_string?(str)
str.scan(ABBA_PATTERN).flatten.count > 0
end
def hypernet_sequences
@hypernet_match ||= @ip_address.scan(HYPERNET_PATTERN).flatten
end
def has_abba?
abba_in_string?(@ip_address) &&
abba_matches.any? do |letters|
letters[0] != letters[1]
end
end
def hypernet_has_abba?
hypernet_sequences.any? do |hypernet|
abba_in_string?(hypernet)
end
end
def abba_valid?
hypernet_has_abba? == false
end
end
class AbbaValidator
def initialize(input, debug = false)
@input = input
@debug = debug
end
def count_tls
@input.inject(0) do |count, ip_address|
abba = Abba.new(ip_address)
puts "#{ip_address} -> #{abba.supports_tls?}" if @debug
count += 1 if abba.supports_tls?
count
end
end
end
if __FILE__==$0
test_input = [
"abca[mnop]qrst",
"abba[mnop]qrst",
"abcd[bddb]xyyx",
"aaaa[qwer]tyui",
"ioxxoj[asdfgh]zxcvbn",
"luqpeubugunvgzdqk[jfnihalscclrffkxqz]wvzpvmpfiehevybbgpg[esjuempbtmfmwwmqa]rhflhjrqjbbsadjnyc",
"tjwhvzwmhppijorvm[egqxqiycnbtxrii]ojmqyikithgouyu[lrllrgezaulugvlj]jdsrysawxkpglgg[mpvkikuabwucwlpqf]cmzkcdnrhwjmfgbmlq"
]
p AbbaValidator.new(test_input, true).count_tls
p AbbaValidator.new(File.readlines("input.txt"), false).count_tls
end
| true |
5bf6cfb345620e80c6a6e6ed245ac33fd274163d | Ruby | eventide-project/identifier-uuid | /lib/identifier/uuid/random.rb | UTF-8 | 831 | 2.515625 | 3 | [
"MIT"
] | permissive | module Identifier
module UUID
class Random
def get
self.class.get
end
def self.get
UUID.format(raw)
end
def self.raw
SecureRandom.uuid
end
def self.configure(receiver, attr_name=nil)
instance = new
if attr_name.nil?
if receiver.respond_to?(:identifier)
attr_name = :identifier
else
attr_name = :uuid
end
end
receiver.send "#{attr_name}=", instance
instance
end
module Substitute
def self.build
Random.new
end
class Random < Identifier::UUID::Random
def get
@id ||= UUID.zero
end
def set(val)
@id = val
end
end
end
end
end
end
| true |
e94ea638c113ddf2a176cd291c6fc640878ee153 | Ruby | lethan/Advent-of-Code | /2019/day19.rb | UTF-8 | 1,473 | 3.25 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'intcode'
program = []
file = File.open('input_day19.txt', 'r')
while (line = file.gets)
program = line.strip.split(',').map(&:to_i)
end
file.close
def print_beam(points)
x_min, x_max = points.keys.map { |a| a[:x] }.minmax
y_min, y_max = points.keys.map { |a| a[:y] }.minmax
(y_min..y_max).each do |y|
(x_min..x_max).each do |x|
print points[{ x: x, y: y }].zero? ? '.' : '#'
end
puts
end
end
def check_in_beam(beamer, x_coord, y_coord)
return false if x_coord.negative? || y_coord.negative?
beamer.restart.input(x_coord).input(y_coord).output == 1
end
beam_checker = Program.new(program)
points = {}
affected = 0
(0..49).each do |x|
(0..49).each do |y|
status = beam_checker.restart.input(x).input(y).output
points[{ x: x, y: y }] = status
affected += 1 if status == 1
end
end
puts affected
in_beam = points.select { |k, v| v == 1 && points[{ x: k[:x] + 1, y: k[:y] + 1 }] == 1 }
upper_bound_x = in_beam.keys.map { |a| a[:x] }.min
upper_bound_y = in_beam.keys.map { |a| a[:y] }.min
needed_size = 100
left = upper_bound_x - (needed_size - 1)
downer = upper_bound_y + (needed_size - 1)
until check_in_beam(beam_checker, left, downer)
upper_bound_y += 1
upper_bound_x += 1 while check_in_beam(beam_checker, upper_bound_x + 1, upper_bound_y)
left = upper_bound_x - (needed_size - 1)
downer = upper_bound_y + (needed_size - 1)
end
puts left * 10_000 + upper_bound_y
| true |
2bdb47d19f833faba0036645be3ee42c23850fdc | Ruby | rhinorphan/gossip_mvc | /lib/controller.rb | UTF-8 | 670 | 2.9375 | 3 | [] | no_license | require 'gossip'
require 'view'
require 'csv'
class Controller
attr_accessor :view
def initialize(view)
@view = view
end
def create_gossip
view.display_create_gossip
puts "Choisi un ID pour ton potin"
id = gets.chomp
puts "Quel est ton nom ?"
author = gets.chomp
puts "Maintenant lâche le potin ! 🤪"
content = gets.chomp
gossip = Gossip.new(id, author, content)
gossip.save
end
def all_gossip
view.display_all_gossip
Gossip.show_all
end
def delete_gossip
view.display_destroy_gossip
Gossip.show_all
id = gets.chomp
Gossip.delete(id)
end
def exit
view.display_exit
end
end
| true |
dce02c9bca0ccd74a61cc1cc3a10cf39856acfb2 | Ruby | charlesskariah/challenge | /app/models/task.rb | UTF-8 | 513 | 2.625 | 3 | [] | no_license | class Task < ActiveRecord::Base
belongs_to :user
has_many :user_tasks
has_many :user_answers
def winner_name
User.find(self.winner).name
end
def current_user_points(current_user_id)
self.user_tasks.where(user_id: current_user_id ).first.points
end
def opponent_user_points(current_user_id)
user_ids = self.user_tasks.map{|x| x.user_id}
current_user_id = [current_user_id]
opponent_id = user_ids - current_user_id
self.user_tasks.where(user_id: opponent_id).first.points
end
end
| true |
5828af419c10a443398c96c57297977b36ad853b | Ruby | Jesus/aoc-2020 | /day-5/solution.rb | UTF-8 | 740 | 3.5625 | 4 | [] | no_license | #!/bin/env ruby
def bsp(code, upper_char, lower_char)
code.each_char.reduce(0) do |acc, c|
if c == upper_char
(acc << 1) + 1
elsif c == lower_char
acc << 1
else
raise ArgumentError, "Unrecognized character: #{c}"
end
end
end
Seat = Struct.new(:row, :column) do
def self.from_boarding_pass_code(line)
Seat.new(
bsp(line[0...7], 'B', 'F'),
bsp(line[7...10], 'R', 'L')
)
end
def id
row * 8 + column
end
end
seats = File.open('input.txt').map do |line|
Seat.from_boarding_pass_code(line)
end
seat_ids = seats.map(&:id)
my_seat = 0.upto(seat_ids.max) do |n|
next if seat_ids.include? n
if seat_ids.include?(n - 1) && seat_ids.include?(n + 1)
puts n
end
end
| true |
f8f630366671b545c524b6591b69a500bb766569 | Ruby | PerleOramay/THP_ruby | /exo_06.rb | UTF-8 | 645 | 3.4375 | 3 | [] | no_license | number_of_hours_worked_per_day = 10
number_of_days_worked_per_week = 5
number_of_weeks_in_THP = 11
puts "Travail : #{number_of_hours_worked_per_day * number_of_days_worked_per_week * number_of_weeks_in_THP}"
#Pour chaque variable une valeur est définie dans les lignes 1 à 3 donc dans la ligne 5 l'opération entre les accolades est possible
puts "Et en minutes ça fait : #{number_of_minutes_in_an_hour * number_of_hours_worked_per_day * number_of_days_worked_per_week * number_of_weeks_in_THP}"
#le terminal affiche une erreur car la variable number_of_minutes_in_an_hour n'est pas définie par une valeur donc l'opération est impossible | true |
ee106e5955255a43be8788ccba73739bc570a835 | Ruby | gps2601/dependency-injection-testing | /spec/exercise_1_spec.rb | UTF-8 | 1,656 | 3.46875 | 3 | [] | no_license | # Amend the following to be testable in isolation.
class Note
def initialize(title, body, note_formatter)
@title = title
@body = body
@formatter = note_formatter
end
def display
@formatter.format(self)
end
attr_reader :title, :body
end
class NoteFormatter
def format(note)
"Title: #{note.title}\n#{note.body}"
end
end
describe Note do
it 'can initialize' do
formatter = double("My formatter")
note = Note.new("This is the title", "This is the body.", formatter)
expect(note).to be_kind_of(Note)
end
it 'can respond to title' do
formatter = double("My formatter")
note = Note.new("This is the title", "This is the body.", formatter)
expect(note.title).to eq("This is the title")
end
it 'can respond to body' do
formatter = double("My formatter")
note = Note.new("This is the title", "This is the body.", formatter)
expect(note.body).to eq("This is the body.")
end
it 'can use the formatter to display information' do
formatter = double("My formatter")
allow(formatter).to receive(:format).and_return("formatted note")
note = Note.new("This is the title", "This is the body.", formatter)
expect(note.display).to eq("formatted note")
end
end
describe NoteFormatter do
it 'can initialize' do
formatter = NoteFormatter.new
expect(formatter).to be_kind_of(NoteFormatter)
end
it 'can formate a note' do
formatter = NoteFormatter.new
note = double("my note", :title => "This is a title", :body => "Body")
formatted_note = formatter.format(note)
expect(formatted_note).to eq("Title: This is a title\nBody")
end
end
| true |
768b75d47f19cd8611d6fdf92ef0625b9d5e3959 | Ruby | FelipeGuz/ruby_kommit_fgs | /unit6/statement_modifiers.rb | UTF-8 | 403 | 3.75 | 4 | [] | no_license | ## Reducing some operations to only one line
## condition IF
number = 5000
verified = true
#=> simple version
if number>2500 && verified
puts "Huge number!"
end
#=> one line version
puts "Huge Number!" if number>2500 && verified
## UNLESS condition
x = 8
#=> simple version
unless x>10
puts "x in NOT greater than 10"
end
#=> one line version
puts "x in NOT greater than 10" unless x > 10
| true |
046f8477999089c711fc0e8e25814fe582e23fb8 | Ruby | catherineemond/challenges | /advent-of-code/advent_of_code_2018/day_2/checksum.rb | UTF-8 | 976 | 3.96875 | 4 | [] | no_license | input = File.read('./input.txt')
def parse(input)
input.split("\n")
end
# - loop over all the box ids
# - if a char appears twice, increment the twice_count by one
# - if a char appears thrice, increment the thrice_count by one
# - special rule:
# - if there is twice a twice count, it counts only once
# - if there is twice a thrice count, it counts only once
# - if there is one of each, it counts once for each
# - in the end multiply the twice_count by the thrice_count
# build a hash of char count?
def checksum(input)
twice_count = 0
thrice_count = 0
parse(input).each do |box_id|
char_count = {}
box_id.chars.each do |char|
if char_count[char]
char_count[char] += 1
else
char_count[char] = 1
end
end
twice_count += 1 if char_count.any? { |char, count| count == 2 }
thrice_count += 1 if char_count.any? { |char, count| count == 3 }
end
twice_count * thrice_count
end
p checksum(input)
| true |
3122f906f497fc4a443c3cd9e0b73af7a84a3d23 | Ruby | costagavras/ruby-fundamentals-methods | /ex2.rb | UTF-8 | 323 | 4.15625 | 4 | [] | no_license | # Define a method called negative? that accepts a number as an argument and returns a boolean (true/false) indicating whether that number is negative or not.
def negative?(my_number)
if my_number < 0
return true
else
return false
end
end
a_num = 3.458930
test_negative = negative?(a_num)
puts test_negative
| true |
cce60ab5a97dbe6d3890665f628936642d308054 | Ruby | sohyunc1990/programming-univbasics-4-simple-looping-lab-atx01-seng-ft-071320 | /lib/simple_loops.rb | UTF-8 | 448 | 3.5625 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def loop_message_five_times(string)
i=0
while i < 5 do
puts string
i += 1
end
end
def loop_message_n_times(string, limit)
i=0
while i < limit do
puts string
i += 1
end
end
def output_array(array)
i=0
while i < array.length do
puts array[i]
i += 1
end
end
def return_string_array(array)
i=0
newarray=[]
while i < array.length do
newarray.push(array[i].to_s)
i += 1
end
newarray
end | true |
02ce58144bf4514fbe7a56c1f96f17cfa8dfab6f | Ruby | hrwilliams/ping_pong_ruby | /lib/ping_pong.rb | UTF-8 | 396 | 3.109375 | 3 | [] | no_license | class Fixnum
define_method(:ping_pong) do
result = []
(1..self).each() do |number|
if number == 0
result.push(number)
elsif number.%(15) == 0
result.push("pingpong")
elsif number.%(5) == 0
result.push("pong")
elsif number.%(3) == 0
result.push("ping")
else
result.push(number)
end
end
result
end
end
| true |
33652dbd75974699cfec748d2a38ff9a0a39a3e3 | Ruby | ViXP/design_patterns_ruby | /prototype/component.rb | UTF-8 | 968 | 2.828125 | 3 | [] | no_license | # CONCRETE COMPONENT
class MarketingCampaignPhase
attr_accessor :title, :goal
attr_reader :planned_costs, :actual_costs
def initialize(args = {})
@actual_costs = nil
@planned_costs = nil
@complete = nil
@goal = ''
@title = ''
define_properties args
end
def complete!(actual_costs = false)
@complete = true
@actual_costs = actual_costs if actual_costs && actual_costs.is_a?(Numeric)
end
def completed?
@complete
end
def to_s
"#{title}\t#{planned_costs}\t#{actual_costs}\t#{goal}\t#{completed?}"
end
def merge(new_args = {})
define_properties new_args
self
end
private
def define_properties(args = {})
@title = args[:title] || @title || ''
@planned_costs = args[:planned_costs] || @planned_costs || 0
@actual_costs = args[:actual_costs] || @actual_costs || @planned_costs
@goal = args[:goal] || @goal || ''
@complete = args[:complete] || @complete || false
end
end
| true |
8d6fd34ac8d13a5d9ea4b49eb8300083d2e90ad0 | Ruby | asoi567/bd_kr | /convert.rb | UTF-8 | 846 | 2.96875 | 3 | [] | no_license | require 'fileutils'
Encoding.default_external = 'CP866'
class Converter
attr_accessor :fio, :dir
def initialize(fio)
@fio = fio.strip[0, 3].upcase
@dir = File.join('converted/', @fio)
end
def perform
FileUtils.rm_r dir if Dir.exists? dir
Dir.mkdir dir
Dir.glob('ASB/*').each do |file_name|
new_file_name = convert file_name.gsub(/^ASB\//, '')
content = File.read file_name
File.write File.join(dir, '/', new_file_name), convert(content)
end
end
private
def convert(string)
string
.gsub(/ASBF_/, "#{fio}F_")
.gsub(/asbf_/, "#{fio.downcase}f_")
.gsub(/asb\s/, "#{fio.downcase} ")
.gsub(/asb_/, "#{fio.downcase}_")
end
end
print 'Enter FIO: '
converter = Converter.new(gets)
puts "Starting converting ASB -> #{converter.fio}"
converter.perform
puts "Done"
| true |
00127778c6c28272229079e2e77e0d8799ff8112 | Ruby | leonshimizu/prework | /Week_5_Prework/oop.rb | UTF-8 | 701 | 4.25 | 4 | [] | no_license | # Rewrite the two hashes to use a class instead. Also write the methods to retrieve the name and the color, and another method to redefine the color.:
boat1 = { "name" => "S. S. Minnow", "color" => "white", "price" => 20000 }
boat2 = { "name" => "Titanic", "color" => "black", "price" => 700000000 }
class Boat
def initialize(name, color, price)
@name = name
@color = color
@price = price
end
def name
@name
end
def color
@color
end
def price
@price
end
def color=(color)
@color = color
end
end
boat1 = Boat.new("S. S. Minnow", "white", 20000)
boat2 = Boat.new("Titanic", "black", 700000000)
p boat1
p boat2
p boat1.name
boat2.color = "red"
p boat2.color | true |
8a3141fcb10efd5cf7cd706d410210daeceaa434 | Ruby | medlib-v2/hosted | /scripts/ports.rb | UTF-8 | 1,704 | 2.6875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Configure custom ports
class Ports
# Default port forwarding
DEFAULT_PORTS = [
{guest: 80, host: 8000},
{guest: 443, host: 44300},
{guest: 3306, host: 33060},
{guest: 5432, host: 54320},
{guest: 8025, host: 8025},
{guest: 27017, host: 27017}
].freeze
attr_accessor :config, :settings
def initialize(config, settings)
@config = config
@settings = settings
standardize
end
def configure
default_ports
return unless settings.key?('ports')
settings['ports'].each do |port|
config.vm.network :forwarded_port,
guest: port['guest'],
host: port['host'],
host_ip: '127.0.0.1',
protocol: port['protocol'],
auto_correct: true
end
end
private
# Standardize ports naming schema
def standardize
if settings.key?('ports')
settings['ports'].each do |port|
port['guest'] ||= port['to'].to_i
port['host'] ||= port['send'].to_i
port['protocol'] ||= 'tcp'
end
else
settings['ports'] = []
end
end
# Use default port forwarding unless overridden
def default_ports
unless settings.key?('default_ports') && settings['default_ports'] == false
DEFAULT_PORTS.each do |ports|
unless settings['ports'].any? {|mapping| mapping['guest'] == ports[:guest]}
config.vm.network :forwarded_port,
guest: ports[:guest],
host_ip: '127.0.0.1',
host: ports[:host],
auto_correct: true
end
end
end
end
end | true |
613a60ddd773434961e56f4f609ab7c00bc3ab97 | Ruby | neworganizing/rails_vip | /tasks/rails_vip_tasks.rake | UTF-8 | 3,599 | 2.546875 | 3 | [
"MIT"
] | permissive | namespace :vip do
desc "Load in a new VIP source file. If VIP_FILE is set to a local file, this file will be imported and VIP_URL (if set) will be stored for reference. If VIP_URL is set and VIP_FILE is not, the file at the URL will be downloaded and then imported."
task :parse => :environment do
s = Source.new
url = ENV['VIP_URL'] || '' #we can live without the URL
file = ENV['VIP_FILE']
if (file.nil? or file.eql?('')) and (url.nil? or url.eql?(''))
puts "ERROR: Must set VIP_URL or VIP_FILE environment variables"
exit 0
end
# url = 'http://www.votinginfoprojectdata.org/data/vipFeed-19/vipFeed-19-2008-10-23T14-18-42.xml.zip')
# file = '../sample1_5.xml'
if file.nil? then #download file from url
require 'net/http'
require 'net/ftp'
require 'uri'
uri = URI.parse(url)
# get the file name
/\/([^\/]*?)$/ =~ uri.path.to_s
filename = Regexp.last_match(1)
# get the extension
/\.([^.]*?)$/ =~ uri.path.to_s
filetype = Regexp.last_match(1)
#make a temporary path for the file
temppath = "downloads/"
pathchars = ("a".."z").to_a
1.upto(20) { |i| temppath << pathchars[rand(pathchars.size - 1)] }
FileUtils.mkdir_p temppath
fullfile = temppath + '/' + filename
if uri.scheme.eql?('http') or uri.scheme.eql?('https')
Net::HTTP.start(uri.host) { |http|
open(fullfile, "wb") { |file|
puts "Starting HTTP download"
resp = http.get(uri.path) {|httpline|
file.write(httpline)
}
}
}
puts "File acquired"
elsif uri.scheme.eql?('ftp')
pieces = uri.path.split('/')
dir = pieces[0 .. pieces.size-2].join('/')
ftpfile = pieces.last
Net::FTP.open(uri.host) { |ftp|
puts ftp.last_response
ftp.login
puts ftp.last_response
puts "FTP Logged in"
ftp.passive = TRUE
ftp.binary = TRUE
ftp.chdir(dir)
puts ftp.last_response
puts ftp.ls
puts ftp.last_response
puts "Requesting: "+ftpfile
resp = ftp.getbinaryfile(ftpfile, fullfile)
puts ftp.last_response
puts "File acquired"
}
else
raise "unexpected url scheme: "+uri.scheme
end
if (filetype == 'zip') then #unzip
puts "Unzipping File"
require 'zip/zip'
#assume that the .zip file is named the same as the file it contains
xmlfile = fullfile[0 .. fullfile.length - 5]
xmlname = filename[0 .. filename.length - 5]
unless (xmlname[xmlname.length - 3 .. xmlname.length - 1].eql?("xml"))
xmlname = xmlname + ".xml"
end
open(xmlfile, "wb") { |fyle|
Zip::ZipFile.open(fullfile) {|f|
f.get_input_stream(xmlname) {|zipstream|
zipstream.each {|zipline|
fyle.write(zipline)
} } } }
file = xmlfile
else #wasn't zipped
file = fullfile
end
end
s.import(file,url)
end
desc "Deactivate source"
task :source_deactivate => :environment do
if (!ENV['VIP_SID'])
puts "USAGE:\n rake vip:source_deactivate VIP_SID=<source_id>"
end
@source = Source.find(ENV['VIP_SID'])
@source.deactivate!
@source.save
end #task
desc "Activate source"
task :source_activate => :environment do
if (!ENV['VIP_SID'])
puts "USAGE:\n rake vip:source_activate VIP_SID=<source_id>"
end
@source = Source.find(ENV['VIP_SID'])
@source.activate!
@source.save
end #task
desc "List active sources"
task :active_sources => :environment do
@sources = Source.find(:all, :conditions => "active = 1")
puts "ID\timport date\tname"
@sources.each do |s|
puts "#{s.id}\t#{s.created_at}\t#{s.name}"
end
end #task
end
| true |
a009bbc28d389ab41d9b3cd89b6a3e84b328c973 | Ruby | AaronRohrbacher/anagrams | /lib/anagrams.rb | UTF-8 | 1,359 | 3.9375 | 4 | [] | no_license | # require('pry')
class Anagram
def initialize(word_array, phrase_input1, phrase_input2)
@phrase1 = word_array[0].upcase.gsub(/[^0-9A-Za-z]/, '')
@phrase2 = word_array[1].upcase.gsub(/[^0-9A-Za-z]/, '')
@phrase_input1 = phrase_input1
@phrase_input2 = phrase_input2
end
def anagram_check()
if @phrase1.chars.sort === @phrase2.chars.sort
return true
else
return false
end
end
def palindrome_check()
phrase = @phrase1 + @phrase2
if phrase === phrase.reverse()
return true
else
return false
end
end
def is_word()
anagram_check_words = @phrase_input1.upcase.split(" ") + @phrase_input2.upcase.split(" ")
return_value = nil
anagram_check_words.each do |word|
if word.include? "A" or word.include? "E" or word.include? "I" or word.include? "O" or word.include? "U" or word.include? "Y"
return_value = true
else
return_value = false
end
if return_value === false
return false
end
end
return return_value
end
def antigram_check()
phrase1_array = @phrase1.upcase.gsub(/[^0-9A-Za-z]/, '').split("")
return_value = nil
phrase1_array.each do |letter|
if @phrase2.include? letter
return false
else
return_value = true
end
end
return return_value
end
end
| true |
7fa4298377bf09537b10da589717ab478eb0aa90 | Ruby | gauravm31/VTAPP | /advance_ruby/object_store/lib/play.rb | UTF-8 | 270 | 2.59375 | 3 | [] | no_license | require_relative 'object_store'
class Play
include MyObjectStore
attr_accessor :age, :fname, :lname, :email
def validate
true
end
validate :email, uniqueness: true
def to_s
"name => #{fname} #{lname}, age => #{age}, email => #{email}"
end
end
| true |
a4d5dfc78ed03c11751f269302f77aae372877e7 | Ruby | AlecHFerguson/BetterMousetrap | /test/models/comment_test.rb | UTF-8 | 2,831 | 2.671875 | 3 | [] | no_license | require 'test_helper'
class CommentTest < ActiveSupport::TestCase
include CommentsHelper
setup do
@user = users(:one)
@gadget = gadgets(:one)
@comment_params = { user_id: @user.id, gadget_id: @gadget.id, title: 'Boolean Operator',
text: 'This is a good way to think logically', have_it: true
}
end
test 'Valid params => comment is saved' do
comment = Comment.new(@comment_params)
assert comment.save
end
# validate user_id
test 'Non-numeric user_id => fails to save' do
comment = Comment.new(@comment_params.merge(user_id: '123'))
assert_not comment.save
assert_equal comment.errors.messages, { user: [NO_USER_FOUND_ERROR] }
end
test 'Nonexistent user_id => fails to save' do
comment = Comment.new(@comment_params.merge(user_id: 9999999))
assert_not comment.save
assert_equal comment.errors.messages, { user: [NO_USER_FOUND_ERROR] }
end
test 'Blank user_id => fails to save' do
comment = Comment.new(@comment_params.merge(user_id: nil))
assert_not comment.save
assert_equal({ user_id: ["can't be blank", 'is not a number'], user: [NO_USER_FOUND_ERROR] },
comment.errors.messages)
end
test 'Missing user_id => fails to save' do
comment = Comment.new(@comment_params.reject { |k,v| k == :user_id })
assert_not comment.save
assert_equal({ user_id: ["can't be blank", 'is not a number'], user: [NO_USER_FOUND_ERROR] },
comment.errors.messages )
end
# validate gadget_id
test 'Non-numeric gadget_id => fails to save' do
comment = Comment.new(@comment_params.merge(gadget_id: '123'))
assert_not comment.save
assert_equal({gadget: [NO_GADGET_FOUND_ERROR]}, comment.errors.messages)
end
test 'Nonexistent gadget_id => fails to save' do
comment = Comment.new(@comment_params.merge(gadget_id: 9999999))
assert_not comment.save
assert_equal({gadget: [NO_GADGET_FOUND_ERROR]}, comment.errors.messages)
end
test 'Blank gadget_id => fails to save' do
comment = Comment.new(@comment_params.merge(gadget_id: nil))
assert_not comment.save
assert_equal({gadget_id: ["can't be blank", 'is not a number'], gadget: [NO_GADGET_FOUND_ERROR]},
comment.errors.messages)
end
test 'Missing gadget_id => fails to save' do
comment = Comment.new(@comment_params.reject { |k,v| k == :gadget_id })
assert_not comment.save
assert_equal({gadget_id: ["can't be blank", 'is not a number'], gadget: [NO_GADGET_FOUND_ERROR]},
comment.errors.messages)
end
# validate title
test 'Title too short => Fails to save' do
comment = Comment.new(@comment_params.merge(title: 'A'*9))
assert_not comment.save
assert_equal(comment.errors.messages,
title: ['is too short (minimum is 10 characters)'])
end
end
| true |
13c91d4518093e254af0d471557648b9ab5ac57c | Ruby | lukaszsliwa/adwords | /lib/adwords.rb | UTF-8 | 820 | 2.609375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # encoding: utf-8
require "config"
module Adwords
VERSION = :v201109
# Sets Adwords configuration options.
#
# @examples
#
# Adwords.configure do |config|
# config.environment = 'sandbox'
# end
#
# @return [Config] The configuration
#
# @since 1.0.0
#
def self.configure
block_given? ? yield(Config) : Config
end
# Checks that SANDBOX is set
#
# @example
#
# puts 'Sandbox is set' if Adwords.sandbox?
#
# @return [true, false]
#
# @since 1.0.0
#
def self.sandbox?
configure.environment == 'SANDBOX'
end
# Checks that PRODUCTION is set
#
# @example
#
# puts 'Production is set' if Adwords.production?
#
# @return [true, false]
#
# @since 1.0.0
#
def self.production?
configure.environment == 'PRODUCTION'
end
end
| true |
73331b3910f43152e1ab12345d40ff1cae7b2c00 | Ruby | moioo/ffaker | /lib/ffaker/phone_number_se.rb | UTF-8 | 3,757 | 2.734375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # encoding: utf-8
module Faker
# Format for swedish numbers, from here
# from http://sv.wikipedia.org/wiki/Telefonnummer
#
# All area codes are from this list
# http://sv.wikipedia.org/wiki/Lista_%C3%B6ver_svenska_riktnummer
#
# - Length 9
# 08-xxx xxx xx, 0xx-xxx xx xx, 0xxx-xx xx xx
# - Length 8
# 08-xxx xx xx, 0xx-xx xx xx, 0xxx-xxx xx
# - Length 7
# 08-xx xx xx, 0xx-xxx xx
#
module PhoneNumberSE
extend ModuleUtils
extend self
def phone_number
case rand(2)
when 0 then home_work_phone_number
when 1 then mobile_phone_number
end
end
def home_work_phone_number
Faker.numerify("0#{phone_number_format}")
end
def mobile_phone_number
Faker.numerify("0#{mobile_phone_number_format}")
end
def international_phone_number
case rand(2)
when 0 then international_mobile_phone_number
when 1 then international_home_work_phone_number
end
end
def country_prefix
COUNTRY_PREFIX.rand
end
def international_mobile_phone_number
Faker.numerify("#{country_prefix} (0)#{mobile_phone_number_format}")
end
def international_home_work_phone_number
Faker.numerify("#{country_prefix} (0)#{phone_number_format}")
end
def area_prefix
PHONE_PREFIX.rand
end
def phone_number_format
prefix = area_prefix
case prefix.length
when 1 then PHONE_FORMAT_PREFIX_2.rand
when 2 then PHONE_FORMAT_PREFIX_3.rand
when 3 then PHONE_FORMAT_PREFIX_4.rand
end % prefix
end
def mobile_prefix
MOBILE_PHONE_PREFIX.rand
end
def mobile_phone_number_format
MOBILE_PHONE_FORMAT.rand % mobile_prefix
end
PHONE_FORMAT_PREFIX_2 = k ["%s-### ### ##",
"%s-### ## ##",
"%s-## ## ##"]
PHONE_FORMAT_PREFIX_3 = k ["%s-### ## ##",
"%s-## ## ##",
"%s-## ###"]
PHONE_FORMAT_PREFIX_4 = k ["%s-## ## ##",
"%s-### ##"]
MOBILE_PHONE_FORMAT = k ["%s#-## ## ##", "%s#-######"]
COUNTRY_PREFIX = k ["+46", "0046"]
MOBILE_PHONE_PREFIX = k %w(70 72 73 76 74)
PHONE_PREFIX = k %w(8 11 120 121 122 123 125 13 140 141 142 143 144 150 151
152 155 156 157 158 159 16 171 173 174 175 176 18 19 21
220 221 222 223 224 225 226 227 23 240 241 243 246 247
248 250 251 253 258 26 270 271 278 280 281 290 291 292
293 294 295 297 300 301 302 303 304 31 320 321 322 325
33 340 345 346 35 36 370 371 372 380 381 382 383 390
392 393 40 410 411 413 414 415 416 417 418 42 430 431
433 435 44 451 454 455 456 457 459 46 470 471 472 474
476 477 478 479 480 481 485 486 490 491 492 493 494 495
496 498 499 500 501 502 503 504 505 506 510 511 512 513
514 515 520 521 522 523 524 525 526 528 530 531 532 533
534 54 550 551 552 553 554 555 560 563 564 565 570 571
573 580 581 582 583 584 585 586 587 589 590 591 60 611
612 613 620 621 622 623 624 63 640 642 643 644 645 647
650 651 652 653 657 660 661 662 663 670 671 672 680 682
684 687 690 691 692 693 695 696 8 90 910 911 912 913
914 915 916 918 920 921 922 923 924 925 926 927 928 929
930 932 933 934 935 940 941 942 943 950 951 952 953 954
960 961 970 971 973 975 976 977 978 980 981)
end
end
| true |
710adb31097aae5c599deb305aa331a72eca409c | Ruby | Argonus/codebook | /studies/algorithms-and-data-structures/labs/lib/exercise_3/solution.rb | UTF-8 | 680 | 3.5 | 4 | [] | no_license | # frozen_string_literal: true
# Implement Merge Sort
module Exercise3
class Solution
attr_reader :comparisons
def initialize(input)
@input = input
@comparisons = 0
end
def run
do_sort(@input)
end
private
def do_sort(input)
return input if input.length <= 1
pivot = input[0]
smaller, greater = partition_by(input[1..-1], pivot)
do_sort(smaller) + [pivot] + do_sort(greater)
end
def partition_by(array, pivot)
smaller, greater = [], []
array.each do |n|
n < pivot ? smaller << n : greater << n
@comparisons += 1
end
[smaller, greater]
end
end
end
| true |
ef78b06878bc04399d0fdb7db181a3d8da8397d0 | Ruby | alexandradlg/bot_twitter | /bot.rb | UTF-8 | 1,079 | 2.546875 | 3 | [] | no_license |
require 'twitter'
require 'dotenv'
Dotenv.load
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_API_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_API_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_API_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_API_ACCESS_TOKEN_SECRET']
end
@results = []
search_terms = ["bde", "startup", "peer learning","université", "student", "computer science", "peer programming", "epitech", "innovation" ]
search_terms.each do |term|
@search = client.user_search(term)
@search.each { |user|
user_tweet = user.screen_name
@results.push(user_tweet)
}
end
@results.each { |user|
user.to_s
client.follow(user)
}
time = rand(36..45)
@results.each { |user|
client.update("Le peer learning t'intéresse ou tu veux apprendre à coder rapidement ? Deviens dev en 80 jours ici ==> https://bit.ly/2wrt50E #{user} #RoR #Peerlearning #coding #THP #bootcamp #ruby #rubyonrails #learn #dev #gratuit" )
sleep time
} | true |
69da492a65922bc95a144ae6c82cc51d3544d3e1 | Ruby | JoseMPena/Command_line | /TODO_Sinatra/app.rb | UTF-8 | 945 | 2.625 | 3 | [] | no_license | require 'sinatra'
require 'sinatra/reloader'
# We're going to need to require our class files
require_relative('lib/task.rb')
require_relative('lib/todo_list.rb')
require "pry"
todo_list = TodoList.new("Jose")
todo_list.load_tasks
tasks = todo_list.tasks
get "/" do
@user = todo_list.user
@tasks = todo_list.tasks
erb :task_view, layout: :layout
end
get "/new_task" do
erb :new_task, layout: :layout
end
post "/create_task" do
completed = (params[:completed] == "yes") ? true : false
todo_list.add_task(Task.new(params[:content], completed))
redirect to("/")
end
post "/complete/task/:p1" do
id = params[:p1].to_i
# binding.pry
complete_task = tasks.find { |task| task.id == id }
complete_task.toggle_complete!
todo_list.save_tasks
redirect to "/"
end
post "/delete/task/:p1" do
id = params[:p1].to_i
to_delete = tasks.find { |task| task.id == id }
todo_list.delete_task(to_delete.id)
redirect to "/"
end
| true |
1a02040646e23d7368495727da6c09174fef076e | Ruby | zdravkoandonov/ruby-fmi | /quine/quine.rb | UTF-8 | 208 | 3.015625 | 3 | [
"MIT"
] | permissive | def quine
a = "def quine\n"
b = ") + \"%p\" % c + b\nend\n\nquine"
puts a + (c = " a = \"def quine\\n\"\n b = \") + \\\"%p\\\" % c + b\\nend\\n\\nquine\"\n puts a + (c = ") + "%p" % c + b
end
quine
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.