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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
499f925ef3d69d8fbef3c8d21e8d56d420c93955 | Ruby | rahulpatel2/exercism | /ruby/pascals-triangle/pascals_triangle.rb | UTF-8 | 423 | 3.671875 | 4 | [] | no_license | # Paskal Tringle In Ruby
class Triangle
def initialize(size)
@size = size
end
def rows
return [[1]] if @size == 1
(1...@size).each_with_object([[1]]) do |index, paskal_rows|
paskal_rows << generate(paskal_rows[index - 1])
end
end
def generate(array)
(0...array.length - 1).each_with_object([1]) do |index, output|
output << array[index] + array[index + 1]
end << 1
end
end
| true |
bdbebd44101380d3b98eac329e241ccaf400a563 | Ruby | AbbottMichael/space_force_2105 | /lib/spacecraft.rb | UTF-8 | 278 | 2.859375 | 3 | [] | no_license | class Spacecraft
attr_reader :name,
:fuel,
:requirements
def initialize(data_hash)
@name = data_hash[:name]
@fuel = data_hash[:fuel]
@requirements = []
end
def add_requirement(data_hash)
@requirements << data_hash
end
end
| true |
c92aa4b0e936ddca467cb2bd5fe1e56ae702d889 | Ruby | antiny/Code4Pro | /db/seeds.rb | UTF-8 | 3,734 | 2.53125 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# AdminUser.create!(email: 'admin@example.com', password: 'password', password_confirmation: 'password')
# require File.expand_path('../seeds_project', __FILE__)
@project1 = Project.create!({
name: 'Kỹ năng thuyết trình và nói trước công chúng',
content: %q(Ngày nay, cùng với nhu cầu phát triển của xã hội, mỗi người trong chúng ta sẽ ít nhất phải đứng trước công chúng vài ba lần trong đời. Bạn phải thay mặt nhóm học ở lớp thuyết trình cho bài tập được giao trước lớp, bạn phải bảo vệ luận văn tốt nghiệp trước Hội đồng các thầy cô, và sau này, bạn còn thuyết phục khách hàng về tính khả thi của dự án mà bạn đang đảm nhận…
Và, sẽ có lúc bạn tự hỏi: tại sao có người nói chuyện trước đám đông lại tự tin và cuốn hút đến vậy, trong khi bạn hay những người khác lại không thể nào hoàn thành bài thuyết trình một cách xuất sắc, dù bạn đã chuẩn bị rất kỹ?
Kỹ năng thuyết trình yếu kém sẽ khiến bạn mất đi nhiều cơ hội nghề nghiệp, thăng tiến và chứng tỏ năng lực của mình với người khác. Và đây là kỹ năng bạn hoàn toàn có thể rèn luyện được.
Khóa học Kỹ năng thuyết trình của Ths. Nguyễn Hoàng Khắc Hiếu – với nhiều năm kinh nghiệm làm diễn giả, sẽ cung cấp cho bạn các kỹ năng cần thiết để thuyết trình một cách ấn tượng, lôi cuốn:
Khóa học Kỹ năng thuyết trình và nói trước công chúng giúp bạn:
- Biết cách chuẩn bị nội dung chất lượng, cách trình bày sáng tạo
- Tận dụng tối đa hiệu quả của cách trình bày PowerPoint
- Các bí quyết thu hút khán giả trong khi thuyết trình như một diễn giả
- Tạo dựng phong cách thuyết trình lôi cuốn của chính bạn
),
price: '200000',
image: File.new("#{Rails.root}/app/assets/images/cover-khoathuyettrinh2.jpg")
})
@project1.tasks.create!({
title: 'CHƯƠNG 1: XÂY DỰNG BẢN THÂN BÀI THUYẾT TRÌNH',
note: '',
video: 'snkfv9k6rp',
header: true,
tag: 0
})
@project1.tasks.create!({
title: 'Bài 1 : Cách mở đầu lập tức gây sự chú ý',
note: '',
video: 'snkfv9k6rp',
header: false,
tag: 1
})
@project1.tasks.create!({
title: 'Bài 2 : Các sai lầm chết người khi mở đầu',
note: '',
video: 'snkfv9k6rp',
header: false,
tag: 2
})
@project1.tasks.create!({
title: 'Bài 3 : Kết thúc ấn tượng để lại dư âm trong lòng khán giả',
note: '',
video: 'snkfv9k6rp',
header: false,
tag: 3
})
@project1.tasks.create!({
title: 'CHƯƠNG 2: HOÀN THIỆN PHONG CÁCH CỦA BẠN',
note: '',
video: 'snkfv9k6rp',
header: true,
tag: 4
})
@project1.tasks.create!({
title: 'Bài 6 : Vượt qua sự hồi hộp khi đứng trước đám đông',
note: '',
video: 'snkfv9k6rp',
header: false,
tag: 5
})
@project1.tasks.create!({
title: 'Bài 7 : Sử dụng ngôn ngữ cơ thể tạo ấn tượng cho buổi thuyết trình',
note: '',
video: 'snkfv9k6rp',
header: false,
tag: 6
})
@project1.tasks.create!({
title: 'Bài 8 : Phương pháp luyện phát âm và giọng nói chuẩn, rõ ràng',
note: '',
video: 'snkfv9k6rp',
header: false,
tag: 7
}) | true |
dbc7c17bb6aee83c3256e2e1a9112f57d544ad01 | Ruby | bharatvb6/Ruby-Learning | /raindrops.rb | UTF-8 | 542 | 3.515625 | 4 | [] | no_license | require 'prime'
class Raindrops
@raindrop_sounds = Hash[3 => "Pling", 5 => "Plang", 7 => "Plong"]
def self.factors(num)
num.prime_division.map(&:first)
end
def self.convert(input)
@sound = ""
@factors = Array.new
@factors = Raindrops.factors(input)
#p "factors of #{input} is #{@factors} and #{@raindrop_sounds[3]}"
for i in 0..@factors.length-1
if @raindrop_sounds.has_key? (@factors[i])
@sound+=@raindrop_sounds[@factors[i]]
end
end
if @sound.empty?
return "#{input}"
else
return @sound
end
end
end | true |
647107835eb5c111e8b5dc035e0344131272b91d | Ruby | salo18/intro-to-ruby | /Chapter4_FlowControl/e6.rb | UTF-8 | 458 | 3.484375 | 3 | [] | no_license | (32 * 4) >= "129" ## false - integer != string ### WRONG - this raises and error but for the same reasons mentioned
847 == '874' ## false - integer != string
'847' < '846' ## false - last value is compared and 6 is not greater than 7
'847' > '846' ## true - last value is compared and 7 is greater than 6
'847' > '8478' ## false - second value has an extra digit and is thus larger
'847' < '8478' ## true - second value has an extra digit and is thus larger | true |
607c5727e373e3ea54ea6ff5656cba8a4b78d42d | Ruby | parkify/parkify-rails | /100028/update_images.rb | UTF-8 | 2,935 | 2.609375 | 3 | [] | no_license | #!/usr/local/bin/ruby
require 'rake'
require 'rest_client'
require 'active_support'
production_server = ( ARGV.include?("--parkify-rails"))
SERVER_URL = "http://parkify-rails-staging.herokuapp.com"
if production_server
SERVER_URL = "http://parkify-rails.herokuapp.com"
end
#find which sign_id to update
current_dir = FileUtils.pwd.split('/').last
sign_id = current_dir.to_i
if(!sign_id)
exit
end
#find what images already exist for this spot
#TODO: make url for this specifically
response_resources = RestClient.get (SERVER_URL + '/resource_offers.json')
response_images = RestClient.get (SERVER_URL + '/images.json')
if(!response_resources || !response_images)
exit
end
resources = ActiveSupport::JSON.decode(response_resources)
images = ActiveSupport::JSON.decode(response_images)
def image?(file_name)
if ([".", ".."].include? file_name)
return false
elsif (!file_name.include? '.')
return false
elsif (["jpg","jpeg"].include? file_name.split('.').last)
return true
else
return false
end
end
def get_name(file_name)
return file_name.split('.')[0...-1].join(".")
end
def clean_images(resources,images)
images.each do |img|
if(img["imageable_type"] == "ResourceOffer" && resources.include?(img["imageable_id"]))
p "Deleting image #{img["id"]}: #{img["imageable_id"]}/#{img["name"]}"
begin
RestClient.delete ("#{SERVER_URL}/images/#{img["id"]}")
rescue => e
end
end
end
end
def push_images(resources,images)
image_names = Dir.new(File.dirname(__FILE__)).entries.reject {|f| !image?(f)}
image_names.each do |img_name|
resources.each do |r|
#check if there's already an image
image_id = nil
images.each do |img|
if(img["imageable_type"] == "ResourceOffer" && r == img["imageable_id"] && img["name"] == get_name(img_name))
image_id = img["id"]
break
end
end
p [r,img_name, get_name(img_name), image_id]
if(! image_id.nil?)
#update image with PUT
p "Updating image #{image_id}: #{r}/#{get_name(img_name)}"
begin
RestClient.put "#{SERVER_URL}/images/#{img[image_id]}",:image => { :name=>get_name(img_name), :image_attachment => File.new(img_name, "rb")}
rescue => e
end
else
#create new image with POST
p "Creating image: #{r}/#{get_name(img_name)}"
begin
RestClient.post "#{SERVER_URL}/images.json", :image => {:name=>get_name(img_name), :image_attachment => File.new(img_name, "rb"), :imageable_type => "ResourceOffer", :imageable_id => r}
rescue => e
end
end
end
end
end
resources = resources.reject {|x| x["sign_id"] != sign_id}.map {|x| x["id"] }
if(ARGV.include?("-c"))
p "Removing all images for sign_id #{sign_id}"
clean_images(resources,images)
elsif(ARGV.include?("-a"))
push_images(resources,images)
end
p "Finished with #{sign_id}"
| true |
f1a2eb4c6a24875341b7ccef973cc595a54f52d7 | Ruby | helmedeiros/ruby_bits | /level_2/1_optional_argument/game.rb | UTF-8 | 155 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | def new_game(name, year = nil, system = nil)
{
name: name,
year: year,
system: system
}
end
game = new_game("Street Figher II")
puts game
| true |
0d4a533825b5f4a965c5cc5082eb796e3345461e | Ruby | nguyenductung/galaxylegend | /lib/bullet.rb | UTF-8 | 1,708 | 2.890625 | 3 | [] | no_license | class Bullet < GameObject
class << self
def image1 window
@image1 ||= Gosu::Image.new(window, "assets/bullet1.png", true)
end
def image2 window
@image2 ||= Gosu::Image.new(window, "assets/bullet2.png", true)
end
def fire_sound window
@fire_sound ||= Gosu::Sample.new(window, "assets/missle_fire.ogg")
end
def impact_sound window
@impact_sound ||= Gosu::Sample.new(window, "assets/missle_impact.ogg")
end
end
def initialize window, source, speed = 10, x = nil, y = nil
@window = window
@source = source
@image = source == @window.ship ? self.class.image1(@window) : self.class.image2(@window)
@x = x || source.x
@y = y || source.y
@width = @image.width
@height = @image.height
@target_x = Constants::END_X
@target_y = Constants::END_Y
@speed = speed
@sound = self.class.fire_sound @window
@sound.play
end
def update
destroy and return if out_of_map?
check_hit
angle = Gosu::angle(@x, @y, @target_x, @target_y)
angle += 180 if @source != @window.ship
move_toward angle unless destroyed?
end
def draw
@image.draw_rot(@x, @y, ZOrder::Bullet, 0, 0.5, 0.5)
end
def destroy
super
@source.bullets.delete self
end
def explode
self.class.impact_sound(@window).play
destroy
end
def check_hit
return if destroyed?
if @source == @window.ship
@window.enemies.each do |enemy|
if collided? enemy
explode
enemy.explode
return
end
end
else
if collided? @window.ship
explode
@window.ship.explode unless @window.ship.has_shield?
end
end
end
end | true |
53ca8a45d626e09151421aea5583401120a4f485 | Ruby | marianneoco/battle | /app.rb | UTF-8 | 931 | 2.75 | 3 | [] | no_license | require 'sinatra'
require './lib/player'
require './lib/computer'
require './lib/game'
class Battle < Sinatra::Base
get '/' do
erb :index
end
post '/names' do
@player1 = Player.new(params[:player_1_name])
if params[:player_2_name].empty?
@player2 = Computer.new("COMPUTER")
else
@player2 = Player.new(params[:player_2_name])
end
@game = Game.new_game(@player1, @player2)
redirect '/play'
end
before do
@game = Game.current_game
end
get '/play' do
if @game.turn.computer?
erb :computer_play
else
erb :play
end
end
post '/attack-result' do
@game.attack(@game.not_turn)
erb :attack
end
post '/attack-paralyse' do
@game.turn.paralyse_used
erb :attack_paralyse
end
post '/continue' do
@game.switch_turn
redirect '/play'
end
# start the server if ruby file executed directly
run! if app_file == $0
end
| true |
8f7b45fc677a0d1bc350dba2ec1c65927952df2b | Ruby | jacobo/tnaidar | /lib/plugins/string_extensions/lib/string_extensions.rb | UTF-8 | 258 | 2.8125 | 3 | [
"MIT"
] | permissive | module StringExtensions
def titlecase
self.gsub(/((?:^|\s)[a-z])/) { $1.upcase }
end
def to_name(last_part = '')
self.underscore.gsub('/', ' ').humanize.titlecase.gsub(/\s*#{last_part}$/, '')
end
end
String.send :include, StringExtensions | true |
abc8f5f25bba93c0fda34aab3c24f89b3db6ef81 | Ruby | RISCfuture/giffy | /app/controllers/slack_command_controller.rb | UTF-8 | 1,389 | 2.578125 | 3 | [] | no_license | require 'slack'
# @abstract
#
# Abstract superclass for all controllers that respond to Slack slash command.
# This controller
#
# * validates the verification token given with the request against the app's
# verification token (ignoring the request if it doesn't match),
# * rescues from exceptions by returning a short string to be displayed on the
# Slack client, and
# * makes available a {#command} method representing the slash command context.
class SlackCommandController < ApplicationController
abstract!
before_action :validate_command
protect_from_forgery with: :null_session
rescue_from(Exception) do |error|
render status: :internal_server_error, body: "An internal error occurred: #{error}"
raise error
end
protected
# @return [Slack::Command] The object containing information about the
# slash-command that invoked this request.
def command
@command ||= Slack::Command.new(
params[:token],
params[:team_id],
params[:team_domain],
params[:channel_id],
params[:channel_name],
params[:user_id],
params[:user_name],
params[:command],
params[:text],
params[:response_url]
)
end
private
def validate_command
return true if command.valid?
render status: :unauthorized, body: t('controllers.application.validate_command.invalid')
return false
end
end
| true |
9afd2e61642986c593b98e550032206072022c6d | Ruby | farishkash/ruby | /note.rb | UTF-8 | 579 | 3.453125 | 3 | [] | no_license | class Note
attr_accessor :notes
def initialize(notes)
@notes = notes
end
def show
puts "Testing this note #{@notes}"
end
def preview
puts "Preview of my notes:"
@notes.each do |note|
if note.notes.length < 30
puts note.notes
else
puts note.notes[0..29] + "(...)"
end
end
end
end
note1 = Note.new("Things I learn from RailsGuides")
note2 = Note.new("The answer is 42")
note3 = Note.new("Interesting gotcha from Stack Overflow")
notes =[note1, note2, note3]
notes_list = Note.new(notes)
notes_list.preview | true |
b0e41aed5218aecc476d3399a3b3305b440a41ad | Ruby | calacademy-research/antcat | /app/services/what_links_here_columns.rb | UTF-8 | 795 | 2.5625 | 3 | [] | no_license | # frozen_string_literal: true
class WhatLinksHereColumns
def initialize record, columns_referencing_record
@record = record
@columns_referencing_record = columns_referencing_record
end
def all
columns
end
def any?
any_columns?
end
private
attr_reader :record, :columns_referencing_record
def any_columns?
columns_referencing_record.each do |(model, column)|
return true if model.where(column => record.id).exists?
end
false
end
def columns
columns_referencing_record.each_with_object([]) do |(model, column), wlh_items|
model.where(column => record.id).pluck(:id).each do |matched_id|
wlh_items << WhatLinksHereItem.new(model.table_name, column, matched_id)
end
end
end
end
| true |
3db9c0853e462a9a136ed9c2ce5a04879ea1388a | Ruby | pastorp3/Telegram_motivational_bot | /lib/bot.rb | UTF-8 | 1,697 | 3.171875 | 3 | [
"MIT"
] | permissive | # rubocop:disable Metrics/MethodLength
# rubocop:disable Layout/LineLength
# rubocop:disable Style/RedundantInterpolation
# rubocop:disable Layout/IndentationConsistency
require 'telegram/bot'
require_relative 'motivate.rb'
require_relative 'joke.rb'
class Bot
def initialize
token = '1167629539:AAGQm4Kj0hUclTkDEKo_ow4X4T3V0N1CljE'
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
case message.text
when '/start'
bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name} , welcome to motivation chat bot created by peter robert, the chat bot is to keep you motivated and entertained. Use /start to start the bot, /stop to end the bot, /motivate to get a diffrent motivational quote everytime you request for it or /joke to get a joke everytime you request for it")
when '/stop'
bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}", date: message.date)
when '/motivate'
values = Motivate.new
value = values.select_random
bot.api.send_message(chat_id: message.chat.id, text: "#{value['text']}", date: message.date)
when '/joke'
values = Joke.new
value = values.make_the_request
bot.api.send_message(chat_id: message.chat.id, text: "#{value['joke']}", date: message.date)
else
bot.api.send_message(chat_id: message.chat.id, text: "Invalid entry, #{message.from.first_name}, you need to use /start, /stop , /motivate or /joke")
end
end
end
end
end
# rubocop: enable Metrics/MethodLength
# rubocop: enable Layout/LineLength
# rubocop: enable Style/RedundantInterpolation
# rubocop: enable Layout/IndentationConsistency
| true |
5bacba83596d3c37300df79793e62600eb057a05 | Ruby | talum/espresso-shot | /lovenotes.rb | UTF-8 | 61 | 2.90625 | 3 | [] | no_license | love = true
while (love)
puts "I love you"
love = false
end | true |
ce62b7ce74725a022962ef07f5fa142e798543b8 | Ruby | Jun-Fukushima/test2 | /test.rb | UTF-8 | 54 | 3.09375 | 3 | [] | no_license | sum=0
(1..100).each do |n|
sum = n+sum
end
puts sum
| true |
e76dda6c351ab7b61e03e99721a5babb24bcf535 | Ruby | dshue20/AA_classwork | /Week_6/W6D3/chess/slideable.rb | UTF-8 | 2,055 | 3.546875 | 4 | [] | no_license | require "byebug"
module Slideable
def possible_moves
x,y = pos
get_bishop_moves(x,y) if move_dirs.include?("diagonal")
get_rook_moves(x,y) if move_dirs.include?("h/v")
moves
end
def get_rook_moves(x,y)
# moving left
temp = x
until temp == 0
temp -= 1
#p moves
break if !check_valid_move([temp,y])
end
# moving right
temp = x
until temp == 7
temp += 1
#p moves
break if !check_valid_move([temp,y])
end
# moving up
temp = y
until temp == 7
temp += 1
break if !check_valid_move([x,temp])
end
# moving down
temp = y
until temp == 0
temp -= 1
break if !check_valid_move([x,temp])
end
moves
end
def get_bishop_moves(x, y)
# diagonal up left
count = 1
until x-count < 0 || y+count > 7
new_pos = [x-count,y+count]
break if !check_valid_move(new_pos)
count += 1
end
# diagonal up right
count = 1
until x+count > 7 || y+count > 7
new_pos = [x+count,y+count]
break if !check_valid_move(new_pos)
count += 1
end
# diagonal down left
count = 1
until x-count < 0 || y-count < 0
new_pos = [x-count,y-count]
break if !check_valid_move(new_pos)
count += 1
end
# diagonal down right
count = 1
until x+count > 7 || y-count < 0
new_pos = [x+count,y-count]
break if !check_valid_move(new_pos)
count += 1
end
moves
end
end
# [x,y]
# diagonal up left: [x-1,y+1]
# diagonal up right: [x+1,y+1]
# diagonal down left: [x-1,y-1]
# diagonal down right: [x+1,y-1]
#Rook: front, back, left, right any # spaces
#Bishop: D.front.right, D.front.left, D.back,right, D.back,left
# | true |
57c6f912183e19ab9629ee6d773d89e11afe56a9 | Ruby | paritoshbotre/Training_josh | /methods.rb | UTF-8 | 408 | 3.5 | 4 | [] | no_license | def sum_of_four num1, num2, num3, num4
sum = num1 + num2 + num3 + num4
end
def addition_of_2 num1, num2
num1 + num2
end
def empty?
end
def concate_string string1, string2
return "Not String Arguments" if !string1.is_a? String
return "Not String Arguments" if !string2.is_a? String
string1 + string2
end
sum_of_four 2, 4, 8, 7
addition_of_2 2, 4
result = is_string? "hello", "world"
puts result
| true |
eb27cdb8771ee7e8353d3084a2bddf470aaaa4f8 | Ruby | violetzijing/practice | /string/camel-string.rb | UTF-8 | 135 | 3.234375 | 3 | [] | no_license | #!/usr/bin/env ruby
#
s = gets.strip
array = s.split("")
count = 1
array.each {|i| count += 1 if ('A'..'Z').include? i }
puts count
| true |
7ee17015568ec5d4229076b301998575ddedce7d | Ruby | 10kh-at-rb/appacademy_curriculum_followup | /w3d2/reply.rb | UTF-8 | 1,550 | 2.90625 | 3 | [] | no_license | require_relative 'questions_database'
require_relative 'table'
class Reply
def self.all
results = QuestionsDatabase.instance.execute('SELECT * FROM replies')
results.map { |result| Reply.new(result) }
end
def self.find_by_question_id(question_id)
results = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
replies
WHERE
replies.question_id = ?
SQL
results.map { |result| Reply.new(result) }
end
def self.find_by_reply_id(id)
results = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
replies
WHERE
replies.id = ?
SQL
Reply.new(results.first)
end
def self.find_by_replier_id(replier_id)
results = QuestionsDatabase.instance.execute(<<-SQL, replier_id)
SELECT
*
FROM
replies
WHERE
replies.replier_id = ?
SQL
Reply.new(results.first)
end
attr_accessor :id, :question_id, :parent_reply_id, :replier_id, :body
def initialize(options = {})
@id = options['id']
@question_id = options['question_id']
@parent_reply_id = options['parent_reply_id']
@replier_id = options['replier_id']
@body = options['body']
end
def author
User::find_by_user_id(@replier_id)
end
def child_replies
Reply.all.select{|reply| reply.parent_reply_id == @id}
end
def parent_reply
Reply::find_by_reply_id(@parent_reply_id)
end
def question
Question::find_by_question_id(@question_id)
end
end
| true |
d35466d44bfca9c1d6048d9e752e82bec86a120d | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/src/4312.rb | UTF-8 | 199 | 3.28125 | 3 | [] | no_license | class Hamming
def compute(left, right)
diff = 0
0.upto([left.length, right.length].min - 1) do |i|
if left[i] != right[i]
diff = diff + 1
end
end
diff
end
end
| true |
49e950d5f29122b094032ddb741af6083c072bd2 | Ruby | regishideki/parrondo_paradox | /game_random.rb | UTF-8 | 190 | 3.03125 | 3 | [] | no_license | class GameRandom
def initialize(games)
@games = games
@random = Random.new
end
def play(chips)
chosen = @random.rand(@games.size)
@games[chosen].play(chips)
end
end
| true |
66833a1c0826ee6e5dbabfc0953a6668e9f3fcf7 | Ruby | kazuminn/my_twitter_scripts | /description_follow.rb | UTF-8 | 915 | 2.5625 | 3 | [] | no_license | # encoding:utf-8
require 'twitter'
client = Twitter::REST::Client.new do |config|
config.consumer_key = ""
config.consumer_secret = ""
config.access_token = ""
config.access_token_secret = ""
end
followers_list = client.friends("")
=begin
followers_list.each do |x|
p x.description
end
=end
number = 1
catch(:out) do
followers_list.each do |x|
followers_list_list = client.friends(x)
followers_list_list.each do |i|
description = i.description
if description =~ /琉大/ && !(description =~ /TOEIC/) then
client.follow(i)
number = number + 1
if number == 100 then
throw :out
end
end
end
end
end
| true |
34d03a884b0b540843136befe3a02514abb14160 | Ruby | deepigarg/rubyx | /test/sol/test_while_statement1.rb | UTF-8 | 1,123 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
require_relative "helper"
module Sol
class TestWhileConditionSlotMachine < MiniTest::Test
include SolCompile
def setup
@compiler = compile_main( "while(5.div4) ; 5.div4 ; end;return" , "Integer.div4")
@ins = @compiler.slot_instructions.next
end
def test_condition_compiles_to_check
assert_equal TruthCheck , @ins.next(4).class
end
def test_condition_is_slot
assert_equal SlottedMessage , @ins.next(4).condition.class , @ins
end
def test_hoisetd
jump = @ins.next(8)
assert_kind_of Jump , jump
assert jump.label.name.start_with?("cond_label") , jump.label.name
end
def test_label
label = @ins
assert_equal Label , label.class
assert label.name.start_with?("cond_label") , label.name
end
def test_array
check_array [Label, MessageSetup, ArgumentTransfer, SimpleCall, TruthCheck ,
MessageSetup, ArgumentTransfer, SimpleCall, Jump, Label ,
SlotLoad, ReturnJump,Label, ReturnSequence, Label ,Label ,
ReturnSequence, Label] , @ins
end
end
end
| true |
23296765a721c3ddb5799dbed68bd3abe881670e | Ruby | dball1126/Coding_problems | /ruby/minimum_dominos.rb | UTF-8 | 641 | 3.515625 | 4 | [] | no_license | def min_domino_rotations(a, b)
aHash = Hash.new(0)
bHash = Hash.new(0)
min = Float::INFINITY
a.each{|x| aHash[x] += 1}
b.each{|x| bHash[x] += 1}
(0...a.length-1).each do |i|
ele1 = a[i]
ele2 = b[i]
if bHash[ele1].has_key?(ele1) && aHash[ele1] + bHash[ele1] >= a.length
min = [min, a.length % ([aHash[ele1], bHash[ele1]].max)].min
end
if aHash[ele2].has_key?(ele2) && bHash[ele2] + aHash[ele2] >= b.length
min = [min, b.length % ([bHash[ele2], aHash[ele2]].max)].min
end
end
min == Float::INFINITY ? -1 : min
end
p min_domino_rotations(A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]) | true |
b2591cfb3555ca3ef88139f3c0fd314b75c50618 | Ruby | sheamunion/dbc-phase-0 | /week-5/die-class/my_solution.rb | UTF-8 | 5,673 | 4.5 | 4 | [
"MIT"
] | permissive | =begin
Die Class 1: Numeric
I worked on this challenge [by myself]
I spent 3.07 hours on this challenge.
0. Pseudocode
Input:
- a number (denoting some number of sides)
- a request to display or set the number of sides of a die
- a request to roll the die
Output:
- a number (the number of sides of a die), and,
- a number (the roll of a die)
Steps:
CREATE a new die with some number of sides
IF the number of sides is LESS THAN 1
RAISE an error that tells us to use a positive integer when we create a die
ELSE
SET the sides of this die EQUAL TO the input number of sides
TELL us how many sides an existing die has
RETURN the number of sides of the specified die
ROLL an existing die
RETURN a random number between 1 and the number of sides of that die
# 1. Initial Solution
=end
class Die
def initialize(sides)
if sides < 1
raise ArgumentError.new("Please use a positive integer when creating a die.")
else
@sides = sides
end
end
def sides
@sides
end
def roll
roll = Random.new
roll.rand(1..@sides)
end
end
# 3. Refactored Solution
class Die
def initialize(sides)
if sides < 1
raise ArgumentError.new("Please use a positive integer when creating a die.")
else
@sides = sides
end
end
attr_reader :sides
def roll
roll = Random.new
roll.rand(1..@sides)
end
end
=begin
# 4. Reflection
What is an ArgumentError and why would you use one?
It is an error that is raised when the type or number of arguments passed does not match the type or number of arguments expected.
What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
I implmented the "attr_reader" and the "rand" methods. Both were easy to use. In reading about attr_reader, I also learned about attr_writer and attr_accessor. The ruby docs for Random was more comprehensive than I expected. All I wanted to know was how to generate a random number when given a range, which I found after a few minutes of reading.
What is a Ruby class?
Technically, a class is an instance of the Class class. As with everything else in Ruby, classes are objects. Classes are the only kind of object that can spawn new objects. Most classes consist of collections of attributes (variables) and behaviors (methods).
Conceptually, a class is like a blueprint. It has all the schematics for creating and manipulating *instances* of itself.
For example, the specific car I drive can be thought of as an instance of a class called Car. Every instance of a car has the same attributes (although not necessarily the same values) and has the same behaviors. The Car class can describe manufacturer, color, model name, engine size, trim level, fuel tank capacity, oil levels, mpg rating etc. We can do things to instances of the Car class like change their current fuel and oil levels, change their color, drive them, park them, and so on.
Why would you use a Ruby class?
Classes are really useful when we want to create many objects that have the same attributes and behaviors. Classes give us the ability to easily create any number of objects with built-in variables and methods. Classes empower us to do acheive comlex and innovative tasks. With classes, we can begin to model our world and to create new worlds limited only by our imagination.
For example, if we want to create a database of cars in a parking lot, we could type the following:
====== WITHOUT A CLASS ======
car1_color = "Red"
car1_make = "Honda"
car1_model = "Fit"
car2_color = "Blue"
car2_make = "Subaru"
car2_model = "Forester"
def change_color(color, new_color)
color = new_color
end
p change_color(car1_color, "Yellow") # => "Yellow"
p change_color(car2_color, "Green") # => "Green"
However, imagine doing this for 100 cars. If we only stick with three variables (color, make, model), we will end up creatng 300 individual variables. Of course, we would probably leverage some iteration to accomplish that task. Regardless, this is not very DRY. Furthermore, it doesn't quite align with our conceptual understanding. A car is a collection of attributes and behaviors. A car's color is not "car color red." A car *is* red.
If we use a class, we can create multiple objects with inherit variables (attributes) and methods (behaviors). This sounds much more close to our conceptual understanding of cars.
====== WITH A CLASS ======
class Car
def initialize(color,make,model)
@color = color
@make = make
@model = model
end
attr_reader :make, :model
attr_accessor :color
end
car1 = Car.new("Red", "Honda", "Fit")
car2 = Car.new("Blue", "Subaru", "Forester")
p car1.color= "Yellow" # >> "Yellow"
p car2.color= "Green" # >> "Green"
What is the difference between a local variable and an instance variable?
Where can an instance variable be used?
A local variable is defined within a method and can only be accessed or modified in the method. An instance variable is unique to the object to which it belongs (i.e. that instance of a class) and can be used by any messages that object responds to. An instance variable can be used by the object that created it. In the Car class, above, @color, @make, and @model are all instance variables. They can be used by any instance of the Car class. For example, the objects car1 and car2 (two different instances of the Car class) each use the instance variable @color.
Futhermore, remember that local variable names follow this style: local_variable. Instance variables are different in that they always begin with a single at sign: @instance_variable.
=end | true |
453d8ee6ef648559411a5f641c7c7265cb004804 | Ruby | ryosuke-endo/constants_management | /lib/constants_management.rb | UTF-8 | 459 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'yaml'
class ConstantsManagement
def initialize(source = self.class.source)
create_const(YAML.load(File.open(source)))
end
def create_const(date)
date.each do |klass, value|
name = value.keys.first.upcase
const = value.values.first
self.class.const_set(klass, Class.new { |k|
const_set(name, const)
})
end
end
class << self
def source(value = nil)
@source ||= value
end
end
end
| true |
a1d0306c15bee7a4d0bc4544f78f9dcb933d13fa | Ruby | pdougall1/game_of_life | /spec/game_spec.rb | UTF-8 | 460 | 2.875 | 3 | [] | no_license |
require 'stringio'
require_relative '../lib/world'
require_relative '../lib/cell'
require_relative '../lib/game'
describe Game do
# not quite sure how to test the IO from the console.
# def get_coordinates
# $stdin.gets.chomp
# end
# before do
# $stdin = StringIO.new("[1,2], [2,2], [3,1]")
# end
# after do
# $stdin = STDIN
# end
# it 'should be able to start' do
# expect(get_coordinates).to be == "[1,2], [2,2], [3,1]"
# end
end
| true |
c00e1b763850536ce58de0f0bace32d73e74971f | Ruby | ChuckJHardy/ParseHub | /lib/parse_hub/promise.rb | UTF-8 | 801 | 2.890625 | 3 | [
"MIT"
] | permissive | class ParseHub
class Promise
RESCUE_WAIT = 5
def initialize(waits:, trys:, answer:, finished:, delete:)
@waits = waits
@trys = trys
@answer = answer
@finished = finished
@delete = delete
end
def self.run(*args, &block)
new(*args).run(&block)
end
def run(&block) # rubocop:disable Metrics/MethodLength
current = 1
while current <= @trys
if @finished.call
block.call(@answer.call)
delete
break
end
sleep(@waits.shift || RESCUE_WAIT)
current += 1
end
fail ParseHub::RunLoopsError, @trys if current > @trys
end
private
def delete
@delete.call if clean?
end
def clean?
ParseHub.configuration.clean
end
end
end
| true |
5bba67cdecb1ab72729bb6801e684e777bad598f | Ruby | fluorine/vowelremoval-gem | /test/test_vowelremoval.rb | UTF-8 | 354 | 2.890625 | 3 | [
"MIT"
] | permissive | require "test/unit"
require "../lib/vowelremoval.rb"
class TestVowelRemoval < Test::Unit::TestCase
def test_vowel_removal1
assert_equal("hola mundo".remove_vowels, "hl mnd")
end
def test_vowel_removal2
assert_equal("aeiou".remove_vowels, "")
end
def test_vowel_removal3
assert_equal("Viva Cristo!".remove_vowels, "Vv Crst!")
end
end | true |
855e9b005598235eab3a95f88112b1d5f2b592c9 | Ruby | aaaa777/musicbot | /lib/bot.rb | UTF-8 | 663 | 2.53125 | 3 | [] | no_license | require 'discordrb'
class MusicBot < Discordrb::Commands::CommandBot
def initialize()
super(
token: ENV['TOKEN'],
prefix: 'm@'# default prefix. it will be selectable by Proc
)
@downloader = YoutubeDL::Client.new
end
def start
run
end
private
def add_command(sym, **options, &block)
command(sym, **options, &block)
end
def play_command(key)
command(key, private: false) do |event, *args|
url = args.join(' ')
begin
url = YoutubeDL::URL.parse(url)
rescue => exception
return 'invalid url!'
end
audio_io = @downloader.download_audio(url)
end
end
end | true |
3d9ba362a4f3057f3c1c769bd03bb343506c7268 | Ruby | emilianolowe/launch-school-exercises | /Ruby/easy/easy1/how_many?.rb | UTF-8 | 352 | 3.703125 | 4 | [] | no_license | #how_many?
def count_occurrences(list)
stock = Hash.new(0)
list.each do |make|
stock[make.downcase] += 1
end
puts stock
end
vehicles = [
'car', 'car', 'truck', 'car', 'SUV', 'truck',
'motorcycle', 'motorcycle', 'car', 'truck'
]
count_occurrences(vehicles)
# Expected Output
=begin
car => 4
truck => 3
SUV => 1
motorcycle => 2
=end | true |
d6c695b2a1ba0cb9206e2280e3b10231f912c460 | Ruby | JustinData/GA-WDI-Work | /w01/d04/Justin/cap.rb | UTF-8 | 555 | 4.09375 | 4 | [] | no_license | # "welcome to class!"
# name of student, it's great to have you"
# " "
#"________________________________________"
# capitalize all names, PJ requires a different method
students =["remy the dog", "pj", "jeff", "peter"]
students.each do |value|
if value == "pj"
puts "welcome to class!"
puts "#{value.upcase}, it's great to have you!"
puts " "
puts "________________________________________"
else
puts "welcome to class!"
puts "#{value.capitalize}, it's great to have you!"
puts " "
puts "________________________________________"
end
end | true |
7484f5cccbeebe688dee2961386875756e33be3b | Ruby | Holy-0116/rent-tools-app | /spec/models/address_spec.rb | UTF-8 | 2,881 | 2.5625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Address, type: :model do
before do
@address = FactoryBot.build(:address)
end
describe "住所登録機能" do
context "住所登録ができるとき" do
it "全ての情報が入力されていれば登録できる" do
expect(@address).to be_valid
end
it "建物名がなくても登録できる" do
@address.building_name = nil
expect(@address).to be_valid
end
end
context "住所登録できないとき" do
it "郵便番号がないと登録できない" do
@address.postal_code = nil
@address.valid?
expect(@address.errors.full_messages).to include("郵便番号を入力してください", "郵便番号はハイフンなしの半角数字(7桁)を入力してください")
end
it "郵便番号は全角数字だと登録できない" do
@address.postal_code = "1234567"
@address.valid?
expect(@address.errors.full_messages).to include("郵便番号はハイフンなしの半角数字(7桁)を入力してください")
end
it "郵便番号はハイフンが含まれていると登録できない" do
end
it "都道府県が選択されていないと登録できない" do
@address.prefecture_id = "0"
@address.valid?
expect(@address.errors.full_messages).to include("都道府県を選んでください")
end
it "市区町村名がないと登録できない" do
@address.city_name = nil
@address.valid?
expect(@address.errors.full_messages).to include("市区町村を入力してください")
end
it "番地がないと登録できない" do
@address.house_number = nil
@address.valid?
expect(@address.errors.full_messages).to include("番地を入力してください")
end
it "電話番号がないと登録できない" do
@address.phone_number = nil
@address.valid?
expect(@address.errors.full_messages).to include("電話番号を入力してください", "電話番号はハイフンなしの半角数字(10~11桁)を入力してください")
end
it "電話番号は全角数字だと登録できない" do
@address.phone_number = "0123456789"
@address.valid?
expect(@address.errors.full_messages).to include("電話番号はハイフンなしの半角数字(10~11桁)を入力してください")
end
it "電話番号はハイフンが含まれていると登録できない" do
@address.phone_number = "000-0000-0000"
@address.valid?
expect(@address.errors.full_messages).to include("電話番号はハイフンなしの半角数字(10~11桁)を入力してください")
end
end
end
end
| true |
8fc727f241bc5e756349f953aa796ac3d6a038c8 | Ruby | AlexisAuriac/202unsold_2018 | /Parameters.rb | UTF-8 | 855 | 3.09375 | 3 | [] | no_license | def usage()
puts("USAGE")
puts("\t./202unsold a b")
puts("DESCRIPTION")
puts("\ta\tconstant computed from the past results")
puts("\tb\tconstant computed from the past results")
end
module Parameters
def Parameters.parseParameters(argv)
if argv.length == 1 and argv[0] == "-h"
usage()
elsif argv.length != 2
STDERR.puts("Invalid number of arguments")
exit(84)
elsif not /^[1-9]\d*$/ =~ argv[0] or
not /^[1-9]\d*$/ =~ argv[1]
STDERR.puts("Invalid arguments: a and b must be positive integers")
exit(84)
elsif argv[0].to_i <= 50 or
argv[1].to_i <= 50
STDERR.puts("Invalid arguments: a and b must be superior to 50")
exit(84)
end
return argv[0].to_i, argv[1].to_i
end
end
| true |
84704f2639259aecd2a8fb4b759e58841ed1eb4a | Ruby | yuta-pharmacy2359/ruby_tutorial | /第4章/Sample4_7_14.rb | UTF-8 | 130 | 3.09375 | 3 | [] | no_license | a = 'iphone'
p a[2] #"h"
p a[2, 3] #"hon"
p a[-2] #n
a[0] = 'X'
p a #"Xphone"
a[1, 4] = 'Y'
p a #"XYe"
a << 'fgh'
p a #"XYefgh" | true |
d484f308857b9203cd74e2858d2f58e643cf783e | Ruby | chevalun/projecteuler | /1-50/pe_34.rb | UTF-8 | 200 | 2.546875 | 3 | [] | no_license | fac = [1]
for i in 1..9 do
fac[i] = fac[i-1]*i
end
s = 0
for i in 3..2540160 do
sum = 0
temp = i.to_s
for j in 0..temp.size-1
sum += fac[temp[j].to_i-48]
end
s += i if sum == i
end
p s | true |
8c1e8c913ca5f5f89702c14249d4a53bc4c128fb | Ruby | CharlesDeLeo979/apis-and-iteration-dc-web-091619 | /lib/command_line_interface.rb | UTF-8 | 161 | 3.21875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def welcome
puts "Welcome to STARWARS SEARCH!"
end
def get_character_from_user
puts "please enter a character name"
char = gets.chomp
char.downcase
end
| true |
5eb2c20bb8e79912a12fdda8405db1e3221fbcd7 | Ruby | Thialison/Marvel-API | /features/step_definitions/marvel_steps.rb | UTF-8 | 1,086 | 2.5625 | 3 | [] | no_license | Dado("que acesse o EndPoint characters") do
@marvel = MarvelChacarters.new
end
Quando("buscar por 5 personagens") do
@marvel.buscar_por_cinco_personagens
end
Quando("buscar as comics de um único personagem") do
@marvel.buscar_comics
end
Quando("buscar por pelo id {string}") do |id|
@marvel_personagem_id = @marvel.buscar_personagem(id)
end
Então("devo visualizar as informações dos 5 personagens") do
json = @marvel.buscar_por_cinco_personagens.parsed_response
personagens = @marvel.valida_5_personagens(json)
status_code = @marvel.buscar_por_cinco_personagens.code
expect(status_code).to be(200)
end
Então("devo visualizar a informação do personagem") do
json = @marvel_personagem_id.parsed_response
nome_estoria = @marvel.valida_nome_estoria(json)
status_code = @marvel_personagem_id.code
expect(status_code).to be(200)
end
Então("devo visualizar as comics do personagem") do
json = @marvel.buscar_comics.parsed_response
comics = @marvel.valida_comics(json)
status_code = @marvel.buscar_comics.code
expect(status_code).to be(200)
end
| true |
dada463e6293f0cb450a893645095cb4dba90aac | Ruby | domo2192/futbol | /test/game_test.rb | UTF-8 | 810 | 2.5625 | 3 | [] | no_license | require 'CSV'
require './test/test_helper'
require 'mocha/minitest'
require './lib/stat_tracker'
require './lib/games_repo'
require './lib/game'
class GameTest < Minitest::Test
def setup
row = CSV.readlines('./data/games.csv', headers: :true, header_converters: :symbol)[0]
@parent = mock('game_repo')
@game1 = Game.new(row, @parent)
end
def test_it_exists_and_has_attributes
assert_equal "2012030221", @game1.game_id
assert_equal "20122013", @game1.season
assert_equal "Postseason", @game1.type
assert_equal 3, @game1.away_team_id
assert_equal 6, @game1.home_team_id
assert_equal 2, @game1.away_goals
assert_equal 3, @game1.home_goals
assert mock(), @game1.parent
end
def test_it_can_report_total_goals
assert_equal 5, @game1.total_goals
end
end
| true |
ba6d986a6bb2a310d564f829f8896cac330b5038 | Ruby | orfah/samples | /l/1/distance.rb | UTF-8 | 5,318 | 3.703125 | 4 | [] | no_license | #!/usr/local/bin/ruby
#
require 'optparse'
require 'pp'
# add a to_radians class to Fixnum and Float. Better solution? Leaves
# out Integer, BigNum, etc...
class Fixnum
def to_radians
self.to_f * (Math::PI/180)
end
end
class Float
def to_radians
self * (Math::PI/180)
end
def mi_to_km
self * 1.60934
end
end
module Distance
# radius of the earth (miles), according to Google
EARTH_RADIUS = 3959
# simple tracker for starting point and ending point, no logic
class Car
attr_accessor :starting_pt, :ending_pt
def initialize(starting_pt, ending_pt)
@starting_pt = starting_pt
@ending_pt = ending_pt
end
end
# latitude and longitude
class Point
attr_accessor :lat, :lng
alias_method :latitude, :lat
alias_method :longitude, :lng
alias_method :lon, :lng
def initialize(lat, lng)
unless lat.respond_to?(:to_radians) and lng.respond_to?(:to_radians)
raise ArgumentError, "Latitude and longitude must be floats"
end
@lat = lat.to_radians
@lng = lng.to_radians
end
# haversine distance calculation, as found on:
# http://andrew.hedges.name/experiments/haversine/
def distance_to(pt)
puts "calculating distance from #{@lat},#{@lng} to #{pt.lat},#{pt.lng}"
dlat = pt.lat - @lat
dlng = pt.lng - @lng
a = (Math.sin(dlat/2))**2 + Math.cos(@lat) * Math.cos(pt.lat) * (Math.sin(dlng/2))**2
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
d = Distance::EARTH_RADIUS * c
puts d
d
end
end
def self.options
opts = {}
# because I've never used a Proc before
car_input = Proc.new { |pos| pos.split(',').collect { |p| p.to_f } }
opt_parser = OptionParser.new do |opt|
opt.banner = "Usage: distance [OPTIONS]"
opt.separator ""
opt.separator "Options"
# required
opt.on("--car1 LOCATION", "input") do |pos|
opts[:car1] = car_input.call(pos)
end
opt.on("--car2 LOCATION", "input") do |pos|
opts[:car2] = car_input.call(pos)
end
opt.on("-i", "--interactive", "interactive mode") do
opts[:interactive] = true
end
opt.on("-km", "--kilometers", "display distance in kilometers") do
opts[:units] = :km
end
opt.on("-mi", "--miles", "display distance in miles (default)") do
opts[:units] = :mi
end
opt.on("-v", "--verbose", "be verbose") do
opts[:verbose] = true
end
opt.on("-h", "--help", "print usage info") do
puts opt_parser
end
end
opt_parser.parse!
opts
end
def self.be_verbose(c1_label, c2_label, distances)
puts "calculating route for #{c1_label}..."
puts " starting at #{c1_label} starting point..."
puts " distance to #{c2_label} starting point: #{distances[0]} ..."
puts " distance to #{c2_label} ending point: #{distances[1]} ..."
puts " distance to #{c1_label} ending point: #{distances[2]} ..."
puts " Total distance: #{distances.reduce(:+)}"
puts
end
def self.find_shortest(car1, car2, verbose=false)
car1_distance = [car1.starting_pt.distance_to(car2.starting_pt)]
car1_distance << car2.starting_pt.distance_to(car2.ending_pt)
car1_distance << car2.ending_pt.distance_to(car1.ending_pt)
be_verbose('car1', 'car2', car1_distance) if verbose
car2_distance = [car2.starting_pt.distance_to(car1.starting_pt)]
car2_distance << car1.starting_pt.distance_to(car1.ending_pt)
car2_distance << car1.ending_pt.distance_to(car2.ending_pt)
be_verbose('car2', 'car1', car2_distance) if verbose
car1_distance = car1_distance.reduce(:+)
car2_distance = car2_distance.reduce(:+)
car1_distance < car2_distance ? car1_distance : car2_distance
end
def self.run(args)
o = options
if o[:verbose]
puts "Read-in options:"
o.each_pair { |k, v| puts " #{k} => #{v}" }
puts
end
if o[:interactive]
cars = [:car1, :car2]
positions = [:starting, :ending]
puts "Starting interactive mode..."
cars.each do |c|
positions.each do |p|
o[c] ||= []
puts "Please enter #{c} #{p} position: "
o[c] += gets.chomp.gsub(/,/, ' ').split
end
puts
end
else
unless o[:car1] and o[:car2] and
o[:car1].length == 4 and
o[:car2].length == 4 and
o[:car1].all? { |p| p.respond_to?(:to_radians) } and
o[:car2].all? { |p| p.respond_to?(:to_radians) }
raise OptionParser::ParseError, "Car starting positions must be provided as floats"
end
end
o[:car1].collect! { |p| p.to_f }
o[:car2].collect! { |p| p.to_f }
c1_start = Point.new(o[:car1][0], o[:car1][1])
c1_end = Point.new(o[:car1][2], o[:car1][3])
c1 = Car.new(c1_start, c1_end)
c2_start = Point.new(o[:car2][0], o[:car2][1])
c2_end = Point.new(o[:car2][2], o[:car2][3])
c2 = Car.new(c2_start, c2_end)
shortest_distance = find_shortest(c1, c2, o[:verbose])
if o[:units] == :km
puts "Converting to km..." if o[:verbose]
shortest_distance = shortest_distance.mi_to_km
end
puts "Shortest Distance: #{shortest_distance} #{o[:units]||'mi'}"
end
end
Distance.run(ARGV)
| true |
a5aa02574e7f2e4ae3f9da9c65593b43b4132e04 | Ruby | bocaruby/jambi | /lib/jambi/gem/catalog.rb | UTF-8 | 487 | 2.671875 | 3 | [] | no_license | class Jambi::Gem::Catalog
attr_reader :dir
def initialize(dir)
raise "Invalid catalog!" if dir.nil? || dir.empty? || !File.exists?(dir)
@dir = dir
end
def gems
@gems ||= Dir["#{@dir}/*"].map {|p| Jambi::Gem.new(p, self)}.sort
end
def gems_by_name(name)
(@gems_by_name ||= {})[name] ||= gems.select {|g| g.name == name}
@gems_by_name[name]
end
def stat
@stat ||= File.stat(@dir)
end
def updated_at
@updated_at ||= stat.mtime
end
end
| true |
d7bb7feee555ad2f2900e113ea8ac63961260aab | Ruby | rgathergood/CodeClan | /week_03/day_03/pizza_shop_end_point/models/customer.rb | UTF-8 | 887 | 3.15625 | 3 | [] | no_license | require_relative('../db/sql_runner.rb')
class Customer
attr_reader(:id, :name)
def initialize(options)
@id = options['id'].to_i if options['id']
@name = options['name']
end
def pizza_orders()
sql = "SELECT * FROM pizza_orders
WHERE customer_id = $1"
values = [@id]
results = SqlRunner.run(sql, values)
orders = results.map {|order| PizzaOrder.new(order)}
return orders
end
def save()
sql =
"INSERT INTO customers(name)
VALUES($1)
RETURNING *;"
values = [@name]
result = SqlRunner.run(sql, values)
@id = result[0]['id'].to_i
end
def Customer.all()
sql = "SELECT * FROM customers;"
customers = SqlRunner.run(sql)
return customers.map {|customer_hash| Customer.new(customer_hash)}
end
def Customer.delete_all()
sql = "DELETE FROM customers"
SqlRunner.run(sql)
end
end #end of class
| true |
307fa906955d81f7b2d6c170470967302556b644 | Ruby | ysulaiman/communique | /experiments/meetings_mate.rb | UTF-8 | 4,924 | 2.53125 | 3 | [] | no_license | # The purpose of this experiment is to study the relation between the number of
# methods that do not contribute to solving the problem at hand and the
# performance of the planner in terms of the number of explored nodes and the
# (execution) time taken by the planner to solve the problem.
#
# The use case and classes/objects used in this experiment are taken from the
# MeetingsMate senior project by Iyad Al Akel, Abdurrahman Al Kalaji, Loai
# Labani, Fahad Al Hazemi, Aseel Ba Haziq, and Hani Al Zahrani.
require_relative 'experiment_helpers'
notification_instance = DbcObject.new('notification', :Notification, {
:@meeting => nil,
:@user_profile => nil
})
vote_instance = DbcObject.new('vote', :Vote, {
:@is_closed => false
})
meeting_instance = DbcObject.new('meeting', :Meeting, {
:@is_final_meeting_time_set => false,
:@is_final_meeting_location_set => false,
:@vote => vote_instance,
:@notification => notification_instance
})
user_profile_instance = DbcObject.new('user_profile', :UserProfile, {
:@is_logged_in => true,
:@notifications => [],
:@meeting => meeting_instance
})
update_user_notifications = DbcMethod.new(:update_user_notifications)
update_user_notifications.precondition = Proc.new do
state.get_instance_of(:Notification).meeting &&
@meeting.is_final_meeting_time_set &&
@meeting.is_final_meeting_location_set
end
update_user_notifications.postcondition = Proc.new do
@notifications << state.get_instance_of(:Notification)
end
user_profile_instance.add_dbc_methods(update_user_notifications)
add_notification = DbcMethod.new(:add_notification)
add_notification.precondition = Proc.new do
state.get_instance_of(:Meeting) &&
state.get_instance_of(:Meeting).vote.is_closed
end
add_notification.postcondition = Proc.new do
@meeting = state.get_instance_of(:Meeting)
@user_profile = state.get_instance_of(:UserProfile)
end
notification_instance.add_dbc_methods(add_notification)
close_vote = DbcMethod.new(:close_vote)
close_vote.precondition = Proc.new do
! @is_closed &&
state.get_instance_of(:Meeting).is_final_meeting_time_set &&
state.get_instance_of(:Meeting).is_final_meeting_location_set
end
close_vote.postcondition = Proc.new { @is_closed = true }
vote_instance.add_dbc_methods(close_vote)
set_final_meeting_location = DbcMethod.new(:set_final_meeting_location)
set_final_meeting_location.precondition = Proc.new { @is_final_meeting_time_set }
set_final_meeting_location.postcondition = Proc.new do
@is_final_meeting_location_set = true
end
set_final_meeting_time = DbcMethod.new(:set_final_meeting_time)
set_final_meeting_time.precondition = Proc.new { true }
set_final_meeting_time.postcondition = Proc.new do
@is_final_meeting_time_set = true
end
meeting_instance.add_dbc_methods(set_final_meeting_location,
set_final_meeting_time)
finalize_meeting_use_case = DbcUseCase.new('Finalize Meeting')
finalize_meeting_use_case.dbc_instances << notification_instance <<
vote_instance << meeting_instance << user_profile_instance
finalize_meeting_use_case.postconditions = {
'meeting' => Proc.new { @is_final_meeting_time_set &&
@is_final_meeting_location_set },
'vote' => Proc.new { @is_closed },
'notification' => Proc.new { ! @meeting.nil? },
'user_profile' => Proc.new { @notifications.include? state.get_instance_named('notification') }
}
ALGORITHM = :best_first_forward_search
puts "Using #{ALGORITHM}"
File.open("#{Time.now.to_i}_#{ALGORITHM}", "w") do |file|
header = %w( NoiseMethods UserTime SystemTime ChildrenUserTime ChildrenSystemTime RealTime GoalTests PlanLength )
file.puts header.join(',')
(0..10).each do |number_of_noise_methods|
print "#{number_of_noise_methods} Noise Methods:"
dummy_dbc_instance = DbcObject.new('dummy_object', :DummyClass, {})
noise_dbc_methods =
NoiseGenerator.generate_dbc_methods(number_of_noise_methods)
dummy_dbc_instance.add_dbc_methods(*noise_dbc_methods)
finalize_meeting_use_case.dbc_instances.delete_at(0) unless
number_of_noise_methods == 0
finalize_meeting_use_case.dbc_instances.unshift(dummy_dbc_instance)
planner = Planner.new
planner.set_up_initial_state(finalize_meeting_use_case)
planner.goals = finalize_meeting_use_case.postconditions
planner.algorithm = ALGORITHM
# Initialize the pseudo-random number generator that will be used in the
# shuffling loop with a fixed seed to make the results reproducible and
# to generate the same sequence of search spaces for the search algorithms.
prng = Random.new(42)
30.times do
data_row = Benchmark.measure { planner.solve(random: prng) }.to_a
data_row.delete_at(0) # Remove the unneeded empty "label" element.
data_row.unshift(number_of_noise_methods)
data_row << planner.number_of_states_tested_for_goals << planner.plan.length
file.puts data_row.join(',')
print '.'
end
puts
end
end
| true |
9a6a5855ea857eb5a79fcf831ea690affbb78f00 | Ruby | petems/rapgenius | /lib/rapgenius/scraper.rb | UTF-8 | 572 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'nokogiri'
require 'httparty'
module RapGenius
module Scraper
BASE_URL = "http://rapgenius.com/".freeze
attr_reader :url
def url=(url)
if !(url =~ /^https?:\/\//)
@url = "#{BASE_URL}#{url}"
else
@url = url
end
end
def document
@document ||= Nokogiri::HTML(fetch(@url))
end
private
def fetch(url)
response = HTTParty.get(url)
if response.code != 200
raise ScraperError, "Received a #{response.code} HTTP response"
end
response.body
end
end
end | true |
7cd421e45d79c596ef505c38e12f482206bdc99a | Ruby | zeuslearning/lara | /app/models/sequence.rb | UTF-8 | 3,550 | 2.578125 | 3 | [
"MIT"
] | permissive | class Sequence < ActiveRecord::Base
attr_accessible :description, :title, :theme_id, :project_id,
:user_id, :logo, :display_title, :thumbnail_url, :abstract
include Publishable # models/publishable.rb defines pub & official
has_many :lightweight_activities_sequences, :order => :position, :dependent => :destroy
has_many :lightweight_activities, :through => :lightweight_activities_sequences, :order => :position
belongs_to :user
belongs_to :theme
belongs_to :project
# scope :newest, order("updated_at DESC")
# TODO: Sequences and possibly activities will eventually belong to projects e.g. HAS, SFF
def name
# activities have names, so to be consistent ...
self.title
end
def time_to_complete
time = 0
lightweight_activities.map { |a| time = time + (a.time_to_complete ? a.time_to_complete : 0) }
time
end
def activities
lightweight_activities
end
def next_activity(activity)
# Given an activity, return the next one in the sequence
get_neighbor(activity, false)
end
def previous_activity(activity)
# Given an activity, return the previous one in the sequence
get_neighbor(activity, true)
end
def to_hash
# We're intentionally not copying:
# - publication status (the copy should start as draft like everything else)
# - is_official (defaults to false, can be changed)
# - user_id (the copying user should be the owner)
{
title: title,
description: description,
abstract: abstract,
theme_id: theme_id,
project_id: project_id,
logo: logo,
display_title: display_title,
thumbnail_url: thumbnail_url
}
end
def duplicate(new_owner)
new_sequence = Sequence.new(self.to_hash)
Sequence.transaction do
new_sequence.title = "Copy of #{self.name}"
new_sequence.user = new_owner
positions = []
lightweight_activities_sequences.each do |sa|
new_a = sa.lightweight_activity.duplicate(new_owner)
new_a.name = new_a.name.sub('Copy of ', '')
new_a.save!
new_sequence.activities << new_a
positions << sa.position
end
new_sequence.save!
# This is not necessary, as 'lightweight_activities_sequences' is ordered by
# position, so we already copied and add activities in a right order. However
# copying exact position values seems to be safer and more resistant
# to possible errors in the future.
new_sequence.lightweight_activities_sequences.each_with_index do |sa, i|
sa.position = positions[i]
sa.save!
end
new_sequence.save!
end
return new_sequence
end
def serialize_for_portal(host)
local_url = "#{host}#{Rails.application.routes.url_helpers.sequence_path(self)}"
data = {
'type' => "Sequence",
'name' => self.title,
'description' => self.description,
'abstract' => self.abstract,
"url" => local_url,
"create_url" => local_url,
"thumbnail_url" => thumbnail_url
}
data['activities'] = self.activities.map { |a| a.serialize_for_portal(host) }
data
end
private
def get_neighbor(activity, higher)
join = lightweight_activities_sequences.find_by_lightweight_activity_id(activity.id)
if join.blank? || (join.first? && higher) || (join.last? && !higher)
return nil
elsif join && higher
return join.higher_item.lightweight_activity
elsif join && !higher
return join.lower_item.lightweight_activity
else
return nil
end
end
end
| true |
06ed9672beb31c7d2a0788c6144ce5ce7056118f | Ruby | mxrch/thp_TDD | /01_temperature/temperature.rb | UTF-8 | 88 | 3 | 3 | [] | no_license | def ftoc(nb)
return (nb - 32) * 5/9
end
def ctof(nb)
return nb.to_f * 9/5 + 32
end
| true |
789c09c8f0159c1dffb381e0fb5c7e499ffd34aa | Ruby | fpcMotif/slack-shellbot | /slack-shellbot/commands/help.rb | UTF-8 | 1,096 | 2.640625 | 3 | [
"MIT"
] | permissive | module SlackShellbot
module Commands
class Help < SlackRubyBot::Commands::Base
HELP = <<-EOS
I am your friendly Shellbot, here to help.
General
-------
help - get this helpful message
uname - print the operating system name
whoami - print your username
Shell
-----
ls - list contents of a directory
pwd - displays current directory
echo - display a message
mkdir <directory> - create a directory
rmdir <directory> - remove a directory
touch <file> - create a file
rm <file> - remove a file
cat <file> - show contents of a file
Programs
--------
vi - a basic vi-like in-place editor
:wq - quit and save current file
:q - quit without saving
EOS
def self.call(client, data, _match)
client.say(channel: data.channel, text: [HELP, SlackShellbot::INFO].join("\n"))
client._say(channel: data.channel, gif: 'help')
logger.info "HELP: #{client.owner}, user=#{data.user}"
end
end
end
end
| true |
c5cc7ab8d5d00c114c9d03a7f177558caea8a58b | Ruby | railsfactory-pavan/Training | /Week-I/parser/check_class.rb | UTF-8 | 588 | 2.796875 | 3 | [] | no_license | #method that check class declaration in cpp file
def class_check(fname)
class_no=0
l_no=0
ufile=File.open(fname,'r')
ufile.each_line{|line|
line.strip!
l_no+=1
if line=~/^((public|protected|private)\s)?(class){1}\s[a-zA-Z_][a-zA-Z0-9_]+(\:((public|private)\s)?[a-zA-Z_][a-zA-Z0-9_]+(\,((public|private)\s)?[a-zA-Z_][a-zA-Z0-9_]+)*)?$/
class_no +=1
else
if line=~/^(.*\s)?(class)/
puts "\n#{line}"
puts "wrong class declaration at line no:#{l_no}"
end
end #end of if
}
return class_no
end #end of get_classes method
| true |
ff4033aac2629d38884bb3837e062f526173ec4d | Ruby | ZulqarnainNazir/impact-sample | /app/classes/feeds/parsers/ical_parser.rb | UTF-8 | 843 | 2.671875 | 3 | [] | no_license | # This parser process ical feeds via an ICS file
require 'icalendar'
module Feeds
module Parsers
class IcalParser < Feeds::BaseParser
def parse(feed)
cal_file = open(feed.url)
calendars = Icalendar::Calendar.parse(cal_file)
calendars.map do |calendar|
calendar.events.map do |event|
event_from_entry(event, feed)
end
end.flatten
end
def event_from_entry(event, feed)
Feeds::Event.new({
event_id: event.uid.to_s,
title: event.summary.try(:to_s).try(:force_encoding, 'utf-8').strip,
summary: event.description.try(:to_s).try(:force_encoding, 'utf-8').strip,
start_date: event.dtstart,
end_date: event.dtend,
location: get_location(event.location),
})
end
end
end
end
| true |
11878e3ae92ca0bb860eb7c38022b79ee0a05a85 | Ruby | sul-dlss/SearchWorks | /app/services/live_lookup/sirsi.rb | UTF-8 | 3,278 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | class LiveLookup
class Sirsi
HIDE_DUE_DATE_LIBS = ['RUMSEYMAP'].freeze
delegate :as_json, :to_json, to: :records
def initialize(ids)
@ids = ids
end
def records
@records ||= response.xpath('//record').map do |record|
LiveLookup::Sirsi::Record.new(record).as_json
end
end
private
def response
@response ||= Nokogiri::XML(response_xml)
end
def response_xml
@response_xml ||= begin
conn = Faraday.new(url: live_lookup_url)
conn.get do |request|
request.options.timeout = 10
request.options.open_timeout = 10
end.body
rescue Faraday::ConnectionFailed
nil
rescue Faraday::TimeoutError
nil
end
end
def live_lookup_url
"#{Settings.LIVE_LOOKUP_URL}?#{live_lookup_query_params}"
end
def live_lookup_query_params
if multiple_ids?
"search=holdings&#{mapped_ids}"
else
"search=holding&id=#{@ids.first}"
end
end
def mapped_ids
@ids.each_with_index.map do |id, index|
"id#{index}=#{id}"
end.join('&')
end
def multiple_ids?
@ids.length > 1
end
class Record
def initialize(record)
@record = record
end
def as_json
{
item_id:,
barcode: item_id,
due_date:,
status:,
current_location: status,
is_available: available?
}
end
def item_id
@record.xpath('.//item_record/item_id').map(&:text).last
end
def due_date
return unless valid_due_date?
due_date_value.gsub(',23:59', '')
end
def available?
due_date.blank?
end
def due_date_value
@record.xpath('.//item_record/date_time_due').map(&:text).last
end
def status
return unless valid_current_location?
current_location.name
end
def current_location_code
@record.xpath('.//item_record/current_location').map(&:text).last
end
private
def library_code
@record.xpath('.//item_record/library').map(&:text).last
end
def home_location_code
@record.xpath('.//item_record/home_location').map(&:text).last
end
def valid_current_location?
return false if current_location_code.blank? ||
current_location_code == 'CHECKEDOUT' ||
current_location_same_as_home_location?
true
end
def current_location_same_as_home_location?
current_location.name == home_location.name ||
Constants::CURRENT_HOME_LOCS.include?(current_location_code)
end
def current_location
Holdings::Location.new(current_location_code, library_code:)
end
def home_location
Holdings::Location.new(home_location_code, library_code:)
end
def valid_due_date?
due_date_value.present? &&
due_date_value != 'NEVER' &&
Constants::HIDE_DUE_DATE_LOCS.exclude?(home_location_code) &&
Constants::HIDE_DUE_DATE_CURRENT_LOCS.exclude?(current_location_code) &&
HIDE_DUE_DATE_LIBS.exclude?(library_code)
end
end
end
end
| true |
6f154f808a1f28f8a93ae6313737013a9c278969 | Ruby | mmc1ntyre/toys | /toys-core/lib/toys/middleware.rb | UTF-8 | 4,321 | 2.65625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# Copyright 2019 Daniel Azuma
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
;
module Toys
##
# A middleware is an object that has the opportunity to alter the
# configuration and runtime behavior of each tool in a Toys CLI. A CLI
# contains an ordered list of middleware, known as the *middleware stack*,
# that together define the CLI's default behavior.
#
# Specifically, a middleware can perform two functions.
#
# First, it can modify the configuration of a tool. After tools are defined
# from configuration, the middleware stack can make modifications to each
# tool. A middleware can add flags and arguments to the tool, modify the
# description, or make any other changes to how the tool is set up.
#
# Second, a middleware can intercept and change tool execution. Like a Rack
# middleware, a Toys middleware can wrap execution with its own code,
# replace it outright, or leave it unmodified.
#
# Generally, a middleware is a class that implements the two methods defined
# in this module: {Toys::Middleware#config} and {Toys::Middleware#run}. A
# middleware can include this module to get default implementations that do
# nothing, but this is not required.
#
module Middleware
##
# This method is called after a tool has been defined, and gives this
# middleware the opportunity to modify the tool definition. It is passed
# the tool definition object and the loader, and can make any changes to
# the tool definition. In most cases, this method should also call
# `yield`, which passes control to the next middleware in the stack. A
# middleware can disable modifications done by subsequent middleware by
# omitting the `yield` call, but this is uncommon.
#
# This basic implementation does nothing and simply yields to the next
# middleware.
#
# @param tool [Toys::Tool] The tool definition to modify.
# @param loader [Toys::Loader] The loader that loaded this tool.
# @return [void]
#
def config(tool, loader) # rubocop:disable Lint/UnusedMethodArgument
yield
end
##
# This method is called when the tool is run. It gives the middleware an
# opportunity to modify the runtime behavior of the tool. It is passed
# the tool instance (i.e. the object that hosts a tool's `run` method),
# and you can use this object to access the tool's options and other
# context data. In most cases, this method should also call `yield`,
# which passes control to the next middleware in the stack. A middleware
# can "wrap" normal execution by calling `yield` somewhere in its
# implementation of this method, or it can completely replace the
# execution behavior by not calling `yield` at all.
#
# Like a tool's `run` method, this method's return value is unused. If
# you want to output from a tool, write to stdout or stderr. If you want
# to set the exit status code, call {Toys::Context#exit} on the context.
#
# This basic implementation does nothing and simply yields to the next
# middleware.
#
# @param context [Toys::Context] The tool execution context.
# @return [void]
#
def run(context) # rubocop:disable Lint/UnusedMethodArgument
yield
end
end
end
| true |
d44d9388ce618d19c13f064195a619edcbdfbc89 | Ruby | cwi-swat/meta-environment | /sisyphus/src/building/session.rb | UTF-8 | 1,352 | 2.765625 | 3 | [] | no_license |
module Building
class Session
attr_reader :time, :host, :db_session
def initialize(time, host, db_session)
@time = time
@host = host
@built = {}
@emails = {}
@db_session = db_session
end
def hostname
if @host =~ /^([a-zA-Z0-9\-_.]+ [a-zA-Z0-9\-_.]+)/ then
return $1
end
if @host =~ /([a-z0-9]+) / then
return $1
end
return @host
end
def empty?
return @built == {}
end
def contains_failures?
@built.each_value do |item|
if !item.success then
return true
end
end
return false
end
def components
return @built.keys
end
def add(revision, item)
@built[revision.component] = item
revision.checkout.extract_emails.each do |addr|
@emails[addr] ||= []
@emails[addr] << item
end
end
def each_email
@emails.each_key do |addr|
yield addr, @emails[addr]
end
end
def item(component)
return @built[component]
end
def has?(component)
return @built.has_key?(component)
end
def has_any?(components)
return components.inject(false) do |cur, component|
cur || has?(component)
end
end
def to_s
return @built.inspect
end
end
end
| true |
efa9db905df48a0f57d4ce39fe33dac0b620031b | Ruby | Tahina93/ruby-event-oop | /lib/event.rb | UTF-8 | 776 | 3.421875 | 3 | [] | no_license | require "pry"
require "time"
class Event
attr_accessor :start_date, :duration, :title, :attendees
def initialize(start_date, duration, title, attendees)
@start_date = Time.parse(start_date)
@duration = duration
@title = title
@attendees = attendees
end
def postpone_24h(start_date)
@start_date = start_date + 86400
end
def end_date
end_date = @start_date + (@duration * 60)
return end_date
end
def is_past?
Time.now > @start_date
end
def is_future?
Time.now < @start_date
end
def is_soon?
Time.now = @start_date + 1800
end
def to_s
puts ">Titre : #{@title}"
puts ">Date de début : #{@start_date}"
puts ">Durée : #{@duration} minutes"
puts ">Invités : #{@attendees}"
end
end
Event | true |
b134b55250e71abab94a4701157fe0887ca039b6 | Ruby | gumayunov/access_schema | /lib/access_schema/loggers/test_logger.rb | UTF-8 | 366 | 2.515625 | 3 | [
"MIT"
] | permissive | module AccessSchema
class TestLogger
attr_reader :output
attr_accessor :log_only_level
%w{debug info warn error fatal}.each do |level|
define_method(level) do |message = nil, &block|
return if log_only_level && level != log_only_level
@output = [@output, message || block.call].compact.join("\n")
end
end
end
end
| true |
d9b7b5aae154d21093584a95a0ff2bb78eb72561 | Ruby | hashcrof/Algorithms | /reverse_polish_notation.rb | UTF-8 | 864 | 3.96875 | 4 | [] | no_license | =begin
Given a math expression in infix notation, generate the postfix notation
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces .
=end
###Shunting-Yard Algorithm
def postfix(s)
s = s.gsub(/\s/, '')
len = s.length
return 0 if len < 1
queue = []
op_stack = []
i = operand = res = 0
while i < len
c = s[i]
if is_digit?(c)
queue << c
else
if c == '*' || c == '/' #higher precedence
if op_stack[-1] == '*' || op_stack[-1] == '/'
queue << op_stack.pop
end
end
op_stack << c
end
i += 1
end
(queue + op_stack.reverse).join
end
def is_digit?(c)
to_digit(c) >= 0
end
def to_digit(c)
c.ord - '0'.ord
end
puts postfix("3+2*2") == '322*+'
puts postfix('3+4*5/6') == '345*6/+'
| true |
d13b6d3a39701f3b6fbffee518b8710f6f5c3817 | Ruby | codeZeilen/cocu | /test/cocu_test.rb | UTF-8 | 1,184 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
require 'cucumber/formatter/cocu'
class CocuTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, Cocu
end
end
class Cucumber::Formatter::CoCu
#public :reformat_name
end
class CocuFormatterTest < ActiveSupport::TestCase
test "reformat name string" do
name_string = "In order to xy\nAs a role\n I want to make a pie.\n"
new_name_string = "In order to xy As a role\nI want to make a pie."
assert_reformat_to name_string, new_name_string
end
test "reformat long name string " do
#Contains 133 characters
name_string = %q(In order to xy As a Role I want to make a
bananananananananananananananananananananana
banananananananananananananananananananana pie)
#Contains 128 Characters
short_name_string = %q(In order to xy As a Role
I want to make a banananananananananananananananana
nanananana banananananananananananananananananan...)
assert_reformat_to name_string, short_name_string
end
private
def assert_reformat_to(old_string, new_string)
a = Cucumber::Formatter::CoCu.new(nil, "./testlog", nil)
r = a.reformat_name(old_string)
assert_equal new_string, r
end
end
| true |
562c350c7bfae7e0f56f3efd9eaba357c2a64499 | Ruby | smith558/HackerRank_solutions | /breaking_the_records.rb | UTF-8 | 389 | 3.578125 | 4 | [] | no_license | # Complete the breakingRecords function below.
def breaking_records(scores)
min, max = scores.first, scores.first
min_breaks, max_breaks = 0, 0
scores.each do |i|
if i > max
max_breaks += 1
max = i
elsif i < min
min_breaks += 1
min = i
end
end
[max_breaks, min_breaks]
end
array = [10, 5, 20, 20, 4, 5, 2, 25, 1]
puts breaking_records array | true |
a30172130d850a062426a729070fc000d3764596 | Ruby | bfolkens/snapshot-ebs | /lib/snapshot_ebs.rb | UTF-8 | 1,729 | 2.546875 | 3 | [] | no_license | require 'rubygems'
require 'logger'
gem 'right_aws', '~>3.0.4'
require 'right_aws'
require 'net/http'
require File.dirname(__FILE__) + '/silence_net_http'
def lock_lvm(options = {}, &block)
lvm_devs = `/sbin/dmsetup ls`.split("\n").map {|line| line.gsub /^(.+?)\t.*/, '\1' }
lvm_devs.each do |lvmdev|
$logger.info "Suspending LVM device #{lvmdev}"
$logger.debug `/sbin/dmsetup -v suspend /dev/mapper/#{lvmdev}` unless options[:dry_run]
end
yield
ensure
# Make SURE these are resumed
lvm_devs.each do |lvmdev|
$logger.info "Resuming LVM device #{lvmdev}"
$logger.debug `/sbin/dmsetup -v resume /dev/mapper/#{lvmdev}` unless options[:dry_run]
end
end
def difference_in_time(from, to)
distance_in_minutes = (((to - from).abs)/60).round
distance_in_seconds = ((to - from).abs).round
case distance_in_minutes
when 0..1439 # 0-23.9 hours
:hourly
when 1440..10079 # 1-6.99 days
:daily
when 10080..43199 # 7-29.99 days
:weekly
when 43200..1051199 # 30-364.99 days
:monthly
else
nil
end
end
def sort_snapshots(ec2_snapshots, ec2_volume, now = Time.now)
snapshots = { :hourly => [], :daily => [], :weekly => [], :monthly => [] }
# Reject those that don't match this volume
this_volume_snaps = ec2_snapshots.reject {|snap| ec2_volume[:aws_id] != snap[:aws_volume_id] }
# Sort the snapshots newest first
this_volume_snaps.sort! {|a, b| Time.parse(b[:aws_started_at]) <=> Time.parse(a[:aws_started_at]) }
# Check dates and form "levels"
last_timestamp = now
this_volume_snaps.each do |snap|
level = difference_in_time(Time.parse(snap[:aws_started_at]), last_timestamp)
last_timestamp = Time.parse(snap[:aws_started_at])
snapshots[level] << snap
end
return snapshots
end
| true |
ab9fd93d0a638cc4ca704a29439cb2f3d4b97ca2 | Ruby | gusmattos1/ruby_fundamentals_gusta | /exercise4.1.rb | UTF-8 | 155 | 3.75 | 4 | [] | no_license | puts "What is your number today?"
number = gets.chomp.to_i
if number > 100
puts "that's a big number!"
else
puts "why not dream a little bigger?"
end
| true |
4ce60306a841c36d61b4335119fb63b9c2c66052 | Ruby | kcsoderstrom/Checkers | /board.rb | UTF-8 | 4,484 | 3.359375 | 3 | [] | no_license | require_relative 'game'
require_relative 'piece'
require_relative 'cursor'
require_relative 'chars_array'
require_relative 'plane_like'
require_relative 'chess_clock'
require_relative 'checkers_errors'
require_relative 'symbol'
require 'colorize'
class Board
include PlaneLike
include CheckersErrors
COLORS = [:red, :black]
attr_reader :cursor, :prev_pos, :clock, :upgrade_cursor
attr_accessor :end_of_turn, :takens
def initialize
@rows = Array.new(8) { Array.new(8) }
place_pieces
@cursor = Cursor.new
@prev_pos = nil
@end_of_turn = false
@clock = ChessClock.new
@takens = [[],[]]
end
def click(turn)
pos = cursor.pos
if self.prev_pos.nil?
self.prev_pos = pos unless self[pos].nil? || self[pos].color != turn
else
begin
move(self.prev_pos, pos, turn)
rescue CheckersError
self.prev_pos = nil # clicked in a bad spot so resets
end
end
end
def select_only_legal_piece(turn)
selectables = self.pieces(turn).reject { |piece| piece.jump_moves.empty? }
if selectables.count == 1
self.prev_pos = selectables[0].pos
cursor.pos = prev_pos
end
end
def selected_piece
self[self.prev_pos] unless self.prev_pos.nil?
end
def opposite(color)
color == COLORS[0] ? COLORS[1] : COLORS[0]
end
def take(start, end_pos)
taken_piece_pos = middle(start, end_pos)
taken_piece = self[taken_piece_pos]
self[taken_piece_pos] = nil
taken_box = ( taken_piece.color == :red ? takens[0] : takens[1] )
taken_box << taken_piece
end
def jump(start, end_pos, color)
self.take(start, end_pos)
if self[end_pos].jump_moves.empty?
self.end_of_turn = true
self.prev_pos = nil
else # For double-jumps
self.end_of_turn = false
self.prev_pos = end_pos
end
end
def slide(start, end_pos, color)
self.end_of_turn = true
self.prev_pos = nil #deselects cursor #probably should rename
end
def move(start, end_pos, color)
raise_move_errors(start, end_pos, color)
moved_piece = self[start]
moved_piece.move(end_pos)
unless moved_piece.is_a?(King) || !moved_piece.at_end?
moved_piece = King.new(self, moved_piece.color, moved_piece.pos)
end
if jump?(start, end_pos)
jump(start, end_pos, color)
else
slide(start, end_pos, color)
end
end
def jump?(pos1, pos2)
(pos1[0] - pos2[0]).abs == 2 && (pos1[1] - pos2[1]).abs == 2
end
def cursor_move(sym,turn)
if sym == :" "
self.click(turn)
elsif sym == :o
return :title_mode
else
cursor.scroll(sym)
end
:board_mode
end
def dup
duped = Board.new
8.times do |y|
rows[y].each_with_index do |piece, x|
duped[[y,x]] = nil # Have to do this bc place_pieces
unless self[[y,x]].nil?
duped[[y,x]] = piece.class.new(duped,piece.color,[y, x])
end
end
end
duped
end
def pieces(color)
self.rows.flatten.compact.select { |piece| piece.color == color }
end
def display(turn)
puts render(turn)
end
def middle(pos1, pos2)
[(pos1[0] + pos2[0]) / 2, (pos1[1] + pos2[1]) / 2]
end
protected
attr_writer :prev_pos
private
attr_accessor :mode
def taken_pieces(color)
color == :red ? takens[0] : takens[1]
end
def place_pieces # kinda illegible
8.times do |col|
rows[col % 2][col] = Piece.new(self, :black, [col % 2, col])
rows[2][(2 * col) % 8] = Piece.new(self, :black, [2, (2 * col) % 8])
rows[6 + (col % 2)][col] = Piece.new(self, :red, [6 + (col % 2), col])
rows[5][(2 * col +1) % 8] = Piece.new(self, :red, [5, (2 * col + 1) % 8])
end
end
def render(turn)
characters_array = CharsArray.new(self, turn).rows.map
white_chars = takens[0].render.sort
black_chars = takens[1].render.sort
str = ''
str << white_chars.drop(8).join << "\n"
str << white_chars.take(8).join << "\n"
characters_array.each do |row|
row.each { |char| str << char }
str << "\n"
end
str << black_chars.take(8).join << "\n"
str << black_chars.drop(8).join << "\n"
str << "Red Current Time: #{clock.convert_times[0]} \t" <<
"Red Total Time: #{clock.convert_times[1]}\n" <<
"Black Current Time: #{clock.convert_times[2]} \t" <<
"Black Total Time: #{clock.convert_times[3]}"
str
end
end | true |
a856d66974b3ef850932791f68fa84ef1ce095b0 | Ruby | dnewbie25/dnewbie25.github.io | /Ruby-Projects/Basic-Projects/Stock-Picker.rb | UTF-8 | 1,156 | 3.59375 | 4 | [] | no_license | stocks_record = [17,3,6,9,15,8,6,1,10]
def stock_picker(stocks)
best_days = []
profit = 0
# loop from zero until array length entirely
(0..(stocks.length-1)).each do |buy|
# loop from day 2 forward for the selling. buy + 1 because otherwise it will start counting from day 2 all the time. This new loop is inclusive-exclusive
((buy + 1)...(stocks.length-1)).each do |sell|
if stocks[sell] - stocks[buy] > profit
best_days.push(buy)
best_days.push(sell)
profit = (stocks[sell] - stocks[buy])
end
end
end
# take buy and selling days, we count from day one not day zero, so this adds 1 to the indexes
buy_selling_days = [best_days.sort[0] + 1, best_days[-1] + 1]
return "The best to buy is day #{buy_selling_days[0]}, with the stock price at $#{stocks[best_days.sort[0]]} and the best day to sell is day #{buy_selling_days[-1]} with the stock price at $#{stocks[best_days.sort[-1]]}.\nThe profits are: $#{profit}"
end
puts stock_picker(stocks_record)
puts "\n*****************************************\n"
puts stock_picker([11,92,75,13,25,47,87,22,89,40]) | true |
daf6a681521315f8f2190bbf683a94ff8c43ad48 | Ruby | toptal/disqus_api | /lib/disqus_api/namespace.rb | UTF-8 | 1,303 | 2.796875 | 3 | [
"MIT"
] | permissive | module DisqusApi
class Namespace
attr_reader :api, :name, :specification
# @param [Api] api
# @param [String, Symbol] name
def initialize(api, name)
@api = api
@name = name
@specification = @api.specifications[@name]
@specification or raise(ArgumentError, "No such namespace <#@name>")
end
# @param [String, Symbol] action
# @param [Hash] arguments Action params
# @return [Request]
def build_action_request(action, arguments = {})
Request.new(api, name, action, arguments)
end
# @param [String, Symbol, Hash] action
# @param [Hash] arguments
# @return [Hash] response
def request_action(action, arguments = {})
build_action_request(action, arguments).response
end
alias_method :perform_action, :request_action
# DisqusApi.v3.users.---->>[details]<<-----
#
# Forwards all API calls under a specific namespace
def method_missing(method_name, *args)
if specification.has_key?(method_name.to_s)
request_action(method_name, *args)
else
raise NoMethodError, "No action #{method_name} registered for #@name namespace"
end
end
def respond_to?(method_name, include_private = false)
specification[method_name.to_s] || super
end
end
end | true |
348fc3a3c4c58bc710f29a58e97bd2e89a17ec64 | Ruby | ipublic/marketplace | /app/models/parties/party_role_kind.rb | UTF-8 | 2,017 | 2.609375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | # Actor roles or categories that a Party entity plays in the context of the enterprise.
module Parties
class PartyRoleKind
include Mongoid::Document
include Mongoid::Timestamps
field :key, type: Symbol
field :title, type: String
field :description, type: String
# Used for enabling/disabling role kinds over time
field :is_published, type: Boolean, default: true
field :start_date, type: Date, default: ->{ TimeKeeper.date_of_record }
field :end_date, type: Date
has_and_belongs_to_many :party_relationship_kinds,
class_name: "Parties::PartyRelationshipKind"
has_many :party_roles,
class_name: 'Parties::PartyRole'
# Associate a business rule for validating a role instance
belongs_to :eligibility_policy,
class_name: 'EligibilityPolicies::EligibilityPolicy',
optional: true
before_validation :assign_key_and_title
validates_presence_of :key, :title, :start_date, :is_published
validates_uniqueness_of :key
index({ key: 1}, { unique: true })
index({ is_published: 1, start_date: 1, end_date: 1 })
# before_validation :set_key
alias_method :is_published?, :is_published
def has_party_relationship_kinds?
party_relationship_kinds.size > 0
end
def key=(new_key)
write_attribute(:key, text_to_symbol(new_key))
end
def publish
write_attribute(:is_published, true)
end
def unpublish
write_attribute(:is_published, false)
end
def is_draft?
!is_published?
end
private
def assign_key_and_title
write_attribute(:key, text_to_symbol(title)) if key.blank? && title.present?
write_attribute(:title, symbol_to_text(key)) if title.blank? && key.present?
end
def text_to_symbol(text)
text.to_s.parameterize.underscore.to_sym
end
def symbol_to_text(symbol)
symbol.to_s.titleize
end
def self.is_valid_key?(key)
all.pluck(:key).include?(key)
end
end
end
| true |
0e3296e192b0b2610c3ad2a0c4297a78f4001fdf | Ruby | takatoshi-maeda/jawbone_up-client | /lib/jawbone_up/client/response.rb | UTF-8 | 756 | 2.671875 | 3 | [
"MIT"
] | permissive | require 'jawbone_up/client/response/meta'
require 'jawbone_up/client/response/item'
module JawboneUp
class Client
class Response
include Enumerable
def initialize(response)
@response = response
end
def code
@response.code
end
def headers
@response.headers
end
def meta
@meta ||= Meta.new(@response)
end
def each
if data.has_key?('items')
data['items'].each do |item|
yield Item.new(item)
end
else
yield Item.new(data)
end
end
def [](key)
data[key]
end
private
def data
@data ||= JSON.parse(@response)['data']
end
end
end
end
| true |
197172662a4639282cef946f507c4c7244e0c5ef | Ruby | davidsonhr1/orby | /scripts/ruby/oracle_sequence_fix.rb | UTF-8 | 3,289 | 2.734375 | 3 | [] | no_license | require_relative '../../require.rb'
require_relative '../../initialize.rb'
include OrbyInitialize
class Recreate_sequence
def initialize
time = Time.new
@arg = OrbyInitialize.init
@sequences_file = YAML.load_file("#{__dir__}/config/sequences.yaml")
printf "Connecting to #{@arg[:url]}/#{@arg[:url].split('-')[1]}, user: #{@arg[:client]} \n"
@db = Sequel.oracle("#{@arg[:url]}/#{@arg[:url].split('-')[1]}", :user => @arg[:client], :password => ENV['ORACLE_PASSWORD'])
@log_file = File.new "#{ENV['HOME']}/Desktop/recr_seq_log_#{time.strftime("%Y%m%d_%H%M%S")}.txt","w"
end
def init
#create_core_sequences
@sequences_file.each{|k,v| recreate(k,v['key'], v['sequence'])}
end
private
def recreate(table, column, sequence)
printf "=> #{sequence}\n"
begin
actual = get_max_key(table, column)
seq = get_sequence(sequence)
if actual.nil? || seq.nil?
raise "this table #{table} or #{seq} not exists"
else
if verify_column_value(actual, seq)
printf "-- Recreating table #{table.upcase}, #{sequence} is less than the table max number, ( max table value: #{actual}, changing sequence to suggested value: #{actual+1})\n".light_yellow
recreate_sequence(sequence, actual+1)
end
end
rescue Sequel::Error => e
@db.run('rollback')
error_code = e.message.split(' ')[1].gsub(':', '')
@log_file.puts ora_exceptions(error_code, e, table, column)
end
end
def get_max_key(table, column)
@db[table.to_sym].max(column.to_sym).to_i
end
def get_sequence(sequence)
sequence_obj = @db.fetch("SELECT coalesce(last_number, 0) as sequence FROM all_sequences WHERE sequence_owner = '#{@arg[:client].upcase}' AND sequence_name = '#{sequence.upcase}'").first
sequence_number = sequence_obj[:sequence].to_i
sequence_number == nil ? (sequence_number = 0) : (sequence_number = sequence_number)
return sequence_number
end
def verify_column_value(val, seq)
val > seq ? (true) : (false)
end
def recreate_sequence(sequence, value)
@db.run("drop sequence #{sequence}")
@db.run("create sequence #{sequence} start with #{value} increment by 1")
end
def create_core_sequences
File.open("#{__dir__}/config/seq_obj.txt").each do |i|
begin
printf "Creating #{i}".light_yellow
system('clear')
@db.run("create sequence #{i} start with 1 increment by 1")
@db.run("commit")
rescue Sequel::Error => e
end
end
end
def ora_exceptions(error_code, body, table, column)
if error_code == 'ORA-00904'
"#{table} - A Coluna usada não foi localizada\n"
elsif error_code == 'ORA-00972'
"#{table} - O nome da tabela ou coluna ultraplassa a precisão permitida\n"
elsif error_code == 'ORA-00942'
"#{table} - A Tabela não existe\n"
else
"#{table} - #{body} - cod: #{error_code} \n"
end
end
end
Recreate_sequence.new.init | true |
d2f771002b8dbd031b2940a164e25d1e62de34f9 | Ruby | bomberstudios/stone | /bin/stone-gen | UTF-8 | 1,375 | 2.875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'fileutils'
require 'rubygems'
def usage
puts <<-EOS
stone-gen model
EOS
end
def model_usage
puts <<-EOS
stone-gen model ModelName field:type field:type ...
e.g. stone-gen model Author name:string street_number:fixnum
Works just like all the other model generators out there,
just remember that Stone only accepts Ruby primitives for
field types (String, Fixnum, etc).
EOS
end
def gen_model(args)
model_name = args.first.camelcase
file_name = model_name.snakecase
args.shift
fields = Hash[*(args.map{|a| a.split(":") }.flatten)]
model_str = "class #{model_name}\n include Stone::Resource\n\n"
for field in fields
unless field.last == "datetime"
model_str << " field :#{field.first}, #{field.last.capitalize}\n"
else
model_str << " field :#{field.first}, DateTime\n"
end
end
model_str << "end"
FileUtils.mkdir(File.join(Dir.pwd, "app/models")) \
unless File.exists?(File.join(Dir.pwd, "app/models"))
File.open(File.join(Dir.pwd, "app/models/#{file_name}.rb"), "w") do |file|
file << model_str
end
puts "Model: #{model_name} created."
end
if ARGV.empty?
usage
else
args = ARGV
case args.first
when "model"
args.shift
if args.empty?
model_usage
else
gen_model(args)
end
else
usage
end
end | true |
c3b5ab5668e8dfac7fafc7e0252ca6a1d91c3767 | Ruby | johnvpetersen/Nerd-Dinner-on-Rails | /lib/jsondinner.rb | UTF-8 | 476 | 2.640625 | 3 | [] | no_license | class JsonDinner
def initialize(dinnerid,title,latitude,longitude,description,rsvpcount,searchlatitude,searchlongitude,searchlocation,distance)
@DinnerID = dinnerid
@Title = title
@Latitude = latitude
@Longitude = longitude
@Description = description
@RSVPCount = rsvpcount
@SearchLatitude = searchlatitude
@SearchLongitude = searchlongitude
@SearchLocation = searchlocation
@Distance = distance
end
end
| true |
86e0ec4f1274e747616e4432a2cbc42096e00253 | Ruby | NoahZinter/relational_rails | /spec/features/manufacturers/vehicles/index_spec.rb | UTF-8 | 4,460 | 2.640625 | 3 | [] | no_license | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Manufacturer Vehicles Index' do
it 'shows all of a manufacturers vehicles' do
manufacturer = Manufacturer.create!(name: 'Zonda', production_capacity: 40, is_open: true)
car_1 = manufacturer.vehicles.create!(name: 'Speedini', year: 1990, price: 56_000, sold: false)
car_2 = manufacturer.vehicles.create!(name: 'Slowstosa', year: 2005, price: 24_000, sold: false)
visit "/manufacturers/#{manufacturer.id}/vehicles"
expect(page).to have_content(car_1.name)
expect(page).to have_content(car_2.name)
end
it 'contains a button to add new vehicle' do
manufacturer = Manufacturer.create!(name: 'Zonda', production_capacity: 40, is_open: true)
visit "/manufacturers/#{manufacturer.id}/vehicles"
expect(page).to have_button("Create a New #{manufacturer.name} Vehicle:")
end
it 'contains a button to alphabetize vehicles' do
manufacturer = Manufacturer.create!(name: 'Zonda', production_capacity: 40, is_open: true)
visit "/manufacturers/#{manufacturer.id}/vehicles"
expect(page).to have_button('Alphabetize Zonda Vehicles')
end
it 'alphabetizes vehicles' do
honda = Manufacturer.create!(name: 'Honda', production_capacity: 28, is_open: true)
honda.vehicles.create!(name: 'Civic', year: 2000, price: 2500, sold: false)
del_sol = honda.vehicles.create!(name: 'Del Sol', year: 2005, price: 4500, sold: false)
honda.vehicles.create!(name: 'CRV', year: 2005, price: 4500, sold: false)
accord = honda.vehicles.create!(name: 'Accord', year: 2000, price: 2500, sold: false)
visit "/manufacturers/#{honda.id}/vehicles"
expect(del_sol.name).to appear_before(accord.name)
click_button 'Alphabetize Honda Vehicles'
expect(accord.name).to appear_before(del_sol.name)
end
it 'has a link to edit each vehicle' do
honda = Manufacturer.create!(name: 'Honda', production_capacity: 28, is_open: true)
honda.vehicles.create!(name: 'Civic', year: 2000, price: 2500, sold: false)
honda.vehicles.create!(name: 'Del Sol', year: 2005, price: 4500, sold: false)
honda.vehicles.create!(name: 'CRV', year: 2005, price: 4500, sold: false)
honda.vehicles.create!(name: 'Accord', year: 2000, price: 2500, sold: false)
visit "/manufacturers/#{honda.id}/vehicles"
expect(page).to have_button('Edit This Civic')
expect(page).to have_button('Edit This Del Sol')
expect(page).to have_button('Edit This CRV')
expect(page).to have_button('Edit This Accord')
end
it 'has a form to filter vehicles by price' do
honda = Manufacturer.create!(name: 'Honda', production_capacity: 28, is_open: true)
visit "/manufacturers/#{honda.id}/vehicles"
expect(page).to have_field('Find Cars Under Price')
expect(page).to have_field('Find Cars Over Price')
end
it 'filters vehicles by price low' do
honda = Manufacturer.create!(name: 'Honda', production_capacity: 28, is_open: true)
civic = honda.vehicles.create!(name: 'Civic', year: 2000, price: 2500, sold: false)
del_sol = honda.vehicles.create!(name: 'Del Sol', year: 2005, price: 4500, sold: false)
crv = honda.vehicles.create!(name: 'CRV', year: 2005, price: 4500, sold: false)
accord = honda.vehicles.create!(name: 'Accord', year: 2000, price: 2500, sold: false)
visit "/manufacturers/#{honda.id}/vehicles"
fill_in 'Find Cars Under Price', with: 3000
click_button 'Find Cars Under Price'
expect(page).not_to have_content('Del Sol')
expect(page).not_to have_content('CRV')
expect(page).to have_content('Civic')
expect(page).to have_content('Accord')
end
it 'filters vehicles by price high' do
honda = Manufacturer.create!(name: 'Honda', production_capacity: 28, is_open: true)
civic = honda.vehicles.create!(name: 'Civic', year: 2000, price: 2500, sold: false)
del_sol = honda.vehicles.create!(name: 'Del Sol', year: 2005, price: 4500, sold: false)
crv = honda.vehicles.create!(name: 'CRV', year: 2005, price: 4500, sold: false)
accord = honda.vehicles.create!(name: 'Accord', year: 2000, price: 2500, sold: false)
visit "/manufacturers/#{honda.id}/vehicles"
fill_in 'Find Cars Over Price', with: 3000
click_button 'Find Cars Over Price'
expect(page).to have_content('Del Sol')
expect(page).to have_content('CRV')
expect(page).not_to have_content('Civic')
expect(page).not_to have_content('Accord')
end
end
| true |
930b9cd3feb756cc510976303e84d89d42675f29 | Ruby | Salsa-Dude/ruby-code-review | /Arrays-III/zip.rb | UTF-8 | 117 | 3.53125 | 4 | [] | no_license |
names = ["joe", "alex", "lina"]
ages = [12, 29, 34]
p names.zip(ages) # [["joe", 12], ["alex", 29], ["lina", 34]]
| true |
acbebad59733033cb293be19a245415e6a9d82a8 | Ruby | AlinaMoskieva/sport_cms | /app/query_objects/top_news_in_category_query.rb | UTF-8 | 642 | 2.6875 | 3 | [] | no_license | class TopNewsInCategoryQuery
DEFAULT_LIMIT = 3
attr_reader :page, :limit
private :page, :limit
def initialize(page, limit: DEFAULT_LIMIT)
@page = page
@limit = limit
end
def all
return top_in_category if top_in_category.any?
top_in_site
end
private
def published_pages
Page.where.not(id: page.id)
end
def top_in_category
@top_in_category ||=
published_pages
.where(category_id: page.category_id)
.order(created_at: :desc)
.limit(limit)
end
def top_in_site
@top_in_site ||=
published_pages
.order(created_at: :desc)
.limit(limit)
end
end
| true |
1c47165c8b41b0a4043b71d4eabc3f254d92030a | Ruby | mb-kaizen/coding-challenges-koans-data-structures-etc. | /data_structures/singly_linked_list_re.rb | UTF-8 | 958 | 3.9375 | 4 | [] | no_license | class Node
attr_accessor :value, :pointer
def initialize(value)
@value = value
@pointer
end
end
class LinkedList
def initialize(value)
@head = Node.new(value)
end
def move_to_last_node
current_node = @head
while current_node.pointer
current_node = current_node.pointer
end
return current_node
end
def push(value)
move_to_last_node.pointer = Node.new(value)
end
def reverse_list
current_node = @head
next_node = nil
previous_node = nil
while current_node
next_node = current_node.pointer
current_node.pointer = previous_node
previous_node = current_node
current_node = next_node
end
@head = previous_node
end
def print_list
current_node = @head
while current_node
p current_node.value
current_node = current_node.pointer
end
end
end
list = LinkedList.new("start")
%w[first second third fourth].each {|x| list.push(x)}
list.print_list
p "------"
list.reverse_list
list.print_list | true |
bbd72f8cb8f35f00e76fc7b03f9b9b8b587ff9d7 | Ruby | soliverit/ollieml | /examples/geneva_scehdule_climate_translation.rb | UTF-8 | 9,913 | 2.640625 | 3 | [] | no_license | CSV_DATA_PATH = "./data/geneva_schedule_climate.csv"
ELEC_COST = 0.153
GAS_COST = 0.034
ELEC_CO2 = 0.519
GAS_CO2 = 0.216
DPP_RATE = 0.035
RETROFIT_COST = 83112
if ! CSV_DATA_PATH
Lpr.p "Define CSV_DATA_PATH before continuing (I've got it in a data/ sub folder"
return
end
Lpr.p """
##
# Introduction / Overview
#
# Classes:
# RegressionDataSet: The data handling library. Fun stuff, honestly
# Lpr: A printing prettifier
#
# Data:
#
# Starts with an alias, electricity and gas keys
# alias: String containing all the info on schedule, year, is retroffited
# naturalGas: kWh
# electricity: kWh
#
# alias key description:
# The data alias naming convention is original/explicit/implicit refers
# to the original model and occupancy schedules. upgraded-90 refers to
# retrofitted models. These have full-<explicit/implicit/original> in their
# alias to dictate their occupancy schedule
#
# All weather data is for Geneva with a four digit year, 1981 to 2013
#
# WARNING: RegressionDataSet doesn't handle Booleans yet, use string names
"""
## Load data
rgDataSet = RegressionDataSet::parseCSV CSV_DATA_PATH
Lpr.p """
##
# Fix alias inconsistency!
#
# Ok, this is on me. In my original data set I used 'full-or' to mean original schedule. Nonetheless,
# this is a good place to use the apply function to repair the broken alias.
#
##
"""
Lpr.d "fixing inconsistent alias"
rgDataSet.apply{|data|
data[:alias].gsub!("full-or", "original")
}
Lpr.p """
##
# Add schedule and year alias keys. See proceeding comment in what aliases segments mean
##
"""
Lpr.d "Injecting schedule alias"
rgDataSet.injectFeatureByFunction(:schedule){|data, newKey| data[:alias].match(/implicit|explicit|original/i).to_s }
Lpr.d "Injecting year"
rgDataSet.injectFeatureByFunction(:year){|data, newKey| data[:alias].match(/\d{4}/).to_s.to_i}
Lpr.d "Injecting retrofited state"
rgDataSet.injectFeatureByFunction(:retrofitted){|data, newKey| (data[:alias].match(/upgraded-90/) ? true : false).to_s}
Lpr.d "Injecting energy cost"
rgDataSet.injectFeatureByFunction(:cost){|data, newKey| data[:electricity] * ELEC_COST + data[:naturalGas] * GAS_COST}
Lpr.d "Dumping to example_feature_inject_results.csv for review"
rgDataSet.toCSV "#{TMP_PATH}/example_feature_inject_results.csv"
Lpr.p """
##
# We're done with the alias feature. Though not necessary, we'll
# drop it.
##
"""
Lpr.d "Dropping alias feature"
rgDataSet.dropFeatures [:alias]
Lpr.p """
##
# Group the data
#
#
# Note: Grouping by function is available. If the alias feature was still present you could
# \"'rgDataSet.groupByFunction{|data| data[:alias].match(/upgraded-90/) ? true : false}\"
# to group by regex match for upgraded
#
# WARNING: This isn't actually used any more. Turns out it's unnecessary. Left in for demonstration
# purposes only.
##
"""
Lpr.d "Grouping by schedule"
rgRetrofittedGrouping = rgDataSet.groupBy(:schedule)
Lpr.p """
##
# Generate simple relational data set
#
# Features:
# Original schedule, year
# New schedule, year, deltaCO2
##
"""
simpleRelationalPayback = RegressionDataSet.new false, [:Original, :New,
:OriginalRetrofitted, :Retrofitted,
:YearX, :YearY, :target]
rgDataSet.each{|topData|
# puts topData[:retrofitted].to_s.downcase == "false"
rgDataSet.each{|data|
next if data[:year] == topData[:year]
next if data[:schedule] == "explicit" || topData[:schedule] == "explicit"
deltaCO2 = ((topData[:electricity] - data[:electricity]) * ELEC_CO2 + (topData[:naturalGas] - data[:naturalGas]) * GAS_CO2) / 2869
simpleRelationalPayback.push(
[topData[:schedule] == "original" ? 0 : 1,
data[:schedule] == "original" ? 0 : 1,
topData[:retrofitted].to_s.downcase == "false" ? 0 : 1,
data[:retrofitted].to_s.downcase == "false" ? 0 : 1,
topData[:year], data[:year], deltaCO2])
}
}
Lpr.d "Dumping #{simpleRelationalPayback.length} entries"
simpleRelationalPayback.toCSV "#{TMP_PATH}simple_relational_data.csv"
Lpr.p """
##
# Create martix of schedule-year data
#
# This will create a new RegressionDataSet which has the alias then every
# relevant year's delta cost from the start record on original data only
#
# Schedule - next year
#
# RegressionDataSet.new takes two parameters, data and features. Only send one
# or the other unless data is an array of arrays.
##
"""
Lpr.d "Creating new RegressionDataSet for year-schedule-retorfitted deltas"
scheduleDeltasDataSet = RegressionDataSet.new false, [:alias, :year, :baseCost, :retrofitted].concat((1981...2013).map{|year|
rgRetrofittedGrouping.keys.map{|scheduleKey|
[
(scheduleKey.to_s + "-" + year.to_s + "-retrofitted").to_sym,
(scheduleKey.to_s + "-" + year.to_s + "-original").to_sym
]
}
}).flatten
Lpr.d "Doing martix transform: That the right term?"
rgDataSet.each{|data|
entry = {alias: data[:schedule], year: data[:year], baseCost: data[:cost], retrofitted: data[:retrofitted]}
rgDataSet.each{|deltaData|
retrofitted = deltaData[:retrofitted].downcase == "true" ? "retrofitted" : "original"
entry[(deltaData[:schedule].to_s + "-" + deltaData[:year].to_s + "-" + retrofitted).to_sym] = entry[:baseCost] - deltaData[:cost]
}
scheduleDeltasDataSet.push entry
}
Lpr.d "Writing schedule delta output file schedule_deltas.csv"
scheduleDeltasDataSet.toCSV "#{TMP_PATH}/schedule_deltas.csv"
Lpr.p """
##
# Create DPP data for unretrofitted Schedule-Climate scenarios.
#
# The first step is to get only the retrofit = 'FALSE' data. This can
# be done with either filterByFunction or select. These return a new
# RegressionDataSet. Both methods take a lambda expression that
# takes one parameter. The hashedData of the rgDataSet is
# iterated over and each hash passed to the method.
##
"""
Lpr.d "Extracting original state data from delta data set"
originalData = scheduleDeltasDataSet.select{|data| data[:retrofitted] == "false"}
Lpr.d "No. original: #{originalData.length}"
Lpr.p """
##
# Removing unwanted features from the data set.
#
# There are two ways of doing this depending on your fancy. Either
# dropFeatures (takes array) or segregate (takes array of features + an optional Boolean to dropping on current).
# In both cases you need to know the features you want. We'll do this by simply
# iterating over the features and looking for 'original'.
#
# dropFeatures vs segregate:
# dropFeatures [<features] - inline drop on this rgDataSet
# segregate [<features>] - return new RegressionDataSet with features
# segregate [<features>], true - As previous and drop features from original
#
# NOTES:
# - RegressionDataSet.features property contains symbols. Convert to string if necessary
##
"""
Lpr.d "Dropping features related to original processes"
originalData.dropFeatures originalData.features.select{|feature| feature.to_s.match(/original/i)}
Lpr.d "Dumping data to original_only_deltas.csv"
originalData.toCSV "#{TMP_PATH}original_only_deltas.csv"
Lpr.p """
##
# Translate savings to discounted payback periods.
#
# Translate savings to constant-cashflow DPPs.
#
# NOTES:
# The feature identification method's a bit lazy. Just makes sure the feature isn't
# retrofit but contains the word. Do whatever
##
"""
Lpr.d "Extract feature set"
targetFeatures = originalData.features.select{|feature| feature.to_s.match(/\d\d\d\d.*retrofit/i)}
Lpr.d "Applying DPP to deltas"
originalData.apply{|data|
targetFeatures.each{|feature|
data[feature] = RegressionDataSet::dpp RETROFIT_COST, data[feature], DPP_RATE
}
}
Lpr.d "Dumping DPP data to geneva_retrofit_dpp.csv"
originalData.toCSV "#{TMP_PATH}geneva_retrofit_dpp.csv"
Lpr.p """
##
# Inject min/max/avg
#
# As with extracting the alias earlier, we're injecting new features.
##
"""
Lpr.d "Inject max value"
originalData.injectFeatureByFunction(:max){|data|
targetFeatures.map{|feature| data[feature]}.max
}
Lpr.d "Inject min value"
originalData.injectFeatureByFunction(:min){|data|
targetFeatures.map{|feature| data[feature]}.select{|val| val != -10}.min
}
Lpr.d "Inject average value"
originalData.injectFeatureByFunction(:avg){|data|
sum = 0
count = 0
targetFeatures.map{|feature| data[feature]}.select{|val|
if val != -10
count += 1
sum += val
end
}
sum / count
}
Lpr.d "Export standard to with stats to average_dpp.csv"
originalData.toCSV "#{TMP_PATH}average_dpp.csv"
Lpr.p """
##
# Create stats table grouping each schedule
#
# TODO: Dec 2019 - Create a method that does this automatically
##
"""
Lpr.d "Creating new RegressionDataSet for Schedule-Climate stats"
statsDataSet = RegressionDataSet.new false, [
:year,
"implicit-min", "implicit-max", "implicit-avg",
"explicit-min", "explicit-max", "explicit-avg",
"original-min", "original-max", "original-avg"
].map{|feature| feature.to_sym}
Lpr.d "Group data by schedules"
scheduleStatGroups = originalData.groupBy(:alias)
Lpr.d "Sort schedule group data sets"
scheduleStatGroups.each{|key, scheduleDataSet| scheduleDataSet.sort!{|a, b| a[:year] <=> b[:year]}}
Lpr.d "Populate stats data set"
(0...scheduleStatGroups[:original].length).each{|idx|
statsDataSet.push({
year: scheduleStatGroups[:original].hashedData[idx][:year],
"original-min": scheduleStatGroups[:original].hashedData[idx][:min],
"original-max": scheduleStatGroups[:original].hashedData[idx][:max],
"original-avg": scheduleStatGroups[:original].hashedData[idx][:avg],
"implicit-min": scheduleStatGroups[:implicit].hashedData[idx][:min],
"implicit-max": scheduleStatGroups[:implicit].hashedData[idx][:max],
"implicit-avg": scheduleStatGroups[:implicit].hashedData[idx][:avg],
"explicit-min": scheduleStatGroups[:explicit].hashedData[idx][:min],
"explicit-max": scheduleStatGroups[:explicit].hashedData[idx][:max],
"explicit-avg": scheduleStatGroups[:explicit].hashedData[idx][:avg],
})
}
Lpr.d "Exporting stats Schedule-Climate Min/Max/Avg data to schedule_stats.csv"
statsDataSet.toCSV "#{TMP_PATH}schedule_stats.csv"
| true |
94921d69fa9fe66c2686d6a140d2dbaeb7827bbb | Ruby | scottrfrancis/RubyPeaks | /lib/trainingpeaks.rb | UTF-8 | 4,889 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | require 'open-uri'
require 'savon'
class TrainingPeaks
TPBASE= 'http://www.trainingpeaks.com/tpwebservices/service.asmx'
TPWSDL= TPBASE + '?WSDL'
@@client = nil
attr_accessor :user, :password, :client, :guid, :athletes, :personID
#
# you can init the class without a user/password, but you'll need one soon enough
# use the user & password setters
def initialize( aUser=nil, aPassword=nil )
@user= aUser
@password= aPassword
@guid=nil # returned from authenticate
@athletes=nil
@personID=nil # needed for lots of calls
end
def getClient
@@client = openClient if @@client.nil?
@@client
end
def openClient
if ( @@client.nil? ) #&& !@user.nil? && !@password.nil? )
@@client = Savon.client( wsdl: TPWSDL )
end
if ( @@client.nil? )
puts( "TrainingPeaks.authenticateAccount:\tCan't open Client" )
end
@@client
end
#
# callTP depends on the client being open. Be sure to check that outside of this function
#
def callTP( method, params=nil )
cl= getClient
msg = { username: @user, password: @password }
msg = msg.each_with_object( params ) { |(k,v), h| h[k] = v } if !params.nil?
resp = cl.call( method.to_sym, message: msg )
end
def authenticateAccount( aUser=nil, aPassword=nil )
@user = aUser if !aUser.nil?; @password = aPassword if !aPassword.nil?
if ( @user.nil? || @password.nil? )
puts( "TrainingPeaks.authenticateAccount:\tCan't authenticate without user and password non-nil" )
else
resp = callTP( :authenticate_account )
@guid = resp.body[:authenticate_account_response][:authenticate_account_result]
end
!@guid.nil? # if guid is non-nil, it worked!
end
def getAccessibleAthletes( athTypes=
[ # "CoachedPremium", # TODO: adding this selector returns null results
"SelfCoachedPremium",
"SharedSelfCoachedPremium",
"SharedCoachedPremium",
"CoachedFree",
"SharedFree",
"Plan"
] )
athletes=nil
resp = callTP( :get_accessible_athletes, { types: athTypes } )
athletes = resp.body[:get_accessible_athletes_response][:get_accessible_athletes_result]
@athletes = athletes
end
#
# reads array of accessible athletes for the account, @user to find the matching athlete with username
# returns the personID for that athlete
# if username is nil, will attempt to match an athlete where username == @user
#
def usePersonIDfromUsername( username=nil )
id = nil
matchuser = username.nil? ? @user : username
if @athletes.nil?
getAccessibleAthletes()
end
if @athletes.length() != 1
puts( "TrainingPeaks.getPersonID:\tathletes has length other than 1")
end
person = @athletes[:person_base]
if person[:username] == matchuser
id = person[:person_id]
end
@personID = id
end
#
# retrieves historical or future scheduled workouts for the current personID (set with usePersonIDfromUsername)
# for date range. dates are of format YYYY-MM-DD, e.g. "2014-10-24"
#
def getWorkouts( start, stop )
workouts = nil
if ( @personID.nil? )
# personID not set... try for current user
usePersonIDfromUsername()
end
resp = callTP( :get_workouts_for_accessible_athlete,
{ personId: @personID, startDate: start, endDate: stop } )
if (!resp.body.nil? && !resp.body[:get_workouts_for_accessible_athlete_response].nil? &&
!resp.body[:get_workouts_for_accessible_athlete_response][:get_workouts_for_accessible_athlete_result].nil? &&
!resp.body[:get_workouts_for_accessible_athlete_response][:get_workouts_for_accessible_athlete_result][:workout].nil? )
workouts = resp.body[:get_workouts_for_accessible_athlete_response][:get_workouts_for_accessible_athlete_result][:workout]
end
end
#
# gets workout data (PWX file) for a single workoutID or array of workoutID(s)
#
def getWorkoutData( workoutID )
usePersonIDfromUsername() if @personID.nil?
resp = callTP( :get_extended_workouts_for_accessible_athlete,
{ personId: @personID, workoutIds: workoutID } )
resp.body[:get_extended_workouts_for_accessible_athlete_response][:get_extended_workouts_for_accessible_athlete_result][:pwx]
end
def saveWorkoutDataToFile( workoutID, filename )
usePersonIDfromUsername() if @personID.nil?
params = { username: @user,
password: @password,
personId: @personID,
workoutIds: workoutID }
url = TPBASE + "/GetExtendedWorkoutsForAccessibleAthlete" + '?' + params.map{|e| e.join('=')}.join('&')
puts( url )
open( filename, 'wb' ) do |f|
f << open( url ).read
end
end
end
| true |
e58aac8466dc332eb93ca324651434a4a0567518 | Ruby | dwillis/mccandlish | /lib/mccandlish/result.rb | UTF-8 | 713 | 2.65625 | 3 | [
"MIT"
] | permissive | module Mccandlish
class Result
attr_reader :hits, :offset, :copyright, :status, :articles, :facets
def initialize(params={})
params.each_pair do |k,v|
instance_variable_set("@#{k}", v)
end
end
def to_s
"<Result: #{hits} hits>"
end
def self.create_from_parsed_response(results)
self.new(:hits => results['response']['meta']['hits'],
:offset => results['response']['meta']['offset'],
:copyright => results['copyright'],
:status => results['status'],
:articles => Article.create_from_results(results['response']['docs']),
:facets => results['response']['facets']
)
end
end
end | true |
d7572e833e8efae23d4384571f8f9d6f1d49e583 | Ruby | monfil/fase1-1 | /semana3/examen2/flight/app/controllers/controller.rb | UTF-8 | 5,538 | 2.859375 | 3 | [] | no_license | class Controller
def initialize(args)
@view = View.new
send(args[0])
end
def index
@view.index
while true
@choice = STDIN.gets.chomp
break if @choice == '1' || @choice == '2' || @choice == '3'
@view.error
end
if @choice == "1"
@view.reservations
reservations
elsif @choice == "2"
@view.admin
admin
elsif @choice == "3"
"Salir"
end
end
def reservations
while true
@choice = STDIN.gets.chomp
break if @choice == '1' || @choice == '2'
@view.error
end
if @choice == "1"
make_reservation
elsif @choice == "2"
"Salir"
end
end
def make_reservation
flight_query = []
puts "From:"
flight_query << STDIN.gets.chomp
puts "To:"
flight_query << STDIN.gets.chomp
puts "Date:"
flight_query << STDIN.gets.chomp
puts "Passengers (1, 2, 3, 4...):"
flight_query << STDIN.gets.chomp
available_flights(flight_query)
end
def available_flights(flight_query)
flight_query_array = Flight.where(to: flight_query[1], from: flight_query[0], date: flight_query[2])
flight_options = []
counter = 1
flight_query_array.each do |flight|
if flight_query[3].to_i <= flight["passengers"]
@view.fligts(counter, flight)
flight_options << flight["num_flight"]
counter += 1
end
end
counter -= 1
if counter > 0
choose_flight(flight_query, flight_options, counter)
else
puts "No hay vuelos disponibles."
puts "Nueva búsqueda:"
make_reservation
end
end
def choose_flight(flight_query, flight_options, counter)
puts "Selecciona tu vuelo:"
while true
flight_choice = STDIN.gets.chomp.to_i
break if (flight_choice <= counter) && (flight_choice != 0)
@view.error
end
present_flight = (Flight.where(num_flight: flight_options[flight_choice - 1]))[0]
user_info(present_flight, flight_query)
end
def user_info(present_flight, flight_query)
users_ids = []
flight_query[3].to_i.times do |i|
puts "Datos de persona " + "#{(i + 1)}" + ":"
puts "Ingresa tu nombre:"
name = STDIN.gets.chomp
puts "Email:"
email = STDIN.gets.chomp
User.create(name: name, email: email, admin: false)
present_user = User.where(name: name, email: email, admin: false)
users_ids << present_user[0]["id"]
end
puts "¿Realizar reservación? SI / NO"
while true
@booking_choice = STDIN.gets.chomp
break if @booking_choice == 'si' || @booking_choice == 'SI' || @booking_choice == 'NO' || @booking_choice == 'no'
@view.error
end
if @booking_choice == 'si' || @booking_choice == 'SI'
create_booking(present_flight, flight_query, users_ids)
create_user_flight(present_flight, flight_query, users_ids)
elsif @booking_choice == 'no' || @booking_choice == 'NO'
index
end
end
def create_booking(present_flight, flight_query, users_ids)
total_cost = present_flight["cost"].to_i * flight_query[3].to_i
book_num = "#{rand(1000..2000)}-#{rand(0..9)}"
Booking.create(num_booking: book_num, flight_id: present_flight["id"], total: total_cost)
present_booking = Booking.where(num_booking: book_num, flight_id: present_flight["id"], total: total_cost)
flight_query[3].to_i.times do |i|
UserBooking.create(id_bookings: present_booking[0]["id"], id_users: users_ids[i])
end
end
def create_user_flight(present_flight, flight_query, users_ids)
flight_query[3].to_i.times do |i|
UserFlight.create(flight_id: present_flight["id"], user_id: users_ids[i])
end
end
def admin
while true
choice = STDIN.gets.chomp
break if User.exists?(name: choice , admin: true)
@view.error
end
puts "Ingrese contraseña:"
while true
choice = STDIN.gets.chomp
break if choice == "password"
@view.error
end
@view.logged_admin
logged_admin
end
def logged_admin
while true
@choice = STDIN.gets.chomp
break if @choice == '1' || @choice == '2' || @choice == '3' || @choice == '4'
@view.error
end
if @choice == '1'
counter = 1
all_flights = Flight.all
all_flights.each do |flight|
@view.fligts(counter, flight)
counter += 1
end
@view.logged_admin
logged_admin
elsif @choice == '2'
puts "Reservaciones:"
counter = 1
booked_flights = Booking.all
booked_flights.each do |booking|
@view.bookings(counter, booking)
counter += 1
end
@view.logged_admin
logged_admin
elsif @choice == '3'
add
end
end
def add
@flight_info = []
puts "Crear vuelo."
puts "Número de vuelo:"
@flight_info << STDIN.gets.chomp
puts "Fecha del vuelo:"
@flight_info << STDIN.gets.chomp
puts "Hora de salida:"
@flight_info << STDIN.gets.chomp
puts "Origen:"
@flight_info << STDIN.gets.chomp
puts "Destino:"
@flight_info << STDIN.gets.chomp
puts "Duración:"
@flight_info << STDIN.gets.chomp
puts "Precio:"
@flight_info << STDIN.gets.chomp
puts "Número de pasajeros:"
@flight_info << STDIN.gets.chomp
Flight.create(num_flight: @flight_info[0], date: @flight_info[1], depart: @flight_info[2], from: @flight_info[3], to: @flight_info[4], duration: @flight_info[5], cost: @flight_info[6], passengers: @flight_info[7])
end
def delete
end
def complete
end
end
| true |
3698189d7453263226a1a192cac35420296d1a91 | Ruby | UchikoMisc/bonus-drink | /bonus_drink.rb | UTF-8 | 317 | 3.375 | 3 | [] | no_license | class BonusDrink
BONUS_AMOUNT=3
def self.total_count_for(amount)
amount + calculate_bonus(amount)
end
def self.calculate_bonus(amount)
bonus = amount / BONUS_AMOUNT
rest = amount % BONUS_AMOUNT
if bonus == 0
return 0
else
bonus + calculate_bonus(bonus+rest)
end
end
end | true |
7d77a56139afa4c5038c234f189ceb91bc826726 | Ruby | jmettraux/ruote | /lib/ruote/exp/fe_save.rb | UTF-8 | 2,142 | 2.65625 | 3 | [
"MIT"
] | permissive | #--
# Copyright (c) 2005-2013, John Mettraux, jmettraux@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Made in Japan.
#++
module Ruote::Exp
#
# Saves the current workitem fields into a variable or into a field.
#
# save :to_field => 'old_workitem'
# # or
# save :to => 'f:old_workitem'
# #
# # saves a copy of the fields of the current workitem into itself,
# # in the field named 'old_workitem'
#
# save :to_variable => '/wix'
# # or
# save :to => 'v:/wix'
# #
# # saves a copy of the current workitem in the varialbe 'wix' at
# # the root of the process
#
# See also the 'restore' expression (Ruote::Exp::RestoreExpression).
#
class SaveExpression < FlowExpression
names :save
def apply
to_v, to_f = determine_tos
if to_v
set_variable(to_v, h.applied_workitem['fields'])
elsif to_f
set_f(to_f, Ruote.fulldup(h.applied_workitem['fields']))
#else
# do nothing
end
reply_to_parent(h.applied_workitem)
end
def reply(workitem)
# empty, never called
end
end
end
| true |
758af17be8f30fc8461b6f0e04e322436078eec1 | Ruby | rgo/adventofcode-2020 | /10-adapter-array/main_2.rb | UTF-8 | 234 | 2.71875 | 3 | [] | no_license | #!/usr/bin/env ruby
# frozen_string_literal: true
require './adapter'
require 'open-uri'
input = URI.open('input.txt').readlines.map(&:to_i)
adapter = Adapter.new(input)
puts "Number of arrangements: #{adapter.count_arrangements}"
| true |
c600bb78fc9872d3e00b61356062361064b4876b | Ruby | ahtee/ruby-nku | /otteb1-lab10/mimeTypeParser.rb | UTF-8 | 1,050 | 3.40625 | 3 | [] | no_license | #!/usr/bin/ruby
#This program was written by Ben Otte.
#This program gets each line of the mime.types file , separates the line, and returns each line in a hash array which we can use for reference.
#Add hash array and use value.join(',')
hashArray = Hash.new
file= File.new("/etc/mime.types") do |file|
while (line = file.gets)
next if line[0] == ?#
next if line == "\n"
list= line.chomp.split
hashArray =
if "#{list[1]}" != ""
puts "#{list[0]}" + " has extensions " + "#{list[1]}"
else
puts "#{list[0]}" + " has no extensions"
end
end
lineHash = Hash.new
File.open("/etc/mime.types", "r") do |file|
file.each_line do |line|
next if line[0] == ?#
next if line == "\n"
line = line.chomp.split
lineHash[line[0]] = line[1..-1]
end
end
lineHash.each do |key, value|
if value.length == 0
puts key + ' has no extensions.'
else
puts key + ' has extensions ' + value.join(',')
end
end
| true |
eb5dab27d1c567c517c8ad0d34d5fce5577a16e5 | Ruby | 16max/rub | /cod/auf/05_class_player.rb | UTF-8 | 1,303 | 4.34375 | 4 | [] | no_license | # a. erstellen Sie eine Klasse mit der Bezeichnung Player
# b. erstellen Sie ein Objekt player1 der Klasse
# c. erstellen Sie eine initialize - Methode, die die Parameter name und health hat und aus diesen Werten die Instanzvariablen @name und @health initialisiert
# d. updaten Sie das Objekt player1 und lassen sich das objekt anzeigen
# e. setzen Sie fuer health einen Standardwert 100
# f. legen Sie eine neues Objekt player2 an, das nur den Namen als Parameter hat
# g. passen Sie die say_hello - Methode aus der vorherigen Übung zur Ausgabe ein, so dass puts player1.say_hello die Ausgabe ergibt
# h. fuegen Sie eine Instanzmethode blam und w00t hinzu, die den Wert fuer health umd 10 hochsetzt, bzw. reduziert und ausgibt: Tom got blamed, bzw. w00ted.
# i. die say_hello - Methode soll aufgerufen werden, wenn nur das Objekt ausgegeben werden soll, also puts players erfolgt.
class Player
def initialize(name, health = 100)
@name = name
@health = health
end
def say_hello
"Ich bin #{@name} mit einem Wert von #{@health}"
end
def blam
@health -= 10
puts "#{@name} got blamed"
end
def w00t
@health += 10
puts "#{@name} got w00ted"
end
end
player1 = Player.new('Ralf', 100)
player2 = Player.new('Jürgen')
players = player1.say_hello, player2.say_hello
puts players | true |
40061f8917e6decbf5c12ba755590fb2ed84524e | Ruby | heather-kirk/activerecord-validations-lab-online-web-pt-011419 | /app/models/post.rb | UTF-8 | 432 | 2.609375 | 3 | [] | no_license | class Post < ActiveRecord::Base
validates :title, presence: true
validates :content, length:{minimum: 250}
validates :summary, length:{maximum: 250}
validates :category, inclusion:{in:%w(Fiction Non-Fiction)}
validate :clickbait?
CLICKBAIT = [/Won't Believe/, /Secret/, /Top[0-9]/, /Guess/]
def clickbait?
if CLICKBAIT.none? {|word| word.match(title)}
errors.add(:title, "Errors")
end
end
end
| true |
2997273fe6b566ec5fce94eeca67a18d92640333 | Ruby | istana/divan | /lib/divan/helpers.rb | UTF-8 | 573 | 2.78125 | 3 | [
"MIT"
] | permissive | require 'cgi'
module Divan
module Helpers
def pacify_blank(*objects)
for object in objects
if object.blank?
raise(ArgumentError, 'Object cannot be blank')
end
end
true
end
def uri_encode(what)
if what.respond_to?(:to_s)
what = what.to_s
else
raise(ArgumentError, 'Argument cannot be converted to string')
end
# URI::encode(what) doesn't encode slash
::CGI.escape(what)
end
# Can call it directly
module_function :uri_encode
# If function is module_function, in mixin it is private
public :uri_encode
end
end
| true |
0a366706806e9956c11519941d40c1fbdd62c25a | Ruby | rossmari/imaged_digits_parser | /lib/rows_excel_builder.rb | UTF-8 | 937 | 2.75 | 3 | [] | no_license | class RowsExcelBuilder
class << self
def generate_xlsx(category_id)
package = Axlsx::Package.new
wb = package.workbook
ws = wb.add_worksheet name: 'First page'
header_style = wb.styles.add_style(b: true, sz: 14, alignment: { horizontal: :center})
ws.add_row(['Name', 'Category'] + RowContent::FIELDS.map(&:capitalize), style: header_style)
Row.where(category: category_id).find_each do |row|
first_row = [ row.name , row.category.name ]
ws.add_row(first_row + content_as_array(row.row_contents.first))
row.row_contents[1..row.row_contents.count].each do |content|
ws.add_row(['', ''] + content_as_array(content))
end
end
package
end
private
def content_as_array(content)
result = []
RowContent::FIELDS.each do |field|
result << content.send(field)
end
return result
end
end
end
| true |
472a88488d0dfa21e0621cc41e73ed67f7e4fa6a | Ruby | AteroConfigs/gurgitate-mail | /gurgitate-mail.RB | UTF-8 | 14,827 | 3.046875 | 3 | [] | no_license | #!/opt/bin/ruby
# -*- encoding : utf-8 -*-
#------------------------------------------------------------------------
# Mail filter package
#------------------------------------------------------------------------
require 'etc'
require 'gurgitate/mailmessage'
require 'gurgitate/deliver'
module Gurgitate
# This is the actual gurgitator; it reads a message and then it can
# do other stuff with it, like saving it to a mailbox or forwarding
# it somewhere else.
#
# To set configuration parameters for gurgitate-mail, use a keyword-
# based system. It's almost like an attribute, only if you give the
# accessor a parameter, it will set the configuration parameter to
# the parameter's value. For instance:
#
# maildir "#{homedir}/Mail"
# sendmail "/usr/sbin/sendmail"
# spoolfile "Maildir"
# spooldir homedir
#
# (This is because of an oddity in Ruby where, even if an
# accessor exists in the current object, if you say:
# name = value
# it'll always create a local variable. Not quite what you
# want when you're trying to set a config parameter. You have
# to say <code>self.name = value</code>, which [I think] is ugly.
#
# In the interests of promoting harmony, of course,
# <code>self.name = value</code> still works.)
#
# The attributes you can define are:
#
# homedir :: Your home directory. This defaults to what your
# actual home directory is.
#
# maildir :: The directory you store your mail in. This defaults
# to the "Mail" directory in your home dir.
#
# logfile :: The path to your gurgitate-mail log file. If you
# set this to +nil+, gurgitate-mail won't log anything.
# The default value is ".gurgitate.log" in your home
# directory.
#
# The following parameters are more likely to be interesting to the
# system administrator than the everyday user.
#
# sendmail :: The full path of your "sendmail" program, or at least
# a program that provides functionality equivalent to
# sendmail.
#
# spoolfile :: The default location to store mail messages, for the
# messages that have been unaffected by your gurgitate
# rules. If an exception is raised by your rules, the
# message will be delivered to the spoolfile.
#
# spooldir :: The location where users' system mail boxes live.
#
# folderstyle :: The style of mailbox to create (and to expect,
# although gurgitate-mail automatically detects the
# type of existing mailboxes). See the separate
# documentation for folderstyle for more details.
class Gurgitate < Mailmessage
include Deliver
# Instead of the usual attributes, I went with a
# reader-is-writer type thing (as seen quite often in Perl and
# C++ code) so that in your .gurgitate-rules, you can say
#
# maildir "#{homedir}/Mail"
# sendmail "/usr/sbin/sendmail"
# spoolfile "Maildir"
# spooldir homedir
#
# This is because of an oddity in Ruby where, even if an
# accessor exists in the current object, if you say:
# name = value
# it'll always create a local variable. Not quite what you
# want when you're trying to set a config parameter. You have
# to say "self.name = value", which (I think) is ugly.
#
# In the interests of promoting harmony, of course, the previous
# syntax will continue to work.
def self.attr_configparam(*syms)
syms.each do |sym|
class_eval %{
def #{sym} *vals
if vals.length == 1
@#{sym} = vals[0]
elsif vals.length == 0
@#{sym}
else
raise ArgumentError,
"wrong number of arguments " +
"(\#{vals.length} for 0 or 1)"
end
end
# Don't break it for the nice people who use
# old-style accessors though. Breaking people's
# .gurgitate-rules is a bad idea.
attr_writer :#{sym}
}
end
end
# The directory you want to put mail folders into
attr_configparam :maildir
# The path to your log file
attr_configparam :logfile
# The full path of your "sendmail" program
attr_configparam :sendmail
# Your home directory
attr_configparam :homedir
# Your default mail spool
attr_configparam :spoolfile
# The directory where user mail spools live
attr_configparam :spooldir
# What kind of mailboxes you prefer
# attr_configparam :folderstyle
# What kind of mailboxes you prefer. Treat this like a
# configuration parameter. If no argument is given, then
# return the current default type.
#
# Depending on what you set this to, some other configuration
# parameters change. You can set this to the following things:
#
# <code>Maildir</code> :: Create Maildir mailboxes.
#
# This sets +spooldir+ to your home
# directory, +spoolfile+ to
# $HOME/Maildir and creates
# mail folders underneath that.
#
# <code>MH</code> :: Create MH mail boxes.
#
# This reads your <code>.mh_profile</code>
# file to find out where you've told MH to
# find its mail folders, and uses that value.
# If it can't find that in your .mh_profile,
# it will assume you want mailboxes in
# $HOME/Mail. It sets +spoolfile+ to
# "inbox" in your mail directory.
#
# <code>Mbox</code> :: Create +mbox+ mailboxes.
#
# This sets +spooldir+ to
# <code>/var/spool/mail</code> and
# +spoolfile+ to a file with your username
# in <code>/var/spool/mail</code>.
def folderstyle(*style)
if style.length == 0 then
@folderstyle
elsif style.length == 1 then
if style[0] == Maildir then
spooldir homedir
spoolfile File.join(spooldir,"Maildir")
maildir spoolfile
elsif style[0] == MH then
mh_profile_path = File.join(ENV["HOME"],".mh_profile")
if File.exists?(mh_profile_path) then
mh_profile = YAML.load(File.read(mh_profile_path))
maildir mh_profile["Path"]
else
maildir File.join(ENV["HOME"],"Mail")
end
spoolfile File.join(maildir,"inbox")
else
spooldir "/var/spool/mail"
spoolfile File.join(spooldir, @passwd.name)
end
@folderstyle = style[0]
else
raise ArgumentError, "wrong number of arguments "+
"(#{style.length} for 0 or 1)"
end
@folderstyle
end
# Set config params to defaults, read in mail message from
# +input+
# input::
# Either the text of the email message in RFC-822 format,
# or a filehandle where the email message can be read from
# recipient::
# The contents of the envelope recipient parameter
# sender::
# The envelope sender parameter
# spooldir::
# The location of the mail spools directory.
def initialize(input=nil,
recipient=nil,
sender=nil,
spooldir="/var/spool/mail",
&block)
@passwd = Etc.getpwuid
@homedir = @passwd.dir;
@maildir = File.join(@passwd.dir,"Mail")
@logfile = File.join(@passwd.dir,".gurgitate.log")
@sendmail = "/usr/lib/sendmail"
@spooldir = spooldir
@spoolfile = File.join(@spooldir,@passwd.name )
@folderstyle = MBox
@rules = []
input_text = ""
input.each_line do |l| input_text << l end
super(input_text, recipient, sender)
instance_eval(&block) if block_given?
end
def add_rules(filename, options = {}) #:nodoc:
if not Hash === options
raise ArgumentError.new("Expected hash of options")
end
if filename == :default
filename=homedir+"/.gurgitate-rules"
end
if not FileTest.exist?(filename)
filename = filename + '.rb'
end
if not FileTest.exist?(filename)
if options.has_key?(:user)
log("#{filename} does not exist.")
end
return false
end
if FileTest.file?(filename) and
( ( not options.has_key? :system and
FileTest.owned?(filename) ) or
( options.has_key? :system and
options[:system] == true and
File.stat(filename).uid == 0 ) ) and
FileTest.readable?(filename)
@rules << filename
else
log("#{filename} has bad permissions or ownership, not using rules")
return false
end
end
# Deletes (discards) the current message.
def delete
# Well, nothing here, really.
end
# This is kind of neat. You can get a header by calling its
# name as a method. For example, if you want the header
# "X-Face", then you call x_face and that gets it for you. It
# raises NameError if that header isn't found.
#
# meth::
# The method that the caller tried to call which isn't
# handled any other way.
def method_missing(meth)
headername=meth.to_s.split(/_/).map {|x| x.capitalize}.join("-")
if headers[headername] then
return headers[headername]
else
raise NameError,"undefined local variable or method, or header not found `#{meth}' for #{self}:#{self.class}"
end
end
# Forwards the message to +address+.
#
# address::
# A valid email address to forward the message to.
def forward(address)
self.log "Forwarding to "+address
IO.popen(@sendmail+" "+address,"w") do |f|
f.print(self.to_s)
end
end
# Writes +message+ to the log file.
def log(message)
if @logfile then
File.open(@logfile,"a") do |f|
f.flock(File::LOCK_EX)
f.print(Time.new.to_s+" "+message+"\n")
f.flock(File::LOCK_UN)
end
end
end
# Pipes the message through +program+. If +program+
# fails, puts the message into +spoolfile+
def pipe(program)
self.log "Piping through "+program
IO.popen(program,"w") do |f|
f.print(self.to_s)
end
return $?>>8
end
# Pipes the message through +program+, and returns another
# +Gurgitate+ object containing the output of the filter
#
# Use it like this:
#
# filter "bogofilter -p" do
# if x_bogosity =~ /Spam/ then
# log "Found spam"
# delete
# return
# end
# end
#
def filter(program,&block)
self.log "Filtering with "+program
IO.popen("-","w+") do |filter|
unless filter then
begin
exec(program)
rescue
exit! # should not get here anyway
end
else
if fork
filter.close_write
g=Gurgitate.new(filter)
g.instance_eval(&block) if block_given?
return g
else
begin
filter.close_read
filter.print to_s
filter.close
rescue
nil
ensure
exit!
end
end
end
end
end
def process(&block) #:nodoc:
begin
if @rules.size > 0 or block
@rules.each do |configfilespec|
begin
eval File.new(configfilespec).read, nil,
configfilespec
rescue ScriptError
log "Couldn't load #{configfilespec}: "+$!
save(spoolfile)
rescue Exception
log "Error while executing #{configfilespec}: #{$!}"
$@.each { |tr| log "Backtrace: #{tr}" }
folderstyle MBox
save(spoolfile)
end
end
if block
instance_eval(&block)
end
log "Mail not covered by rules, saving to default spool"
save(spoolfile)
else
save(spoolfile)
end
rescue Exception
log "Error while executing rules: #{$!}"
$@.each { |tr| log "Backtrace: #{tr}" }
log "Attempting to save to spoolfile after error"
folderstyle MBox
save(spoolfile)
end
end
end
end
| true |
91e9fab8b0e2c65919c76d9e8f264384b4aa4218 | Ruby | famished-tiger/Rley | /lib/rley/sppf/alternative_node.rb | UTF-8 | 1,369 | 2.640625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
require_relative 'composite_node'
module Rley # This module is used as a namespace
module SPPF # This module is used as a namespace
# A node in a parse forest that is a child
# of a parent node with :or refinement
class AlternativeNode < CompositeNode
# @return [String] GFG vertex label
attr_reader(:label)
# @return [Syntax::NonTerminal] Link to lhs symbol
attr_reader(:symbol)
# @param aVertex [GFG::ItemVertex]
# A GFG vertex that corresponds to a dotted item
# with the dot at the end) for the alternative under consideration.
# @param aRange [Lexical::TokenRange]
# A range of token indices corresponding to this node.
def initialize(aVertex, aRange)
super(aRange)
@label = aVertex.label
@symbol = aVertex.dotted_item.lhs
end
# Emit a (formatted) string representation of the node.
# Mainly used for diagnosis/debugging purposes.
# @return [String]
def to_string(indentation)
"Alt(#{label})#{range.to_string(indentation)}"
end
# Part of the 'visitee' role in Visitor design pattern.
# @param aVisitor[ParseTreeVisitor] the visitor
def accept(aVisitor)
aVisitor.visit_alternative(self)
end
end # class
end # module
end # module
# End of file
| true |
5ea45f305f03842299e787ec91673c2ca103b4c0 | Ruby | snorkpete/everycent | /spec/models/shared_examples/cumulative_allocation_spec.rb | UTF-8 | 2,401 | 2.84375 | 3 | [
"MIT"
] | permissive |
shared_examples_for "CumulativeAllocation" do
describe "#CumulativeAllocation" do
before do
@budget = create(:budget, start_date: Date.new(2019, 12, 25))
@allocation = create(:allocation, budget: @budget, is_cumulative: true, amount: 6200)
end
it "has a flag that determines if allocation is cumulative or not" do
@allocation = Allocation.new
expect(@allocation.is_cumulative).to eq false
allocation = Allocation.new is_cumulative: true
expect(allocation.is_cumulative).to eq true
end
it "divides the the amount proportionally among the days of the month, even for the first week" do
expect(@allocation.amount_for_week(1)).to eq 600
end
it "divides the the amount proportionally among the days of the month" do
expect(@allocation.amount_for_week(2)).to eq 1400
end
it "handles fractions by rounding down" do
allocation = create(:allocation, budget: @budget, is_cumulative: true, amount: 1000)
expect(allocation.amount_for_week(2)).to eq 225
end
describe "#spent" do
before do
@week_one_transaction_1 = create(:transaction, allocation: @allocation, transaction_date: Date.new(2019, 12, 25), withdrawal_amount: 100, deposit_amount: 0)
@week_one_transaction_2 = create(:transaction, allocation: @allocation, transaction_date: Date.new(2019, 12, 26), withdrawal_amount: 150, deposit_amount: 0)
@week_one_transaction_3 = create(:transaction, allocation: @allocation, transaction_date: Date.new(2019, 12, 27), withdrawal_amount: 200, deposit_amount: 0)
@week_two_transaction_1 = create(:transaction, allocation: @allocation, transaction_date: Date.new(2019, 12, 28), withdrawal_amount: 300, deposit_amount: 0)
@week_two_transaction_2 = create(:transaction, allocation: @allocation, transaction_date: Date.new(2019, 12, 29), withdrawal_amount: 400, deposit_amount: 0)
end
it "sums transactions for week one" do
expect(@allocation.spent_for_week(1)).to eq(450)
end
it "sums transactions for week two" do
expect(@allocation.spent_for_week(2)).to eq(700)
end
it "sums transactions for week three" do
expect(@allocation.spent_for_week(3)).to eq(0)
end
it "sums transactions for week four" do
expect(@allocation.spent_for_week(4)).to eq(0)
end
end
end
end
| true |
c9754b47451f084b89e8042500677d6f26b9f4f1 | Ruby | Adedee/ruby | /Exercise13/lib/FactorialClass.rb | UTF-8 | 240 | 3.546875 | 4 | [] | no_license | class Factorial
def initialize(text)
@num = text
end
def to_s
fnum = Float(@num)
j = fnum
(2..fnum).step(1).reverse_each do |i|
j = j*(i - 1)
end
puts "#{fnum.to_i}! is #{j.to_i}"
end
end | true |
636a9a82e9ad13e4258f36d98f6162ac348bd3de | Ruby | DovileSand/Battle | /spec/player_spec.rb | UTF-8 | 521 | 2.703125 | 3 | [] | no_license | require 'player'
describe Player do
subject(:duck) {Player.new('Duck')}
subject(:eagle) {Player.new('Eagle')}
context '#player_name' do
it 'returns player name' do
expect(duck.player_name).to eq('Duck')
end
end
context '#attack' do
it 'reduces player hitpoints' do
expect(eagle).to receive(:receive_damage)
duck.attack(eagle)
end
end
context '#receive_damage' do
it 'damages player' do
expect{duck.receive_damage}.to change{duck.points}.by(-1)
end
end
end
| true |
dbf3943bd8c96a82da87ec88e739618a4a2f7f94 | Ruby | zeroDivisible/advent-of-code | /2018/ruby/day_02/ruby/script.rb | UTF-8 | 681 | 3.296875 | 3 | [] | no_license | require 'set'
input = File.readlines('input.txt')
# step 1
twos = 0
threes = 0
input.each do |line|
counts = line.each_char.to_a.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
twos += 1 if counts.values.include?(2)
threes += 1 if counts.values.include?(3)
end
puts twos * threes
# step 2
lines = []
input.each do |line|
lines << line.each_char.to_a
end
(0...(lines.length)).each do |a|
(a+1...(lines.length)).each do |b|
diff = {}
(0...lines[a].length).each do |c|
unless lines[a][c] == lines[b][c]
diff[c] = lines[a][c]
end
end
if diff.length == 1
lines[a].slice!(diff.keys.first)
puts lines[a].join
end
end
end
| true |
8a7544e0b2480dd66d368c9b99f4189d1f0ab4ec | Ruby | invalidusrname/adventofcode | /2018/ruby/lib/advent_06.rb | UTF-8 | 3,481 | 3.640625 | 4 | [] | no_license | class Coordinate
attr_reader :x, :y, :count
attr_writer :count
def initialize(x, y)
@x = x
@y = y
@count = 1
end
def to_s
name
end
def name
"(#{x},#{y})"
end
end
class ChronalCoordinates
attr_reader :coordinates
def initialize(coordinates)
@coordinates = coordinates
@grid = {}
@counts = Hash.new(0)
fill_grid
fill_closest
fill_counts
end
def min_x
@min_x ||= @coordinates.collect(&:x).min
end
def max_x
@max_x ||= @coordinates.collect(&:x).max
end
def min_y
@min_y ||= @coordinates.collect(&:y).min
end
def max_y
@max_y ||= @coordinates.collect(&:y).max
end
def infinite_coordinate?(coordinate)
x = coordinate.x
y = coordinate.y
((min_x == x) || (max_x == x) || (min_y == y) || (max_y == y))
end
def infinite_locations
locations = []
(min_x..max_x).each do |x|
(min_y..max_y).each do |y|
point = Coordinate.new(x, y)
closest = @grid[point.to_s]
if closest.is_a?(Coordinate)
locations << closest if infinite_coordinate?(point)
end
end
end
locations.uniq
end
def largest_area
infinite = infinite_locations
allowed = @counts.reject do |c, _total|
infinite.any? { |i| i.x == c.x && i.y == c.y }
end
@counts.collect do |coordinate, total|
total if allowed.include?(coordinate)
end.flatten.compact.max
end
def get_coordinate(point)
@coordinates.detect { |c| c.x == point.x && c.y == point.y }
end
def manhattan_distance(p, q)
(p.x - q.x).abs + (p.y - q.y).abs
end
def fill_grid
(min_x..max_x).each do |x|
(min_y..max_y).each do |y|
point = Coordinate.new(x, y)
@grid[point.to_s] = get_coordinate(point) || '.'
end
end
end
def fill_closest
(min_x..max_x).each do |x|
(min_y..max_y).each do |y|
point = Coordinate.new(x, y)
next if @grid[point.to_s].is_a?(Coordinate)
coordinate = closest_coordinate(point)
if coordinate
@grid[point.to_s] = coordinate
# puts "NEAREST [#{point}] => #{coordinate.name}"
end
end
end
end
def fill_counts
@grid.each do |_key, value|
@counts[value] += 1 if value.is_a?(Coordinate)
end
end
def closest_coordinate(point)
nearest_distance = nil
nearest = nil
# puts "SCANNING: #{point}"
@coordinates.each do |c|
distance = manhattan_distance(point, c)
# puts "CHECKING: #{c} distance #{distance}"
if nearest_distance.nil?
nearest_distance = distance
nearest = c
elsif distance < nearest_distance
nearest_distance = distance
nearest = c
elsif distance == nearest_distance
nearest = nil
end
end
# puts "NEAREST -> #{nearest}"
nearest
end
def print_grid
puts "(#{min_x},#{min_y}) <> (#{max_x},#{max_y})"
(min_x..max_x).each do |x|
(min_y..max_y).each do |y|
point = Coordinate.new(x, y)
value = @grid[point.to_s].to_s
print "#{value} "
end
puts
end
end
def largest_region
count = 0
(min_x..max_x).each do |x|
(min_y..max_y).each do |y|
point = Coordinate.new(x, y)
total = @coordinates.inject(0) do |sum, c|
sum + manhattan_distance(point, c)
end
count += 1 unless total >= 10_000
end
end
count
end
end
| true |
f8690bd0242e170a55d99d8c9374ef3635337b33 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/b7609a3c4e6c4931aae1f70d53ff7ead.rb | UTF-8 | 583 | 3.609375 | 4 | [] | no_license | class Bob
SAID_NOTHING_REPLY = 'Fine. Be that way!'
YELLING_REPLY = 'Woah, chill out!'
QUESTION_REPLY = 'Sure.'
DEFAULT_REPLY = 'Whatever.'
QUESTION_MARK = '?'
def hey (message)
if said_nothing? message
SAID_NOTHING_REPLY
elsif yelling? message
YELLING_REPLY
elsif question? message
QUESTION_REPLY
else
DEFAULT_REPLY
end
end
def yelling?(message)
message.upcase == message
end
def question?(message)
message.end_with? QUESTION_MARK
end
def said_nothing?(message)
message.to_s.strip.empty?
end
end
| true |
ad447417512cfcc0386aa82e2ca3246310ab4e00 | Ruby | kevinkim1030/ruby-enumerables-cartoon-collections-lab-nyc-web-102819 | /cartoon_collections.rb | UTF-8 | 459 | 3.421875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves(names)
i = 0
while i < names.length
puts "#{i + 1}. #{names[i]}"
i +=1
end
end
def summon_captain_planet(array)
new_array = []
array.collect do |i|
new_array << "#{i.capitalize}!"
end
new_array
end
def long_planeteer_calls(array)
array.any? do |i|
i.length > 4
end
end
def find_the_cheese(array)
array.find do |cheese|
cheese == "cheddar" || cheese == "gouda" || cheese == "camembert"
end
end
| true |
892940e9cf68062d0e301fb2d05bbab12711898d | Ruby | tbierwirth/battleship | /test/board_test.rb | UTF-8 | 5,875 | 3.40625 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require 'pry'
require './lib/board'
require './lib/cell'
require './lib/ship'
class BoardTest < MiniTest::Test
def setup
@board = Board.new
@cruiser = Ship.new("Cruiser", 3)
@submarine = Ship.new("Submarine", 2)
end
def test_board_exists
assert_instance_of Board, @board
end
def test_board_has_cells
# check all values are instances of cells
# check keys (A1) -
# check that .cells returns a Hash -
assert_instance_of Hash, @board.cells
end
def test_first_element_of_hash
assert_instance_of Cell, @board.cells["A1"]
end
def test_valid_cell_coordinates
assert @board.valid_coordinate?(["A1"])
assert @board.valid_coordinate?(["D4"])
refute @board.valid_coordinate?(["A5"])
refute @board.valid_coordinate?(["E1"])
refute @board.valid_coordinate?(["A22"])
end
def test_ship_length_to_valid_placements
refute @board.valid_placement?(@cruiser, ["A1", "A2"])
refute @board.valid_placement?(@submarine, ["A2", "A3", "A4"])
end
def test_letters_same
coordinates = ["A1", "A2", "A3"]
assert @board.letters_same?(coordinates)
end
def test_letters_are_different
coordinates = ["B2", "A3", "A4"]
refute @board.letters_same?(coordinates)
end
def test_numbers_same
coordinates = ["A1", "B1", "C1"]
assert @board.numbers_same?(coordinates)
end
def test_numbers_are_different
coordinates = ["A2", "B1", "C1"]
refute @board.numbers_same?(coordinates)
end
def test_letters_consecutive
coordinates = ["A1", "B1", "C1"]
assert @board.letters_consecutive?(coordinates)
end
def test_numbers_consecutive
coordinates = ["A1", "A2", "A3"]
assert @board.numbers_consecutive?(coordinates)
end
def test_ship_valid_placement_consecutive
refute @board.valid_placement?(@cruiser, ["A1", "A2", "A4"])
refute @board.valid_placement?(@submarine, ["A1", "C1"])
refute @board.valid_placement?(@cruiser, ["A3", "A2", "A1"])
refute @board.valid_placement?(@submarine, ["C1", "B1"])
end
def test_ship_valid_placement_diagonal
refute @board.valid_placement?(@cruiser, ["A1", "B2", "C3"])
refute @board.valid_placement?(@submarine, ["C2", "D3"])
end
def test_ship_valid_placement
assert true, @board.valid_placement?(@cruiser, ["B1", "C1", "D1"])
assert true, @board.valid_placement?(@submarine, ["A1", "A2"])
refute @board.valid_placement?(@submarine, ["E1", "E2"])
end
def test_place_ship
@board.place(@cruiser, ["A1", "A2", "A3"])
cell_1 = @board.cells["A1"]
cell_2 = @board.cells["A2"]
cell_3 = @board.cells["A3"]
assert_equal @cruiser, cell_1.ship
assert_equal @cruiser, cell_2.ship
assert_equal @cruiser, cell_3.ship
assert_equal cell_3.ship, cell_2.ship
end
def test_for_overlapping_ships
@board.place(@cruiser, ["A1", "A2", "A3"])
refute @board.valid_placement?(@submarine, ["A1", "B1"])
end
def test_board_renders
expected = " 1 2 3 4 \n" +
"A . . . . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board
end
def test_board_renders_ship
@board.place(@cruiser, ["A1", "A2", "A3"])
expected = " 1 2 3 4 \n" +
"A S S S . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
def test_board_renders_ship
@board.place(@cruiser, ["A1", "A2", "A3"])
expected = " 1 2 3 4 \n" +
"A S S S . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
def test_board_renders_ship_and_fired_upon
@board.place(@cruiser, ["A1", "A2", "A3"])
@board.cells["A1"].fire_upon
expected = " 1 2 3 4 \n" +
"A H S S . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
def test_board_renders_ship_and_fired_upon
@board.place(@cruiser, ["A1", "A2", "A3"])
@board.cells["A1"].fire_upon
expected = " 1 2 3 4 \n" +
"A H S S . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
def test_board_changes_with_ships
@board.place(@cruiser, ["A1", "A2", "A3"])
expected = " 1 2 3 4 \n" +
"A S S S . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
def test_board_renders_missed_shots
@board.place(@cruiser, ["A1", "A2", "A3"])
@board.cells["B1"].fire_upon
expected = " 1 2 3 4 \n" +
"A S S S . \n" +
"B M . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
def test_board_renders_sunk_ship
@board.place(@cruiser, ["A1", "A2", "A3"])
@board.cells["A1"].fire_upon
@board.cells["A2"].fire_upon
@board.cells["A3"].fire_upon
expected = " 1 2 3 4 \n" +
"A X X X . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
def test_board_renders_hit
@board.place(@cruiser, ["A1", "A2", "A3"])
@board.cells["A1"].fire_upon
@board.cells["A2"].fire_upon
expected = " 1 2 3 4 \n" +
"A H H S . \n" +
"B . . . . \n" +
"C . . . . \n" +
"D . . . . \n"
assert_equal expected, @board.render_board(true)
end
end
| true |
520c3d128885506591ea688f1885fda5e7a492c7 | Ruby | onk/brahman | /lib/brahman/mergeinfo.rb | UTF-8 | 1,225 | 2.984375 | 3 | [
"MIT"
] | permissive | module Brahman
class Mergeinfo
# mergeinfo string to list
#
# あいまいな入力も受け付け
# * m-n を展開し
# * r を取り除いて
# 配列にして返す
def self.str_to_list(mergeinfo)
mergeinfo.split(',').map{|e|
if e =~ /-/
min,max = e.delete("r").split("-")
(min..max).to_a
else
e
end
}.flatten.map{|rev|
rev.delete("r")
}.sort
end
def self.mergeinfo(parent_path)
`svn mergeinfo --show-revs eligible #{parent_path}`.split("\n").map{|rev|
rev = rev.chomp
rev.delete("r")
}.sort
end
def self.mergeinfo_str_from_modified_diff(str, target_path)
merged_lines = str.split("Modified: svn:mergeinfo\n").last
merged_line = merged_lines.lines.detect {|l|
l =~ /#{target_path}:/
}.chomp
merged_line.split(":").last
end
# 数字が連続する場合にその箇所をハイフンにする
def self.hyphenize(nums)
nums.inject([]) { |arr, n| arr[n-1] = n; arr }
.chunk { |n| !n.nil? || nil }
.map { |_, gr| gr.size > 1 ? "#{gr.first}-#{gr.last}" : "#{gr.first}" }
.join(',')
end
end
end
| true |
ce0f684d0123fcb0f9c5c16b65380798c2afee73 | Ruby | pofystyy/codewars | /7 kyu/square_every_digit.rb | UTF-8 | 390 | 4.375 | 4 | [] | no_license | # https://www.codewars.com/kata/546e2562b03326a88e000020
# Details:
# Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
# Note: The function accepts an integer and returns an integer
def square_digits num
num.digits.reverse.map { |i| i ** 2 }.join.to_i
end
| true |
942dcca3a75750a31fa494e5a51c6256bebb303f | Ruby | mpatel5/Cards | /cards.rb | UTF-8 | 794 | 4.125 | 4 | [] | no_license | class Card
attr_accessor :rank, :suit
def initialize(rank, suit)
self.rank = rank
self.suit = suit
end
def output_card
puts "#{self.rank} of #{self.suit}"
end
end
class Deck
def initialize
@cards = []
@ranks = [1,2,3,4,5,6,7,8,9,10,:jack,:queen,:king,:ace]
@suits = [:diamonds,:hearts,:clubs,:spades]
@ranks.each do |rank|
@suits.each do |suit|
@cards << Card.new(rank, suit)
end
end
end
def shuffle
@cards.shuffle!
end
def output
@cards.each do |card|
card.output_card
end
end
def deal
@cards.shift.output_card
end
end
deck=Deck.new
deck.shuffle
puts("The shuffled deck is:")
deck.output
puts("First card is:")
deck.deal
| true |
6b3189d65f2884c1bb14b0b863992828e73a3af9 | Ruby | GAnjali/ruby-practice | /6.arrays/array_operations.rb | UTF-8 | 573 | 3.9375 | 4 | [] | no_license | array = [1, 'Bob', 4.33, 'another string']
puts array.first
puts array.first(2)
puts array.last
puts array[3]
array.push(3)
puts array
array.pop
puts array
array.concat([2, 3])
array << 3
puts array
array = Array.new(4)
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array.map{|num| num**2}
array
array.collect{|num| num**2}
array
array.delete_at(2)
array
array.delete(3)
array
array.uniq
array.select {|num| num>4}
array.include?(3)
array.each_index { |i| puts "This is index #{i}" }
array.each_with_index { |val, idx| puts "#{idx+1}. #{val}" }
puts array.sort
puts array | true |
92d9aec820b4cfcfa65cad7d8c348a20f3e04190 | Ruby | marek2901/subject_manager_demo_app | /app/models/participant.rb | UTF-8 | 548 | 2.609375 | 3 | [] | no_license | class Participant
include ActiveModel::Model
attr_accessor :subject_id, :participant_id
validates_presence_of :subject_id, :participant_id
def save
if valid?
begin
Subject.find(subject_id).students << Student.find(participant_id)
rescue StandardError
false
end
true
else
false
end
end
class << self
def unassign(subject_id, participant_id)
Subject.find(subject_id).students.delete(Student.find(participant_id))
rescue StandardError
false
end
end
end
| true |
7c4b7e77472a9b12164e1f00685eee9518c95615 | Ruby | spinute/rumale | /lib/rumale/nearest_neighbors/k_neighbors_classifier.rb | UTF-8 | 6,666 | 3.25 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | # frozen_string_literal: true
require 'rumale/base/base_estimator'
require 'rumale/base/classifier'
module Rumale
# This module consists of the classes that implement estimators based on nearest neighbors rule.
module NearestNeighbors
# KNeighborsClassifier is a class that implements the classifier with the k-nearest neighbors rule.
# The current implementation uses the Euclidean distance for finding the neighbors.
#
# @example
# estimator =
# Rumale::NearestNeighbors::KNeighborsClassifier.new(n_neighbors: 5)
# estimator.fit(training_samples, traininig_labels)
# results = estimator.predict(testing_samples)
#
class KNeighborsClassifier
include Base::BaseEstimator
include Base::Classifier
# Return the prototypes for the nearest neighbor classifier.
# If the metric is 'precomputed', that returns nil.
# If the algorithm is 'vptree', that returns Rumale::NearestNeighbors::VPTree.
# @return [Numo::DFloat] (shape: [n_training_samples, n_features])
attr_reader :prototypes
# Return the labels of the prototypes
# @return [Numo::Int32] (size: n_training_samples)
attr_reader :labels
# Return the class labels.
# @return [Numo::Int32] (size: n_classes)
attr_reader :classes
# Create a new classifier with the nearest neighbor rule.
#
# @param n_neighbors [Integer] The number of neighbors.
# @param algorithm [String] The algorithm is used for finding the nearest neighbors.
# If algorithm is 'brute', brute-force search will be used.
# If algorithm is 'vptree', vantage point tree will be used.
# This parameter is ignored when metric parameter is 'precomputed'.
# @param metric [String] The metric to calculate the distances.
# If metric is 'euclidean', Euclidean distance is calculated for distance between points.
# If metric is 'precomputed', the fit and predict methods expect to be given a distance matrix.
def initialize(n_neighbors: 5, algorithm: 'brute', metric: 'euclidean')
check_params_numeric(n_neighbors: n_neighbors)
check_params_positive(n_neighbors: n_neighbors)
check_params_string(algorith: algorithm, metric: metric)
@params = {}
@params[:n_neighbors] = n_neighbors
@params[:algorithm] = algorithm == 'vptree' ? 'vptree' : 'brute'
@params[:metric] = metric == 'precomputed' ? 'precomputed' : 'euclidean'
@prototypes = nil
@labels = nil
@classes = nil
end
# Fit the model with given training data.
#
# @param x [Numo::DFloat] (shape: [n_training_samples, n_features]) The training data to be used for fitting the model.
# If the metric is 'precomputed', x must be a square distance matrix (shape: [n_training_samples, n_training_samples]).
# @param y [Numo::Int32] (shape: [n_training_samples]) The labels to be used for fitting the model.
# @return [KNeighborsClassifier] The learned classifier itself.
def fit(x, y)
x = check_convert_sample_array(x)
y = check_convert_label_array(y)
check_sample_label_size(x, y)
raise ArgumentError, 'Expect the input distance matrix to be square.' if @params[:metric] == 'precomputed' && x.shape[0] != x.shape[1]
@prototypes = if @params[:metric] == 'euclidean'
if @params[:algorithm] == 'vptree'
VPTree.new(x)
else
x.dup
end
end
@labels = Numo::Int32.asarray(y.to_a)
@classes = Numo::Int32.asarray(y.to_a.uniq.sort)
self
end
# Calculate confidence scores for samples.
#
# @param x [Numo::DFloat] (shape: [n_testing_samples, n_features]) The samples to compute the scores.
# If the metric is 'precomputed', x must be a square distance matrix (shape: [n_testing_samples, n_training_samples]).
# @return [Numo::DFloat] (shape: [n_testing_samples, n_classes]) Confidence scores per sample for each class.
def decision_function(x)
x = check_convert_sample_array(x)
if @params[:metric] == 'precomputed' && x.shape[1] != @labels.size
raise ArgumentError, 'Expect the size input matrix to be n_testing_samples-by-n_training_samples.'
end
n_prototypes = @labels.size
n_neighbors = [@params[:n_neighbors], n_prototypes].min
n_samples = x.shape[0]
n_classes = @classes.size
scores = Numo::DFloat.zeros(n_samples, n_classes)
if @params[:metric] == 'euclidean' && @params[:algorithm] == 'vptree'
neighbor_ids, = @prototypes.query(x, n_neighbors)
n_samples.times do |m|
neighbor_ids[m, true].each { |n| scores[m, @classes.to_a.index(@labels[n])] += 1.0 }
end
else
distance_matrix = @params[:metric] == 'precomputed' ? x : PairwiseMetric.euclidean_distance(x, @prototypes)
n_samples.times do |m|
neighbor_ids = distance_matrix[m, true].to_a.each_with_index.sort.map(&:last)[0...n_neighbors]
neighbor_ids.each { |n| scores[m, @classes.to_a.index(@labels[n])] += 1.0 }
end
end
scores
end
# Predict class labels for samples.
#
# @param x [Numo::DFloat] (shape: [n_testing_samples, n_features]) The samples to predict the labels.
# If the metric is 'precomputed', x must be a square distance matrix (shape: [n_testing_samples, n_training_samples]).
# @return [Numo::Int32] (shape: [n_testing_samples]) Predicted class label per sample.
def predict(x)
x = check_convert_sample_array(x)
if @params[:metric] == 'precomputed' && x.shape[1] != @labels.size
raise ArgumentError, 'Expect the size input matrix to be n_samples-by-n_training_samples.'
end
decision_values = decision_function(x)
n_samples = x.shape[0]
Numo::Int32.asarray(Array.new(n_samples) { |n| @classes[decision_values[n, true].max_index] })
end
# Dump marshal data.
# @return [Hash] The marshal data about KNeighborsClassifier.
def marshal_dump
{ params: @params,
prototypes: @prototypes,
labels: @labels,
classes: @classes }
end
# Load marshal data.
# @return [nil]
def marshal_load(obj)
@params = obj[:params]
@prototypes = obj[:prototypes]
@labels = obj[:labels]
@classes = obj[:classes]
nil
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.