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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ace0198b65746a328ddd71c876a2a586eb8860a4 | Ruby | svkmax/hour_refactoring | /controllers/promo_messages_controller.rb | UTF-8 | 3,356 | 2.578125 | 3 | [] | no_license | # frozen_string_literal: true
# in general luck of guards for each method in controller
# check required params for method and generate user message.
# params without daddy object(promo_message)
# rails way is require promo_message object in params
# so it will be promo_message[:date_from], promo_message[:date_to]
# promo_message[:body] etc.
# But if this feature works, so we cant change interface without client side
class PromoMessagesController < ApplicationController
# do not know what instance variable 'provider' for,
# looks like it is redundant
def new
promo_user_params
@message = PromoMessage.new
# if here is complex logic, I think it should be separate classes,
# one with sql's other with params checker guard which describes whole controller methods.
# This is a simples way with fat model, fat models can be fixed with
# service objects or by separating models from business logic or
# by presenter pattern or several more ways.
# if we stay with extra method we hiding params which required for method
users(date_from: params[:date_from], date_to: params[:date_to]).page(params[:page])
end
# I prefer dry/transaction for complex logic of saving
# but for now, or in simplest way I think ith should be moved at least
# in model, or create service object, but again, service object should be generalized
# to avoid situation with tons different service objects where each have own rules
# and own interface to use
def create
@message = PromoMessage.new(promo_message_params)
# looks like paging here is redundant but, not sure maybe some
# client can use this variable, but it is local, magic monkey patching
users = users.page(params[:page])
# what if fail?
if @message.save && send_message(users.map(&:phone))
redirect_to promo_messages_path, notice: 'Messages Sent Successfully!'
else
render :new
end
end
# due to REST we can not use extra words in endpoint naming
# so download_csv goes to GET csv
# assume that it is rails and all lib folder is autoloaded
def csv
# if we stay with extra method we hiding params which required for method
promo_user_params
users = users
send_data Csv.contacts(users), filename: "promotion-users-#{Time.zone.today}.csv"
end
private
# also should be moved in place where business logic is
# as it is simplified example I assume that in real life there is connection between
# promo_message and user, so maybe it can go there(in PromoMessage class)
def send_message(recipients)
# not necessary optimization, just for fun
# did not use it in real life
promo_send_job = PromoMessagesSendJob.method(:perform_later)
# if ruby 2.7 can use numbered params
recipients.each { promo_send_job.call(@1)}
end
# i think such methods should not be in controller
# but just for minimum dry for now
# if we have presenter or other layer of abstraction such methods goes there
def users
User.published_between_users(date_from: params[:date_from],
date_to: params[:date_to],
published_ads_counts: 1)
end
def promo_message_params
params.permit(:body, :date_from, :date_to)
end
def promo_user_params
params.require(:date_from, :date_to)
end
end
| true |
a1ce32340de2058f8dde2307a15a5aa8599b0360 | Ruby | mwagner19446/wdi_work | /w01/d04/Jennifer_Gapay/file_io.rb | UTF-8 | 705 | 3.203125 | 3 | [] | no_license | # File.open("README.md", "r") do |f|
# puts "Hello #{f.gets}!"
# end
f = File.new("README.md", "r")
puts "Hello #{f.read}!"
f.close
# f = File.new("README.md", "r")
# puts "Hello #{f.gets.chomp}!"
# puts "Hello #{f.gets.chomp}!"
# puts "Hello #{f.gets.chomp}!"
# f.close
# f = File.new("README.md", "r")
# puts "Hello #{f.gets.chomp}!"
# f.seek 27
# puts "Hello #{f.gets.chomp}!"
# f.close
# f = File.new("README.md", "r")
# f.each_line do |line|
# puts "Hello #{line.chomp}!"
# end
# f.close
## --- OPENING BELOW IN APPEND MODE -----
#(NOT WORKING - FIND OUT WHY)
# f = File.new("README.md", "a+")
# f.puts "TESTING"
# f = File.new("README.md", "r+")
# f.puts "PJ, Jeff and Yannick"
# f.close | true |
54747dee5c05d61e263d86e055d715461ddbb72d | Ruby | lkriffell/battleship | /test/ship_test.rb | UTF-8 | 712 | 3.1875 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/ship'
class ShipTest < Minitest::Test
def test_ship_exists
ship = Ship.new("Cruiser", 3)#The 3 refers to length
assert_instance_of Ship, ship
end
def test_ship_has_health
ship = Ship.new("Cruiser", 3)
assert_equal 3, ship.health
end
def test_ship_can_have_different_attributes
ship = Ship.new("Submarine", 2)
assert_equal 2, ship.health
assert_equal "Submarine", ship.name
end
def test_ship_can_be_hit
ship = Ship.new("Cruiser", 3)
ship.hit
assert_equal 2, ship.health
end
def test_ship_can_sink
ship = Ship.new("Submarine", 0)
assert_equal true, ship.sunk?
end
end
| true |
47441cf75b6089f50fdcbba1badfbb8ed61eae39 | Ruby | hasyung/Hrms | /app/models/night_record.rb | UTF-8 | 322 | 2.75 | 3 | [] | no_license | class NightRecord < ActiveRecord::Base
def is_invalid
(self.shifts_type == "两班倒" && self.night_number > 16) || (self.shifts_type == "三班倒" && self.night_number > 11) || (self.shifts_type == "四班倒" && self.night_number > 8)
end
def calc_amount
self.night_number * self.subsidy.to_f
end
end
| true |
7d8e6fe08063f08187b498ea7e50e9948d85b707 | Ruby | aaanu/exercism_ruby | /difference-of-squares/difference_of_squares.rb | UTF-8 | 640 | 3.96875 | 4 | [] | no_license | =begin
Write your code for the 'Difference Of Squares' exercise in this file. Make the tests in
`difference_of_squares_test.rb` pass.
To get started with TDD, see the `README.md` file in your
`ruby/difference-of-squares` directory.
=end
class Squares
def initialize(num)
@num = num
end
def square_of_sum # (1 + 2 + 3 + .. N)^2
@square_of_sum = ((1..@num).sum)**2
end
def sum_of_squares # 1^2 + 2^2 + ... N^2
@sum_of_squares = (1..@num).map {|num| num**2}.sum
end
def difference # square of the sum minus sum of the squares
self.square_of_sum - self.sum_of_squares
end
end
| true |
714a691359685c67a4c27cf23a6ea421d2574365 | Ruby | taka12natu/sdgs | /lib/translation.rb | UTF-8 | 684 | 2.8125 | 3 | [] | no_license | require 'net/http'
require 'uri'
require 'json'
module Translation
class << self
def translate_to_japanese(context)
url = URI.parse('https://www.googleapis.com/language/translate/v2')
params = {
q: context,
target: "ja", # 翻訳したい言語
source: "en", # 翻訳する言語の種類
key: ENV['GOOGLE_API_KEY']
}
url.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(url)
json = res.body
# レスポンスのjsonの言語の翻訳結果の部分のパラメータをパースする
"#{JSON.parse(json)["data"]["translations"].first["translatedText"]}"
end
end
end | true |
c74d1fd721d58d50298289150bd59c0b54a5dd40 | Ruby | Shender012/week2 | /child.rb | UTF-8 | 84 | 3.40625 | 3 | [] | no_license | print "Enter child's age "
age = gets.chomp.to_i
puts "Are we there yet? " * age | true |
e00999b5e07069cad8047dbf9daf50ba47d757e4 | Ruby | funmia/student-directory | /directory.rb | UTF-8 | 3,862 | 4.03125 | 4 | [] | no_license | require 'csv'
COHORT_LIST =[:january,:february,:march,:april,:may,:june,:july,:august,:september,:october,:november,:december]
@students = [] #an empty array accessible to all methods
def print_menu
# print the menu and ask the user what to do
puts "1. Input the students"
puts "2. Show the students"
puts "3. Save the list to a file"
puts "4. Load the list from students.csv"
puts "9. Exit" # 9 because we'll be adding more items
end
def interactive_menu
loop do
# print the menu of options
print_menu
# read input and save to a variable
selection = STDIN.gets.chomp
# do what the user has asked
process(selection)
end
end
def process(selection)
case selection
when "1"
puts "Please follow the instructions below............."
puts
input_students()
when "2"
center_align("Now showing all students in the directory.............")
puts
show_students()
when "3"
save_students()
when "4"
center_align("Successfully loaded all student data.............")
puts
load_students()
when "9"
center_align("Thank you, Bye..............")
puts
exit
else
puts "I don't know what you meant, try again"
end
end
def add_to_students_array(name, cohort)
@students << {name: name, cohort: cohort.to_sym}
end
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
puts "Enter a name"
name = STDIN.gets.delete("\n")
# while the name is not empty, repeat this code
while !name.empty? do
puts "Enter the student's cohort"
cohort = STDIN.gets.delete("\n")
if cohort.empty?
cohort = :not_decided
end
# add the student hash to the array
add_to_students_array(name, cohort)
if @students.size > 1
puts "Now we have #{@students.count} students"
else
puts "Now we have #{@students.count} student"
end
# get another name from the user
puts "Enter a name"
name = STDIN.gets.delete("\n")
end
end
def show_students
print_header()
print_students_list()
print_footer()
end
# Aligns the text to the center
def center_align(text)
width = 200
puts text.center(width)
end
def print_header
center_align("The students of Villians Academy")
center_align( "-------------")
puts
end
def print_students_list
if @students.empty?
center_align("Please enter at least one student.")
puts
end
@students = @students.sort_by {|student| COHORT_LIST.index(student[:cohort])}
@students.each_with_index do |student, i|
center_align("#{i + 1}. #{@students[i][:name]} (cohort: #{@students[i][:cohort]})")
end
end
def print_footer
center_align("Overall, we have #{@students.count} great students")
puts
end
def get_file_name
puts "Please input the name of your file with a .csv extension or hit enter to save as students.csv"
@file_name = STDIN.gets.chomp
if @file_name.empty?
@file_name = "students.csv"
end
@file_name
end
def save_students
get_file_name()
CSV.open(@file_name, "w") do |csv|
@students.each do |student|
csv << [student[:name], student[:cohort]]
end
end
puts "Your file as been saved as #{@file_name}"
end
def load_students(file_name = "students.csv")
CSV.foreach("students.csv") do |row|
name, cohort = row
@students << {name: name, cohort: cohort.to_sym}
end
end
def try_load_students
filename = ARGV.first # first argument from the command line
if filename.nil? # if no file is given
load_students()
elsif File.exists?(filename) # if it exists
load_students(filename)
puts "Loaded #{@students.count} from #{filename}"
else # if it doesn't exist
puts "Sorry, #{filename} doesn't exist."
exit # quit the program
end
end
try_load_students()
interactive_menu()
| true |
9d8c116c21732bb9217eb2d73053a46047bb1e3c | Ruby | textchimp/wdi19-homework | /daniel_ting/week_05/wednesday/warmup.rb | UTF-8 | 146 | 3.203125 | 3 | [] | no_license | def cipher(string)
string.downcase.split("").each do |char|
print (122 - (char.ord - 97)).chr
end
puts
end
cipher 'test'
cipher 'gvhg'
| true |
892b03ad283eeefe70f2939ae3bdc098175686c5 | Ruby | bubbaspaarx/simple-blackjack-cli-london-web-060418 | /lib/blackjack.rb | UTF-8 | 1,562 | 3.734375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def welcome
# code #welcome here
puts "Welcome to the Blackjack Table"
end
def deal_card
# code #deal_card here
return rand(1..11)
end
def display_card_total(card_total)
# code #display_card_total here
puts "Your cards add up to #{card_total}"
end
def prompt_user
# code #prompt_user here
puts "Type 'h' to hit or 's' to stay"
end
def get_user_input
# code #get_user_input here
gets.chomp
end
def end_game(card_total)
# code #end_game here
puts "Sorry, you hit #{card_total}. Thanks for playing!"
end
def initial_round
# code #initial_round here
total = deal_card + deal_card
display_card_total(total)
total
end
# it "calls on #prompt_user then #get_user_input" do
# expect($stdout).to receive(:puts).with("Type 'h' to hit or 's' to stay")
# expect(self).to receive(:get_user_input).and_return("s")
# hit?(7)
# end
def hit?(current_total)
prompt_user
input = get_user_input
if input == "s"
current_total
elsif input == "h"
new_total = deal_card + current_total
p new_total
else
invalid_command
prompt_user
end
end
def invalid_command
# code invalid_command here
puts "Please enter a valid command"
end
#####################################################
# get every test to pass before coding runner below #
#####################################################
def runner
# code runner here
welcome
total = hit?(initial_round)
until total > 21
total = hit?(total)
display_card_total(total)
end
display_card_total(total)
end_game(total)
end | true |
ea07518ee0a2de1df08e01e53a39f2b152466f7f | Ruby | resputin/the_odin_project | /Ruby/testing/time_travel/spec/caesar_cipher_spec.rb | UTF-8 | 1,039 | 3.46875 | 3 | [] | no_license | require "caesar_cipher"
describe ".caesar_cipher" do
context "given out of bounds letters" do
it "returns same letter" do
expect(caesar_cipher(",", 5)).to eq(",")
end
it "handles spaces" do
expect(caesar_cipher(" ", 5)).to eq(" ")
end
end
context "given lowercase letters" do
it "returns same letter" do
expect(caesar_cipher("a", 0)).to eq("a")
end
it "shifts correctly" do
expect(caesar_cipher("a", 1)).to eq("b")
end
it "shifts over range" do
expect(caesar_cipher("z", 1)).to eq("a")
end
end
context "given uppercase letters" do
it "returns same letter" do
expect(caesar_cipher("A", 0)).to eq("A")
end
it "shifts correctly" do
expect(caesar_cipher("A", 1)).to eq("B")
end
it "shifts over range" do
expect(caesar_cipher("Z", 1)).to eq("A")
end
end
context "given phrases" do
it "translates whole phrases" do
expect(caesar_cipher("What a string!", 5)).to eq("Bmfy f xywnsl!")
end
end
end | true |
1dba845b2cd616a633cab7932d86e6737382e119 | Ruby | wenbo/smart_ruby_codes | /threads/thread_current.rb | UTF-8 | 258 | 3.140625 | 3 | [] | no_license | # coding: utf-8
# 线程变量
count = 0
threads =[]
10.times do |i|
threads[i] = Thread.new do
sleep(rand(0.1))
Thread.current["myvalue"] =count #将值赋给当前变量
count += 1
end
end
threads.each { |t| t.join; puts t["myvalue"] }
| true |
7efff2578030528b6147f906a90eca3ceb2a06a3 | Ruby | RatheN/pl_table_cli | /lib/cli.rb | UTF-8 | 2,918 | 3.453125 | 3 | [
"MIT"
] | permissive | class CLI
def run
welcome
setup
prompt_for_table
team_selection
end_prompt
end
def welcome
puts "\n\n----------------------------------------"
puts "Welcome to the 2018/19 Premier League Table."
puts "View different sections of the table and find more information on your favorite teams."
end
def setup
teams = Scraper.scrape_index
Team.make_teams(teams)
end
def prompt_for_table
puts "\n\nWould you like to view the top of the table or the bottom of the table?"
puts "(please enter: 'top' or 'bottom')"
input = gets.strip.downcase
if input == "top"
input = 0
show_table(input)
elsif input == "bottom"
input = 10
show_table(input)
else
puts "\nPlease enter a valid option."
prompt_for_table
end
end
def team_selection
puts "\n\n----------------------------------------"
puts "What team would you like more information on?"
puts "(Enter a number from 1 - 20)"
input = gets.strip.to_i
if input >= 1 && input <= 20
team_info(input-1)
else
while input < 1 || input > 20
puts "Please enter a valid number from 1 - 20"
input = gets.strip.to_i
end
team_info(input-1)
end
end
def show_table(s)
if s == 0
puts "\n\n----------Top of the 2018/19 Premier League Table----------\n\n"
Team.all[s, 10].each do |t|
puts "#{t.rank}. #{t.name}"
end
else
puts "\n\n----------Bottom of the 2018/19 Premier League Table----------\n\n"
Team.all[s, 10].each do |t|
puts "#{t.rank}. #{t.name}"
end
end
end
def team_info(r)
team = Team.all[r]
Scraper.scrape_team_page(team) if !team.full_name
puts "\n\n---------------#{team.full_name}---------------\n\n"
puts "Nickname(s): #{team.nickname}"
puts "Ground(stadium): #{team.ground}"
puts "Capacity: #{team.capacity}"
puts "Founded: #{team.founded}"
puts "Owner(s): #{team.owner}"
puts "Chairman(Chairmen): #{team.chairman}"
puts "Manager: #{team.manager}"
puts "Website: #{team.website}"
end_prompt
end
def end_prompt
puts "\n\n----------------------------------------"
puts "Would you like to view a different section of the table, search for a different team, restart, or exit?"
puts "('table', 'team', 'restart', or 'exit')"
input = gets.strip.downcase
if input == "table"
prompt_for_table
end_prompt
elsif input == "team"
team_selection
end_prompt
elsif input == "restart"
run
elsif input == "exit"
closing_statement
else
puts "\nPlease enter a valid option."
end_prompt
end
end
def closing_statement
puts "\n\nThank you. Best of luck to your favorite team next year!"
exit
end
end
| true |
7a2002aa7fd342ddcc09ad6947327feff20cf8d1 | Ruby | chef/license-acceptance | /components/ruby/spec/license_acceptance/strategy/prompt_spec.rb | UTF-8 | 3,847 | 2.546875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | permissive | require "spec_helper"
require "license_acceptance/strategy/prompt"
require "license_acceptance/product"
require "tty-prompt"
RSpec.describe LicenseAcceptance::Strategy::Prompt do
let(:output) { StringIO.new }
let(:config) do
instance_double(LicenseAcceptance::Config, output: output)
end
let(:acc) { LicenseAcceptance::Strategy::Prompt.new(config) }
let(:prompt) { instance_double(TTY::Prompt) }
let(:p1) { instance_double(LicenseAcceptance::Product, id: "foo", pretty_name: "Pretty Name") }
let(:missing_licenses) { [p1] }
before do
expect(TTY::Prompt).to receive(:new).at_least(:once).and_return(prompt)
end
describe "when the user accepts" do
it "returns true" do
expect(prompt).to receive(:ask).and_return("yes")
msg1 = /License that need accepting:\n \* #{p1.pretty_name}/m
msg2 = /product license persisted\./
b = Proc.new { [] }
expect(acc.request(missing_licenses, &b)).to eq(true)
expect(output.string).to match(msg1)
expect(output.string).to match(msg2)
end
describe "when there are multiple products" do
let(:p2) { instance_double(LicenseAcceptance::Product, id: "bar", pretty_name: "Other") }
let(:missing_licenses) { [p1, p2] }
it "returns true" do
expect(prompt).to receive(:ask).and_return("yes")
msg1 = /Licenses that need accepting:\n \* #{p1.pretty_name}\n \* #{p2.pretty_name}/m
msg2 = /product licenses persisted\./
msg3 = /2 product licenses\nmust be accepted/m
b = Proc.new { [] }
expect(acc.request(missing_licenses, &b)).to eq(true)
expect(output.string).to match(msg1)
expect(output.string).to match(msg2)
expect(output.string).to match(msg3)
end
end
describe "when the callback returns an error" do
it "returns true" do
expect(prompt).to receive(:ask).and_return("yes")
msg1 = /License that need accepting:\n \* #{p1.pretty_name}/m
msg2 = /Could not persist acceptance:/
b = Proc.new { [StandardError.new("foo")] }
expect(acc.request(missing_licenses, &b)).to eq(true)
expect(output.string).to match(msg1)
expect(output.string).to match(msg2)
end
end
end
describe "when the prompt times out" do
it "returns false" do
expect(Timeout).to receive(:timeout).twice.and_yield
expect(prompt).to receive(:ask).twice.and_raise(LicenseAcceptance::Strategy::PromptTimeout)
expect(prompt).to receive(:unsubscribe).twice
expect(prompt).to receive(:reader).twice
msg1 = /Prompt timed out./
b = Proc.new { [] }
expect(acc.request(missing_licenses, &b)).to eq(false)
expect(output.string).to match(msg1)
end
end
describe "when the user declines twice" do
it "returns false" do
expect(prompt).to receive(:ask).twice.and_return("no")
msg1 = /License that need accepting:\n \* #{p1.pretty_name}/m
msg2 = /product license persisted\./
b = Proc.new { raise "should not be called" }
expect(acc.request(missing_licenses, &b)).to eq(false)
expect(output.string).to match(msg1)
expect(output.string).to_not match(msg2)
end
end
describe "when the user declines once then accepts" do
it "returns true" do
expect(prompt).to receive(:ask).and_return("no")
expect(prompt).to receive(:ask).and_return("yes")
msg1 = /License that need accepting:\n \* #{p1.pretty_name}/m
msg2 = /product license persisted\./
msg3 = /If you do not accept this license you will\nnot be able to use Chef products/m
b = Proc.new { [] }
expect(acc.request(missing_licenses, &b)).to eq(true)
expect(output.string).to match(msg1)
expect(output.string).to match(msg2)
expect(output.string).to match(msg3)
end
end
end
| true |
5dbbb063aa404b79caa026f2d52f2ef8ed06d45d | Ruby | wsierradev/Launch-Academy-2017 | /challenges/odd-numbers/lib/odd_numbers.rb | UTF-8 | 163 | 2.59375 | 3 | [] | no_license | # Wasn't sure if I was supposed to work from the test file or not so I worked from the file in the lib folder.
odd = 1
while odd < 100 do
puts odd
odd += 2
end
| true |
e7a0af8f8db4575706afa01fbf4e9f783525c3b5 | Ruby | claracodes/interview-prep | /solutions/single_number.rb | UTF-8 | 761 | 4.25 | 4 | [] | no_license | # Brute force with #count
# O(n^2) time and O(1) space
def single_number(num)
num.each do |n|
return n if num.count(n) == 1
end
end
# Tally
# O(n) time and O(n) space
def single_number(nums)
nums.each_with_object(Hash.new(0)) { |n, h| h[n] += 1 }
end
# XOR operator or bitwise operator
# O(n) time and O(1) space
def single_number(nums)
result = 0
nums.each do |singular_num|
result = result ^ singular_num
end
result
end
=begin
*** bitwise operator walk through ***
nums = [2, 2, 1]
result ^ singular_num
0 ^ 2 = 00 ^ 10 = 10 = 2 < -- result
2 ^ 2 = 10 ^ 10 = 00 = 0 < -- result
0 ^ 1 = 00 ^ 01 = 01 = 1 < -- result
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 1 = 0
1 ^ 0 = 1
if array is [4, 1, 2, 1, 2]
4 ^ 1 ^ 2 ^ 1 ^ 2 = 1 ^ 4 ^ 1 ^ 2 ^ 2
=end
| true |
d6c082ca972bc8cbfde4ca692c24d030abcb69bc | Ruby | svenfuchs/memoize | /spec/memoize_spec.rb | UTF-8 | 478 | 2.984375 | 3 | [
"MIT"
] | permissive | describe Memoize do
let(:const) do
Class.new do
include Memoize
def count
@count ||= 0
@count += 1
end
memoize :count
prepend Module.new {
attr_reader :called
def count
@called ||= 0
@called += 1
super
end
}
end
end
let(:obj) { const.new }
before { 10.times { obj.count } }
it { expect(obj.count).to eq 1 }
it { expect(obj.called).to eq 10 }
end
| true |
80795110a624a407b6c4173110cff3d790c81c68 | Ruby | zendesk/em-http-request | /spec/stub_server.rb | UTF-8 | 993 | 2.515625 | 3 | [
"MIT"
] | permissive | class StubServer
module Server
attr_accessor :keepalive
def receive_data(data)
if echo?
send_data("HTTP/1.0 200 OK\r\nContent-Length: #{data.bytesize}\r\nContent-Type: text/plain\r\n\r\n")
send_data(data)
else
send_data @response
end
close_connection_after_writing unless keepalive
end
def echo= flag
@echo = flag
end
def echo?
!!@echo
end
def response=(response)
@response = response
end
end
def initialize options = {}
options = {:response => options} if options.kind_of?(String)
options = {:port => 8081, :host => '127.0.0.1'}.merge(options)
host = options[:host]
port = options[:port]
@sig = EventMachine::start_server(host, port, Server) do |server|
server.response = options[:response]
server.echo = options[:echo]
server.keepalive = options[:keepalive]
end
end
def stop
EventMachine.stop_server @sig
end
end
| true |
c48bf84f63ab7fc64a3149ee2dabf3dfb34f0207 | Ruby | kremso/tmzone | /lib/tort/default_search.rb | UTF-8 | 760 | 2.625 | 3 | [] | no_license | require 'tort/external_search'
require 'tort/downloader'
require 'tort/parallel_hits_fetcher'
require 'tort/page_search'
module Tort
class DefaultSearch
def initialize(engine_name, list_parser, mark_parser, instructions_factory)
@engine_name = engine_name
@list_parser = list_parser
@mark_parser = mark_parser
@instructions_factory = instructions_factory
end
def search(phrase, &block)
downloader = Downloader.new
page_search = Tort::PageSearch.new(downloader, @list_parser, @instructions_factory)
hit_fetcher = Tort::ParallelHitsFetcher.new(downloader, @mark_parser)
engine = Tort::ExternalSearch.new(@engine_name, page_search, hit_fetcher)
engine.search(phrase, &block)
end
end
end
| true |
3462a38c7d8ad4cd6b8dadf64116455f70359d81 | Ruby | thebravoman/software_engineering_2015 | /hm_count_words/B_12_Emiliqn_Gospodinov/word_counter/folder_parser.rb | UTF-8 | 447 | 2.609375 | 3 | [] | no_license | require_relative 'file_parser'
module WordCounter
class FolderParser
def parse_folder folder
directory = folder.gsub("\n",'')
directory.insert(directory.size, '/**/*.*')
Dir.glob(directory).each do |file|
result = FileParser.new.parse_file file
if ARGV[2] == 'csv' or ARGV[2] == nil
result.to_csv
elsif ARGV[2] == 'json'
result.to_json
elsif ARGV[2] == 'xml'
result.to_xml
end
end
end
end
end
| true |
dff411b841a9481b2881fc2a897cac01e612fb3b | Ruby | Shadowssong/Battle-muffin | /lib/battle-muffin/character_profile/character.rb | UTF-8 | 2,200 | 2.796875 | 3 | [
"MIT"
] | permissive | require_relative 'achievements'
require_relative 'appearance'
require_relative 'audit'
require_relative 'feed'
require_relative 'guild'
require_relative 'hunter_pets'
require_relative 'items'
require_relative 'mounts'
require_relative 'pet_slots'
require_relative 'pets'
require_relative 'progression'
require_relative 'pvp'
require_relative 'quests'
require_relative 'reputation'
require_relative 'stats'
require_relative 'talents'
require_relative 'titles'
class Character
include Character::Achievements
include Character::Appearance
include Character::Audit
include Character::Feed
include Character::Guild
include Character::HunterPets
include Character::Items
include Character::Mounts
include Character::PetSlots
include Character::Pets
include Character::Progression
include Character::PVP
include Character::Quests
include Character::Reputation
include Character::Stats
include Character::Talents
include Character::Titles
def initialize(api_handler, realm, character_name)
@api_handler = api_handler
@info = @api_handler.query("character/#{realm}/#{character_name}?")
end
def all_info
all_items = %w{ achievements appearance audit feed guild hunterPets items mounts petSlots pets progression pvp quests reputation stats talents titles }
@api_handler.query("character/#{realm}/#{name}?fields=#{all_items.join(",")}&")
end
def last_modified
@info['lastModified']
end
def name
@info['name']
end
def realm
@info['realm']
end
def battlegroup
@info['battlegroup']
end
def class
@info['class']
end
def race
@info['race']
end
def gender
@info['gender']
end
def level
@info['level']
end
def achievement_points
@info['achievement_points']
end
def thumbnail
@info['thumbnail']
end
def thumbnail_url(region="us")
"http://#{region}.battle.net/static-render/#{region}/#{thumbnail}"
end
def calc_class
@info['calcClass']
end
def total_honorable_kills
@info['totalHonorableKills']
end
def item_url(slot, size=56)
icon = self.get_items[slot]['icon']
"http://media.blizzard.com/wow/icons/#{size}/#{icon}.jpg"
end
end
| true |
66a34d0e6582d30b9efdbf56daf5b544c273bc61 | Ruby | clodiap/CodeWars | /spec/CountCharacters_spec.rb | UTF-8 | 502 | 2.96875 | 3 | [] | no_license | require_relative '../lib/CountCharacters'
describe "ordered_count" do
it "Count the number of occurrences of each character and return it as a list of tuples in order of appearance" do
expect(ordered_count("abracadabra")).to eq([['a', 5], ['b', 2], ['r', 2], ['c', 1], ['d', 1]])
expect(ordered_count("aaaabbcccccccccdd")).to eq([['a', 4], ['b', 2], ['c', 9], ['d', 2]])
expect(ordered_count("claudia")).to eq([['c', 1], ['l', 1], ['a', 2], ['u', 1], ['d', 1], ['i', 1]])
end
end
| true |
3e24898859ba8ad5252705b8121b8fb2c0f87d77 | Ruby | ashamani9/Ruby | /AverageArray.rb | UTF-8 | 187 | 3.328125 | 3 | [] | no_license | # Calculate Average Value of Array Elements
num= Array[23,12,14,23,22,34,12,45,67,89]
sum=0
num.each { |b| sum += b }
average = sum / num.length
puts "The average is : #{average}" | true |
7bc25b0997048060921f03bf3488f94d8ef6a4b2 | Ruby | derrick-long/Launch_Projects | /optimal-guesser/guess_number.rb | UTF-8 | 1,055 | 4.09375 | 4 | [] | no_license | require 'pry'
# def median(array)
# sorted = array.sort
# mid = (sorted.length - 1)/2.0
# (sorted[mid.floor] + sorted[mid.ceil]) / 2
# end
def guess_number(min, max)
# You can call the `check` method with a number to see if it
# is the hidden value.
#
# If the guess is correct, it will return 0.
# If the guess is too high, it will return 1.
# If the guess is too low, it will return -1.
#
# If you call `check` too many times, the program will crash.
#
# e.g. if the hidden number is 43592, then
#
# check(50000) # => 1
# check(40000) # => -1
# check(43592) # => 0
#
# When you've figured out what the hidden number is, return it
# from this method.
#how many times do we get to iterate, and I guess, the start guess should be the
#middle of the pack
while min <= max
current_guess = (min + max)/2
result = check(current_guess)
return current_guess if result == 0
if result == 1
max = current_guess - 1
elsif result == -1
min = current_guess + 1
end
end
end
| true |
2516dc7195b8250c16d7c9d9cfe0c42e765e476b | Ruby | kaninfod/pt_api | /db/migrate/20170814150419_add_hamming_function.rb | UTF-8 | 684 | 2.515625 | 3 | [] | no_license | class AddHammingFunction < ActiveRecord::Migration[5.1]
def change
ActiveRecord::Base.connection.execute <<-SQL
CREATE FUNCTION `HAMMINGDISTANCE`(A BINARY(32), B BINARY(32)) RETURNS int(11)
DETERMINISTIC
RETURN
BIT_COUNT(CONV(HEX(SUBSTRING(A, 1, 8)), 16, 10) ^CONV(HEX(SUBSTRING(B, 1, 8)), 16, 10))
+BIT_COUNT( CONV(HEX(SUBSTRING(A, 9, 8)), 16, 10) ^ CONV(HEX(SUBSTRING(B, 9, 8)), 16, 10))
+BIT_COUNT( CONV(HEX(SUBSTRING(A, 17, 8)), 16, 10) ^ CONV(HEX(SUBSTRING(B, 17, 8)), 16, 10))
+BIT_COUNT( CONV(HEX(SUBSTRING(A, 25, 8)), 16, 10) ^ CONV(HEX(SUBSTRING(B, 25, 8)), 16, 10));
SQL
end
end
| true |
a51032a63f44200427c88feb8ab1996281509133 | Ruby | thomaswhyyou/pepperjam | /lib/tasks/scraper.rake | UTF-8 | 8,809 | 2.8125 | 3 | [] | no_license | require 'csv'
namespace :scraper do
desc "Scrape pepperjamnetwork.com for program info and scan for bidding policy"
task pepperjam: :environment do
time_start = Time.now
start_point = 0
# Initiate a ICONV object to convert/uniform encodings to utf-8
encoding_converter = Iconv.new('UTF-8', 'LATIN1')
# Initiate a Mechanize object, request for pepperjam site and log in with credentials.
agent = Mechanize.new
target_host = 'http://www.pepperjamnetwork.com'
agent.get(target_host) do |page|
login_form = page.form_with(name: 'login') do |form|
form.email = ENV['PEPPERJAM_UN']
form.passwd = ENV['PEPPERJAM_PW']
end
login_form.submit
end
# Once logged in, fetch & parse through csv file to extract all available program ids
csv_raw_data = agent.get("#{target_host}/affiliate/program/manage?&csv=1")
csv_into_array = CSV.parse(csv_raw_data.body)
csv_into_array.shift # drop the headings
prgm_ids_array = csv_into_array.map! { |x| x[0] }
puts "UPDATE: Total of #{prgm_ids_array.count} programs available"
# Iterate thru program ids, retrieve detail information and save them into database
scraping_count = 0
prgm_ids_array.count.times do |i|
prgm_url = "#{target_host}/affiliate/program/popup?programId=#{prgm_ids_array[i]}"
prgm_page = agent.get(prgm_url)
desc_page = agent.get("#{target_host}/affiliate/program/description?programId=#{prgm_ids_array[i]}")
# Shortcuts
header = prgm_page.search('.program-header')
tabcontents = prgm_page.search('.tab-content')
# Variables used to calculate other properties
company_name = header.css('.program-name').text.gsub(/^\s+|\s+$/, "")
description = desc_page.search('.pd_desc').text.gsub(/^\s+|\s+$/, "")
restricted_keywords = check_capture_keywords(encoding_converter, tabcontents[4], "Restricted Keywords:")
Program.create(
prgm_count: i + 1,
prgm_id: prgm_ids_array[i],
prgm_url: prgm_url,
company_name: company_name,
logo_url: check_capture_logo_url(header),
site_address: header.css('.websiteurl').text(),
categories: header.css('.base-info div')[1].children[2].text.gsub(/^\s+|\s+$/, ""),
mobile_tracking: header.css('.base-info div')[2].children[2].text.gsub(/^\s+|\s+$/, ""),
status: check_capture_status(header),
description: description,
contact_info: organize_contact_info(tabcontents[1].css('div')),
offer_terms: organize_offer_terms(tabcontents[2]),
offer_note: tabcontents[2].css('.note').text,
coockie_duration: organize_term_options(tabcontents[2], "Cookie Duration:"),
lock_period: organize_term_options(tabcontents[2], "Lock Period:"),
promo_methods: organize_promo_methods(tabcontents[3]),
suggested_keywords: check_capture_keywords(encoding_converter, tabcontents[4], "Suggested Keywords:"),
restricted_keywords: restricted_keywords,
bidding_policy: check_policy(company_name, description, restricted_keywords)
)
scraping_count += 1
puts "Scraping.. total of #{scraping_count} so far."
end
# Console logs for monitoring
time_finished = Time.now
seconds_taken = time_finished - time_start
puts "This rake task has taken #{seconds_taken} secs or #{seconds_taken / 60} minutes."
end
end
#############################################################################################
# Helper Functions - Organizers
#############################################################################################
def organize_contact_info(raw_object)
organized_contact = []
raw_object.each do |div|
break if div.text.gsub(/^\s+|\s+$/, "") == "Address:"
organized_contact << div.text.gsub(/^\s+|\s+$/, "").gsub(/\n|\s{2,}/," ")
end
organized_contact << "Address: "+ raw_object[-1].text.gsub(/^\s+|\s+$/, "").gsub(/\n|\s{2,}/," ")
end
def organize_offer_terms(raw_object)
offer_array = []
if raw_object.css('.pd_left').count != 0
raw_object.css('.pd_left').count.times do |i|
offer_array << [raw_object.css('.pd_left')[i].text.gsub(/^\s+|\s+$/, ""),
raw_object.css('.pd_right')[i].text.gsub(/^\s+|\s+$/, "")]
end
else
link_to_details = "http://www.pepperjamnetwork.com/" + raw_object.css('.yellow_bld')[0].attributes['href'].value
offer_array << ["Link for details", link_to_details]
end
return offer_array
end
def organize_term_options(raw_object, option_label)
if raw_object.search("[text()*=\"#{option_label}\"]").count == 0
return ["", ""]
else
option_term = raw_object.search("[text()*=\"#{option_label}\"]").first.parent.next_element.text.gsub(/^\s+|\s+$/, "")
return [option_label, option_term]
end
end
def organize_promo_methods(raw_object)
promo_methods_array = []
raw_object.css('li').each do |li|
promo_methods_array << li.text
end
return promo_methods_array
end
def check_capture_logo_url(raw_object)
if raw_object.css('.logo div img').empty?
return "n/a"
else
return raw_object.css('.logo div img').first.attributes['src'].value
end
end
def check_capture_status(raw_object)
if raw_object.css('.current-status').empty?
return "n/a"
else
return raw_object.css('.current-status').first.children.first.text.gsub!("Your Status: ", "")
end
end
def check_capture_keywords(converter_object, raw_object, label_text)
if raw_object.search("[text()*=\"#{label_text}\"]").empty?
return "n/a"
else
raw_text = raw_object.search("[text()*=\"#{label_text}\"]").first.next.text
processed_text = converter_object.iconv(raw_text)
return processed_text.gsub(/^\s+|\s+$/, "")
end
end
#############################################################################################
# Helper Functions - Scanner
#############################################################################################
# 'check_policy' function will scan the data and categorize the policy into the following categories:
# [:allowed, "direct-pos"]
# [:allowed, "implied-pos"]
# [:prohibited, "strong-neg"]
# [:prohibited, "implied-neg"]
def check_policy(company_name, description, restricted_keywords)
# Step 1: Direct positive indicator check
if restricted_keywords.downcase.scan('open search policy').count != 0
return [:allowed, "direct-pos"]
# Step 2: Strong negagtive indicator check
elsif check_strong_neg(description + restricted_keywords) != 0
return [:prohibited, "strong-neg"]
# Step 3-A: Implied negagtive indicator check by company name
elsif restricted_keywords.downcase.scan(company_name.downcase).count != 0
return [:prohibited, "implied-neg"]
# Step 3-B: Implied negagtive indicator check by implied negative phrases
elsif check_implied_neg(description + restricted_keywords) != 0
return [:prohibited, "implied-neg"]
# Step 4: Interpret as an implied positive if not caught by none of the above
else
return [:allowed, "implied-pos"]
end
end
def check_strong_neg(text_for_scan)
detected_indicator = 0
strong_negatives = ["no tm bidding",
"no trade mark bidding",
"no trademark bidding",
"no keyword bidding",
"not allow trademark",
"not allow tm bidding",
"no kw bidding",
"no paid search allowed",
"branded keywords bidding is not allowed",
"tm bidding is not allowed",
"trademark bidding is not allowed",
"trademark bidding not allowed",
"trademarks or any variation",
"tm bidding is prohibited",
"tm bidding prohibited",
"trademark bidding is prohibited",
"trademark bidding prohibited"]
strong_negatives.each do |neg|
break if detected_indicator != 0
detected_indicator += (text_for_scan).downcase.scan(neg).count
end
return detected_indicator
end
def check_implied_neg(text_for_scan)
detected_indicator = 0
implied_negatives = ["not permitted to bid",
"may not bid",
"prohibited to bid",
"any variation",
"misspelling",
"including but not limited to"]
implied_negatives.each do |neg|
break if detected_indicator != 0
detected_indicator += (text_for_scan).downcase.scan(neg).count
end
return detected_indicator
end
| true |
56bff0fd648faa2f7500548a78eda34a52455761 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/meetup/45b03a5813a2419ba4bc733a8c2f9bfc.rb | UTF-8 | 1,495 | 3.453125 | 3 | [] | no_license | module TimeTricks
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def days_in_month(month, year = Time.now.year)
return 29 if month == 2 && Date.gregorian_leap?(year)
COMMON_YEAR_DAYS_IN_MONTH[month]
end
end
class Meetup
include TimeTricks
DAYS = {
sunday: 0,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
}
def initialize(month, year)
@base_date = Date.new(year, month, 1)
@month = month
@year = year
end
def day(weekday, schedule)
until right_schedule?(schedule) && right_day?(weekday)
@base_date += 1
end
@base_date
end
def what_day
DAYS.invert[@base_date.wday]
end
def right_day?(weekday)
what_day == weekday
end
def right_schedule?(schedule)
case schedule
when :teenth
(13..19) === @base_date.mday
when :first
date_range(0) === @base_date.mday
when :second
date_range(1) === @base_date.mday
when :third
date_range(2) === @base_date.mday
when :fourth
date_range(3) === @base_date.mday
when :last
(days_in_month(@month,@year)-6..days_in_month(@month,@year)) === @base_date.mday
else
raise ArgumentError, "Invalid schedule: #{p schedule}"
end
end
def date_range(week)
days_in_week = 7
week_start = ((week * days_in_week)+1)
week_finish = week_start + days_in_week - 1
(week_start..week_finish)
end
end
| true |
86aca1719fd794768f01603f2e463abb18a0ebbc | Ruby | adamberman/learning_sql | /Question.rb | UTF-8 | 1,708 | 2.90625 | 3 | [] | no_license | require './QuestionsDatabase.rb'
require './Reply.rb'
require './QuestionFollower.rb'
require './QuestionLike.rb'
require './SaveModel.rb'
class Question
include SaveModel
def self.all
questions = QuestionsDatabase.instance.execute('SELECT * FROM questions')
questions.map {|question| User.new(question)}
end
attr_reader :id
attr_accessor :title, :body, :user_id
def initialize(options = {})
@id = options['id']
@title = options['title']
@body = options['body']
@user_id = options['user_id']
end
def self.find_by_id(id)
query = <<-SQL
SELECT
*
FROM
questions
WHERE
id = ?
SQL
hash = QuestionDatabase.instance.execute(query, id).first
self.class.new(hash)
end
def self.find_by_author_id(author_id)
query = <<-SQL
SELECT
*
FROM
questions
WHERE
user_id = ?
SQL
array = QuestionDatabase.instance.execute(query, author_id)
array.map! { |hash| self.class.new(hash) }
end
def author
query = <<-SQL
SELECT
*
FROM
users
WHERE
id = ?
SQL
array = QuestionDatabase.instance.execute(query, user_id)
array.map! { |hash| self.class.new(hash) }
end
def replies
Reply.find_by_question_id(id)
end
def followers
QuestionFollower.followers_for_question_id(id)
end
def self.most_followed(n)
QuestionFollower.most_followed_questions(n)
end
def likers
QuestionLikes.likers_for_question_id(id)
end
def num_likes
QuestionLikes.num_likes_for_question_id(id)
end
def self.most_liked(n)
QuestionLike.most_liked_questions(n)
end
end | true |
4d6986c67e1a98702303d0a09b96003bcddbc14a | Ruby | cowboyd/baseline | /spec/baseline_spec.rb | UTF-8 | 1,648 | 2.703125 | 3 | [] | no_license |
require File.dirname(__FILE__) + '/../lib/baseline.rb'
include Baseline
describe Baseline do
it "can parse a simple option" do
Parser.new.tap do |p|
p.option do |o|
o.name = "v"
end
p.parse("-v 1.9").tap do |options|
options[:v].should == "1.9"
end
end
end
it "will treat arguments as boolean if the option is a switch and not consume the following argument" do
Parser.new.tap do |p|
p.option do |o|
o.name = "v"
o.switch = true
end
p.parse("-v 1.9").tap do |options|
options[:v].should be(true)
options.args.should == ['1.9']
end
end
end
it "is an error if there is an option that is not specified" do
Parser.new.tap do |p|
p.parse("-v").errors.tap do |errors|
errors.length.should == 1
errors.first.tap do |e|
e.option_name.should == "v"
e.error_type.should be(UnknownOptionError)
end
end
end
end
it "allows long options to be specified if preceded by a --" do
Parser.new.tap do |p|
p.option do |o|
o.name = 'version'
end
p.parse("--version=1.9").tap do |options|
options[:version].should == 1.9
end
end
end
it "allows long options to also be switches"
it "is optional to use the '=' sign for long options"
it "is illegal for long options that are switches to use the '=' sign"
it "has symbolic options as well as positional arguments"
it "understands arrays as well as strings"
it "allows you handle missing options that were not specified ahead of time"
end | true |
035b371991812ac6481a23b22f92ec91a22ba00b | Ruby | sa2taka/rootine | /vendor/bundle/ruby/2.6.0/gems/ruby-graphviz-1.2.4/lib/graphviz/utils/colors.rb | UTF-8 | 29,683 | 3.046875 | 3 | [
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later"
] | permissive | require 'graphviz/core_ext'
class GraphViz
module Utils
class Colors
HEX_FOR_COLOR = /[0-9a-fA-F]{2}/
RGBA = /^(#{HEX_FOR_COLOR})(#{HEX_FOR_COLOR})(#{HEX_FOR_COLOR})(#{HEX_FOR_COLOR})?$/
attr_reader :r, :g, :b, :a
attr_reader :h, :s, :v
def initialize
@r, @g, @b, @a, @h, @s, @v, @color = nil, nil, nil, nil, nil, nil, nil, nil
end
def rgb(r, g, b, a = nil)
if r.is_a?(Integer)
r = r.to_s.convert_base(10, 16)
end
unless r.is_a?(String) and HEX_FOR_COLOR.match(r)
raise ColorException, "Bad red value"
end
if g.is_a?(Integer)
g = g.to_s.convert_base(10, 16)
end
unless g.is_a?(String) and HEX_FOR_COLOR.match(g)
raise ColorException, "Bad green value"
end
if b.is_a?(Integer)
b = b.to_s.convert_base(10, 16)
end
unless b.is_a?(String) and HEX_FOR_COLOR.match(b)
raise ColorException, "Bad blue value"
end
if a.is_a?(Integer)
a = a.to_s.convert_base(10, 16)
end
unless a.nil? or (a.is_a?(String) and HEX_FOR_COLOR.match(a))
raise ColorException, "Bad alpha value"
end
@r = r
@g = g
@b = b
@a = a
@color = COLORS.key(rgba_string.downcase)
@h, @s, @v = rgb_to_hsv(@r, @g, @b)
end
def hsv(h, s, v)
unless h.is_a?(Float) and s.is_a?(Float) and v.is_a?(Float)
raise ColorException, "Bas HSV value"
end
@h = h
@s = s
@v = v
@r, @g, @b = hsv_to_rgb(@h, @s, @v)
@color = COLORS.key(rgba_string.downcase);
end
def name(c = nil)
return @color if c.nil?
@color = c
rgb = COLORS[c]
unless rgb.nil?
m = RGBA.match(rgb)
@r = m[1]
@g = m[2]
@b = m[3]
@h, @s, @v = rgb_to_hsv(@r, @g, @b)
end
end
def rgba_string(c = "")
unless @r.nil?
"#{c}#{@r}#{@g}#{@b}#{((@a.nil?)?"":@a)}"
else
nil
end
end
def hsv_string(s = ", ")
unless @h.nil?
"#{@h}#{s}#{@s}#{s}#{@v}"
else
nil
end
end
def rgb_to_hsv(r, g, b)
Colors.rgb_to_hsv(r, g, b)
end
def hsv_to_rgb(h, s, v)
Colors.hsv_to_rgb(h, s, v)
end
class <<self
def rgb(r, g, b, a = nil)
color = Colors.new
color.rgb(r, g, b, a)
color
end
def hsv(h, s, v)
color = Colors.new
color.hsv(h, s, v)
color
end
def name(c)
color = Colors.new
color.name(c)
color
end
def rgb_to_hsv(r, g, b)
h, s, v = 0.0, 0.0, 0.0
_r = r.convert_base(16, 10).to_f / 255.0
_g = g.convert_base(16, 10).to_f / 255.0
_b = b.convert_base(16, 10).to_f / 255.0
rgb = [ _r, _g, _b ]
min = rgb.min
max = rgb.max
v = max
delta = max - min
if max != 0.0
s = delta / max
else
return [-1, 0, v]
end
if _r == max
h = ( _g - _b ) / delta
elsif( _g == max )
h = 2 + ( _b - _r ) / delta
else
h = 4 + ( _r - _g ) / delta
end
h = h * 60
h = h + 360 if h < 0
h = h / 360.0
[h, s, v]
end
def hsv_to_rgb(h, s, v)
_h, _s, _v = h.to_f * 360.0, s.to_f, v.to_f
if _s == 0.0
r = (_v * 255 ).to_i.to_s.convert_base(10,16)
return [r, r, r]
end
_h = _h / 60.0
i = _h.floor
f = _h - i
p = _v * ( 1.0 - _s )
q = _v * ( 1.0 - _s * f )
t = _v * ( 1.0 - _s * ( 1 - f ) )
case i
when 0
r = _v
g = t
b = p
when 1
r = q
g = _v
b = p
when 2
r = p
g = _v
b = t
when 3
r = p
g = q
b = _v
when 4
r = t
g = p
b = _v
else
r = _v
g = p
b = q
end
[
(r * 255).to_i.to_s.convert_base(10, 16),
(g * 255).to_i.to_s.convert_base(10, 16),
(b * 255).to_i.to_s.convert_base(10, 16)
]
end
end
COLORS = {
"aliceblue" => "f0f8ff",
"antiquewhite" => "faebd7",
"antiquewhite1" => "ffefdb",
"antiquewhite2" => "eedfcc",
"antiquewhite3" => "cdc0b0",
"antiquewhite4" => "8b8378",
"aquamarine" => "7fffd4",
"aquamarine1" => "7fffd4",
"aquamarine2" => "76eec6",
"aquamarine3" => "66cdaa",
"aquamarine4" => "458b74",
"azure" => "f0ffff",
"azure1" => "f0ffff",
"azure2" => "e0eeee",
"azure3" => "c1cdcd",
"azure4" => "838b8b",
"beige" => "f5f5dc",
"bisque" => "ffe4c4",
"bisque1" => "ffe4c4",
"bisque2" => "eed5b7",
"bisque3" => "cdb79e",
"bisque4" => "8b7d6b",
"black" => "000000",
"blanchedalmond" => "ffebcd",
"blue" => "0000ff",
"blue1" => "0000ff",
"blue2" => "0000ee",
"blue3" => "0000cd",
"blue4" => "00008b",
"blueviolet" => "8a2be2",
"brown" => "a52a2a",
"brown1" => "ff4040",
"brown2" => "ee3b3b",
"brown3" => "cd3333",
"brown4" => "8b2323",
"burlywood" => "deb887",
"burlywood1" => "ffd39b",
"burlywood2" => "eec591",
"burlywood3" => "cdaa7d",
"burlywood4" => "8b7355",
"cadetblue" => "5f9ea0",
"cadetblue1" => "98f5ff",
"cadetblue2" => "8ee5ee",
"cadetblue3" => "7ac5cd",
"cadetblue4" => "53868b",
"chartreuse" => "7fff00",
"chartreuse1" => "7fff00",
"chartreuse2" => "76ee00",
"chartreuse3" => "66cd00",
"chartreuse4" => "458b00",
"chocolate" => "d2691e",
"chocolate1" => "ff7f24",
"chocolate2" => "ee7621",
"chocolate3" => "cd661d",
"chocolate4" => "8b4513",
"coral" => "ff7f50",
"coral1" => "ff7256",
"coral2" => "ee6a50",
"coral3" => "cd5b45",
"coral4" => "8b3e2f",
"cornflowerblue" => "6495ed",
"cornsilk" => "fff8dc",
"cornsilk1" => "fff8dc",
"cornsilk2" => "eee8cd",
"cornsilk3" => "cdc8b1",
"cornsilk4" => "8b8878",
"crimson" => "dc143c",
"cyan" => "00ffff",
"cyan1" => "00ffff",
"cyan2" => "00eeee",
"cyan3" => "00cdcd",
"cyan4" => "008b8b",
"darkgoldenrod" => "b8860b",
"darkgoldenrod1" => "ffb90f",
"darkgoldenrod2" => "eead0e",
"darkgoldenrod3" => "cd950c",
"darkgoldenrod4" => "8b6508",
"darkgreen" => "006400",
"darkkhaki" => "bdb76b",
"darkolivegreen" => "556b2f",
"darkolivegreen1" => "caff70",
"darkolivegreen2" => "bcee68",
"darkolivegreen3" => "a2cd5a",
"darkolivegreen4" => "6e8b3d",
"darkorange" => "ff8c00",
"darkorange1" => "ff7f00",
"darkorange2" => "ee7600",
"darkorange3" => "cd6600",
"darkorange4" => "8b4500",
"darkorchid" => "9932cc",
"darkorchid1" => "bf3eff",
"darkorchid2" => "b23aee",
"darkorchid3" => "9a32cd",
"darkorchid4" => "68228b",
"darksalmon" => "e9967a",
"darkseagreen" => "8fbc8f",
"darkseagreen1" => "c1ffc1",
"darkseagreen2" => "b4eeb4",
"darkseagreen3" => "9bcd9b",
"darkseagreen4" => "698b69",
"darkslateblue" => "483d8b",
"darkslategray" => "2f4f4f",
"darkslategray1" => "97ffff",
"darkslategray2" => "8deeee",
"darkslategray3" => "79cdcd",
"darkslategray4" => "528b8b",
"darkslategrey" => "2f4f4f",
"darkturquoise" => "00ced1",
"darkviolet" => "9400d3",
"deeppink" => "ff1493",
"deeppink1" => "ff1493",
"deeppink2" => "ee1289",
"deeppink3" => "cd1076",
"deeppink4" => "8b0a50",
"deepskyblue" => "00bfff",
"deepskyblue1" => "00bfff",
"deepskyblue2" => "00b2ee",
"deepskyblue3" => "009acd",
"deepskyblue4" => "00688b",
"dimgray" => "696969",
"dimgrey" => "696969",
"dodgerblue" => "1e90ff",
"dodgerblue1" => "1e90ff",
"dodgerblue2" => "1c86ee",
"dodgerblue3" => "1874cd",
"dodgerblue4" => "104e8b",
"firebrick" => "b22222",
"firebrick1" => "ff3030",
"firebrick2" => "ee2c2c",
"firebrick3" => "cd2626",
"firebrick4" => "8b1a1a",
"floralwhite" => "fffaf0",
"forestgreen" => "228b22",
"gainsboro" => "dcdcdc",
"ghostwhite" => "f8f8ff",
"gold" => "ffd700",
"gold1" => "ffd700",
"gold2" => "eec900",
"gold3" => "cdad00",
"gold4" => "8b7500",
"goldenrod" => "daa520",
"goldenrod1" => "ffc125",
"goldenrod2" => "eeb422",
"goldenrod3" => "cd9b1d",
"goldenrod4" => "8b6914",
"gray" => "808080",
"gray0" => "000000",
"gray1" => "030303",
"gray10" => "1a1a1a",
"gray100" => "ffffff",
"gray11" => "1c1c1c",
"gray12" => "1f1f1f",
"gray13" => "212121",
"gray14" => "242424",
"gray15" => "262626",
"gray16" => "292929",
"gray17" => "2b2b2b",
"gray18" => "2e2e2e",
"gray19" => "303030",
"gray2" => "050505",
"gray20" => "333333",
"gray21" => "363636",
"gray22" => "383838",
"gray23" => "3b3b3b",
"gray24" => "3d3d3d",
"gray25" => "404040",
"gray26" => "424242",
"gray27" => "454545",
"gray28" => "474747",
"gray29" => "4a4a4a",
"gray3" => "080808",
"gray30" => "4d4d4d",
"gray31" => "4f4f4f",
"gray32" => "525252",
"gray33" => "545454",
"gray34" => "575757",
"gray35" => "595959",
"gray36" => "5c5c5c",
"gray37" => "5e5e5e",
"gray38" => "616161",
"gray39" => "636363",
"gray4" => "0a0a0a",
"gray40" => "666666",
"gray41" => "696969",
"gray42" => "6b6b6b",
"gray43" => "6e6e6e",
"gray44" => "707070",
"gray45" => "737373",
"gray46" => "757575",
"gray47" => "787878",
"gray48" => "7a7a7a",
"gray49" => "7d7d7d",
"gray5" => "0d0d0d",
"gray50" => "7f7f7f",
"gray51" => "828282",
"gray52" => "858585",
"gray53" => "878787",
"gray54" => "8a8a8a",
"gray55" => "8c8c8c",
"gray56" => "8f8f8f",
"gray57" => "919191",
"gray58" => "949494",
"gray59" => "969696",
"gray6" => "0f0f0f",
"gray60" => "999999",
"gray61" => "9c9c9c",
"gray62" => "9e9e9e",
"gray63" => "a1a1a1",
"gray64" => "a3a3a3",
"gray65" => "a6a6a6",
"gray66" => "a8a8a8",
"gray67" => "ababab",
"gray68" => "adadad",
"gray69" => "b0b0b0",
"gray7" => "121212",
"gray70" => "b3b3b3",
"gray71" => "b5b5b5",
"gray72" => "b8b8b8",
"gray73" => "bababa",
"gray74" => "bdbdbd",
"gray75" => "bfbfbf",
"gray76" => "c2c2c2",
"gray77" => "c4c4c4",
"gray78" => "c7c7c7",
"gray79" => "c9c9c9",
"gray8" => "141414",
"gray80" => "cccccc",
"gray81" => "cfcfcf",
"gray82" => "d1d1d1",
"gray83" => "d4d4d4",
"gray84" => "d6d6d6",
"gray85" => "d9d9d9",
"gray86" => "dbdbdb",
"gray87" => "dedede",
"gray88" => "e0e0e0",
"gray89" => "e3e3e3",
"gray9" => "171717",
"gray90" => "e5e5e5",
"gray91" => "e8e8e8",
"gray92" => "ebebeb",
"gray93" => "ededed",
"gray94" => "f0f0f0",
"gray95" => "f2f2f2",
"gray96" => "f5f5f5",
"gray97" => "f7f7f7",
"gray98" => "fafafa",
"gray99" => "fcfcfc",
"green" => "008000",
"green1" => "00ff00",
"green2" => "00ee00",
"green3" => "00cd00",
"green4" => "008b00",
"greenyellow" => "adff2f",
"grey" => "808080",
"grey0" => "000000",
"grey1" => "030303",
"grey10" => "1a1a1a",
"grey100" => "ffffff",
"grey11" => "1c1c1c",
"grey12" => "1f1f1f",
"grey13" => "212121",
"grey14" => "242424",
"grey15" => "262626",
"grey16" => "292929",
"grey17" => "2b2b2b",
"grey18" => "2e2e2e",
"grey19" => "303030",
"grey2" => "050505",
"grey20" => "333333",
"grey21" => "363636",
"grey22" => "383838",
"grey23" => "3b3b3b",
"grey24" => "3d3d3d",
"grey25" => "404040",
"grey26" => "424242",
"grey27" => "454545",
"grey28" => "474747",
"grey29" => "4a4a4a",
"grey3" => "080808",
"grey30" => "4d4d4d",
"grey31" => "4f4f4f",
"grey32" => "525252",
"grey33" => "545454",
"grey34" => "575757",
"grey35" => "595959",
"grey36" => "5c5c5c",
"grey37" => "5e5e5e",
"grey38" => "616161",
"grey39" => "636363",
"grey4" => "0a0a0a",
"grey40" => "666666",
"grey41" => "696969",
"grey42" => "6b6b6b",
"grey43" => "6e6e6e",
"grey44" => "707070",
"grey45" => "737373",
"grey46" => "757575",
"grey47" => "787878",
"grey48" => "7a7a7a",
"grey49" => "7d7d7d",
"grey5" => "0d0d0d",
"grey50" => "7f7f7f",
"grey51" => "828282",
"grey52" => "858585",
"grey53" => "878787",
"grey54" => "8a8a8a",
"grey55" => "8c8c8c",
"grey56" => "8f8f8f",
"grey57" => "919191",
"grey58" => "949494",
"grey59" => "969696",
"grey6" => "0f0f0f",
"grey60" => "999999",
"grey61" => "9c9c9c",
"grey62" => "9e9e9e",
"grey63" => "a1a1a1",
"grey64" => "a3a3a3",
"grey65" => "a6a6a6",
"grey66" => "a8a8a8",
"grey67" => "ababab",
"grey68" => "adadad",
"grey69" => "b0b0b0",
"grey7" => "121212",
"grey70" => "b3b3b3",
"grey71" => "b5b5b5",
"grey72" => "b8b8b8",
"grey73" => "bababa",
"grey74" => "bdbdbd",
"grey75" => "bfbfbf",
"grey76" => "c2c2c2",
"grey77" => "c4c4c4",
"grey78" => "c7c7c7",
"grey79" => "c9c9c9",
"grey8" => "141414",
"grey80" => "cccccc",
"grey81" => "cfcfcf",
"grey82" => "d1d1d1",
"grey83" => "d4d4d4",
"grey84" => "d6d6d6",
"grey85" => "d9d9d9",
"grey86" => "dbdbdb",
"grey87" => "dedede",
"grey88" => "e0e0e0",
"grey89" => "e3e3e3",
"grey9" => "171717",
"grey90" => "e5e5e5",
"grey91" => "e8e8e8",
"grey92" => "ebebeb",
"grey93" => "ededed",
"grey94" => "f0f0f0",
"grey95" => "f2f2f2",
"grey96" => "f5f5f5",
"grey97" => "f7f7f7",
"grey98" => "fafafa",
"grey99" => "fcfcfc",
"honeydew" => "f0fff0",
"honeydew1" => "f0fff0",
"honeydew2" => "e0eee0",
"honeydew3" => "c1cdc1",
"honeydew4" => "838b83",
"hotpink" => "ff69b4",
"hotpink1" => "ff6eb4",
"hotpink2" => "ee6aa7",
"hotpink3" => "cd6090",
"hotpink4" => "8b3a62",
"indianred" => "cd5c5c",
"indianred1" => "ff6a6a",
"indianred2" => "ee6363",
"indianred3" => "cd5555",
"indianred4" => "8b3a3a",
"indigo" => "4b0082",
"invis" => "fffffe",
"ivory" => "fffff0",
"ivory1" => "fffff0",
"ivory2" => "eeeee0",
"ivory3" => "cdcdc1",
"ivory4" => "8b8b83",
"khaki" => "f0e68c",
"khaki1" => "fff68f",
"khaki2" => "eee685",
"khaki3" => "cdc673",
"khaki4" => "8b864e",
"lavender" => "e6e6fa",
"lavenderblush" => "fff0f5",
"lavenderblush1" => "fff0f5",
"lavenderblush2" => "eee0e5",
"lavenderblush3" => "cdc1c5",
"lavenderblush4" => "8b8386",
"lawngreen" => "7cfc00",
"lemonchiffon" => "fffacd",
"lemonchiffon1" => "fffacd",
"lemonchiffon2" => "eee9bf",
"lemonchiffon3" => "cdc9a5",
"lemonchiffon4" => "8b8970",
"lightblue" => "add8e6",
"lightblue1" => "bfefff",
"lightblue2" => "b2dfee",
"lightblue3" => "9ac0cd",
"lightblue4" => "68838b",
"lightcoral" => "f08080",
"lightcyan" => "e0ffff",
"lightcyan1" => "e0ffff",
"lightcyan2" => "d1eeee",
"lightcyan3" => "b4cdcd",
"lightcyan4" => "7a8b8b",
"lightgoldenrod" => "eedd82",
"lightgoldenrod1" => "ffec8b",
"lightgoldenrod2" => "eedc82",
"lightgoldenrod3" => "cdbe70",
"lightgoldenrod4" => "8b814c",
"lightgoldenrodyellow" => "fafad2",
"lightgray" => "d3d3d3",
"lightgrey" => "d3d3d3",
"lightpink" => "ffb6c1",
"lightpink1" => "ffaeb9",
"lightpink2" => "eea2ad",
"lightpink3" => "cd8c95",
"lightpink4" => "8b5f65",
"lightsalmon" => "ffa07a",
"lightsalmon1" => "ffa07a",
"lightsalmon2" => "ee9572",
"lightsalmon3" => "cd8162",
"lightsalmon4" => "8b5742",
"lightseagreen" => "20b2aa",
"lightskyblue" => "87cefa",
"lightskyblue1" => "b0e2ff",
"lightskyblue2" => "a4d3ee",
"lightskyblue3" => "8db6cd",
"lightskyblue4" => "607b8b",
"lightslateblue" => "8470ff",
"lightslategray" => "778899",
"lightslategrey" => "778899",
"lightsteelblue" => "b0c4de",
"lightsteelblue1" => "cae1ff",
"lightsteelblue2" => "bcd2ee",
"lightsteelblue3" => "a2b5cd",
"lightsteelblue4" => "6e7b8b",
"lightyellow" => "ffffe0",
"lightyellow1" => "ffffe0",
"lightyellow2" => "eeeed1",
"lightyellow3" => "cdcdb4",
"lightyellow4" => "8b8b7a",
"limegreen" => "32cd32",
"linen" => "faf0e6",
"magenta" => "ff00ff",
"magenta1" => "ff00ff",
"magenta2" => "ee00ee",
"magenta3" => "cd00cd",
"magenta4" => "8b008b",
"maroon" => "800000",
"maroon1" => "ff34b3",
"maroon2" => "ee30a7",
"maroon3" => "cd2990",
"maroon4" => "8b1c62",
"mediumaquamarine" => "66cdaa",
"mediumblue" => "0000cd",
"mediumorchid" => "ba55d3",
"mediumorchid1" => "e066ff",
"mediumorchid2" => "d15fee",
"mediumorchid3" => "b452cd",
"mediumorchid4" => "7a378b",
"mediumpurple" => "9370db",
"mediumpurple1" => "ab82ff",
"mediumpurple2" => "9f79ee",
"mediumpurple3" => "8968cd",
"mediumpurple4" => "5d478b",
"mediumseagreen" => "3cb371",
"mediumslateblue" => "7b68ee",
"mediumspringgreen" => "00fa9a",
"mediumturquoise" => "48d1cc",
"mediumvioletred" => "c71585",
"midnightblue" => "191970",
"mintcream" => "f5fffa",
"mistyrose" => "ffe4e1",
"mistyrose1" => "ffe4e1",
"mistyrose2" => "eed5d2",
"mistyrose3" => "cdb7b5",
"mistyrose4" => "8b7d7b",
"moccasin" => "ffe4b5",
"navajowhite" => "ffdead",
"navajowhite1" => "ffdead",
"navajowhite2" => "eecfa1",
"navajowhite3" => "cdb38b",
"navajowhite4" => "8b795e",
"navy" => "000080",
"navyblue" => "000080",
"none" => "fffffe",
"oldlace" => "fdf5e6",
"olivedrab" => "6b8e23",
"olivedrab1" => "c0ff3e",
"olivedrab2" => "b3ee3a",
"olivedrab3" => "9acd32",
"olivedrab4" => "698b22",
"orange" => "ffa500",
"orange1" => "ffa500",
"orange2" => "ee9a00",
"orange3" => "cd8500",
"orange4" => "8b5a00",
"orangered" => "ff4500",
"orangered1" => "ff4500",
"orangered2" => "ee4000",
"orangered3" => "cd3700",
"orangered4" => "8b2500",
"orchid" => "da70d6",
"orchid1" => "ff83fa",
"orchid2" => "ee7ae9",
"orchid3" => "cd69c9",
"orchid4" => "8b4789",
"palegoldenrod" => "eee8aa",
"palegreen" => "98fb98",
"palegreen1" => "9aff9a",
"palegreen2" => "90ee90",
"palegreen3" => "7ccd7c",
"palegreen4" => "548b54",
"paleturquoise" => "afeeee",
"paleturquoise1" => "bbffff",
"paleturquoise2" => "aeeeee",
"paleturquoise3" => "96cdcd",
"paleturquoise4" => "668b8b",
"palevioletred" => "db7093",
"palevioletred1" => "ff82ab",
"palevioletred2" => "ee799f",
"palevioletred3" => "cd6889",
"palevioletred4" => "8b475d",
"papayawhip" => "ffefd5",
"peachpuff" => "ffdab9",
"peachpuff1" => "ffdab9",
"peachpuff2" => "eecbad",
"peachpuff3" => "cdaf95",
"peachpuff4" => "8b7765",
"peru" => "cd853f",
"pink" => "ffc0cb",
"pink1" => "ffb5c5",
"pink2" => "eea9b8",
"pink3" => "cd919e",
"pink4" => "8b636c",
"plum" => "dda0dd",
"plum1" => "ffbbff",
"plum2" => "eeaeee",
"plum3" => "cd96cd",
"plum4" => "8b668b",
"powderblue" => "b0e0e6",
"purple" => "800080",
"purple1" => "9b30ff",
"purple2" => "912cee",
"purple3" => "7d26cd",
"purple4" => "551a8b",
"red" => "ff0000",
"red1" => "ff0000",
"red2" => "ee0000",
"red3" => "cd0000",
"red4" => "8b0000",
"rosybrown" => "bc8f8f",
"rosybrown1" => "ffc1c1",
"rosybrown2" => "eeb4b4",
"rosybrown3" => "cd9b9b",
"rosybrown4" => "8b6969",
"royalblue" => "4169e1",
"royalblue1" => "4876ff",
"royalblue2" => "436eee",
"royalblue3" => "3a5fcd",
"royalblue4" => "27408b",
"saddlebrown" => "8b4513",
"salmon" => "fa8072",
"salmon1" => "ff8c69",
"salmon2" => "ee8262",
"salmon3" => "cd7054",
"salmon4" => "8b4c39",
"sandybrown" => "f4a460",
"seagreen" => "2e8b57",
"seagreen1" => "54ff9f",
"seagreen2" => "4eee94",
"seagreen3" => "43cd80",
"seagreen4" => "2e8b57",
"seashell" => "fff5ee",
"seashell1" => "fff5ee",
"seashell2" => "eee5de",
"seashell3" => "cdc5bf",
"seashell4" => "8b8682",
"sienna" => "a0522d",
"sienna1" => "ff8247",
"sienna2" => "ee7942",
"sienna3" => "cd6839",
"sienna4" => "8b4726",
"skyblue" => "87ceeb",
"skyblue1" => "87ceff",
"skyblue2" => "7ec0ee",
"skyblue3" => "6ca6cd",
"skyblue4" => "4a708b",
"slateblue" => "6a5acd",
"slateblue1" => "836fff",
"slateblue2" => "7a67ee",
"slateblue3" => "6959cd",
"slateblue4" => "473c8b",
"slategray" => "708090",
"slategray1" => "c6e2ff",
"slategray2" => "b9d3ee",
"slategray3" => "9fb6cd",
"slategray4" => "6c7b8b",
"slategrey" => "708090",
"snow" => "fffafa",
"snow1" => "fffafa",
"snow2" => "eee9e9",
"snow3" => "cdc9c9",
"snow4" => "8b8989",
"springgreen" => "00ff7f",
"springgreen1" => "00ff7f",
"springgreen2" => "00ee76",
"springgreen3" => "00cd66",
"springgreen4" => "008b45",
"steelblue" => "4682b4",
"steelblue1" => "63b8ff",
"steelblue2" => "5cacee",
"steelblue3" => "4f94cd",
"steelblue4" => "36648b",
"tan" => "d2b48c",
"tan1" => "ffa54f",
"tan2" => "ee9a49",
"tan3" => "cd853f",
"tan4" => "8b5a2b",
"thistle" => "d8bfd8",
"thistle1" => "ffe1ff",
"thistle2" => "eed2ee",
"thistle3" => "cdb5cd",
"thistle4" => "8b7b8b",
"tomato" => "ff6347",
"tomato1" => "ff6347",
"tomato2" => "ee5c42",
"tomato3" => "cd4f39",
"tomato4" => "8b3626",
"transparent" => "fffffe",
"turquoise" => "40e0d0",
"turquoise1" => "00f5ff",
"turquoise2" => "00e5ee",
"turquoise3" => "00c5cd",
"turquoise4" => "00868b",
"violet" => "ee82ee",
"violetred" => "d02090",
"violetred1" => "ff3e96",
"violetred2" => "ee3a8c",
"violetred3" => "cd3278",
"violetred4" => "8b2252",
"wheat" => "f5deb3",
"wheat1" => "ffe7ba",
"wheat2" => "eed8ae",
"wheat3" => "cdba96",
"wheat4" => "8b7e66",
"white" => "ffffff",
"whitesmoke" => "f5f5f5",
"yellow" => "ffff00",
"yellow1" => "ffff00",
"yellow2" => "eeee00",
"yellow3" => "cdcd00",
"yellow4" => "8b8b00",
"yellowgreen" => "9acd32",
"aqua" => "00ffff",
"darkblue" => "00008b",
"darkcyan" => "008b8b",
"darkgray" => "a9a9a9",
"darkgrey" => "a9a9a9",
"darkmagenta" => "8b008b",
"darkred" => "8b0000",
"fuchsia" => "ff00ff",
"lightgreen" => "90ee90",
"lime" => "00ff00",
"olive" => "808000",
"silver" => "c0c0c0",
"teal" => "008080"
}
end
end
end
| true |
078c4a89f7ba0b683f4668c4559a0ab8a4aa8ccd | Ruby | lrnzgll/Design-Patterns | /observer-pattern/v1/delivery_driver.rb | UTF-8 | 146 | 2.78125 | 3 | [] | no_license | class DeliveryDriver
def update(pizza)
puts "New status update for pizza #{pizza.style}"
puts "The pizza is #{pizza.status} "
end
end
| true |
69a6c0c754d7894733d8843dfecd92857e68eaf9 | Ruby | jzntam/CodeCore_Alumni | /spec/controllers/cohorts_controller_spec.rb | UTF-8 | 3,685 | 2.53125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe CohortsController, type: :controller do
let(:cohort) { create(:cohort) }
let(:cohort_1) { create(:cohort) }
let(:user) { create(:user) }
describe "GET #index" do
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
it "returns all cohorts" do
get :index
expect( assigns(:cohorts) ).to match_array([cohort_1, cohort])
end
it "renders the index templaye" do
get :index
expect(response).to render_template(:index)
end
end
describe "GET #show" do
before {login(user)}
it "returns http success" do
get :show, id: cohort.id
expect(response).to have_http_status(:success)
end
it "renders show page" do
get :show, id: cohort.id
expect(response).to render_template(:show)
end
end
describe "GET #new" do
context "user is not signed in" do
it "returns http redirect" do
get :new
expect(response).to have_http_status(:redirect)
end
end
context "user is signed in" do
before {login(user)}
it "returns http success" do
get :new
expect(response).to have_http_status(:success)
end
it "renders a new template" do
get :new
expect(response).to render_template(:new)
end
end
end
describe "GET #create" do
# let(:cohort_valid_request)
context "User is not signed in" do
it "returns http redirect" do
get :create
expect(response).to have_http_status(:redirect)
end
end
context "User is signed in and creates a valid request" do
def valid_request
login(user)
post :create, cohort: {title: "Some title", details: "Some detail"}
end
it "creates a new cohort" do
get :create
expect{valid_request}.to change {Cohort.count}.by(1)
end
end
context "User is signed in and creates an invalid request" do
def invalid_request
login(user)
post :create, cohort: {title: "", details: ""}
end
it "does not create a new cohort" do
get :create
expect{invalid_request}.to change {Cohort.count}.by(0)
end
end
end
describe "GET #edit" do
it "returns http success" do
login(user)
get :edit, id: cohort.id
expect(response).to have_http_status(:success)
end
it "renders the edit page" do
login(user)
get :edit, id: cohort.id
expect(response).to render_template(:edit)
end
it "redirects when user not signed in" do
get :edit, id: cohort.id
expect(response).to have_http_status(:redirect)
end
end
describe "GET #update" do
before {login(user)}
before {patch :update, id: cohort.id, cohort: {title: "edited title"}}
it "returns http redirect" do # when cohort is updated, it redirects to root path
# login(user)
expect(response).to have_http_status(:redirect)
end
it "redirects to cohort root path" do
login(user)
expect(response).to redirect_to( cohorts_path )
end
end
describe "GET #delete" do
def valid_request
login(user)
delete :destroy, id: cohort.id
end
it "returns http redirect" do
valid_request
expect(response).to have_http_status(:redirect)
end
it "redirects to root path" do
valid_request
expect(response).to redirect_to( cohorts_path )
end
it "deletes the cohort in the database" do
login(user)
cohort
expect{
delete :destroy, id: cohort.id
}.to change {Cohort.count}.by(-1)
end
end
end
| true |
d520eaf70fc0293d47033ab119c17adc7c215820 | Ruby | DianaE620/Torteria | /torteria.rb | UTF-8 | 4,128 | 3.171875 | 3 | [] | no_license | $pan = 60
$aguacate = 30
$mayonesa = 30
class Torta
@@numero_tortas = 0
def initialize(extras)
@pan = 2
@aguacate = 1
@mayonesa = 1
@@numero_tortas += 1
"Torta numero: #{@@numero_tortas}"
p Torta.bodega
end
def self.bodega
$pan -= 2
$aguacate -= 1
$mayonesa -= 1
"Quedan en bodega pan-> #{$pan}, aguacate-> #{$aguacate}, mayonesa-> #{$mayonesa}"
end
end
class TortaPastor < Torta
def initialize(extras)
"Torta de Pastor"
@extras = extras
@time = 8
super
end
end
class TortaRusa < Torta
def initialize(extras)
"Torta Rusa"
@extras = extras
@time = 6
super
end
end
class TortaSuiza < Torta
def initialize(extras)
"Torta Suiza"
@extras = extras
@time = 4
super
end
end
class TortaHawaiana < Torta
def initialize(extras)
"Torta Hawaiana"
@extras = extras
@time = 4
super
end
end
class Cocina
@@tortas = 0
@@bandeja = []
def initialize
"Nuevo pedido"
end
def pedido
return "Ya no quedan ingredientes para crear mas tortas" if $pan < 1 || $aguacate < 1 || $mayonesa < 1
@@tortas = 0
@@bandeja = []
menu = ["Pastor", "Rusa", "Suiza", "Hawaiana"]
max_horno = rand(1..4)
for i in 1..max_horno
r = rand(0..3)
if menu[r] == "Pastor"
@@bandeja << TortaPastor.new(["pastor", "queso", "pina"])
@@tortas += 1
end
if menu[r] == "Rusa"
@@bandeja << TortaRusa.new(["pierna", "queso", "jamon"])
@@tortas += 1
end
if menu[r] == "Suiza"
@@bandeja << TortaRusa.new(["pierna", "queso", "jamon"])
@@tortas += 1
end
if menu[r] == "Hawaiana"
@@bandeja << TortaHawaiana.new(["jamon", "queso", "pina"])
@@tortas += 1
end
return "Ya no quedan ingredientes para crear mas tortas" if $pan < 1 || $aguacate < 1 || $mayonesa < 1
end
p "El numero de tortas en el pedido es de #{@@tortas} y son: #{@@bandeja}"
puts
end
def horno
p "Ingresa en el horno #{@@bandeja}"
puts
haw = []
pas = []
rus = []
sui = []
tortas_listas = []
@@bandeja.each do |torta|
if torta.to_s.include?("Pastor")
pas << torta.to_s
elsif torta.to_s.include?("Hawaiana")
haw << torta.to_s
elsif torta.to_s.include?("Rusa")
rus << torta.to_s
elsif torta.to_s.include?("Suiza")
sui << torta.to_s
end
end
if pas.length > 0
# time_cooked = 8
time_cooked = 0
while time_cooked < 8
time_cooked += 1
p "cocinando tortas de pastor tiene #{time_cooked} minutos en el horno"
end
if time_cooked == 8
p "Tortas Listas #{pas}"
puts
end
end
if haw.length > 0
# time_cooked = 4
time_cooked = 0
while time_cooked < 4
time_cooked += 1
p "cocinando tortas hawainas tiene #{time_cooked} minutos en el horno"
end
if time_cooked == 4
p "Tortas Listas #{haw}"
puts
end
end
if rus.length > 0
# time_cooked = 6
time_cooked = 0
while time_cooked < 6
time_cooked += 1
p "cocinando tortas rusas tiene #{time_cooked} minutos en el horno"
end
if time_cooked == 6
p "Tortas Listas #{rus}"
puts
end
end
if sui.length > 0
# time_cooked = 4
time_cooked = 0
while time_cooked < 4
time_cooked += 1
p "cocinando tortas suizas tiene #{time_cooked} minutos en el horno"
end
if time_cooked == 4
p "Tortas Listas #{sui}"
puts
end
end
end
end # Final Clase Cocina
p cocinero = Cocina.new
puts "----------------------------------------- Pedido ---------------------------------------------------------------"
p cocinero.pedido
puts "-------------------------------------- Entrada al horno -------------------------------------------------------"
p cocinero.horno
# [[TortaPastor.new(["pastor", "queso", "pina"])],
# [TortaRusa.new(["pierna", "queso", "jamon"])],
# [TortaSuiza.new(["queso_blanco", "queso", "amarillo"])],
# [TortaHawaiana.new(["jamon", "queso", "pina"])]]
| true |
7261cb7d36a561042e9785349dd5d8ef43181d4b | Ruby | mcinello/object_oriented_programming | /player.rb | UTF-8 | 965 | 3.796875 | 4 | [] | no_license | class Player
def initialize
@gold_coins = 0
@health_points = 10
@lives = 5
end
#answer 6
def level_up #works
@lives += 1
return @lives
end
#answer 7
def collect_treasure #works
@gold_coins += 1
if @gold_coins % 10 == 0
Player.new.level_up
return level_up
end
end
#answer 8
def do_battle(damage)
@health_points -= damage #works
if @health_points < 1 #works
@lives -= 1
if @lives == 0
puts "#{@lives} lives! You lose."
Player.new.restart
return restart
end
@health_points = 10
return @health_points
end
return @health_points
end
def restart
@gold_coins = 0
@health_points = 10
@lives = 5 #reset all attributes back to starting values
end
end
player1 = Player.new
puts player1.inspect
20.times do
player1.collect_treasure
puts player1.inspect
end
7.times do
player1.do_battle(10)
puts player1.inspect
end
| true |
1e41a91e52a1a8365e60bfa62597a93a5c9c5b85 | Ruby | halhelms/ruby-stuff | /ARGF.rb | UTF-8 | 262 | 3.0625 | 3 | [] | no_license | KEYS = ( 'a'..'z' ).to_a
VALUES = KEYS.rotate( 13 )
CYPHER = Hash[ KEYS.zip( VALUES ) ]
def sekrit( text )
text.downcase.chars.map{ |char| CYPHER[ char ] || char }.join
#text
end
ARGF.each_line do |line|
print "#{ARGF.path}: #{ sekrit( line ) }"
end | true |
3a9056ba11f47c500a844709dc1ae197ab3b6868 | Ruby | Freeman1524/learnrubythehardway | /ex4.rb | UTF-8 | 978 | 3.6875 | 4 | [] | no_license | cars = 100 # amount of cars
space_in_a_car = 4.0 # how many people car can hold
drivers = 30 # amount of drivers
passengers = 90 # amount of passengers
cars_not_driven = cars - drivers # cars not being driven
cars_driven = drivers # cars being driven
carpool_capacity = cars_driven * space_in_a_car # how many people can be transported
average_passengers_per_car = passengers / cars_driven #average passenger per car
# Shows cars available
puts "There are #{cars} cars available."
# Shows drivers available
puts "There are only #{drivers} drivers available."
# Shows empty cars
puts "There will be #{cars_not_driven} empty cars today."
# Shows amounty of people that can be transported
puts "We can transport #{carpool_capacity} people today."
# Shows amounter of passengers being carpooled today.
puts "We have #{passengers} to carpool today."
# Shows the average amount of passengers we can hold per car.
puts "We need to put about #{average_passengers_per_car} in each car." | true |
4f8d57aeb52eefbf90f3f43eac354c43701f0571 | Ruby | X140Yu/algorithm-solutions | /LeetCode/69.sqrtx.rb | UTF-8 | 1,041 | 3.5625 | 4 | [
"MIT"
] | permissive | # [69] Sqrt(x)
#
# https://leetcode.com/problems/sqrtx/description/
#
# * algorithms
# * Easy (29.32%)
# * Source Code: 69.sqrtx.rb
# * Total Accepted: 281.2K
# * Total Submissions: 949.8K
# * Testcase Example: '4'
#
# Implement int sqrt(int x).
#
# Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
#
# Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
#
# Example 1:
#
#
# Input: 4
# Output: 2
#
#
# Example 2:
#
#
# Input: 8
# Output: 2
# Explanation: The square root of 8 is 2.82842..., and since
# the decimal part is truncated, 2 is returned.
#
#
# @param {Integer} x
# @return {Integer}
def my_sqrt(x)
return 1 if x == 1
trigger(x, 0, x / 2)
end
def trigger(x, left, right)
mid = (left + right) / 2
if mid * mid <= x && (mid + 1) * (mid + 1) > x
return mid
elsif mid * mid > x
trigger(x, left, mid - 1)
else
trigger(x, mid + 1, right)
end
end
| true |
e85e7e2d2997d177186cebe1bec02cd3c3a92662 | Ruby | fossabot/rightcert | /lib/rightcert/certificate_cache.rb | UTF-8 | 1,345 | 3.1875 | 3 | [
"MIT"
] | permissive | module RightCert
# Implements a simple LRU cache: items that are the least accessed are
# deleted first.
class CertificateCache
# Max number of items to keep in memory
DEFAULT_CACHE_MAX_COUNT = 100
# Initialize cache
def initialize(max_count = DEFAULT_CACHE_MAX_COUNT)
@items = {}
@list = []
@max_count = max_count
end
# Add item to cache
def put(key, item)
if @items.include?(key)
delete(key)
end
if @list.size == @max_count
delete(@list.first)
end
@items[key] = item
@list.push(key)
item
end
alias :[]= :put
# Retrieve item from cache
# Store item returned by given block if any
def get(key)
if @items.include?(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
@list.push(key)
@items[key]
else
return nil unless block_given?
self[key] = yield
end
end
alias :[] :get
# Delete item from cache
def delete(key)
c = @items[key]
if c
@items.delete(key)
@list.each_index do |i|
if @list[i] == key
@list.delete_at(i)
break
end
end
c
end
end
end
end | true |
1eb67509fa20be48dac0e2b523e6bc67953899f0 | Ruby | skoba/mml-ruby | /spec/mml/insurance_client_spec.rb | UTF-8 | 1,296 | 2.578125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | describe MML::InsuranceClient do
let(:name) { MML::Name.new(repCode: 'A', fullname: 'Shinji KOBAYASHI')}
let(:address) { MML::Address.new(repCode: 'A', addressClass: 'business', tableId: 'MML0025', full: '506, Dept. 9, Kyoto Research Park (KRP), Awata-cho 91, Chudoji, Shimogyo-ku, Kyoto-city')}
let(:phone) { MML::Phone.new(telEquipType: 'PH', area: '075', city: '874', number: '7030') }
let(:insurance_client) {MML::InsuranceClient.new(personName: [name], addresses: [address], phones: [phone])}
it 'is an instance of MML::InsuranceClient' do
expect(insurance_client).to be_an_instance_of MML::InsuranceClient
end
it 'personName should be assigned properly' do
expect(insurance_client.personName[0].fullname).to eq 'Shinji KOBAYASHI'
end
it 'personName is optional' do
expect {insurance_client.personName = nil}.not_to raise_error
end
it 'addresses should be assigned properly' do
expect(insurance_client.addresses[0].addressClass).to eq 'business'
end
it 'addresses is optional' do
expect {insurance_client.addresses = nil}.not_to raise_error
end
it 'phones should be properly assigned' do
expect(insurance_client.phones[0].city).to eq '874'
end
it 'phones is optional' do
expect{insurance_client.phones = nil}.not_to raise_error
end
end
| true |
a6b64c7494a9ae11a0232a78678f6012b561477d | Ruby | billc2021/DojoAssignments | /04RAILS/02OOP/exercise_files/03bMammalClass.rb | UTF-8 | 365 | 3.921875 | 4 | [] | no_license | class Mammal
def initialize
puts "I am alive"
end
def breath
puts "Inhale and exhale"
end
def who_am_i
# printing the current object
puts self
end
end
my_mammal = Mammal.new # => "I am alive"
my_mammal.who_am_i # => #<Mammal:0x007f9e86025dd8>
my_mammal.who_am_i.breath # => undefined method `breath' for nil:NilClass (NoMethodError) | true |
869dd4d148b318f560dc666a9b1c010d573aeeaf | Ruby | akhitrykh/traning | /test_puppies/features/support/pages/shopping_cart_page.rb | UTF-8 | 1,262 | 3 | 3 | [
"Unlicense"
] | permissive | class ShoppingCartPage
include PageObject
NAME_COLUMN = 1
SUBTOTAL_COLUMN = 3
LINES_PER_PUPPY = 6
button(:proceed_to_checkout, :value => 'Complete the Adoption')
button(:continue_shoping, :value => 'Adopt Another Puppy')
table(:cart, :index => 0)
cell(:cart_total, :class => 'total_cell')
def name_for_line_item(line_item)
#cart_line_item(line_item)[NAME_COLUMN].text
table_value(line_item, NAME_COLUMN)
end
def subtotal_for_line_item(line_item)
table_value(line_item, SUBTOTAL_COLUMN)
end
private
def table_value(lineitem, column)
row = (lineitem.to_i - 1) * LINES_PER_PUPPY
cart_element[row][column].text
end
end
=begin
def subtotal_for_line_item(line_item)
cart_line_item(line_item)[SUBTOTAL_COLUMN].text
end
def cart_total
@browser.td(:class => 'total_cell').text
end
private
def row_for(line_item)
(line_item - 1) * LINES_PER_PUPPY
end
def cart_line_item(line_item)
@browser.table(:index => 0)[row_for(line_item)]
end
def proceed_to_checkout
@browser.button(:value => 'Complete Adoption').click
end
def continue_shopping
@browser.button(:value => 'Adopt Another Puppy').click
end
end
=end | true |
d7e33acee65549f4511ae6d286427409949444fe | Ruby | DaveKeith/planeswalkr | /app/models/card.rb | UTF-8 | 1,520 | 2.5625 | 3 | [] | no_license | class Card < ActiveRecord::Base
belongs_to :card_set
validates_presence_of :name, :multiverse_id, :type, :card_set_id
validates :multiverse_id, uniqueness: true
# include PgSearch
# pg_search_scope :search_by_name, :against => :name
# pg_search_scope :search_by_mana_cost, :against => :mana_cost
IMAGE_BASE_URI = "https://s3.amazonaws.com/images.planeswalker.io"
BASIC_LANDS = ["Island", "Forest", "Mountain", "Plains", "Swamp"]
def image_url
"#{IMAGE_BASE_URI}/#{self.card_set.image_dir}/#{self.image_name}.jpg"
end
def image_name
if self.name.include?(":")
self.name.gsub(/:/, "")
elsif BASIC_LANDS.include?(self.name)
"#{self.name} [#{self.card_number}]"
else
self.name
end
end
def self.import_from_json(card_data)
match = card_data['imageName'].match(/.+(\d)$/)
Card.new(name: card_data["name"],
mana_cost: card_data["manaCost"],
converted_cost: card_data["cmc"],
card_type: card_data["type"],
subtypes: card_data["subtypes"],
supertypes: card_data["supertypes"],
rarity: card_data["rarity"],
text: card_data["text"],
flavor: card_data["flavor"],
artist: card_data["artist"],
power: card_data["power"],
toughness: card_data["toughness"],
card_number: match ? match[1] : nil,
colors: card_data["colors"],
multiverse_id: card_data["multiverseid"])
end
end
| true |
2f56508405797dc9bf68409b2c6d27053e214236 | Ruby | AnKiTKaMbOj18/LearnRubyWithExamples | /3.datatypes.rb | UTF-8 | 1,647 | 4.375 | 4 | [
"MIT"
] | permissive | # Data types represents a type of data such as text, string, numbers, etc.
# There are different data types in Ruby:
# Numbers , Strings , Symbols , Hashes , Arrays , Booleans
#Numbers - Integers and floating point numbers come in the category of numbers
#Intergers - 2 , 3 , 4 etc
num1 = 2;
num2 = 3;
puts num1 + num2;
puts num1 * num2;
#Floating point
flt1 = 2.5;
flt2 = 3.5;
puts = flt1+flt2;
puts = flt1*flt2;
#Strings - A string is a group of letters that represent a sentence or a word
puts "ice" + "cream";
str1 = "some text";
str2 = "other text";
puts str1.length
puts str1 + str2;
#Symbols - Symbols are like strings. A symbol is preceded by a colon (:). For example,
#Symbols are unique identifiers and represent static values,
#while string represent values that change.
def test()
end
f1 = :test;
puts "string".object_id
puts "string".object_id
puts f1.object_id
puts f1.object_id
#In the above snapshot, two different object_id is created
#for string but for symbol same object_id is created.
#Hashes - A hash assign its values to its keys. They can be looked up by their keys.
# Value to a key is assigned by => sign. A key/value pair is separated with a comma
# between them and all the pairs are enclosed within curly braces. For example,
data = {"Akash" => "Physics", "Ankit" => "Chemistry", "Aman" => "Maths"};
puts data
puts data["Ankit"]
#Array - An array stroes data or list of data. It can conatain all types of data , data in array
# is separated by cooma and are enclosed by square brakets
arr = [ "test" , "some" , "hello"];
puts arr;
puts arr.length
| true |
7fb94b6c0ff94104dea8568a75161c6ae515033b | Ruby | guosamuel/rateMyInstructor-backend | /app/models/student.rb | UTF-8 | 550 | 2.546875 | 3 | [] | no_license | class Student < ApplicationRecord
has_secure_password
has_many :reviews
has_many :instructors, through: :reviews
validates :first_name, presence: true
validates :last_name, presence: true
validates :password_digest, presence: true
validate :unique_full_name
def unique_full_name
student = Student.find_by("lower(first_name) = ? AND lower(last_name) = ?", self.first_name.downcase, self.last_name.downcase)
if student
self.errors.add(:first_name, "A user with the same first and last name exists")
end
end
end
| true |
993df1c12f9344d8a36db84456f4706aad890842 | Ruby | Vawx/code_wars_kata | /non_code_wars/lib/06_performance_monitor.rb | UTF-8 | 710 | 3.25 | 3 | [] | no_license | # Measure gap of time
def measure( testCount = 0 )
start = Time.now # start time before yields
if testCount == 0
yield if block_given? # if testCount is 0, yield to block
else
testCount.times do yield( ) # for every testCount, yield to block
end
end
finish = Time.now # finish time after yields
if testCount == 0
testCount = 1 # set testCount to 1 after yields if its zero, so when we use it to divide times, its not divide-by-zero
end
elapsed = ( finish - start ) / testCount # total time is that of ending - start, divided by the argument being passed in, which vary by test - some tests simply want the yield and dont use the elapsed return
end
| true |
8f8379b2f569b85c0b618ee12b00dd1b95098dfc | Ruby | kenkeiter/timely-ruby | /benchmarking/stress.rb | UTF-8 | 1,114 | 2.546875 | 3 | [
"MIT"
] | permissive | require "benchmark"
require "timely"
unless RUBY_PLATFORM =~ /java/i
require 'hiredis'
timely = Timely::Connection.new(:driver => :hiredis)
else
timely = Timely::Connection.new
end
ITERATIONS = 100
Benchmark.bm(42) do |x|
series_name = (0...8).map{65.+(rand(26)).chr}.join
x.report "Insert 10k records" do
10_000.times do |i|
timely.set(series_name, i, :value => i)
end
end
x.report "(#{ITERATIONS} x) Fetch 10k records as JSON objects" do
ITERATIONS.times do |_|
timely.members(series_name, "json.object", "value")
end
end
x.report "(#{ITERATIONS} x) Fetch 10k records as JSON arrays" do
ITERATIONS.times do |_|
timely.members(series_name, "json.array", "value")
end
end
x.report "(#{ITERATIONS} x) Fetch range (2500..7000) as JSON objects" do
ITERATIONS.times do |_|
timely.range(series_name, "json.object", 2500, 7000, "value")
end
end
x.report "(#{ITERATIONS} x) Fetch range (2500..7000) as JSON arrays" do
ITERATIONS.times do |_|
timely.range(series_name, "json.array", 2500, 7000, "value")
end
end
end | true |
8d29e55c7efed7c9ebfcb8d7bdce5ee3b8c50deb | Ruby | ryogrid/hirameitter | /lib/scraper/.svn/text-base/microformats.rb.svn-base | UTF-8 | 2,421 | 2.71875 | 3 | [] | no_license | require "time"
module Scraper
module Microformats
class HCard < Scraper::Base
process ".fn", :fn=>:text
process ".given-name", :given_name=>:text
process ".family-name", :family_name=>:text
process "img.photo", :photo=>"@src"
process "a.url", :url=>"@href"
result :fn, :given_name, :family_name, :photo, :url
def collect()
unless fn
if self.fn = given_name
self.given_name << " #{family_name}" if family_name
else
self.fn = family_name
end
end
end
end
class HAtom < Scraper::Base
class Entry < Scraper::Base
array :content, :tags
process ".entry-title", :title=>:text
process ".entry-content", :content=>:element
process ".entry-summary", :summary=>:element
process "a[rel~=bookmark]", :permalink=>["@href"]
process ".author.vcard, .author .vcard", :author=>HCard
process ".published", :published=>["abbr@title", :text]
process ".updated", :updated=>["abbr@title", :text]
process "a[rel~=tag]", :tags=>:text
def collect()
self.published = Time.parse(published)
self.updated = updated ? Time.parse(updated) : published
end
result :title, :content, :summary, :permalink, :author, :published, :updated, :tags
end
class Feed < Scraper::Base
array :entries
process ".hentry", :entries=>Entry
def result()
entries
end
end
array :feeds, :entries
# Skip feeds, so we don't process them twice.
process ".hfeed", :skip=>true, :feeds=>Feed
# And so we can collect unwrapped entries into a separate feed.
process ".hentry", :skip=>true, :entries=>Entry
# And collect the first remaining hcard as the default author.
process ".vcard", :hcard=>HCard
def collect()
@feeds ||= []
@feeds << entries if entries
for feed in feeds
for entry in feed
entry.author = hcard unless entry.author
end
end
end
result :feeds
end
end
end
| true |
84736f8e2d2dec302db68ab9391a36fbd31da335 | Ruby | rafinulman/api_projects | /coords_to_weather.rb | UTF-8 | 995 | 3.640625 | 4 | [] | no_license | require 'open-uri'
require 'json'
puts "Let's get the weather forecast for your location."
puts "What is the latitude?"
the_latitude = gets.chomp
puts "What is the longitude?"
the_longitude = gets.chomp
# Now look up the weather at the lat-long
# Create a new URL
weather_URL = "https://api.forecast.io/forecast/48fc563a00174884d3e75edc1cb3ddad/#{the_latitude},#{the_longitude}"
weather_data = open(weather_URL).read
parsed_weather_data = JSON.parse(weather_data)
# Find the correct values
the_temperature = parsed_weather_data["currently"]["temperature"]
the_hour_outlook = parsed_weather_data["minutely"]["summary"]
the_day_outlook = parsed_weather_data["hourly"]["summary"]
# Ultimately, we want the following line to work when uncommented:
# puts "The current temperature at #{the_latitude}, #{the_longitude} is #{the_temperature} degrees."
# puts "The outlook for the next hour is: #{the_hour_outlook}"
# puts "The outlook for the next day is: #{the_day_outlook}"
| true |
edcb5f38f4b22904f6c24a1c5c5020ffc4886c1a | Ruby | fuzzylita/activerecord-validations-lab-v-000 | /app/models/post.rb | UTF-8 | 505 | 2.984375 | 3 | [] | no_license | require 'pry'
class Post < ActiveRecord::Base
def clickbaity?
clicky = ["Won't Believe", "Secret", "Top
[number]", "Guess"]
unless !self.title.nil? && clicky.any? {|word| self.title.include?(word)}
errors[:title] << 'Title not Clickbaity Enough'
end
end
validates :title, presence: true
validate :clickbaity?
validates :content, length: { minimum: 250 }
validates :summary, length: { maximum: 250 }
validates :category, inclusion: { in: %w(Fiction Non-Fiction)}
end | true |
d8d179babd642563eb7d88488509dcc462b6b22a | Ruby | j-resilient/sudoku | /Game.rb | UTF-8 | 1,736 | 3.65625 | 4 | [] | no_license | require_relative 'Board.rb'
require 'byebug'
class Game
def initialize
@board = Board.new
end
def play
until @board.solved?
# debugger
@board.render
position, value = get_input
@board.update_tile(position, value)
end
@board.render
puts "You win!"
end
def get_input
[get_position, get_value]
end
def get_position
print "Please enter the position of the tile you want to change (i.e. row, column): "
position = validate_position(gets.chomp)
position
end
def validate_position(position)
get_position if position.length != 3 || !position.include?(",")
pos = format_position(position)
pos = check_digits(pos)
return pos if tile_given?(pos)
get_position
end
def format_position(position)
position.delete(",").split("")
end
def check_digits(pos)
pos.map do |num|
if num =~ /[[:digit:]]/ && acceptable_number?(num)
num.to_i
else
get_position
end
end
end
def acceptable_number?(pos)
# pos.all? { |num| num =~ /[[:digit:]]/ && num.to_i < 9 && num.to_i >= 0 }
pos.to_i < 9 && pos.to_i >= 0
end
def tile_given?(pos)
@board[pos].given
end
def get_value
print "Please enter a value (i.e. a digit 1-9): "
validate_value(gets.chomp)
end
def validate_value(value)
value.to_i if value =~ /[[:digit:]]/
return value if value.to_i > 0 && value.to_i <= 9
get_value
end
end
if $PROGRAM_NAME == __FILE__
game = Game.new
game.play
end | true |
f6775dcc8bbf1ed2a333a207118caaa6fd99b64c | Ruby | amcritchie/g3-assessment-week-7 | /application.rb | UTF-8 | 1,274 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'sinatra/base'
require 'gschool_database_connection'
require "rack-flash"
require './lib/country_list'
require_relative "lib/message_list"
class Application < Sinatra::Application
enable :sessions
use Rack::Flash
def initialize
super
@database_connection = GschoolDatabaseConnection::DatabaseConnection.establish(ENV['RACK_ENV'])
@message_table = MessageTable.new(
GschoolDatabaseConnection::DatabaseConnection.establish(ENV["RACK_ENV"])
)
end
get '/' do
messages = @message_table.messages
erb :index, :locals => {:messages => messages}
end
post "/message" do
if params[:message] == ""
flash[:registration] = "Please enter a message before submitting."
redirect "/"
end
flash[:notice] = "Thanks for the message"
@message_table.create(params[:username],params[:message])
redirect "/"
end
get '/continents' do
all_continents = CountryList.new.continents
erb :continents, locals: { continents: all_continents }
end
get '/continents/:continent_name' do
list_of_countries = CountryList.new.countries_for_continent(params[:continent_name])
erb :countries, locals: { countries: list_of_countries, continent: params[:continent_name] }
end
end
| true |
e4cad4c287e09c3c15164a16b846005f287d6097 | Ruby | vanekpe8/MI-RUB-Homeworks | /Uloha4/lib/InputLoader.rb | UTF-8 | 2,133 | 3.625 | 4 | [] | no_license | #This module contains tools to handle input of this application. That includes parsing command line arguments or reading data file
module Input
#This class handles file reading
class InputLoader
#Creates new instance of InputLoader, given a file to read
def initialize(file)
@file = file
end
#This method could be used to determine if the input is read completely
def done?
@file.eof?
end
#Reads next line from the file. This may throw an exception when end of file is reached. To avoid this, try calling InputLoader#done? before this method.
def nextLine
@file.readline.chomp
end
end
#This class handles parsing of command line
class ArgumentsParser
#Creates new instance of ArgumentsParser and sets the encryption / decryption key to default_key value
def initialize(default_key)
@key = default_key
@show_help = false
@file = nil
@encrypt = false
end
#This method, given an array of command line arguments, parses any number of arguments and sets all class variables.
def parse(argv)
len = argv.count
if(len == 0)
@show_help = true
return
end
index = 0
begin
arg = argv[index]
if(arg == "-k" || arg == "--key")
raise 'Key value must be specified after "-k" or "--key" switch.' if(index == len-1)
@key = Integer(argv[index+1])
index = index + 1
elsif(arg == "-h" || arg == "--help")
@show_help = true
elsif(arg == "-e" || arg == "--encrypt")
@encrypt = true
else
@file = File.new(arg)
end
index = index + 1
end while(index < len)
end
#Encryption / decryption key.
attr_reader :key
#This attribute tells its caller, if the help should be shown.
attr_reader :show_help
#A text file which contents are to be decrypted (or encrypted eventualy).
attr_reader :file
#This attribute tells its caller, if the given file should be encrypted (if not, it should be decrypted).
attr_reader :encrypt
end
end
| true |
89676cfa30a39104949c4b4f16a73039275d2873 | Ruby | Trishthedish/list-implementations-cont | /lotto.rb | UTF-8 | 911 | 3.84375 | 4 | [] | no_license | require './array-list.rb'
require './linked-list.rb'
require 'awesome_print'
class Lotto
def initialize
@ticket = ArrayList.new
while @ticket.size < 5
auto_num = rand(55) + 1
if !@ticket.include?(auto_num)
@ticket.add(auto_num)
end
end
end
def display_ticket
@ticket.sort.display
end
end
# sort method are needed.
# reverse method are needed.
lotto_sim = Lotto.new
ap "Your ticket is......"
ap lotto_sim.display_ticket
# Assignment
# reverse is # 1 questions asked.
# + Let's modify `lotto.rb` so that ticket numbers are displayed in ascending order. Do this by adding `@ticket.sort` to the `display_ticket` method and add this functionality to both `array-list.rb` and `linked-list.rb`
# + Add a method `sort` to `array-list.rb`
# + Add a method `sort` to `linked-list.rb`
# + Write a method `reverse` for both `array-list.rb` and `linked-list.rb`
| true |
bcdd2c2b59ff1d9eadea2363b766c56a568a8cca | Ruby | elledouglas/Georgie | /base/generator.rb | UTF-8 | 809 | 2.84375 | 3 | [] | no_license | class Generator
def self.invoke(command)
send(command.slice(2..-1).gsub('-', '_'))
end
def self.reset_exercises
destroy_exercises
create_exercises
end
def self.destroy_exercises
Dir.glob('episode-*').each do |folder|
puts "Removing #{folder}"
FileUtils.rm_r folder
end
end
def self.create_exercises
exercises_folder = './base/exercises/.DO-NOT-LOOK-IN-THIS-FOLDER-UNLESS-YOU-WANT-THE-ANSWERS-TO-THE-EXERCISES'
Dir.glob("#{exercises_folder}/**").each do |folder|
episode_number = folder[/\d+$/]
new_episode_folder = "episode-#{episode_number}"
puts "Creating #{new_episode_folder}"
FileUtils.cp_r 'base/episode-skeleton/', new_episode_folder
FileUtils.cp_r(Dir.glob("#{folder}/*"), new_episode_folder)
end
end
end
| true |
88907c16254a596f6c0d76dcc791e5b86c989b61 | Ruby | maximkoo/ruby-repo | /api.rb | UTF-8 | 357 | 2.65625 | 3 | [] | no_license | require "Win32API"
message = "This is a sample Windows message box generated using Win32API"
title = "Win32API from Ruby"
api = Win32API.new('user32', 'MessageBox',['L', 'P', 'P', 'L'],'I')
api.call(0,message,title,0)
x1=5
x2=10
isVert=true
#puts a
puts (233+(357-353)*(231-233).fdiv(372-353)).round
puts 101/(1.85*1.85)
puts 504/18 | true |
a03c196a222df09aa4c6f8a5630ecdb2bf929b2c | Ruby | fisherman1234/cuisine | /app/models/recipe.rb | UTF-8 | 1,455 | 2.5625 | 3 | [] | no_license | class Recipe < ActiveRecord::Base
require 'open-uri'
require "net/http"
require "uri"
attr_accessible :difficulty, :preparation_time, :price, :cooking_time, :selection_id, :rating, :title, :instructions, :dish_type, :cost , :is_vegetarian , :picture_url , :marmiton_id, :ingredients
belongs_to :marmiton_selection, :foreign_key => :selection_id
def fetch
url = "http://m.marmiton.org/webservices/json.svc/GetRecipeById?SiteId=1&appversion=mmtiphfrora&RecipeId=#{marmiton_id}"
http_get = Net::HTTP.get(URI.parse(url))
puts url
JSON.parse(http_get)
end
def page_url
fetch["data"]["items"].first["pageURL"]
end
def import
data = fetch["data"]["items"].first
self.difficulty = data["difficulty"]
self.preparation_time=data["preparationTime"].match(/(\d*)/)[1]
self.cost = data["cost"]
self.cooking_time=data["cookingTime"].match(/(\d*)/)[1]
self.rating=data["rating"]
self.instructions=data["preparationList"]
if self.instructions.nil?
self.instructions = data["text"]
end
self.is_vegetarian = data["isVegetarian"]
self.picture_url= data["pictures"].first["url"] if data["pictures"].first
self.ingredients= data["ingredientList"]
self.save!
end
def self.import_all
Recipe.where("instructions is null").each do |recipe|
recipe.import
sleep_time = rand(5)
puts "sleeps for #{sleep_time}"
sleep sleep_time
end
end
end | true |
24a2546680db9c242e811c0220d932a2708d8e34 | Ruby | meh9184/coding-test-practice | /myrealtrip/practice.rb | UTF-8 | 905 | 4.46875 | 4 | [] | no_license | arr = [2,4,7,2,5]
# input / output
intput = gets.chomp()
puts intput
# if
if arr.length % 2 == 1
puts '홀수 개'
elsif arr.length % 2 == 0
puts '짝수 개'
else
puts '있을 수 없는 경우'
end
# for
for i in 0...5
puts "#{i}번째 값 = #{arr[i]}"
end
# while
i=0
while i < arr.length
puts "#{i}번째 값 = #{arr[i]}"
i += 1
end
# each
arr.each do |a|
puts "#{a}"
end
# map
arr2 = arr.map {|a|
a + 1
}
puts arr2
# inject
grades = [88,99,73,56,87,64]
sum = grades.inject do |stock, grade|
stock + grade
end
average = sum / grades.length
puts average
# include
str = 'eunhwan moon'
puts str.include? 'moon'
# 대문자 변환
str = 'eunhwan moon'
for i in 0...str.length
str[i] = str[i].upcase
end
puts str
# int <-> string
str = '123'
int = 123
puts str.to_i + 123
puts int.to_s + '123' | true |
d945bcd102ceb5ffff471a2d50e66ebed73e2557 | Ruby | sQilver/gizma | /test_script.rb | UTF-8 | 2,799 | 2.640625 | 3 | [] | no_license | require './initialize'
binding.pry
# options = Selenium::WebDriver::Firefox::Options.new(args: ['-headless'])
# driver = Selenium::WebDriver.for :firefox, options: options
# binding.pry
# driver.navigate.to 'https://www.youtube.com/feed/trending'
# binding.pry
# first_line_text = driver.find_element(xpath: "(//yt-formatted-string[@class='style-scope ytd-video-renderer'])[1]").text
# two_line_text = driver.find_element(xpath: "(//yt-formatted-string[@class='style-scope ytd-video-renderer'])[3]").text
# three_line_text = driver.find_element(xpath: "(//yt-formatted-string[@class='style-scope ytd-video-renderer'])[5]").text
# for_line_text = driver.find_element(xpath: "(//yt-formatted-string[@class='style-scope ytd-video-renderer'])[7]").text
# five_line_text = driver.find_element(xpath: "(//yt-formatted-string[@class='style-scope ytd-video-renderer'])[9]").text
# old_positions = $youtube_positions[:old_positions]
# binding.pry
# # message_sender.send_for_users("New 1 youtube position: #{first_line_text}") unless old_positions.include?(first_line_text)
# # message_sender.send_for_users("New 2 youtube position: #{two_line_text}") unless old_positions.include?(two_line_text)
# # message_sender.send_for_users("New 3 youtube position: #{three_line_text}") unless old_positions.include?(three_line_text)
# # message_sender.send_for_users("New 4 youtube position: #{for_line_text}") unless old_positions.include?(for_line_text)
# # message_sender.send_for_users("New 5 youtube position: #{five_line_text}") unless old_positions.include?(five_line_text)
# $youtube_positions[1] = first_line_text
# $youtube_positions[2] = two_line_text
# $youtube_positions[3] = three_line_text
# $youtube_positions[4] = for_line_text
# $youtube_positions[5] = five_line_text
# puts "youtube first_line_text- #{first_line_text}"
# puts "youtube two_line_text- #{two_line_text}"
# puts "youtube three_line_text- #{three_line_text}"
# puts "youtube for_line_text- #{for_line_text}"
# puts "youtube five_line_text- #{five_line_text}"
# $youtube_positions[:old_positions] << first_line_text unless $youtube_positions[:old_positions].include?(first_line_text)
# $youtube_positions[:old_positions] << two_line_text unless $youtube_positions[:old_positions].include?(two_line_text)
# $youtube_positions[:old_positions] << three_line_text unless $youtube_positions[:old_positions].include?(three_line_text)
# $youtube_positions[:old_positions] << for_line_text unless $youtube_positions[:old_positions].include?(for_line_text)
# $youtube_positions[:old_positions] << five_line_text unless $youtube_positions[:old_positions].include?(five_line_text)
# $youtube_positions = { a: 1, b: 2, c: 3 }
# YmlManager.new.load_youtube_positions
# YmlManager.new.save_youtube_positions
| true |
0874ce72376cc0aa0d18d0382ee4cfc5ff1dadb5 | Ruby | noahfeder/shootings_db | /app/controllers/people_controller.rb | UTF-8 | 1,006 | 2.5625 | 3 | [] | no_license | class PeopleController < ApplicationController
def index
build_query(params)
people = Person.where(@query).order(@order)
render json: people
end
private
def build_query(params)
return nil if !params || params.keys.length == 0
@query = {}
params.each do |key, value|
@query[key] = value if validQuery?(key)
end
if params[:date_min] || params[:date_max]
@query[:date] = ( (params[:date_min] || Time.new(2000))..(params[:date_max] || Time.now) )
end
if params[:age_min] || params[:age_max]
@query[:age] = ( (params[:age_min] ? params[:age_min].to_i : 0)..(params[:age_max] ? params[:age_max].to_i : 1000) )
end
@order = validQuery?(params[:order]) ? params[:order] : ''
end
def validQuery?(key)
valid = ['name', 'age', 'gender', 'race', 'image_url', 'date', 'street', 'city', 'state', 'zip', 'county', 'agency', 'cause', 'disposition', 'charges', 'link_url', 'mental_illness', 'armed']
valid.include?(key)
end
end
| true |
116276fb1a47eaaa4ba57d7cddecad542d165351 | Ruby | MONAKA0721/cookpad-internship-2020-summer-pbl | /app/models/ingredient.rb | UTF-8 | 999 | 2.90625 | 3 | [] | no_license | class Ingredient < ApplicationRecord
MAX_NAME_LENGTH = 255
MAX_QUANTITY_LENGTH = 255
belongs_to :recipe
validates :name, presence: true, length: { maximum: MAX_NAME_LENGTH }
validates :quantity, presence: true, length: { maximum: MAX_QUANTITY_LENGTH }
def group_1
['ごはん', 'パン', 'じゃがいも', 'うどん']
end
def group_2
['りんご', 'すいか', 'みかん', '柿', 'バナナ']
end
def group_3
['たこ', '卵', '肉', 'チーズ', '大豆']
end
def group_4
['牛乳', 'ヨーグルト']
end
def group_5
['マヨネーズ', 'ベーコン', 'ピーナッツ']
end
def group_6
['大根', 'ねぎ', 'もやし']
end
def nutrition
[group_1, group_2, group_3, group_4, group_5, group_6].each_with_index do |group, index|
if group.include?(name)
return index, 1
end
end
return 6, 1
end
end
| true |
75c9483667050109f2fd3a3d53e237d66538fed0 | Ruby | tohyongcheng/ga-examples | /day1/hashes_ex1.rb | UTF-8 | 183 | 3.546875 | 4 | [] | no_license | h = {0 => "Zero", 1 => "One", :two => "Two", "two" => 2}
# 1
h[1]
#2
h[:two]
#3
h["two"]
#4
h[3] = "Three"
#5
h[:four] = 4
is = {true => "It's true!", false => "It's false"} | true |
7fbe4cc2a6e62c383efc598f777d6f337fd45cf0 | Ruby | jamesscalise/key-for-min-value-online-web-pt-081219 | /key_for_min.rb | UTF-8 | 371 | 3.546875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
mKey = nil
mValue = nil
name_hash.each{|key, value|
if mKey
if value < mValue
mKey = key
mValue = value
end
else
mKey = key
mValue = value
end
}
mKey
end | true |
4ba1fe0372a6669c910fb8b4e447bd1c1ea62e33 | Ruby | tsubasa00119/ruby_lesson | /index.rb | UTF-8 | 929 | 3.625 | 4 | [] | no_license | #料理注文サービス
require "./food"
require "./drink"
require "date"
puts "名前を入力してください"
name = gets.chomp
puts "#{name}さん、いらっしゃいませ"
puts "メニューはこちらです"
food1 = Food.new(name: "ピザ", price: 800,calorie:700)
food2 = Food.new(name: "すし", price: 1000,calorie:600)
drink1 = Drink.new(name:"コーラ",price:300,amount:400)
drink2 = Drink.new(name:"お茶",price:200,amount:500)
menus = [food1,food2,drink1,drink2]
index = 0
menus.each do |menu|
puts "#{index}.#{menu.info}"
index += 1
end
puts "-----------"
puts "メニュー番号を選択してください"
order = gets.chomp.to_i
selected_menu = menus[order]
puts "選択されたメニュー:#{selected_menu.name}"
puts "個数を入力してください(3つ以上で100円引き)"
count = gets.chomp.to_i
puts "お会計は#{selected_menu.get_total_price(count)}円です"
| true |
d86e6a622e9bb32a4d9b680cc78f59f764f893ea | Ruby | ali/Euler | /Euler-18.rb | UTF-8 | 1,935 | 4.0625 | 4 | [] | no_license | # Project Euler - Problem #18 (and #67)
# Solved by Ali Ukani on Jan 1, 2012
# By starting at the top of the triangle below and moving to adjacent numbers on the row below, find the maximum total from top to bottom of a given triangle.
# http://projecteuler.net/problem=18
# http://projecteuler.net/problem=67
# This solution works for both problems #18 and #67. I decided that in order to run this you need to either give it file (Euler-18.txt or Euler-67.txt in this repository) or the argument "example".
require "test/unit"
@example = [[3],
[7, 4],
[2, 4, 6],
[8, 5, 9, 3]]
# Returns the larger of two integers
def max (a, b)
if (a > b)
return a
else
return b
end
end
assert_equal(max(1, 0), 1)
assert_equal(max(0, 1), 1)
assert_equal(max(1, 1), 1)
# Returns the largest sum of any path of a triangle
def solve (triangle = example)
t = triangle
2.upto(t.size) do |o|
r = t.size - o
0.upto(t[r].size - 1) do |c|
t[r][c] += max(t[r+1][c], t[r+1][c+1])
end
end
return t[0][0]
end
# Reads a file as a triangle
def read (file)
if (!File.exist?(file))
puts "File #{file} does not exist."
end
triangle = []
f = File.new(file)
f.each do |line|
triangle << line.strip.split(" ").collect{|i| i.to_i}
end
return triangle
end
# Runs the program
def main (args)
if args.empty?
puts "I need a local text file as an argument."
puts "For example, try downloading this file and passing the filename as an argument:\n\thttp://projecteuler.net/project/triangle.txt"
puts "Then type: ruby Euler-18.rb triangle.txt'"
puts "Or, if you want to see an example, type:\n\truby Euler-18.rb example"
elsif args[0] == "example"
# Example mode outputs the example triangle.
width = @example.last.size * 2 - 1
@example.each do |line|
puts line.join(" ").center(width)
end
puts "\nMax sum: #{solve(@example)}"
else
triangle = read(args[0])
puts solve(triangle)
end
end
main(ARGV) | true |
5008a42f7e5deafd7ab703a554b4b3ddc0651d80 | Ruby | CepCap/ThinkneticaRuby | /lesson6/passengers_train.rb | UTF-8 | 430 | 2.921875 | 3 | [] | no_license | require_relative 'train'
require_relative 'cargo_wagon'
require_relative 'passengers_wagon'
class PassengersTrain < Train
def hook_wagon(wagon)
if wagon.is_a? PassengersWagon
super
else
puts "Вагон не пассажирский."
end
end
def unhook_wagon(wagon)
if wagon.is_a? PassengersWagon
super
else
puts "Вагон не пассажирский."
end
end
end | true |
06c00294374935d614965fab88e08deb42b051e6 | Ruby | ayva/prep_ruby_challenges | /overlap.rb | UTF-8 | 248 | 2.96875 | 3 | [] | no_license | def overlap(r1,r2)
return false if r1[0][0] >= r2[1][0] || r2[0][0] >= r1[1][0]
return false if r1[0][1] >= r2[1][1] || r2[0][1] >= r1[1][1]
return true
end
#overlap([[0,0],[3,3]],[[1,1],[4,5]])
#overlap([ [0,0],[1,4] ], [ [1,1],[3,2] ])
| true |
eb39e91495fbf87bdf9d1bd410f335e82f1d5e96 | Ruby | srikaanthtb/bank_tech_test | /lib/bank_account.rb | UTF-8 | 1,205 | 3.578125 | 4 | [] | no_license | # frozen_string_literal: true
require_relative './transaction'
require_relative './bank_statement'
class Bankaccount
attr_reader :transactions, :balance
def initialize(statement = Bankstatement.new, transaction = Transaction)
@transactions = []
@balance = 0
@statement = statement
@transaction = transaction
end
def deposit(amount)
raise "You cannot deposit a negative amount" if amount < 0
increase_balance(amount)
credit = create_credit(amount)
save(credit)
end
def withdraw(amount)
raise "You cannot withdraw a negative amount" unless amount.positive?
raise "You do not have sufficent funds" if @balance < amount
decrease_balance(amount)
debit = create_debit(amount)
save(debit)
end
def summary
@statement.print(@transactions)
end
private
def create_credit(amount)
@transaction.new(0, amount, @balance)
end
def create_debit(amount)
@transaction.new(amount, 0, @balance)
end
def save(transaction)
@transactions << transaction
end
def increase_balance(amount)
@balance += amount
end
def decrease_balance(amount)
@balance -= amount
end
end
| true |
83f09b335683f80baf2547f84af0cbb952f09844 | Ruby | id774/sandbox | /ruby/machine-learning/recommendation/recommendations.rb | UTF-8 | 6,120 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
require 'awesome_print'
def critics
{
'Lisa Rose' => {
'Lady in the Water' => 2.5,
'Snake on the Plane' => 3.5,
'Just My Luck' => 3.0,
'Superman Returns' => 3.5,
'You, Me and Dupree' => 2.5,
'The Night Listener' => 3.0
},
'Gene Seymour' => {
'Lady in the Water' => 3.0,
'Snake on the Plane' => 3.5,
'Just My Luck' => 1.5,
'Superman Returns' => 5.0,
'The Night Listener' => 3.0,
'You, Me and Dupree' => 3.5
},
'Michael Phillips' => {
'Lady in the Water' => 2.5,
'Snake on the Plane' => 3.0,
'Superman Returns' => 3.5,
'The Night Listener' => 4.0
},
'Claudia Puig' => {
'Snake on the Plane' => 3.5,
'Just My Luck' => 3.0,
'The Night Listener' => 4.5,
'Superman Returns' => 4.0,
'You, Me and Dupree' => 2.5
},
'Mick LaSalle' => {
'Lady in the Water' => 3.0,
'Snake on the Plane' => 4.0,
'Just My Luck' => 2.0,
'Superman Returns' => 3.0,
'The Night Listener' => 3.0,
'You, Me and Dupree' => 2.0
},
'Jack Matthews' => {
'Lady in the Water' => 3.0,
'Snake on the Plane' => 4.0,
'The Night Listener' => 3.0,
'Superman Returns' => 5.0,
'You, Me and Dupree' => 3.5
},
'Toby' => {
'Snake on the Plane' => 4.5,
'You, Me and Dupree' => 1.0,
'Superman Returns' => 4.0
},
}
end
def critics_ja
{
'山田' => {
'カレー' => 2.5,
'ラーメン' => 3.5,
'チャーハン' => 3.0,
'寿司' => 3.5,
'牛丼' => 2.5,
'うどん' => 3.0
},
'田中' => {
'カレー' => 3.0,
'ラーメン' => 3.5,
'チャーハン' => 1.5,
'寿司' => 5.0,
'うどん' => 3.0,
'牛丼' => 3.5
},
'佐藤' => {
'カレー' => 2.5,
'ラーメン' => 3.0,
'寿司' => 3.5,
'うどん' => 4.0
},
'中村' => {
'ラーメン' => 3.5,
'チャーハン' => 3.0,
'うどん' => 4.5,
'寿司' => 4.0,
'牛丼' => 2.5
},
'川村' => {
'カレー' => 3.0,
'ラーメン' => 4.0,
'チャーハン' => 2.0,
'寿司' => 3.0,
'うどん' => 3.0,
'牛丼' => 2.0
},
'鈴木' => {
'カレー' => 3.0,
'ラーメン' => 4.0,
'うどん' => 3.0,
'寿司' => 5.0,
'牛丼' => 3.5
},
'下林' => {
'ラーメン' => 4.5,
'牛丼' => 1.0,
'寿司' => 4.0
},
}
end
def sim_distance(prefs, person1, person2)
shared_items_a = shared_items_a(prefs, person1, person2)
return 0 if shared_items_a.size == 0
sum_of_squares = shared_items_a.inject(0) {|result, item|
result + (prefs[person1][item]-prefs[person2][item])**2
}
return 1/(1+sum_of_squares)
end
def sim_pearson(prefs, person1, person2)
shared_items_a = shared_items_a(prefs, person1, person2)
n = shared_items_a.size
return 0 if n == 0
sum1 = shared_items_a.inject(0) {|result,si|
result + prefs[person1][si]
}
sum2 = shared_items_a.inject(0) {|result,si|
result + prefs[person2][si]
}
sum1_sq = shared_items_a.inject(0) {|result,si|
result + prefs[person1][si]**2
}
sum2_sq = shared_items_a.inject(0) {|result,si|
result + prefs[person2][si]**2
}
sum_products = shared_items_a.inject(0) {|result,si|
result + prefs[person1][si]*prefs[person2][si]
}
num = sum_products - (sum1*sum2/n)
den = Math.sqrt((sum1_sq - sum1**2/n)*(sum2_sq - sum2**2/n))
return 0 if den == 0
return num/den
end
def top_matches(prefs, person, n=5, similarity=:sim_pearson)
scores = Array.new
prefs.each do |key,value|
if key != person then
scores << [__send__(similarity,prefs,person,key),key]
end
end
scores.sort.reverse[0,n]
end
def get_recommendations(prefs, person, similarity=:sim_pearson)
totals_h = Hash.new(0)
sim_sums_h = Hash.new(0)
prefs.each do |other,val|
next if other == person
sim = __send__(similarity,prefs,person,other)
next if sim <= 0
prefs[other].each do |item, val|
if !prefs[person].keys.include?(item) || prefs[person][item] == 0 then
totals_h[item] += prefs[other][item]*sim
sim_sums_h[item] += sim
end
end
end
rankings = Array.new
totals_h.each do |item,total|
rankings << [total/sim_sums_h[item], item]
end
rankings.sort.reverse
end
def transform_prefs(prefs)
result = Hash.new
prefs.each do |person,score_h|
score_h.each do |item,score|
result[item] ||= Hash.new
result[item][person] = score
end
end
result
end
def shared_items_a(prefs, person1, person2)
prefs[person1].keys & prefs[person2].keys
end
def test_critics
puts "critics"
ap critics
puts "sim_distance(critics, 'Lisa Rose', 'Gene Seymour')"
ap sim_distance(critics, 'Lisa Rose', 'Gene Seymour')
puts "sim_pearson(critics, 'Lisa Rose', 'Gene Seymour')"
ap sim_pearson(critics, 'Lisa Rose', 'Gene Seymour')
puts "top matches of Toby"
ap top_matches(critics, 'Toby')
puts "get recommendations of Toby"
ap get_recommendations(critics, 'Toby')
puts "top matches of 'Superman Returns'"
movies = transform_prefs(critics)
ap top_matches(movies, 'Superman Returns')
end
def test_critics_ja
puts "元のテストデータ"
ap critics_ja
puts "'山田', '田中' がどれくらい似ているか (distance)"
ap sim_distance(critics_ja, '山田', '田中')
puts "'山田', '田中' がどれくらい似ているか (pearson)"
ap sim_pearson(critics_ja, '山田', '田中')
puts "下林に似ているユーザー"
ap top_matches(critics_ja, '下林')
puts "下林におすすめのメニュー"
ap get_recommendations(critics_ja, '下林')
puts "寿司に似ているメニュー"
movies = transform_prefs(critics_ja)
ap top_matches(movies, '寿司')
end
if $0 == __FILE__ then
test_critics_ja
end
| true |
c85fef10ecbdcf6a3e5f4e893c2f47a15a367f78 | Ruby | Rayxan/Programming_UNB | /Software Engeneer/Homework1(answer to get ass example)/Homework1/Part6/part6b.rb | UTF-8 | 213 | 3.0625 | 3 | [] | no_license | class String
def palindrome?
string = self
string = string.downcase().gsub!(/\W+/i, '')
return string.reverse() == string
end
end
puts "Sator Arepo, tenet OpEra Rotas".palindrome?
| true |
149fdb21b02c684bea134cdf7883d4b926969e3f | Ruby | coderschool/advanced_ruby_lab_1 | /todo_m8.rb | UTF-8 | 2,321 | 3.84375 | 4 | [] | no_license | class Todo
include Enumerable
attr_reader :title, :tasks
def initialize(title)
@title = title
@tasks = []
end
def add_task(task)
@tasks << task
end
def each(&block)
@tasks.each(&block)
end
end
class Task
attr_reader :name
def initialize(name)
@name = name
end
# an empty default for a subclass to implement
def get_time_required
0 # number of minutes
end
def total_number_basic_tasks
1
end
end
class ReadingTask < Task
def initialize(name = nil)
super(name || 'Read the task out loud')
end
def get_time_required
1
end
end
class CodingTask < Task
def initialize
super('Coding')
end
def get_time_required
15
end
end
class ProofingTask < Task
def initialize
super("Double check to make sure things look good")
end
def get_time_required
5
end
end
class CompositeTask < Task
def initialize(name)
super(name)
@sub_tasks = []
end
def add_sub_task(task)
@sub_tasks << task
end
def remove_sub_task(task)
@sub_tasks.delete(task)
end
def get_time_required
@sub_tasks.map(&:get_time_required).reduce(0, :+)
end
def [](index)
@sub_tasks[index]
end
def []=(index, task)
@sub_tasks[index] = task
end
def <<(task)
add_sub_task(task)
end
def total_number_basic_tasks
@sub_tasks.map(&:total_number_basic_tasks).reduce(0, :+)
end
end
class MilestoneTask < CompositeTask
def initialize(name)
super(name)
add_sub_task ReadingTask.new
add_sub_task CodingTask.new
add_sub_task ProofingTask.new
end
end
todo = Todo.new "Lab 1"
todo.add_task MilestoneTask.new("Milestone 8")
todo.add_task Task.new("Discuss with my partner")
todo.add_task Task.new("Ask the instructor some questions")
todo.add_task ReadingTask.new("Look up the any? method")
puts "Are any composite tasks? %s" % todo.any? {|task| task.total_number_basic_tasks > 1}
puts "Any complex tasks in #{todo.title}: %s" % todo.select {|task| task.total_number_basic_tasks > 1}.map(&:name)
puts "Loop all tasks by todo.each:"
# print all tasks
todo.each do |task|
puts "- #{task.name}"
end
puts "Look for easy tasks based on time required:"
todo.group_by(&:get_time_required).each do |key, tasks|
puts "%4s minutes: %s" % [ key, tasks.map(&:name).join(', ') ]
end
| true |
fea1984eea768057dcea10cdbda3712b0c53b254 | Ruby | AlexFrz/ruby-peerprog | /exo_21.rb | UTF-8 | 182 | 3.21875 | 3 | [] | no_license | puts "Salut, bienvenue dans ma super pyramide ! Combien d'étages veux-tu ?"
n = gets.chomp
a = 1
while a.to_i <= n.to_i
puts ("*" * a.to_i).rjust(n.to_i)
a = a.to_i + 1
end | true |
61edb47ad363e68fb995300a19c5176e59c1e3d8 | Ruby | microverse-projects/advanced-building-blocks | /enumerable_methods/lib/enumerable_methods.rb | UTF-8 | 818 | 3.5 | 4 | [] | no_license | # Enumerable module
module Enumerable
def my_each
for i in self
yield(i)
end
self
end
def my_each_with_index
(0..length - 1).my_each do |x|
yield(self[x], x)
end
self
end
def my_select
arr = []
my_each do |x|
arr << x if yield(x)
end
arr
end
def my_all?
status = true
my_each do |x|
return !status unless yield(x)
end
status
end
def my_any?
status = false
my_each do |x|
return !status if yield(x)
end
status
end
def my_none?
status = true
my_each do |x|
return !status if yield(x)
end
status
end
def my_count
n = 0
my_each { n += 1 }
n
end
def my_inject(memo = self[0])
my_each do |x|
memo = yield(memo, x)
end
memo
end
end
| true |
967abc32f3cab493da98696869982e541c3b5079 | Ruby | oneortwo/windchecker | /lib/image_picker.rb | UTF-8 | 527 | 3.046875 | 3 | [] | no_license | class ImagePicker
def pick(path)
sanity_check(path)
images = get_images(path)
return images.sample
end
def get_images(path)
images = Dir.entries(path)
images.delete_if { |x| x == '.' }
images.delete_if { |x| x == '..' }
images.delete_if { |x| x == '.DS_Store'}
images.delete_if { |x| x == '.git'}
raise 'directory is empty ' + path if images.length == 0
return images
end
def sanity_check(path)
raise 'directory not found ' + path if not File.directory?(path)
end
end
| true |
a986d2a24a7ac6b8b8a026ddf7905539bfda8531 | Ruby | sato11/everystudy | /twitter_migrator/main.rb | UTF-8 | 344 | 2.6875 | 3 | [] | no_license | require 'twitter'
require 'dotenv'
require 'forwardable'
require './client.rb'
require './app.rb'
app = App.new
f, n = app.f, app.n
loop do
app.menu
input = gets.chomp.to_i
puts # return
case input
when 1
app.list_friends(f)
when 2
app.list_friends(n)
when 3
break
else
puts app.send(:not_supported)
end
end
| true |
9c438323f6670ad10d5f4807d94535a6c97fe220 | Ruby | bother7-learn/playlister-sinatra-web-071717 | /app/models/artist.rb | UTF-8 | 364 | 2.71875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Artist < ActiveRecord::Base
has_many :songs
has_many :song_genres, through: :songs
has_many :genres, through: :song_genres
def slug
string = self.name.downcase
string.gsub!(/[()!@%&"]/,'')
array = string.split(" ")
array.join("-")
end
def self.find_by_slug(string)
self.all.find {|instance| instance.slug == string}
end
end
| true |
daf502159ebc8ad532484739940591163a8e91c7 | Ruby | xDD-CLE/katas | /langstons_ant/samjones/lib/grid_navigable.rb | UTF-8 | 282 | 2.90625 | 3 | [] | no_license | module GridNavigable
attr_accessor :x, :y
def at(x, y)
self.x=x
self.y=y
self
end
def move_direction!(direction)
public_send(direction)
end
def north
self.y = y-1
end
def south
self.y = y+1
end
def east
self.x = x+1
end
def west
self.x = x-1
end
end
| true |
78b6160310edba2107d9c81a48b16961fe16c082 | Ruby | Buzonxxxx/ruby-practice | /Collections/array-2.rb | UTF-8 | 319 | 2.640625 | 3 | [] | no_license | #join
clients = ["iOS", "Android", "BE", "Web", "iOS Web"]
p clients
p clients.join(',')
p clients.join('-')
p clients.join('&')
#push\pop
#push on item
p clients.push("WebTV")
#multiple push
p clients.push("auHikari", "Chromecast")
#pop one item
p clients.pop
p clients
#pop last two items
p clients.pop(2)
p clients | true |
333ac295d0a6cdfe8a8145f1825493a9d84907ab | Ruby | halogenandtoast/alchemist | /lib/alchemist.rb | UTF-8 | 1,263 | 2.578125 | 3 | [
"MIT"
] | permissive | require "alchemist/conversion_table"
require "alchemist/measurement"
require "alchemist/compound_measurement"
require "alchemist/module_builder"
require "alchemist/configuration"
require "alchemist/library"
require "alchemist/conversion_calculator"
module Alchemist
autoload :Earth, "alchemist/objects/planets/earth"
class IncompatibleTypeError < StandardError ; end
class GeospatialArgumentError < StandardError ; end
def self.setup(category = nil)
if category
load_category category
else
load_all_categories
end
end
def self.measure(value, unit, exponent = 1.0)
Measurement.new(value, unit, exponent)
end
def self.measure_prefixed(value, prefix, unit)
exponent = library.exponent_for(unit, prefix)
Measurement.new(value, unit, exponent, prefix: prefix)
end
def self.library
@library ||= Library.new
end
def self.config
@configuration ||= Configuration.new
end
def self.register(types, names, value)
library.register(types, names, value)
end
def self.reset!
@library = nil
@configuration = nil
end
private
def self.load_all_categories
library.load_all_categories
end
def self.load_category(category)
library.load_category(category)
end
end
| true |
e760e124d520fb3e461b59a3a1b26c88576b7000 | Ruby | concos/Ruby-Exercises- | /Ruby_Assignments.rb | UTF-8 | 622 | 4.0625 | 4 | [] | no_license | arr = [1,2,3,4,5,6,7,8,9,10]
arr.each {|x| puts x}
arr.each do |x|
if x >= 5
puts x
end
end
arr.select do |y|
if y % 2 != 0
puts y
end
end
arr << 11
puts arr
arr.unshift(0)
puts arr
arr.uniq
puts arr
# An array is an ordered type integer indexed collection of objects
# A hash is an unordered object indexed collection of objects (or key vale pairs)
hash_8 = {'age' => 3, 'gender' => 'male' }
puts hash_8
hash_9 = {age: 3, gender: 'male'}
puts hash_9
h = {a:1, b:2, c:3, d:4}
h[:b]
h[:e] = 5
puts h
h.delete_if do |k,v|
v < 3.5
end
puts h
h[:yes] = [1,2,3]
puts h
a = [{}, {}, {}]
| true |
800f6b38e566fae78ae1ef821e7488ca11b84f18 | Ruby | a-chaudhari/ruby1459 | /handlers/nickname.rb | UTF-8 | 658 | 2.515625 | 3 | [] | no_license | def ERR_NICKNAMEINUSE(chunks, raw)
@nickname += '_'
self.write("NICK #{@nickname}")
emit(:self_new_nickname, @nickname)
end
def NICK(chunks, raw)
old_nick = chunks[0].split('!', 2).first
new_nick = chunks[2]
command = {
from: old_nick,
to: new_nick
}
if old_nick == @nickname
@nickname = new_nick
emit(:self_new_nickname, command)
else
@channels.values.each do |chan|
users = chan.users
if users.keys.include?(old_nick)
users.delete(old_nick)
users.merge!(nick_hash(new_nick))
end
chan._recv(:userlist_changed, nil)
chan._recv(:new_nickname, command)
end
end
end
| true |
a632d6e5aad55f4d6527110a0e0413ac63559abe | Ruby | Dizney23/oop_bank_account | /bank_account.rb | UTF-8 | 598 | 3.609375 | 4 | [] | no_license | class BankAccount
@balance = nil
def initialize(balance, name)
@balance = balance
if balance <= 200
raise ArgumentError.new "Error:Did not meet min balance!"
end
end
def balance
@balance
end
def deposit(deposit_amt)
@balance += deposit_amt
end
def withdraw(withdraw_amt)
@balance -= withdraw_amt
end
def transfer(transfer_amt, bank_account)
@balance -= transfer_amt
bank_account.deposit(transfer_amt)
end
def self.minimum_balance=(minimum_balance)
@@minimum_balance = minimum_balance
end
def self.minimum_balance
@@minimum_balance
end
end
| true |
307ce00da1d48d356eadddaf951505aa783df6ff | Ruby | IQ-SCM/switchboard | /bin/switchboard | UTF-8 | 738 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env ruby -rubygems
require 'switchboard'
require 'switchboard/commands'
require 'optparse'
ARGV.clone.options do |opts|
# opts.banner = "Usage: example.rb [options]"
command = Switchboard::Commands::Default
command.options(opts)
cmd = []
argv = []
# force optparse into being a command parser
opts.order! do |arg|
cmd << arg
if c = Switchboard::COMMANDS[cmd * "_"]
command = c
command.options(opts)
elsif c = Switchboard::COMMANDS["_" + cmd * "_"]
command = c
else
# unrecognized, unclaimed argument; keep as ARGV
argv << arg
end
end
# correct ARGV to match unrecognized, unclaimed arguments
ARGV.reject! { |v| !argv.include?(v) }
command
end.run!
| true |
0b2ade867fad28912e6ecbdf5a981a6d225ba3fb | Ruby | manheim/backupsss | /lib/backupsss.rb | UTF-8 | 2,450 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'aws-sdk'
require 'rufus-scheduler'
require 'backupsss/tar'
require 'backupsss/backup'
require 'backupsss/backup_dir'
require 'backupsss/backup_bucket'
require 'backupsss/janitor'
require 'backupsss/version'
require 'backupsss/configuration'
# A utility for backing things up to S3.
module Backupsss
# A Class for running this backup utility
class Runner
attr_accessor :config
def initialize
@config = Backupsss::Configuration.new
end
def run
config.backup_freq ? run_scheduled : run_oneshot
end
private
def call
push_backup(*prep_for_backup)
cleanup_local
cleanup_remote
end
def prep_for_backup
filename = "#{Time.now.to_i}.tar"
backup = Backupsss::Backup.new(
{
s3_bucket_prefix: config.s3_bucket_prefix,
s3_bucket: config.s3_bucket,
filename: filename
}, Aws::S3::Client.new(region: config.aws_region)
)
[filename, backup]
end
def push_backup(filename, backup)
puts 'Create and Upload Tar: Starting'
backup.put_file(
Backupsss::Tar.new(
config.backup_src_dir,
"#{config.backup_dest_dir}/#{filename}"
).make
)
puts 'Create and Upload Tar: Finished'
end
def cleanup_local
local_janitor = Janitor.new(
driver: BackupDir.new(dir: config.backup_dest_dir)
)
local_janitor.rm_garbage(local_janitor.sift_trash)
end
def cleanup_remote
remote_janitor = Janitor.new(
driver: BackupBucket.new(
dir: "#{config.s3_bucket}/#{config.s3_bucket_prefix}",
region: config.aws_region
),
retention_count: config.remote_retention
)
remote_janitor.rm_garbage(remote_janitor.sift_trash)
end
def run_scheduled
$stdout.puts "Schedule provided, running with #{config.backup_freq}"
scheduler = Rufus::Scheduler.new
scheduler.cron(config.backup_freq, blocking: true) { make_call }
scheduler.join
end
def run_oneshot
$stdout.puts 'No Schedule provided, running one time task'
make_call
end
def make_call
call
rescue => exc
error_message =
"ERROR - backup failed: #{exc.message}\n#{exc.backtrace.join("\n\t")}"
if config.backup_freq
$stderr.puts error_message
else
abort(error_message)
end
end
end
end
| true |
1a74a4552a6f17e1e54a5441bca84ad2700c3b9d | Ruby | csaunders/citation | /model/tag.rb | UTF-8 | 496 | 2.671875 | 3 | [] | no_license | class Tag < Sequel::Model
set_schema do
primary_key :id
String :name
index :name
end
create_table unless table_exists?
def self.normalize(tag)
tag.strip.downcase
end
def self.find_or_create_missing(tags)
tags = tags.sort.uniq
entries = order(:name).where(name: tags).all
tags.map do |tag|
entry = entries.shift
if entry.nil? || entry.name != tag
entry = new(name: tag).save
entry.save
end
entry
end
end
end
| true |
f7ccde806ab415334937a726624af87318bbb3f7 | Ruby | clearwater-rb/bowser | /opal/bowser/event_target.rb | UTF-8 | 1,346 | 3.078125 | 3 | [
"MIT"
] | permissive | require 'bowser/event'
module Bowser
module EventTarget
# Add the block as a handler for the specified event name. Will use either
# `addEventListener` or `addListener` if they exist.
#
# @param event_name [String] the name of the event
# @return [Proc] the block to pass to `off` to remove this handler
# @yieldparam event [Bowser::Event] the event object
def on event_name, &block
wrapper = proc { |event| block.call Event.new(event) }
if `#@native.addEventListener !== undefined`
`#@native.addEventListener(event_name, wrapper)`
elsif `#@native.addListener !== undefined`
`#@native.addListener(event_name, wrapper)`
else
warn "[Bowser] Not entirely sure how to add an event listener to #{self}"
end
wrapper
end
# Remove an event handler
#
# @param event_name [String] the name of the event
# @block the handler to remove, as returned from `on`
def off event_name, &block
if `#@native.removeEventListener !== undefined`
`#@native.removeEventListener(event_name, block)`
elsif `#@native.removeListener !== undefined`
`#@native.removeListener(event_name, block)`
else
warn "[Bowser] Not entirely sure how to remove an event listener from #{self}"
end
nil
end
end
end
| true |
a916f99fca4157241100c6d3031ed28101ef2360 | Ruby | jacooobi/university_projects | /Algorytmy i Struktury Danych/Sorting/lib/merge_sort.rb | UTF-8 | 452 | 3.515625 | 4 | [] | no_license | require_relative 'shared'
def merge_sort(arr)
return false unless array_of_numbers?(arr)
return arr if arr.size <= 1
left = merge_sort arr[0, arr.size / 2]
right = merge_sort arr[arr.size / 2, arr.size]
merge(left, right)
end
def merge(left, right)
res = []
while left.size > 0 and right.size > 0
if left[0] <= right[0]
res << left.shift
else
res << right.shift
end
end
res.concat(left).concat(right)
end | true |
d7f69b108e4cf6a399fc6d6c41b02d576f47c180 | Ruby | BJSummerfield/brighton_scrape | /brighton.rb | UTF-8 | 10,895 | 2.5625 | 3 | [] | no_license | require 'selenium-webdriver'
require 'csv'
require './.env.rb'
@driver = Selenium::WebDriver.for :chrome
@wait = Selenium::WebDriver::Wait.new(timeout: 120)
@driver.manage.timeouts.implicit_wait = 20
def runner
information_to_write = []
user_name = USER_NAME
company_id = COMPANY_ID
password = PASSWORD
login(user_name, company_id, password)
data_capture_test(information_to_write)
write_file(information_to_write, '../csv/brighton_test.csv')
end
#**********
#Navigation
#**********
def login(user_name, company_id, password)
@driver.get "https://www.brightonbest.com/#"
add_input(@driver, :id, "custno", company_id)
add_input(@driver, :id, "userid", user_name)
add_input(@driver, :id, "password", password)
click_element(@driver, :id, 'login')
end
def go_to_new_quote_page
click_element(@driver, :id, 'btnNew')
# sleep(6)
wait_element(@driver, :class, 'dynatree-has-children')
end
def go_to_quotation_spec_page
click_element(@driver, :id, 'QOspec')
# sleep(6)
wait_element(@driver, :class, 'dynatree-has-children')
end
def go_to_quotation_matched_page
click_element(@driver, :id, 'QOmatched')
# sleep(6)
wait_element(@driver, :css, '[aria-describedby="grid_item"]')
end
def go_to_shopping_cart_page
click_element(@driver, :id, 'QOcart')
# sleep(6)
wait_element(@driver, :id, '1_sec')
end
#************
#Data Capture
#************
# def data_capture(information_to_write)
# go_to_new_quote_page
# item_list_hash = build_item_list_hash
# item_list_hash.each do |i, iv|
# click_top_list(i.to_i)
# sleep(0.25)
# iv.each do |j, jv|
# click_child_list(i.to_i, j.to_i)
# sleep(0.25)
# jv.each do |k|
# click_checkbox(i.to_i, j.to_i, k.to_i)
# item_scrape_runner(information_to_write)
# click_checkbox(i.to_i, j.to_i, k.to_i)
# end
# end
# end
# end
def data_capture_test(information_to_write)
go_to_new_quote_page
item_list_hash = Hash.new
item_list_hash = build_item_list_hash
item_list_hash.each do |i, iv|
if i == '3'
click_top_list(i.to_i)
# sleep(0.25)
iv.each do |j, jv|
if j == "2"
click_child_list(i.to_i, j.to_i)
# sleep(0.25)
jv.each do |k|
if k == "0" || k == "1"
click_checkbox(i.to_i, j.to_i, k.to_i)
item_scrape_runner(information_to_write)
click_checkbox(i.to_i, j.to_i, k.to_i)
end
end
end
end
end
end
return information_to_write
end
def build_item_list_hash
hash = Hash.new
quote_li_array = select_child_elements(@driver, :class, 'dynatree-container')
(quote_li_array.length).times do |i|
hash["#{i}"] = {}
expand_list(quote_li_array[i])
child_li_array = select_child_elements(quote_li_array[i], :css, 'ul')
(child_li_array.length).times do |j|
expand_list(child_li_array[j])
hash["#{i}"]["#{j}"] = []
sub_child_li_array = select_child_elements(child_li_array[j], :css, 'ul')
(sub_child_li_array.length).times do |k|
hash["#{i}"]["#{j}"] << k.to_s
end
end
end
return hash
end
def item_scrape_runner(information_to_write)
go_to_quotation_matched_page
quotation_matched_loop(information_to_write)
go_to_quotation_spec_page
# sleep(2)
return information_to_write
end
# def quotation_matched_loop_test
# last_page = false
# page_number_input = get_element(@driver, :class, "ui-pg-input")
# 2.times do
# # until last_page == true
# increase_order_pkg_test
# pages_class = get_pages_class
# if pages_class.include?('ui-state-disabled')
# last_page = true
# end
# if last_page == false
# increase_quotation_matched_page_number(page_number_input)
# end
# end
# end
def quotation_matched_loop(information_to_write)
last_page_number = get_element(@driver, :id, 'sp_1_pager').text.to_i
last_page_number.times do |i|
if i != 0
go_to_quotation_matched_page
# sleep(2)
page_number_input = get_element(@driver, :class, "ui-pg-input")
increase_quotation_matched_page_number(page_number_input, (i-1))
# sleep(2)
strike_out_quoted
increase_quotation_matched_page_number(page_number_input, i)
# sleep(2)
end
increase_order_pkg_test
# increase_order_pkg
go_to_shopping_cart_page
scrape_table(information_to_write)
go_to_quotation_spec_page
end
go_to_quotation_matched_page
page_number_input = get_element(@driver, :class, "ui-pg-input")
increase_quotation_matched_page_number(page_number_input, (last_page_number - 1))
strike_out_quoted
return information_to_write
end
def strike_out_quoted
# sleep(2)
checkboxes = get_elements(@driver, :css, '[type="checkbox"]')
rows = get_elements(@driver, :class, 'ui-row-ltr')
# (checkboxes.length).times do |i|
# checkboxes[i].click
# wait_strikethrough(rows, i)
(checkboxes.length / 10).times do |i|
checkboxes[i].click
wait_strikethrough(rows, i)
end
# sleep(3)
end
def increase_order_pkg_test
hash = Hash.new
hash["bulk"] = reduce_inputs('[aria-describedby="grid_order_bulk"]')
hash["package"] = reduce_inputs('[aria-describedby="grid_order_package"]')
hash.each do |key, value|
(value.length / 10).times do |i|
add_input(value[i], :class, 'mEdit', '1')
add_input(value[i], :class, 'mEdit', "\n")
wait_for_load(@driver, :id, 'Waiting_Dlg')
end
end
end
def increase_order_pkg
hash = Hash.new
hash["bulk"] = reduce_inputs('[aria-describedby="grid_order_bulk"]')
hash["package"] = reduce_inputs('[aria-describedby="grid_order_package"]')
hash.each do |key, value|
(value.length).times do |i|
add_input(value[i], :class, 'mEdit', '1')
add_input(value[i], :class, 'mEdit', "\n")
wait_for_load(@driver, :id, 'Waiting_Dlg')
end
end
end
def increase_quotation_matched_page_number(page_number_input, index)
page_number = page_number_input.attribute('value')
page_number_input.clear
add_input(@driver, :class, 'ui-pg-input', (index + 1))
add_input(@driver, :class, 'ui-pg-input', "\n")
end
def scrape_table(information_to_write)
table_rows = shopping_cart_table_rows
table_loop(table_rows, information_to_write)
return information_to_write
end
def table_loop(table_rows, information_to_write)
i = 0
(table_rows.length / 2).times do
first_row = table_rows[i]
second_row = table_rows[i + 1]
item_hash = scrape_row(first_row, second_row)
if check_inventory(item_hash)
information_to_write << item_hash
end
i += 2
end
return information_to_write
end
def scrape_row(first_row, second_row)
hash = Hash.new
hash['Part Number'] = get_element(second_row, :css, 'span').text
hash['Description'] = get_element(first_row, :class, 'divitmdesc').text
hash['Type'] = check_type(first_row)
hash['Pack-Size'] = get_element(first_row, :class, 'ordqty').attribute('value')
hash['Weight'] = get_element(first_row, :class, 'spantxtWeight').text
hash['Cost'] = get_element(first_row, :class, 'spantxtAmount').text
hash['Stock'] = check_stock(second_row)
return hash
end
def check_type(first_row)
columns = get_elements(first_row, :css, 'td')
return columns[3].text
end
def check_stock(second_row)
stock_message = get_element(second_row, :class, 'divStockInfo').text
return stock_message if stock_message == "In Stock"
return "Out of Stock" if stock_message.include?('Check Alternative Warehouse')
return nil
end
def check_inventory(item)
if item["Stock"] == nil
return false
end
return true
end
def write_file(file, filename)
CSV.open(filename, 'wb') do |csv|
array = []
file[0].each do |k,v|
array << k
end
csv << array
file.each do |item|
array = []
item.each do |k,v|
array << v
end
csv << array
end
end
end
#****************
#Selectors
#****************
def reduce_inputs(selector_name)
get_elements(@driver, :css, selector_name).reduce([]) do |memo, element|
if @driver.execute_script("return arguments[0].childElementCount" , element) > 0
memo << element
end
memo
end
end
def click_top_list(i)
quote_li_array = select_child_elements(@driver, :class, 'dynatree-container')
expand_list(quote_li_array[i])
end
def click_child_list(i, j)
quote_li_array = select_child_elements(@driver, :class, 'dynatree-container')
child_li_array = select_child_elements(quote_li_array[i], :css, 'ul')
expand_list(child_li_array[j])
end
def click_checkbox(i,j,k)
quote_li_array = select_child_elements(@driver, :class, 'dynatree-container')
child_li_array = select_child_elements(quote_li_array[i], :css, 'ul')
sub_child_li_array = select_child_elements(child_li_array[j], :css, 'ul')
click_element(sub_child_li_array[k], :class, 'dynatree-checkbox')
end
def expand_list(element)
click_element(element, :class, 'dynatree-expander')
end
def shopping_cart_table_rows
full_table = get_element(@driver, :css, 'tbody')
table_rows = get_elements(full_table, :class, 'ui-widget-content')
return table_rows
end
def get_pages_class
pages = get_element(@driver, :id, 'next_pager')
pages_class = pages.attribute('class')
return pages_class
end
def select_child_elements(instance, selector, selector_name)
parent = get_element(instance, selector, selector_name)
child_array = @driver.execute_script("return arguments[0].childNodes" , parent)
return child_array
end
def click_element(instance, selector, selector_name)
element = @wait.until {
element = instance.find_element(selector, selector_name)
element if element.displayed?
}
element.click
end
def get_element(instance, selector, selector_name)
element = @wait.until {
element = instance.find_element(selector, selector_name)
element if element != nil
}
return element
end
def get_elements(instance, selector, selector_name)
elements = @wait.until {
elements = instance.find_elements(selector, selector_name)
elements if elements != []
}
return elements
end
def add_input(instance, selector, selector_name, input)
element = @wait.until {
element = instance.find_element(selector, selector_name)
element if element.displayed?
}
element.send_keys(input)
end
def wait_for_load(instance, selector, selector_name)
@wait.until {
element = instance.find_element(selector, selector_name)
element if !element.displayed?
}
end
def wait_element(instance, selector, selector_name)
element = @wait.until {
element = instance.find_element(selector, selector_name)
return if element != nil
}
end
def wait_strikethrough(rows, i)
@wait.until {
element = get_element(rows[i], :css, '[disabled="disabled"]')
return if element != nil
}
end
runner
#capture the input boxes after elements in wati strikethrough
| true |
83f55089715052b7beb0c06732d91bcd780559e8 | Ruby | micko45/ruby_code | /ham_radio/api/access_qrz_api.rb | UTF-8 | 2,136 | 2.765625 | 3 | [] | no_license | #!/bin/env ruby
#Use qrz_api to connect to qz and get some info.
require "./qrz_api.rb"
require 'optparse'
require './adif_api.rb'
##############
#SetUP
##############
#Create hash required by qrz api
args = Hash[
:url => "http://xmldata.qrz.com/xml/current",
:agen => "mmg-1.0.1",
:user => "ei5hsb",
:pass => "Letmein_123" ]
#Get options
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
opts.on("-c", "--callsign CALLSIGN") do |lib|
options[:callsign] = lib
end
end.parse!
##################
#functions
##################
#lookup previous QSO
def cntCallHis(data, tosearch)
testarray = ADIF2Hash.searchArray('call', tosearch, data)
return testarray.length
end
#Count the qso per country.
def cntCtrylHis(data, tosearch)
testarray = ADIF2Hash.searchArray('country', tosearch, data)
return testarray.length
end
#sort and print output.
def printout(qrzInfo,history)
puts "Callsign: #{qrzInfo['Callsign']['call']}"
puts "Name: #{qrzInfo['Callsign']['fname']} #{qrzInfo['Callsign']['name']}"
puts "Address: #{qrzInfo['Callsign']['addr2']}"
puts "Country: #{qrzInfo['Callsign']['country']}"
puts "Previous Contacts: #{history[:callcount]}"
puts "Previous Country: #{history[:ctrycount]}"
puts "https://www.qrz.com/db/#{qrzInfo['Callsign']['call']}"
end
###########'
#Main #
###########'
#Create hash for adif file
adifFile = '/mediashare/medishare/current_Log.ADI'
adifData = ADIF2Hash.hash(adifFile)
#Check if call sign is a option
if options[:callsign].to_s != ''
qrzInfo = GetQRZ.callSignLookup(GetQRZ.login(args), options[:callsign], args)
else
print "call sign to lookup> "
callsign = $stdin.gets.chomp
if callsign == ""
callsign = "ei5hsb"
qrzInfo = GetQRZ.callSignLookup(GetQRZ.login(args), callsign, args)
end
end
#Get call sign QSO history
history = { :callcount => cntCallHis(adifData, qrzInfo['Callsign']['call']),
:ctrycount => cntCtrylHis(adifData, qrzInfo['Callsign']['country']) }
printout(qrzInfo, history)
| true |
1ea6312a29f7886e61b854e546b93976af83abbe | Ruby | Muffin1/MEDI6 | /Group Project/lib/admin.rb | UTF-8 | 4,815 | 3.234375 | 3 | [] | no_license | require 'person.rb'
require 'doctor.rb'
require 'receptionist.rb'
require 'md5'
require 'user_account.rb'
class Admin < Person
attr_accessor :id, :password
def initialize()
if(search_by_id(5000,"../csv/user.csv")==nil)
set_privileges(5000,MD5.hexdigest("admin"),"a")
end
end
def add_doctor(idNumber,firstName, lastName, address, date_of_birth ,phoneNumber, email, specialization, password)
doctor = Doctor.new()
encrypted_password = MD5.hexdigest(password)
a_id = doctor.id_generator()
doctor.add_doctor(a_id, idNumber, firstName, lastName, address, date_of_birth, phoneNumber, email, specialization, encrypted_password)
doctor.set_privileges(a_id,encrypted_password,"d")
return doctor
end
def add_receptionist(idNumber, firstName, lastName, address, date_of_birth, phoneNumber, email, password)
receptionist = Receptionist.new()
encrypted_password = MD5.hexdigest(password)
a_id = receptionist.id_generator()
receptionist.add_receptionist(a_id,idNumber, firstName, lastName, address, date_of_birth, phoneNumber, email, encrypted_password)
receptionist.set_privileges(a_id, encrypted_password,"r")
return receptionist
end
def select_user_to_add(option)
answer =option
while (true)
if (answer=="1") then
create_doctor()
puts "\n"
system("pause")
clear_screen
display_admin_options()
print "Your option:> "
answer = gets.chomp()
if ((answer!="1" and answer!="2") or answer=="\n")
clear_screen
break
end
elsif(answer=="2") then
create_receptionist()
puts "\n"
system("pause")
clear_screen
display_admin_options()
print "Your option:> "
answer = gets.chomp()
if ((answer!="1" and answer!="2") or answer=="\n")
clear_screen
break
end
else
puts "\n"
puts 'Wrong Input'
end
end
end
def display_admin_options()
puts "\n"
puts "Administrator options:"
puts"--------------------------------------------------"
puts "1)Enter (1) to register a doctor.. "
puts "2)Enter (2) to register a receptionist.. "
puts "3)Enter any key to logout.. "
puts"--------------------------------------------------"
end
def create_doctor()
#------------------------------------------------------------------
#--------------------------after refactoring--------------------------------
clear_screen
puts "You may now register a new doctor"
puts"--------------------------------------------------\n"
puts "Please provide doctor' s information below"
puts "\n"
details = Array.new
index = 0
prompts = ["Id number:> ","First name:> ","Last name:> ","Address:> ","Date of birth:> ","Telephone number:> ","Email:> ","Specialization:> ","Password:> "]
prompts.each do |prompt|
print prompt
details[index] = gets.chomp()
puts ""
index += 1
end
doctor = add_doctor(details[0],details[1],details[2],details[3],details[4],details[5],details[6],details[7],details[8])
puts "\n"
puts"==================================================\n"
puts "Doctor '#{doctor.first_name}' has registered!"
puts"--------------------------------------------------\n"
puts "Identification details: "
print"System id:#{doctor.system_id}\n"
print"Password:#{details[8]}\n"
puts"--------------------------------------------------\n"
end
def create_receptionist()
#------------------------------------------------------------------
#--------------------------after refactoring--------------------------------
clear_screen
puts "You may now register a new receptionist"
puts"--------------------------------------------------\n"
puts "Please provide receptionist' s information below"
puts "\n"
details = Array.new
index = 0
prompts = ["Id number:> ","First name:> ","Last name:> ","Address:> ","Date of birth:> ","Telephone number:> ","Email:> ","Password:> "]
prompts.each do |prompt|
print prompt
details[index] = gets.chomp()
puts ""
index += 1
end
receptionist = add_receptionist(details[0],details[1],details[2],details[3],details[4],details[5],details[6],details[7])
puts "\n"
puts"==================================================\n"
puts "Receptionist '#{receptionist.first_name}' has registered!"
puts"--------------------------------------------------\n"
puts "Identification details: "
print"System id:#{receptionist.system_id}\n"
print"Password:#{details[7]}\n"
puts"--------------------------------------------------\n"
end
end | true |
8975859917efb278e40a075d5543cd0acb529861 | Ruby | rmueck/aix-puppet | /lib/puppet/provider/download/suma.rb | UTF-8 | 6,620 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | require_relative '../../../puppet_x/Automation/Lib/Log.rb'
require_relative '../../../puppet_x/Automation/Lib/Suma.rb'
require_relative '../../../puppet_x/Automation/Lib/Nim.rb'
require_relative '../../../puppet_x/Automation/Lib/Utils.rb'
# ##############################################################################
# name : 'suma' provider of 'download' custom-type
# description :
# implement "suma-download" functionality above suma command.
# ##############################################################################
Puppet::Type.type(:download).provide(:suma) do
include Automation::Lib
commands :lsnim => '/usr/sbin/lsnim'
commands :nim => '/usr/sbin/nim'
commands :rm => '/bin/rm'
# ###########################################################################
# exists?
# Method Ensure Action Ensure state
# result value transition
# ======= ======= ======================= ================
# true present manage other properties n/a
# false present create method absent → present
# true absent destroy method present → absent
# false absent do nothing n/a
# ###########################################################################
def exists?
Log.log_info("Provider suma 'exists?' method : we want to realize : \"#{resource[:ensure]}\" for \
type=\"#{resource[:type]}\" into directory=\"#{resource[:root]}\" from=\"#{resource[:from]}\" \
to \"#{resource[:to]}\" lpp_source=\"#{resource[:lpp_source]}\" force=#{resource[:force]}.")
creation_done = true
Log.log_debug('Suma.new')
@suma = Suma.new([resource[:root],
resource[:force],
resource[:from],
resource[:to],
resource[:type],
resource[:to_step],
resource[:lpp_source]])
Log.log_info('dir_metadata=' + @suma.dir_metadata)
Log.log_info('dir_lpp_sources=' + @suma.dir_lpp_sources)
Log.log_info('lpp_source=' + @suma.lpp_source)
if resource[:force].to_s == 'yes'
creation_done = false
begin
location = Nim.get_location_of_lpp_source(@suma.lpp_source)
Log.log_info('Nim.get_location_of_lpp_source ' + @suma.lpp_source + ' : ' + location)
unless location.nil? || location.empty?
Log.log_info('Removing contents of NIM lpp_source ' + @suma.lpp_source + ' : ' + location)
FileUtils.rm_rf Dir.glob("#{location}/*")
Log.log_info('Removing NIM lpp_source ' + @suma.lpp_source)
Nim.remove_lpp_source(@suma.lpp_source)
end
rescue Puppet::ExecutionFailure => e
Log.log_debug('NIM Puppet::ExecutionFailure e=' + e.to_s)
end
elsif resource[:ensure].to_s != 'absent'
exists = Nim.lpp_source_exists?(@suma.lpp_source)
if exists
Log.log_info('NIM lpp_source resource ' + @suma.lpp_source + ' already exists, suma steps not necessary.')
Log.log_info('You can force through \'force => "yes"\' a new suma preview or download with creation of new NIM lpp_source resource.')
else
Log.log_info('NIM lpp_source resource ' + @suma.lpp_source + ' does not exists.')
creation_done = false # this will trigger creation
end
end
Log.log_info('Provider suma "exists!" method returning ' + creation_done.to_s)
creation_done
end
# ###########################################################################
#
#
# ###########################################################################
def create
Log.log_info("Provider suma 'create' method : doing \"#{resource[:ensure]}\" \
for type=\"#{resource[:type]}\" into directory=\"#{resource[:root]}\" \
from=\"#{resource[:from]}\" to \"#{resource[:to]}\" \
lpp_source=\"#{resource[:lpp_source]}\".")
Log.log_info('dir_metadata=' + @suma.dir_metadata)
Log.log_info('dir_lpp_sources=' + @suma.dir_lpp_sources)
Log.log_info('lpp_source=' + @suma.lpp_source)
# TODO : check if preview can be skipped if "step_to => :download"
Log.log_debug('Launching now suma.preview')
begin
missing = @suma.preview
Log.log_debug('suma.preview shows that missing=' + missing.to_s)
if missing
if @suma.to_step.to_s == 'download'
Log.log_debug('Launching now suma.download')
downloaded = @suma.download
Log.log_debug('downloaded=' + downloaded.to_s)
else
Log.log_debug('suma.download not necessary as only preview is required')
end
else
Log.log_debug('suma.download not necessary as preview shows nothing is missing ')
end
#
if @suma.to_step.to_s == 'download'
exists = Nim.lpp_source_exists?(@suma.lpp_source)
if !exists
Log.log_debug('Nim.define_lpp_source')
Nim.define_lpp_source(@suma.lpp_source,
@suma.dir_lpp_sources,
'built by Puppet AixAutomation')
else
Log.log_info('NIM lpp_source resource ' + @suma.lpp_source + ' already exists, creation not done.')
Log.log_info('You can force through \'force => "yes"\' a new suma download and creation of new NIM lpp_source resource.')
end
end
rescue SumaPreviewError, SumaDownloadError => e
Log.log_err('Exception ' + e.to_s)
end
Log.log_debug('End of suma.create')
end
# ###########################################################################
#
#
# ###########################################################################
def destroy
Log.log_info("Provider suma 'destroy' method : doing \"#{resource[:ensure]}\" \
for type=\"#{resource[:type]}\" into directory=\"#{resource[:root]}\" \
from=\"#{resource[:from]}\" to \"#{resource[:to]}\" \
lpp_source=.\"#{resource[:lpp_source]}\".")
Log.log_debug('dir_metadata=' + @suma.dir_metadata)
Log.log_debug('dir_lpp_sources=' + @suma.dir_lpp_sources)
Log.log_debug('lpp_source=' + @suma.lpp_source)
Log.log_info('Cleaning directories' + @suma.dir_lpp_sources + ' and ' + @suma.dir_metadata)
rm('-r', '-f', @suma.dir_lpp_sources)
rm('-r', '-f', @suma.dir_metadata)
Log.log_debug('Cleaning directories done')
Log.log_info('Removing NIM lpp_source resource ' + @suma.lpp_source)
Nim.remove_lpp_source(@suma.lpp_source)
Log.log_debug('Removing NIM lpp_source resource done')
Log.log_debug('End of suma.destroy')
end
end
| true |
315409b9cbe411132d5e87bef640a8a688dd1428 | Ruby | lnchambers/refugee_project_backend | /app/presenters/results_presenter.rb | UTF-8 | 1,802 | 2.96875 | 3 | [] | no_license | class ResultsPresenter < ApplicationController
def initialize(params)
@age = params[:age].to_i unless params[:age].nil?
@name = params[:name]
@gender = params[:gender]
@country_of_origin = params[:country_of_origin]
@group_size = params[:group_size].to_i unless params[:group_size].nil?
@country_of_seperation = params[:country_of_seperation]
end
def get_results
return { message: "At least one attribute is needed" } if attributes_empty?
NeuralNet.new.create_results(format_params)
format_results
end
private
attr_reader :age, :name, :gender, :country_of_origin, :group_size, :country_of_seperation
def params_to_array
[age, name, gender, country_of_origin, group_size, country_of_seperation]
end
def sanitized_params
params_to_array.map do |attribute|
sum_of_attribute(attribute) if attribute.class == String
end
end
def format_params
sanitized_params.map do |attribute|
attribute ? attribute : " "
end
end
def format_results
CSV.open('./public/data/results.csv') do |row|
row.shift
shifted_row = row.shift
if shifted_row[1] == "0"
clean_disk
return {status: "Deceased"}
elsif shifted_row[1] == "2"
clean_disk
return {status: "Cannot locate"}
else
clean_disk
return {status: "Located"}
end
end
end
def clean_disk
FileUtils.rm('./public/data/results.csv')
FileUtils.rm('./public/data/submission.csv')
end
def attributes_empty?
format_params.uniq.count == 1 && format_params.uniq[0] == " "
end
def sum_of_attribute(attribute)
attribute.chars.sum do |letter|
letter.ord
end
end
end
| true |
1a83e760700283cb4ff6ca5934e7dce2c31d10aa | Ruby | cristianrennella/launchschool | /120/lesson_5/exercises.rb | UTF-8 | 350 | 3.125 | 3 | [] | no_license | # Game Description: Display the board. User make a choice. Computar make a choice. Update board.
# Until there are three choices in one row (horizontal or diagonal) and win / lose. Or tie.
# nouns: board, user, computer
# verbs: display, choice, evaluates
# nouns: game engine (evaluates), board (display, update), user (choice) , computer (choice) | true |
6c85cb1b2d5b6bb5976cc1151e9edf98e14c1a97 | Ruby | sunteya/wido.old | /plugins/lm2doc_converter.rb | UTF-8 | 994 | 2.53125 | 3 | [] | no_license | require "lm2doc"
module Jekyll
class MarkdownConverter < Converter
def matches_with_lm2doc_support(ext)
return false if @config['markdown'] == "lm2doc"
matches_without_lm2doc_support(ext)
end
alias_method_chain :matches, :lm2doc_support
end
class Lm2docConverter < Converter
safe true
pygments_prefix "\n"
pygments_suffix "\n"
def setup
return if @setup
@setup = true
if @config['markdown'] == "lm2doc"
begin
require "lm2doc"
rescue LoadError
raise FatalException.new("Missing dependency: lm2doc")
end
end
end
def matches(ext)
rgx = '(' + @config['markdown_ext'].gsub(',','|') +')'
ext =~ Regexp.new(rgx, Regexp::IGNORECASE)
end
def output_ext(ext)
".html"
end
def convert(content)
setup
converter = Lm2doc::Markdown.new
converter.content = content
converter.as_html
end
end
end
| true |
ea909b922e97c5ced7cd242d4c59382e0493e565 | Ruby | HarikrishnaBatta/tennis-scoreboard-ng | /lib/api_constraints.rb | UTF-8 | 972 | 2.8125 | 3 | [] | no_license | # Determine if a router request matches an api version number
class ApiConstraints
# * *Args* : options
# - +version+ -> number
# - Version number to match
# - +default+ -> Boolean
# - If request does not identify a version, default to +version+
def initialize(options)
@version = options[:version]
@default = options[:default]
end
# Determine whether a request matches
# an api version number
#
# * *Args* :
# - +request+ -> router request
# * *Returns* : Boolean
# - +:true+ - the request matches the api version
# - +:false+ - the request does not match the api version
def matches?(request)
accept = request.headers['Accept']
if accept.nil?
@default
else
if @default && !accept.include?(PREFIX)
true
else
accept.include?("#{PREFIX}#{@version}")
end
end
end
private
# version prefix string
PREFIX = 'application/tennis.scoreboard.v'
end
| true |
873cdecfc4a37cc7ee630b8e16302a9c369f92a1 | Ruby | fernandoamz/ConwayRB | /conway.rb | UTF-8 | 3,494 | 3.484375 | 3 | [] | no_license | class Conway
def muestras
pobladores = 15
celulas = [pobladores]
for i in 0...pobladores
celulas[i] = [pobladores]
for j in 0...pobladores
celulas[i][j] = rand(0..1)
end
end
return celulas
end
def buscarVecinos(x,y)
contador = 0;
#Revisar celda izquierda de la posición actual
if estado(x-1, y)
contador += 1
end
# Revisar superior izquierda
if estado(x-1, y-1)
contador += 1
end
# Revisar inferior izquierda
if estado(x-1, y+1)
contador += 1
end
# Revisar celda de arriba del posicion actual
if estado(x , y-1)
contador += 1
end
# celda derecha de la posicion actual
if estado(x , y+1)
contador += 1
end
# Esquina superior izquierda de la posicion actual
if estado(x+1, y-1)
contador += 1
end
# Revisar esquina inferior derecha
if estado(x+1, y+1)
contador += 1
end
# Revisar celda de abajo de la posicion actual
if estado(x+1, y)
contador += 1
end
return contador;
end
def estado(x,y)
if muestras[x]
if muestras[x][y] == 1
return true;
else
return false;
end
end
end
def generaciones
for x in 0...muestras.size
for y in 0...muestras.size
valor = muestras[x][y]
contador = buscarVecinos(x,y)
result = 0
# Si esta viva y tiene menos de dos vecinos muere
if valor && contador < 2
result = 0;
end
# si tiene valor y tiene 2 o tres vecinos vive
if valor && (contador == 2 || contador == 3)
result = 1;
end
# si tiene mas de tres vecinos muere
if valor && contador > 3
result = 0;
end
# Si no tiene valor y tiene tres vecinos vivos Nace
if !valor && contador == 3
result = 1;
end
muestras[x][y] = result;
end
#return muestras
end
print "------------------- \n"
print muestras
print "------------------- \n"
end
end
def starting(numberGenerations)
for i in 0...numberGenerations
Conway.new.generaciones
puts "Generacion número: #{i+1}"
end
end
def play
puts "Iniciar nueva generación ¿y/n?"
response = gets.chomp
if response == "y"
puts "¿Cuantas generaciones deseas ver?"
numberGenerations = gets.chomp.to_i
starting(numberGenerations)
puts "¿Crear más generaciones y/n?"
result = gets.chomp
if result == "y"
puts "¿Cuantas generaciones deseas agregar?"
numberGenerations = gets.chomp.to_i
starting(numberGenerations)
play
elsif result == "n"
return
end
elsif response == "n"
return
elsif response != "n" && response != "s"
puts "debes seleccionar al menos una opción"
play
end
end
play | true |
3d8f3453546b7debeb75275c46f1cbc5fa1d72b9 | Ruby | MDamjanovic/school_generator | /spec/models/student_spec.rb | UTF-8 | 2,036 | 2.546875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Student, type: :model do
it "expect to belong to school" do
t = Student.reflect_on_association(:school)
expect(t.macro).to eq(:belongs_to)
end
it "expect to belong to department" do
t = Student.reflect_on_association(:department)
expect(t.macro).to eq(:belongs_to)
end
it "has a valid factory" do
expect(build(:student, students_school: 1, students_department: 2)).to be_valid
expect(build(:student, students_school: 1)).to be_valid
expect(build(:student)).not_to be_valid
end
let(:user) { build(:user, email: 'some.other.school@test.com') }
let(:school) { create(:school, user_email: 'some.other.school@test.com') }
let(:student) { build(:student, students_school: school.id ) }
let(:department) { create(:department, num:1, school: school.id) }
let(:studentWithDepartment) { create(:student, students_school: school.id ,students_department: department.id) }
subject {student}
describe "public instance methods" do
context "responds to its methods" do
it { should respond_to(:name) }
it { should respond_to(:gender) }
it { should respond_to(:with_special_needs) }
it { should respond_to(:department) }
end
end
context "executes methods correctly" do
context "#department?" do
it "returns nil if student dont have department" do
expect(student.department).to eq(nil)
end
it "returns department number if student has department" do
expect(studentWithDepartment.department).to eql(department.number)
end
end
end
it "expect to be male or female" do
expect(student.gender).to match /((fe)?male)/
end
invalid_student = Student.new(name: "Name", school_id: 1)
it "must have a gender" do
expect(invalid_student).not_to be_valid
expect(invalid_student.errors[:gender].size).to eql(2)
end
it "expect to be male or female" do
expect(student.gender).to match /((fe)?male)/
end
end
| true |
163cae146e03e0e3d95769359fd887ce653885f2 | Ruby | boost/safety_cone | /lib/safety_cone/filter.rb | UTF-8 | 1,760 | 2.546875 | 3 | [
"MIT"
] | permissive | module SafetyCone
# Module for Filtering requests and raise notices
# and take measures
module Filter
# Method to include to base class.
# This lets declare a before filter here
def self.included(base)
if Rails.version.to_i >= 5
base.before_action :safety_cone_filter
else
base.before_filter :safety_cone_filter
end
end
# Filter method that does the SafetyCone action
# based on the configuration.
def safety_cone_filter
if cone = fetch_cone
if cone.type == 'notice'
flash.now["safetycone_#{notice_type(cone.type)}"] = cone.message
else
flash["safetycone_#{notice_type(cone.type)}"] = cone.message
end
redirect_to safety_redirect if cone.type == 'block'
end
end
private
# Fetches a configuration based on current request
def fetch_cone
paths = SafetyCone.paths
if path = paths[request_action]
key = request_action
elsif cone = paths[request_method]
key = request_method
else
return false
end
path = Path.new(key, path)
path.fetch
%w[notice block].include?(path.type) ? path : false
end
# Method to redirect a request
def safety_redirect
request.env['HTTP_REFERER'] || root_path
end
# Returns type of notice
def notice_type(type)
type == 'notice' ? 'notice' : 'alert'
end
# Returns the current request action as a symbol
def request_method
request.method.to_sym
end
# Returns the current controller_action as a symbol
def request_action
"#{controller_name}_#{action_name}".to_sym
end
end
end
| true |
64f861c20ef9bdfea2b2b263044192ac1bfe0660 | Ruby | Andyagus/afpray | /lib/player.rb | UTF-8 | 1,939 | 2.84375 | 3 | [
"MIT"
] | permissive | require 'open-uri'
class Player
def initialize(ping_url=nil)
if ping_url
logger.info("[player] set ping_url to #{ping_url}")
@ping_url = ping_url
end
@queue = []
@options = ""
@thread = nil
at_exit{
kill_thread
}
end
attr_reader :queue
attr_writer :options
def current
@queue.first
end
def play_files(list)
logger.info "[player] play_files"
@queue = list
restart_thread
end
def add_files(list)
@queue.concat list
end
def play_wait
logger.info "[player] play_wait"
_play current
end
def pause
logger.info "[player] pause"
kill_thread
end
def resume
logger.info "[player] resume"
restart_thread
end
def prev_song
logger.info "[player] prev"
@queue.rotate!(-1)
end
def next_song
logger.info "[player] succ"
@queue.rotate!
end
private
def restart_thread
kill_thread
@thread = Thread.new{
loop do
ping!
play_wait
next_song
end
}
end
def kill_thread
@thread.kill if @thread
_stop
end
# Issue HTTP GET to @ping_url.
# Used for running afpray with pow,
# because pow terminates the app in 15min
# This prevents pow to restart afplay
# (unless you have a song longer than 15min!).
def ping!
if @ping_url
logger.info("[player] ping #{@ping_url}")
s = open(@ping_url).read
logger.info("[player] ping ok: read #{s.bytesize}")
end
end
def logger; Rails.logger; end
class AFPlay < Player
def initialize(*args)
super(*args)
@process = nil
end
# Brocking API
def _play(path)
logger.info "[player] play #{path}"
@process = ChildProcess.build("afplay", *@options.split, path)
@process.io.inherit!
@process.start
@process.wait
end
def _stop
@process.stop if @process && @process.alive?
end
end
end
| true |
7f7ce3eee8b95a6bcf5682cae3cefab762fff87a | Ruby | LewisYoul/5_Battle | /spec/game_spec.rb | UTF-8 | 479 | 2.859375 | 3 | [] | no_license | require 'game'
describe Game do
let(:player1) { double(:player1, reduce_hp: true, name: true) }
let(:player2) { double(:player2, reduce_hp: true, name: true) }
let(:game1) { described_class.new(player1, player2) }
describe "#attack" do
context "when attacking" do
it "calls player.reduce_hp" do
expect(game1.turn).to eq(1)
end
it "should be turn 2" do
game1.attack
expect(game1.turn).to eq(2)
end
end
end
end
| true |
0b63eece89f6acd390ef0ef27064a8a26baf59b7 | Ruby | stickysidedown/LaunchSchool-Intro-to-Programming | /ruby_intro_book/other_stuff/exercise_1_other_stuff.rb | UTF-8 | 186 | 2.6875 | 3 | [] | no_license |
def ifLab(string)
if /lab/ =~ string
puts string
else
puts "No Lab"
end
end
ifLab("laboratory")
ifLab("experiment")
ifLab("Pans Labyrinth")
ifLab("elaborate")
ifLab("polar bear") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.