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 |
---|---|---|---|---|---|---|---|---|---|---|---|
95a24b375c28782032382eab6234acee58a81d70
|
Ruby
|
sattelbergerp/ttt-with-ai-project-cb-000
|
/bin/tictactoe
|
UTF-8
| 790 | 3.203125 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require_relative '../config/environment'
loop do
puts "CLI Ruby"
puts "1. 2 Player"
puts "2. 1 Player"
puts "3. 0 Player (AI vs. AI)"
puts "exit. Exit the game"
print "Select Option (1-3): "
inputs = gets.strip.split(" ")
skip_aftergame = false
case inputs[0]
when "1"
start_game(Players::Human, Players::Human)
when "2"
start_game(Players::Human, Players::Computer)
when "3"
start_game(Players::Computer, Players::Computer)
when "wargames"
if inputs.count > 1 && inputs[1].to_i > 0
run_ai_test(inputs[1].to_i)
else
run_ai_test
end
when "exit"
break
else
puts "Unreconized input."
skip_aftergame=true
end
if !skip_aftergame
print "Return to main menu (y/n): "
ret_in = gets.strip.downcase
break if ret_in=="n"
end
end
| true |
f27f044867e74dfb9a1ae085c89dc9809bc34564
|
Ruby
|
hmohamed0/ruby_fundamentals2
|
/exersize6.rb
|
UTF-8
| 761 | 3.953125 | 4 |
[] |
no_license
|
def list_groceries(list)
list.each do |x| puts "* " + x end
puts
end
grocery_list = ["carrots","toilet paper","apples","salmon"]
list_groceries(grocery_list)
#2 adds rice to list
grocery_list << "rice"
list_groceries(grocery_list)
puts grocery_list.length
puts
#4 Checks list to see if bananas included
product_to_check = "bananas"
if grocery_list.include?(product_to_check)
puts "You don't need to pick up bananas today"
puts
else
puts "You need to pick up bananas"
puts
end
# 5 List second item in the list
puts grocery_list[1]
puts
#6 Sorts list & outputs it with asterisks
grocery_list = grocery_list.sort
list_groceries(grocery_list)
#7 Delete salmon from list and redisplay it
grocery_list.delete("salmon")
list_groceries(grocery_list)
| true |
b81b524929c79f8da7c0c12e1a5bbe08bfed4738
|
Ruby
|
DragDropQueen/groupify
|
/lib/groupify/group.rb
|
UTF-8
| 181 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
module Groupify
module Group
def random
all.shuffle
end
def groups(n)
per = (all.count / n.to_f).ceil
random.each_slice(per).to_a
end
end
end
| true |
b0b5aecaadc8fc05a5c259d030426d3c7d1cd833
|
Ruby
|
UbuntuEvangelist/therubyracer
|
/vendor/bundle/ruby/2.5.0/gems/amqp-1.8.0/examples/queues/using_explicit_acknowledgements.rb
|
UTF-8
| 2,957 | 2.8125 | 3 |
[
"Ruby",
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# encoding: utf-8
require "bundler"
Bundler.setup
$:.unshift(File.expand_path("../../../lib", __FILE__))
require 'amqp'
puts "=> Subscribing for messages using explicit acknowledgements model"
puts
# this example uses Kernel#sleep and thus we must run EventMachine reactor in
# a separate thread, or nothing will be sent/received while we sleep() on the current thread.
t = Thread.new { EventMachine.run }
sleep(0.5)
# open two connections to imitate two apps
connection1 = AMQP.connect
connection2 = AMQP.connect
connection3 = AMQP.connect
channel_exception_handler = Proc.new { |ch, channel_close| EventMachine.stop; raise "channel error: #{channel_close.reply_text}" }
# open two channels
channel1 = AMQP::Channel.new(connection1)
channel1.on_error(&channel_exception_handler)
# first app will be given up to 3 messages at a time. If it doesn't
# ack any messages after it was delivered 3, messages will be routed to
# the app #2.
channel1.prefetch(3)
channel2 = AMQP::Channel.new(connection2)
channel2.on_error(&channel_exception_handler)
# app #2 processes messages one-by-one and has to send and ack every time
channel2.prefetch(1)
# app 3 will just publish messages
channel3 = AMQP::Channel.new(connection3)
channel3.on_error(&channel_exception_handler)
exchange = channel3.direct("amq.direct")
queue1 = channel1.queue("amqpgem.examples.acknowledgements.explicit", :auto_delete => false)
# purge the queue so that we don't get any redeliveries from previous runs
queue1.purge
queue1.bind(exchange).subscribe(:ack => true) do |metadata, payload|
# do some work
sleep(0.2)
# acknowledge some messages, they will be removed from the queue
if rand > 0.5
# FYI: there is a shortcut, metadata.ack
channel1.acknowledge(metadata.delivery_tag, false)
puts "[consumer1] Got message ##{metadata.headers['i']}, ack-ed"
else
# some messages are not ack-ed and will remain in the queue for redelivery
# when app #1 connection is closed (either properly or due to a crash)
puts "[consumer1] Got message ##{metadata.headers['i']}, SKIPPPED"
end
end
queue2 = channel2.queue!("amqpgem.examples.acknowledgements.explicit", :auto_delete => false)
queue2.subscribe(:ack => true) do |metadata, payload|
metadata.ack
# app 2 always acks messages
puts "[consumer2] Received #{payload}, redelivered = #{metadata.redelivered}, ack-ed"
end
# after some time one of the consumers quits/crashes
EventMachine.add_timer(4.0) {
connection1.close
puts "----- Connection 1 is now closed (we pretend that it has crashed) -----"
}
EventMachine.add_timer(10.0) do
# purge the queue so that we don't get any redeliveries on the next run
queue2.purge {
connection2.close {
connection3.close { EventMachine.stop }
}
}
end
i = 0
EventMachine.add_periodic_timer(0.8) {
3.times do
exchange.publish("Message ##{i}", :headers => { :i => i })
i += 1
end
}
t.join
| true |
9fa3952f3818b36e63993e587f885c589603c535
|
Ruby
|
mlibrary/pairtree
|
/lib/pairtree.rb
|
UTF-8
| 3,095 | 2.90625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
require "pairtree/identifier"
require "pairtree/path"
require "pairtree/obj"
require "pairtree/root"
require "fileutils"
module Pairtree
class IdentifierError < RuntimeError; end
class PathError < RuntimeError; end
class VersionMismatch < RuntimeError; end
SPEC_VERSION = 0.1
##
# Instantiate a pairtree at a given path location
# @param [String] path The path in which the pairtree resides
# @param [Hash] args Pairtree options
# @option args [String] :prefix (nil) the identifier prefix used throughout the pairtree
# @option args [String] :version (Pairtree::SPEC_VERSION) the version of the pairtree spec that this tree conforms to
# @option args [Boolean] :create (false) if true, create the pairtree and its directory structure if it doesn't already exist
def self.at path, args = {}
args = {prefix: nil, version: nil, create: false}.merge(args)
args[:version] ||= SPEC_VERSION
args[:version] = args[:version].to_f
root_path = File.join(path, "pairtree_root")
prefix_file = File.join(path, "pairtree_prefix")
version_file = File.join(path, pairtree_version_filename(args[:version]))
existing_version_file = Dir[File.join(path, "pairtree_version*")].max
if args.delete(:create)
if File.exist?(path) && !File.directory?(path)
raise PathError, "#{path} exists, but is not a valid pairtree root"
end
FileUtils.mkdir_p(root_path)
unless File.exist? prefix_file
File.write(prefix_file, args[:prefix].to_s)
end
if existing_version_file
if existing_version_file != version_file
stored_version = existing_version_file.scan(/([0-9]+)_([0-9]+)/).flatten.join(".").to_f
raise VersionMismatch, "Version #{args[:version]} specified, but #{stored_version} found."
end
else
args[:version] ||= SPEC_VERSION
version_file = File.join(path, pairtree_version_filename(args[:version]))
File.write(version_file, %(This directory conforms to Pairtree Version #{args[:version]}. Updated spec: http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html))
existing_version_file = version_file
end
else
unless File.directory? root_path
raise PathError, "#{path} does not point to an existing pairtree"
end
end
stored_prefix = File.read(prefix_file)
unless args[:prefix].nil? || (args[:prefix].to_s == stored_prefix)
raise IdentifierError, "Specified prefix #{args[:prefix].inspect} does not match stored prefix #{stored_prefix.inspect}"
end
args[:prefix] = stored_prefix
stored_version = existing_version_file.scan(/([0-9]+)_([0-9]+)/).flatten.join(".").to_f
args[:version] ||= stored_version
unless args[:version] == stored_version
raise VersionMismatch, "Version #{args[:version]} specified, but #{stored_version} found."
end
Pairtree::Root.new(File.join(path, "pairtree_root"), args)
end
class << self
private
def pairtree_version_filename(version)
"pairtree_version#{version.to_s.tr(".", "_")}"
end
end
end
| true |
5fc2fd2a3f57238c4c395782ca0b7f8ad59a3cbc
|
Ruby
|
CoderAcademy-SYD/payme
|
/payme.rb
|
UTF-8
| 1,452 | 2.90625 | 3 |
[] |
no_license
|
#
# payme - A easy way to pay me :)
#
# Required libraries
require_relative "payment"
require_relative "ux"
# Main
Ux.welcome
Ux.say_title('Money')
amount = Ux.ask_number("How much would you like to Pay (USD): ", Float,
Payment::AMOUNT_MIN, Payment::AMOUNT_MAX)
Ux.say_title("Personal Info")
name = Ux.ask("Your full name: ")
email = Ux.ask("Your email address: ")
Ux.say_title("Payment Info")
cc_number = Ux.ask("Credit/Debit Card number: ").delete(' ')
cc_exp_month = Ux.ask_number("Card expiry month: ", Integer,
Payment::MONTH_MIN, Payment::MONTH_MAX)
cc_exp_year = Ux.ask_number("Card expiry year: ", Integer,
Payment::YEAR_MIN, Payment::YEAR_MAX)
cc_cvc = Ux.ask_private("Card CVC: ", Integer) { |q| q.echo = "*" }
Ux.say_title('Verifying')
if(Payment.card_valid?(cc_number))
Ux.say("Your card is #{Ux.colour("valid",'green')} (#{Payment.card_brand_name(cc_number)})")
Ux.say_title('Transaction')
Ux.say("Running transaction")
tok = Payment.create_token(cc_number, cc_exp_month, cc_exp_year, cc_cvc)
charge = Payment.charge(amount, Payment::CURRENCY_DEFAULT, tok)
Ux.say("Transaction successful")
Ux.say("Thankyou for sending Saad $#{amount}")
Payment.send_email(name, email, amount)
Ux.say("We have just emailed you a receipt at #{email}")
Ux.say('Bye')
else
Ux.say("Your card is #{Ux.colour("not valid",'red')} ... Exiting ...")
end
| true |
cafa4d97b5c74af2389a3ca3c0230e42ce0bddac
|
Ruby
|
kremso/tmzone
|
/lib/tort/cache.rb
|
UTF-8
| 653 | 2.5625 | 3 |
[] |
no_license
|
require 'tort/cache/redis_backend'
require 'yaml'
module Tort
class Cache
def initialize(namespace, searcher, backend = Tort::RedisBackend.new(namespace))
@searcher = searcher
@backend = backend
end
def search(phrase, &block)
if (batched_results = @backend.fetch(phrase))
YAML::load(batched_results).each do |results|
block.call(results)
end
else
batched_results = []
@searcher.search(phrase) do |results|
batched_results << results
block.call(results)
end
@backend.put(phrase, YAML::dump(batched_results))
end
end
end
end
| true |
7638010165ccaf342fafd42956c6f809d8b07305
|
Ruby
|
daimyo-college/ruby-super-intro-lesson
|
/rines/chapter6/3-9.rb
|
UTF-8
| 136 | 2.765625 | 3 |
[] |
no_license
|
menu = {"コーヒー" => 300,"カフェラテ" => 400,}
menu.each{|key,value|
if value >= 350
puts "#{key} - #{value}円"
end
}
| true |
e668c358e2ff9a010397f7c73a118b601b8cf9f4
|
Ruby
|
vladcenan/ruby_training_modules
|
/exceptions.rb
|
UTF-8
| 249 | 2.625 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
files = ['exceptionsfile1.txt', 'exceptionsfile2.txt']
files.each do |f|
begin
file = open(f)
if file
puts 'File opened successfully'
end
rescue StandardError
puts f+' do not exist!'
next
end
end
| true |
6c0c42cc1441aec626f4df6cfec8713c7b687bba
|
Ruby
|
danguita/profile-updater
|
/lib/github_api/request.rb
|
UTF-8
| 407 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
require_relative "client"
module ProfileUpdater
module GithubApi
class EmptyBioError < StandardError; end
class Request
attr_reader :bio
def initialize(bio:)
@bio = bio.to_s.strip.force_encoding(Encoding::UTF_8).freeze
end
def call
raise EmptyBioError, "Bio can't be empty" if bio.empty?
CLIENT.update_user(bio: bio)
end
end
end
end
| true |
44ddbe5c715174e3984e89e45625f0e3599f7cc0
|
Ruby
|
Mattlk13/maglev
|
/src/test/testGlobals6.rb
|
UTF-8
| 415 | 3.125 | 3 |
[] |
no_license
|
class CA
RuntimeArg = []
NoArg = [ 5 ]
class CB
class NoArg < self
end
end
NoArg.each { | e | RuntimeArg << CB::NoArg }
end
r = CA::NoArg
unless r == [ 5 ]
raise 'ERROR'
end
r = CA::RuntimeArg
# puts r.length
# puts r[0].class
unless r == [ CA::CB::NoArg ]
raise 'ERROR'
end
# puts r.length
# puts 'yyy'
r = CA::CB::NoArg
unless r == CA::CB::NoArg
# puts r.class
raise 'ERROR'
end
true
| true |
59e971d4f73379a997ee1d53fbb97792ca65ccee
|
Ruby
|
galestorm/hotel
|
/specs/block_spec.rb
|
UTF-8
| 1,428 | 2.78125 | 3 |
[] |
no_license
|
require_relative 'spec_helper'
describe 'Block' do
let(:check_in) {Date.new(2017,9,5)}
let(:check_out) {Date.new(2017,9,7)}
let(:rooms) {[Hotel_System::Room.new(1)]}
let(:rate_adjustor) {0.75}
let(:my_block) {Hotel_System::Block.new(check_in, check_out, rooms, rate_adjustor)}
describe 'initialize' do
it 'is initialized with a check_in date, check_out date, rooms, and a rate adjustor' do
my_block.must_be_instance_of Hotel_System::Block
my_block.check_in.must_equal check_in
my_block.check_out.must_equal check_out
my_block.rooms.must_equal rooms
my_block.rate_adjustor.must_equal rate_adjustor
end
end
describe 'block_reserve' do
it 'adds a room to a list of reservations within the block' do
my_block.reserve_in_block.must_be_instance_of Array
my_block.rooms_reserved_in_block.each {|room| room.must_be_instance_of Hotel_System::Room}
end
it 'does not allow you to reserve a room if all rooms in block are already reserved' do
my_block.reserve_in_block
proc {my_block.reserve_in_block}.must_raise StandardError
end
end
describe 'find_avail_rooms' do
it 'lists all rooms available within the block' do
my_block.find_avail_rooms.must_be_instance_of Array
my_block.find_avail_rooms.length.must_equal 1
my_block.reserve_in_block
my_block.find_avail_rooms.length.must_equal 0
end
end
end
| true |
e45d9844fab60e0dade1aa541d8f74677f766e94
|
Ruby
|
justindelatorre/ruby_challenges
|
/medium_1/3_pig_latin/pig_latin.rb
|
UTF-8
| 952 | 3.53125 | 4 |
[] |
no_license
|
=begin
https://launchschool.com/exercises/0b445a57
=end
class PigLatin
def self.translate(phrase)
words = phrase.split
arr = words.map do |word|
self.apply_pig_latin(word)
end
arr.size > 1 ? arr.join(' ') : arr.join
end
private
def self.apply_pig_latin(word)
length = word.size - 1
if self.three_letter_rule?(word)
word[3..length] + word[0..2] + 'ay'
elsif self.two_letter_rule?(word)
word[2..length] + word[0..1] + 'ay'
elsif self.other_rules?(word)
word + 'ay'
elsif self.one_letter_rule?(word)
word[1..length] + word[0] + 'ay'
else
word + 'ay'
end
end
def self.three_letter_rule?(word)
word.match(/^sch|thr|[a-z]{1}qu/)
end
def self.two_letter_rule?(word)
word.match(/^ch|qu|th/)
end
def self.one_letter_rule?(word)
word.match(/^[^aeiou]{1}/)
end
def self.other_rules?(word)
word.match(/^xr|yt/)
end
end
| true |
6e126c43d4438f9fe515dc074cf86e7054218b96
|
Ruby
|
marinacor1/headcount
|
/lib/result_set.rb
|
UTF-8
| 280 | 2.65625 | 3 |
[] |
no_license
|
require_relative 'result_entry'
require 'pry'
class ResultSet
attr_reader :matching_districts, :statewide_average
def initialize(entries = [])
@matching_districts = entries.fetch(:matching_districts)
@statewide_average = entries.fetch(:statewide_average)
end
end
| true |
7dda6bf9bcead50ace973f73ddfe09ab5978c50c
|
Ruby
|
neilkelty/learning_ruby
|
/learn_to_program/ch6.rb
|
UTF-8
| 1,995 | 4.15625 | 4 |
[] |
no_license
|
section_break = '====================================='
# List of the 10 methods we've covered in chapters 1 - 5
# puts, gets, to_s, to_i, to_f, chomp, +, -, *, /
puts('hello'.+ 'world')
puts((10.* 9).+ 9)
puts self
puts section_break #Not part of the tutorial, just helps me visually.
#6.1 Fancy String Methods
var1 = 'stop'
var2 = 'deliver repaid desserts'
var3 = '....TCELES B HUSP A magic spell?'
puts var1.reverse
puts var2.reverse
puts var3.reverse
puts var1
puts var2
puts var3
puts section_break #Not part of the tutorial, just helps me visually.
puts 'What famous movie star are you named after?'
first_name = gets.chomp
puts 'How about that terrible middle name your mother gave you?'
middle_name = gets.chomp
puts 'What surname did your father shame you with?'
last_name = gets.chomp
full_name = first_name + ' ' + middle_name + ' ' + last_name
num_chars_in_full_name = first_name.length + middle_name.length + last_name.length
puts 'Did you know ther are ' + num_chars_in_full_name.to_s + ' characters'
puts 'in your name, ' + full_name + '?'
puts section_break #Not part of the tutorial, just helps me visually.
letters = 'aAbBcCdDeE'
puts letters.upcase
puts letters.downcase
puts letters.swapcase
puts letters.capitalize
puts ' a'.capitalize #this doesn't work since capitalize only works on the first letter
puts letters
puts section_break #Not part of the tutorial, just helps me visually.
line_width = 50
puts 'Old Mother Hubbart'.center(line_width)
puts 'Sat in her cupboard'.center(line_width)
puts 'Eating her curtds and why'.center(line_width)
puts 'When along came a spider'.center(line_width)
puts 'Who sat down beside her'.center(line_width)
puts 'And scared her poor shoe dog away'.center(line_width)
puts section_break #Not part of the tutorial, just helps me visually.
line_width = 40
str = '--> text <--'
puts(str.ljust(line_width))
puts(str.center(line_width))
puts(str.rjust(line_width))
puts(str.ljust(line_width/2))
puts(str.rjust(line_width/2))
| true |
81343b589ab46dadaec9a49955580be1f00dd268
|
Ruby
|
tchiu2/stock-portfolio-server
|
/app/services/portfolio_builder.rb
|
UTF-8
| 579 | 2.71875 | 3 |
[] |
no_license
|
module PortfolioBuilder
def self.build(positions)
return positions if positions.empty?
symbols = positions.keys.join(",")
quotes = Iex::Client.quotes(symbols)
positions.reduce({}) do |acc, (k, v)|
quote = quotes[k.to_s]["quote"]
acc.merge(k => {
symbol: k,
name: quote["companyName"],
shares: v,
price: quote["latestPrice"],
value: v * quote["latestPrice"],
change: quote["change"],
changePct: quote["changePercent"],
})
end
.select { |_, v| v[:shares] > 0 }
end
end
| true |
8860f7651fcfc7318ea54195c493aa5ff5d588ee
|
Ruby
|
RomanADavis/learn-programming
|
/learn-ruby-the-hard-way/game/scene.rb
|
UTF-8
| 336 | 3.84375 | 4 |
[] |
no_license
|
class Room
def initialize(name)
@name = name
@visible = [] #list of interactables in the romm
@hidden = [] #hidden items
end
def reveal(item)
if @hidden.include? item
puts "#{item} revealed!"
@visible << @hidden.delete(item)
else
puts "#{item} isn't here."
end
end
end
| true |
65b45fd9a5b54cbdc79fd3f65281e01e096a5cd5
|
Ruby
|
wfsiew/Akamomiji_rails
|
/app/models/reservation.rb
|
UTF-8
| 904 | 2.625 | 3 |
[] |
no_license
|
class Reservation < ActiveRecord::Base
attr_accessible :id, :location, :name, :pax, :phone_no, :remarks, :reserve_date, :reserve_time,
:status, :table
self.table_name = 'reservation'
validates_presence_of :location, message: 'Location is required'
validates_presence_of :name, message: 'Name is required'
validates_presence_of :pax, message: 'Pax is required'
validates_presence_of :phone_no, message: 'Phone no. is required'
validates_presence_of :reserve_date, message: 'Reserve date is required'
validates_presence_of :reserve_time, message: 'Reserve time is required'
validates_presence_of :status, message: 'Status is required'
validates_presence_of :table, message: 'Table is required'
def location_str
ApplicationHelper::Location.str(self.location)
end
def status_str
ApplicationHelper::ReservationStatus.str(self.status)
end
end
| true |
4d6328c7f56adf5c39247090717ad5c247ff6878
|
Ruby
|
Steiner87/Time
|
/app2.rb
|
UTF-8
| 2,543 | 3.25 | 3 |
[] |
no_license
|
def get_dates years,months,days,hours=0,minuts=0,seconds=0
# 1) Создаем объект date и присваиваем ему введенные значения
date=Time.new(years,months,days,hours,minuts,seconds)
# 2)Переводим объект в цифровое Unix отображение
date_unix=date.to_i #Дата в Unix системе исчесления
puts date.strftime "%a, %d %b %Y %H:%M:%S" #Выводим дату в заданом формате впервый раз
date_unix=date.to_i
first_day=days #Фиксируем день с которого был начан отсчет
# 3) Создаем цикл для вывода даты с интервалом в 15 мин
x=true
while x
hours1=Time.at(date_unix).hour
date_unix+=15*60
hours2=Time.at(date_unix).hour
if hours1!=hours2
x=false
end
get_settings date_unix
end
puts '==============================================='
# 4) Создаем цикл для вывода даты с интервалом в 30 мин
x=0
while x!=5
hours1=Time.at(date_unix).hour
date_unix+=30*60
hours2=Time.at(date_unix).hour
if hours1!=hours2
hours1=hours2
x+=1
end
get_settings date_unix
end
puts '==============================================='
# 5) Создаем цикл для вывода даты с интервалом в 1 час
x=0
while x!=7
date_unix+=60*60
x+=1
get_settings date_unix
end
puts '==============================================='
# 6) Создаем цикл для вывода даты с интервалом в 24 часа
x=first_day
while x!=first_day+4
date_unix+=24*60*60
x+=1
get_settings date_unix
end
puts '==============================================='
return 1
end
def get_settings date_unix
years=Time.at(date_unix).year
months=Time.at(date_unix).month
days=Time.at(date_unix).day
hours=Time.at(date_unix).hour
minuts=Time.at(date_unix).min
seconds=Time.at(date_unix).sec
date=Time.new(years,months,days,hours,minuts,seconds)
puts date.strftime "%a, %d %b %Y %H:%M:%S"
end
get_dates 2016,12,22
#get_dates 2017,12,22,19,0,0
| true |
e469822454839d4d2a3446aeb44c6e2cd627aa14
|
Ruby
|
matt-12/Final-Project
|
/FinalProject.rb
|
UTF-8
| 3,037 | 2.90625 | 3 |
[] |
no_license
|
puts "Welcome to Stratego!"
puts "If you take the button labled 'f' then you win!""
require 'fox16'
include Fox
class HelloWorldWindow < FXMainWindow
def initialize(app)
super(app, 'Hello World Program')
@mtx = FXMatrix.new(self, 6)
numbers1 = ["F", "5", "4", "4", "3", "3", "3", "2", "2", "2", "2", "1", "1", "1", "1", "1"].shuffle
numbers2 = ["F", "5", "4", "4", "3", "3", "3", "2", "2", "2", "2", "1", "1", "1", "1", "1"].shuffle
8.times do
6.times do |i|
btn = FXButton.new(@mtx, '', :opts => BUTTON_NORMAL|LAYOUT_FIX_WIDTH|LAYOUT_FIX_HEIGHT, :width => 50, :height => 50)
btn.textColor = :white
if i == 0 || i == 1
btn.backColor = "red"
btn.text = numbers1.pop
elsif i == 2 || i == 3
btn.backColor = "white"
elsif i == 4 || i == 5
btn.backColor = "blue"
btn.text = numbers2.pop
end
btn.connect(SEL_COMMAND) do
if btn.backColor == 4294967295 # white
# nothing
elsif btn.backColor == Fox.fxcolorfromname("red") # red
# fetch the new btn
btn_row = @mtx.rowOfChild(btn)
btn_col = @mtx.colOfChild(btn)
new_btn = @mtx.childAtRowCol(btn_row+1, btn_col)
# if the new btn is white then
if new_btn && new_btn.backColor == Fox.fxcolorfromname("white")
# moves the btn
btn.backColor = "white"
new_btn.backColor = "red"
new_btn.text = btn.text
btn.text = ""
#if red is bigger than blue
elsif new_btn && new_btn.backColor == Fox.fxcolorfromname("blue")
if btn.text.to_i > new_btn.text.to_i
new_btn.backColor = "red"
btn.backColor = "blue"
new_btn.text = btn.text
btn.backColor = "white"
btn.text = ""
end
end
# for blue
elsif btn.backColor == Fox.fxcolorfromname("blue") # blue
btn_row = @mtx.rowOfChild(btn)
btn_col = @mtx.colOfChild(btn)
new_btn = @mtx.childAtRowCol(btn_row-1, btn_col)
if new_btn && new_btn.backColor == Fox.fxcolorfromname("white")
btn.backColor = "white"
new_btn.backColor = "blue"
new_btn.text = btn.text
btn.text = ""
# if blue is bigger than red
elsif new_btn && new_btn.backColor == Fox.fxcolorfromname("red")
if btn.text.to_i > new_btn.text.to_i
new_btn.backColor = "blue"
btn.backColor = "red"
new_btn.text = btn.text
btn.backColor = "white"
btn.text = ""
end
end
end
end
end
end
end
# don't touch this
def create
super
self.show(PLACEMENT_SCREEN)
end
end
# never touch these
app = FXApp.new
HelloWorldWindow.new(app)
app.create
app.run
| true |
27c661f11d9fbe2ab929a3d5132d32b47a8deb92
|
Ruby
|
james-cape/potluck
|
/test/dish_test.rb
|
UTF-8
| 547 | 2.796875 | 3 |
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/pride'
require './lib/dish'
require 'pry'
class DishTest < Minitest::Test
def setup
@dish = Dish.new("Couscous Salad", :appetizer)
end
def test_dish_exists
expected = Dish
actual = @dish
assert_instance_of expected, actual
end
def test_salad_name
expected = "Couscous Salad"
actual = @dish.name
assert_equal expected, actual
end
def test_salad_category
expected = "Couscous Salad"
actual = @dish.name
assert_equal expected, actual
end
end
| true |
179541f91b42249ffd598cf36a76ae531e26cca2
|
Ruby
|
DragonRuby/dragonruby-game-toolkit-contrib
|
/dragon/easing.rb
|
UTF-8
| 3,080 | 2.8125 | 3 |
[
"LicenseRef-scancode-other-permissive",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# easing.rb has been released under MIT (*only this file*).
module GTK
module Easing
def self.ease start_tick, current_tick, duration, *definitions
ease_extended start_tick,
current_tick,
start_tick + duration,
initial_value(*definitions),
final_value(*definitions),
*definitions
end
def self.ease_extended start_tick, current_tick, end_tick, default_before, default_after, *definitions
definitions.flatten!
definitions = [:identity] if definitions.length == 0
duration = end_tick - start_tick
elapsed = current_tick - start_tick
y = elapsed.percentage_of(duration).cap_min_max(0, 1)
definitions.map do |definition|
y = Easing.exec_definition(definition, start_tick, duration, y)
end
y
end
def self.ease_spline start_tick, current_tick, duration, spline
ease_spline_extended start_tick, current_tick, start_tick + duration, spline
end
def self.ease_spline_extended start_tick, current_tick, end_tick, spline
return spline[-1][-1] if current_tick >= end_tick
duration = end_tick - start_tick
t = (current_tick - start_tick).fdiv duration
time_allocation_per_curve = 1.fdiv(spline.length)
spline_t = t.fdiv(time_allocation_per_curve)
curve_index = spline_t.to_i
curve_t = spline_t - spline_t.to_i
Geometry.cubic_bezier curve_t, *spline[curve_index]
end
def self.initial_value *definitions
definitions.flatten!
return Easing.exec_definition (definitions.at(-1) || :identity), 0, 10, 0
end
def self.final_value *definitions
definitions.flatten!
return Easing.exec_definition (definitions.at(-1) || :identity), 0, 10, 1.0
end
def self.exec_definition definition, start_tick, duration, x
if definition.is_a? Symbol
return Easing.send(definition, x).cap_min_max(0, 1)
elsif definition.is_a? Proc
return definition.call(x, start_tick, duration).cap_min_max(0, 1)
end
raise <<-S
* ERROR:
I don't know how to execute easing function with definition #{definition}.
S
end
def self.identity x
x
end
def self.flip x
1 - x
end
def self.quad x
x * x
end
def self.cube x
x * x * x
end
def self.quart x
x * x * x * x * x
end
def self.quint x
x * x * x * x * x * x
end
def self.smooth_start_quad x
quad x
end
def self.smooth_stop_quad x
flip(quad(flip(x)))
end
def self.smooth_start_cube x
cube x
end
def self.smooth_stop_cube x
flip(cube(flip(x)))
end
def self.smooth_start_quart x
quart x
end
def self.smooth_stop_quart x
flip(quart(flip(x)))
end
def self.smooth_start_quint x
quint x
end
def self.smooth_stop_quint x
flip(quint(flip(x)))
end
end
end
Easing = GTK::Easing
| true |
1ab142b59978d944cfcfc4e825197ed6169f16cd
|
Ruby
|
peperon/ProjectEulerProblems
|
/problem9_spec.rb
|
UTF-8
| 246 | 2.71875 | 3 |
[] |
no_license
|
require './problem9'
describe Problem9Solution do
it "Finds the special pythagorean triplet" do
solution = Problem9Solution.new
a, b, c = solution.find
expect(a * a + b * b).to eq(c * c)
expect(a + b + c).to eq(1000)
end
end
| true |
d111b871e1792347b37a3c01a57ab48e47d5843e
|
Ruby
|
ambshar/lsruby
|
/assessment/atbash.rb
|
UTF-8
| 455 | 3.375 | 3 |
[] |
no_license
|
require 'pry'
class Atbash
KEYS = ("a".."z").to_a
VALUES = KEYS.reverse
CODE_KEY = Hash[KEYS.zip(VALUES)]
def self.encode(string)
string_array = string.downcase.scan(/[a-z0-9]/)
#output = []
result = string_array.each_with_object([]) do |chr, output|
output << (chr.to_i == 0 ? CODE_KEY[chr] : chr)
end
result.join.scan(/.{1,5}/).join(" ")
binding.pry
end
end
p Atbash.encode("the whole 45 thing@ is that...")
| true |
6d30496bae2f69780271a6b3c1fb9921bdf334da
|
Ruby
|
jonnyguio/GildedRose-Refactoring-Kata
|
/ruby/gilded_rose.rb
|
UTF-8
| 1,245 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
class GildedRose
def initialize(items)
@items = items
end
def update_quality
@items.each do |item|
if item.name.include?('Backstage passes')
item.quality += 1 if item.sell_in > 10
item.quality += 2 if (item.sell_in <= 10) && (item.sell_in > 5)
item.quality += 3 if item.sell_in <= 5
item.sell_in -= 1
item.quality = 0 if item.sell_in.negative?
elsif !item.name.include?('Sulfuras')
factor = 0
factor = case item.name
when 'Aged Brie'
1
when /Conjured/
-2
else
-1
end
item.sell_in -= 1
if (item.quality >= 0) && (item.quality <= 50)
item.quality += factor
item.quality += factor if item.sell_in.negative?
end
item.quality = 50 if item.quality > 50
item.quality = 0 if item.quality.negative?
end
end
end
end
class Item
attr_accessor :name, :sell_in, :quality
def initialize(name, sell_in, quality)
@name = name
@sell_in = sell_in
@quality = quality
end
def to_s
"#{@name}, #{@sell_in}, #{@quality}"
end
end
| true |
79fdacb4c6db27331a135ebe45cdd08bc4a58209
|
Ruby
|
DrDhoom/RMVXA-Script-Repository
|
/Himeworks/Post_Battle_Events.rb
|
UTF-8
| 6,632 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
=begin
#===============================================================================
Title: Post-Battle Events
Author: Hime
Date: Nov 18, 2015
--------------------------------------------------------------------------------
** Change log
Nov 18, 2015
- fixed bug where post battle victory event only ran once
Aug 10, 2013
- Re-structured script to make compatibility easier to handle
May 12, 2013
- Initial release
--------------------------------------------------------------------------------
** Terms of Use
* Free to use in non-commercial projects
* Contact me for commercial use
* No real support. The script is provided as-is
* Will do bug fixes, but no compatibility patches
* Features may be requested but no guarantees, especially if it is non-trivial
* Credits to Hime Works in your project
* Preserve this header
--------------------------------------------------------------------------------
** Description
This script allows you to set up troop event pages as "post battle" events.
These events will run after the battle is over, but before the game leaves
the battle scene. It allows you to run extra events that should occur after
the victory/defeat message.
--------------------------------------------------------------------------------
** Installation
Place this script below Materials and above Main
--------------------------------------------------------------------------------
** Usage
To set a post-battle event page, add one of the following comments
<post battle victory> - runs after victory
<post battle defeat> - runs after defeat
The page will automatically be run when the condition is met.
--------------------------------------------------------------------------------
** Compatibility
This script defines custom victory and defeat processing methods in
BattleManager.
#===============================================================================
=end
$imported = {} if $imported.nil?
$imported["TH_PostBattleEvents"] = true
#===============================================================================
# ** Configuration
#===============================================================================
module TH
module Post_Battle_Events
Victory_Regex = /<post battle victory>/i
Defeat_Regex = /<post battle defeat>/i
end
end
#===============================================================================
# ** Rest of script
#===============================================================================
module RPG
class Troop
def post_battle_victory_event
return @post_battle_events[:victory] unless @post_battle_events.nil?
parse_post_battle_event
return @post_battle_events[:victory]
end
def post_battle_defeat_event
return @post_battle_events[:defeat] unless @post_battle_events.nil?
parse_post_battle_event
return @post_battle_events[:defeat]
end
def parse_post_battle_event
@post_battle_events = {}
to_delete = []
@pages.each do |page|
if page.parse_post_battle_event(@post_battle_events)
to_delete << page
end
end
to_delete.each do |page|
@pages -= to_delete
end
end
end
class Troop::Page
def parse_post_battle_event(post_events)
@list.each do |cmd|
if cmd.code == 108
if cmd.parameters[0] =~ TH::Post_Battle_Events::Victory_Regex
post_events[:victory] = self
return true
elsif cmd.parameters[0] =~ TH::Post_Battle_Events::Defeat_Regex
post_events[:defeat] = self
return true
end
end
end
return false
end
end
end
module BattleManager
#-----------------------------------------------------------------------------
# Overwrite.
#-----------------------------------------------------------------------------
def self.process_victory
play_battle_end_me
replay_bgm_and_bgs
$game_message.add(sprintf(Vocab::Victory, $game_party.name))
display_exp
gain_gold
gain_drop_items
gain_exp
process_post_victory_event #-- you can customize this
SceneManager.return
battle_end(0)
return true
end
#-----------------------------------------------------------------------------
#
#-----------------------------------------------------------------------------
def self.process_defeat
$game_message.add(sprintf(Vocab::Defeat, $game_party.name))
wait_for_message
process_post_defeat_event #-- you can customize this
if @can_lose
revive_battle_members
replay_bgm_and_bgs
SceneManager.return
else
SceneManager.goto(Scene_Gameover)
end
battle_end(2)
return true
end
def self.process_post_victory_event
SceneManager.scene.process_post_victory_event if $game_troop.post_battle_victory_event
end
def self.process_post_defeat_event
SceneManager.scene.process_post_defeat_event if $game_troop.post_battle_defeat_event
end
end
#-------------------------------------------------------------------------------
# Post battle process events defined in the troop objects
#-------------------------------------------------------------------------------
class Game_Troop < Game_Unit
def post_battle_victory_event
troop.post_battle_victory_event
end
def post_battle_defeat_event
troop.post_battle_defeat_event
end
def setup_victory_event
return unless post_battle_victory_event
@interpreter.setup(post_battle_victory_event.list)
end
def setup_defeat_event
return unless post_battle_defeat_event
@interpreter.setup(post_battle_defeat_event.list)
end
end
#-------------------------------------------------------------------------------
# Perform post-process battle event processing
#-------------------------------------------------------------------------------
class Scene_Battle < Scene_Base
def process_post_victory_event
$game_troop.setup_victory_event
while !scene_changing?
$game_troop.interpreter.update
wait_for_message
wait_for_effect if $game_troop.all_dead?
process_forced_action
break unless $game_troop.interpreter.running?
update_for_wait
end
end
def process_post_defeat_event
$game_troop.setup_defeat_event
while !scene_changing?
$game_troop.interpreter.update
wait_for_message
wait_for_effect if $game_party.all_dead?
process_forced_action
break unless $game_troop.interpreter.running?
update_for_wait
end
end
end
| true |
4fa0cc888dd5fb0fda7a0baedc2ed7b134e34d3c
|
Ruby
|
smirik/Three-body-resonances
|
/classes/body.rb
|
UTF-8
| 195 | 2.75 | 3 |
[] |
no_license
|
require 'classes/body_elements.rb'
require 'classes/degrees.rb'
class Body
attr_accessor :mass, :pos, :vel, :time
def pp
puts "Axis: #{@axis}, mean motion: #{@mean_motion}"
end
end
| true |
3877d99cf8d67d292381360543e364ed4f282ada
|
Ruby
|
srekhi/goal_tracker
|
/app/models/post.rb
|
UTF-8
| 540 | 2.734375 | 3 |
[] |
no_license
|
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# body :text
# author :string
#
class Post < ApplicationRecord
validate :has_sunny_in_body
validates :body, presence: true, length: { minimum: 7 }
validates :author, presence: true
def has_sunny_in_body
unless self.body && self.body.include?("Sunny")
errors[:body] << "Doesn't have a reference to Sunny!"
end
end
end
| true |
ccd7e579dd9e63ab9cfbc3177a0a5e59104df481
|
Ruby
|
ReaazDollie/dummy_text
|
/lib/dummy_text/word.rb
|
UTF-8
| 383 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
require 'dummy_text/text'
module DummyText
class Word < Text
def initialize
end
def render(count, template)
data = get_file_as_array(template)
data.join.split('. ').join.split[0...count].join(" ")
end
def self.number_of_words(template)
data = self.get_file_as_string(template)
data.scan(/(\w|-)+/).size
end
end
end
| true |
15afa81e9bb6f97e9121658ae48d8051c5770898
|
Ruby
|
tdyer/EMRack
|
/event_machine/async_server.rb
|
UTF-8
| 1,310 | 2.578125 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
# http://www.igvita.com/2008/05/27/ruby-eventmachine-the-speed-demon/
require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
# install the gem
# gem install eventmachine_httpserver
# to run:
# async_server.rb
# 5 clients each making 2 requests
# ab -n 10 -c 5 http://127.0.0.1:9292/
class SimpleASyncHandler < EM::Connection
include EM::HttpServer
def post_init
puts "SimpleASyncHandler#post_init: establishing a connection with client, thread = #{Thread.current}"
super
end
def process_http_request
puts "SimpleASyncHandler#process_http_request: BEGIN"
response = EM::DelegatedHttpResponse.new(self)
http = EM::Protocols::HttpClient.request(:host=>"127.0.0.1", :port=>3333,:request=>"/" )
# setup callback handler, when the client responds
http.callback do |reply|
puts "SimpleASyncHandler#process_http_request: responding in the callback"
response.status = 200
response.content_type 'text/html'
response.content = reply[:content]
response.send_response
end
puts "SimpleASyncHandler#process_http_request: DONE"
end
end
EM.run do
puts "EM#run: thread = #{Thread.current}"
puts "EM#run: Starting a HTTP server on port 8011"
EM.start_server '0.0.0.0', 8011, SimpleASyncHandler
end
| true |
8347accf89b2ce1f5f2f234bf51625eb416dceae
|
Ruby
|
nysol/doc
|
/olddoc/mcmd/jp/examples/mjoin.rb
|
UTF-8
| 1,127 | 2.78125 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
# coding: utf-8
require "./mkTex.rb"
File.open("dat1.csv","w"){|fpw| fpw.write(
<<'EOF'
item,date,price
A,20081201,100
A,20081213,98
B,20081002,400
B,20081209,450
C,20081201,100
EOF
)}
File.open("ref1.csv","w"){|fpw| fpw.write(
<<'EOF'
item,cost
A,50
B,300
E,200
EOF
)}
############## 例1
title="基本例"
comment=<<'EOF'
入力ファイルにある\verb|item|項目と、
参照ファイルにある\verb|item|項目を比較し同じ値の場合、\verb|cost|項目を結合する。
EOF
scp=<<'EOF'
more dat1.csv
more ref1.csv
mjoin k=item f=cost m=ref1.csv i=dat1.csv o=rsl1.csv
more rsl1.csv
EOF
run(scp,title,comment)
############## 例2
title="未結合データ出力"
comment=<<'EOF'
入力ファイルにある\verb|item|項目と、
参照ファイルにある\verb|item|項目を比較し同じ値の場合、\verb|cost|項目を結合する。
その際、参照データにない入力データと参照データにない範囲データをNULL値として出力する。
EOF
scp=<<'EOF'
mjoin k=item f=cost m=ref1.csv -n -N i=dat1.csv o=rsl2.csv
more rsl2.csv
EOF
run(scp,title,comment)
| true |
9d5c9c84321eac28cc6cca022c8a0870fc7b0066
|
Ruby
|
software-engineering-amsterdam/many-ql
|
/geert.kai/spec/type_checker_spec.rb
|
UTF-8
| 1,489 | 2.703125 | 3 |
[] |
no_license
|
require_relative "spec_helper"
describe "Type checker" do
it "detects duplicate labels" do
question = QL::AST::Question.new("Wat is uw leeftijd?", "leeftijd", IntegerType.new)
form = Form.new("dubbel label", [question, question])
errors = form.accept(DuplicateLabelChecker.new)
expect(errors.first.message).to match /Duplicate label: Wat is uw leeftijd?/
expect(errors.size).to eq 1
end
xit "detects if the type doesn't match up" do
question = QL::AST::Question.new("Wat is je naam?", "naam", StringType.new)
conditional = IfElse.new(GreaterThan.new(Variable.new("naam"), IntegerLiteral.new(8)), [], [])
form = Form.new("Test", [question, conditional])
errors = form.accept(TypeChecker.new)
expect(errors.first.message).to match /not a valid argument type/
expect(errors.size).to eq 1
end
it 'complains if expression of a conditional is not of type boolean' do
conditional = IfElse.new(IntegerLiteral.new(3), [], [])
form = Form.new("Test", [conditional])
errors = form.accept(TypeChecker.new)
expect(errors.first.message).to match /not a boolean/
expect(errors.size).to eq 1
end
it 'detects undefined variables' do
conditional = IfElse.new(Equal.new(Variable.new("naam"), StringLiteral.new("Geert")), [], [])
form = Form.new("Test", [conditional])
errors = form.accept(UndefinedVariableChecker.new)
expect(errors.first.message).to match /naam/
expect(errors.size).to eq 1
end
end
| true |
8163d43059685e39149c1057337044c772419bf6
|
Ruby
|
cycloped-io/cycloped-io
|
/classification/utils/select_specs.rb
|
UTF-8
| 2,122 | 2.8125 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
# encoding: utf-8
require 'bundler/setup'
$:.unshift 'lib'
$:.unshift '../category-mapping/lib'
require 'slop'
require 'csv'
require 'cycr'
require 'progress'
require 'mapping'
options = Slop.new do
banner '#{$PROGRAM_NAME} -f terms.csv -o specs.csv -t term [-h host] [-p port]\n' +
'Select specs or instances of the term from the file with Cyc terms'
on :f=, :input, 'File with Cyc terms: id, name', required: true
on :o=, :output, 'File with specs', required: true
on :r=, :rest, 'File with the remainin terms', required: true
on :t=, :term, 'Term whose specs are selected', required: true, as: Symbol
on :h=, :host, 'Cyc host (localhost)', default: 'localhost'
on :p=, :port, 'Cyc port (3601)', as: Integer, default: 3601
on :m=, :mode, 'Select: s - specs, i - instances, m - min specs', default: 's'
end
begin
options.parse
rescue Exception
puts options
exit
end
method =
if options[:mode] == 's'
:genls?
else
:isa?
end
cyc = Cyc::Client.new(host: options[:host], port: options[:port], cache: true)
name_service = Mapping::Service::CycNameService.new(cyc)
selected = 0
unselected = 0
CSV.open(options[:input],"r:utf-8") do |input|
CSV.open(options[:output],"w") do |output|
CSV.open(options[:rest],"w") do |rest|
begin
input.with_progress do |id,name|
term = name_service.find_by_id(id)
if term.nil?
puts "Missing term #{id} #{name}"
next
end
result = false
if options[:mode] == 'm'
result = (cyc.with_any_mt{|c| c.min_genls(term) } || []).include?(options[:term])
else
result = cyc.with_any_mt{|c| c.send(method,term,options[:term]) }
end
if result
output << [id,name]
selected += 1
else
rest << [id,name]
unselected += 1
end
end
rescue Interrupt
# interrupt gracefully
end
end
end
end
puts "Selected/unselected #{selected}/#{unselected}/#{(selected/(selected + unselected).to_f * 100).round(1)}%"
| true |
3c898dd2796ae916ab02f33d96a21c314d043aa0
|
Ruby
|
chdmark/phase-0
|
/week-5/calculate-mode/my_solution.rb
|
UTF-8
| 2,219 | 4.03125 | 4 |
[
"MIT"
] |
permissive
|
# Calculate the mode Pairing Challenge
# I worked on this challenge with Mike Cerrone
# I spent 1.5 hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented.
# 0. Pseudocode
# What is the input? An Array of strings or integers
# What is the output? (i.e. What should the code return?) The mode of that array
# What are the steps needed to solve the problem?
#Create a method that takes an array as the argument
#Create a new hash that sets the value to zero and iterate through all of the array elements
#Increment the value by one
# 1. Initial Solution
def mode(array)
h = Hash.new(0)
array.each do |i|
h[i] += 1
end
h.sort_by {|key, value| p value}
key = h.keys[0]
p key
p Array.new(1, key)
end
mode([8,4,5,3,3,3,2,2,1])
# 3. Refactored Solution
def mode(array)
h = Hash.new(0)
array.each do |i|
h[i] += 1
end
mode_array=[]
h.each do |key, value|
if value == h.values.max
mode_array.push(key)
end
end
p mode_array
end
mode([6, 5, 5, 5, 9])
# 4. Reflection
=begin
Which data structure did you and your pair decide to implement and why?
Were you more successful breaking this problem down into implementable pseudocode than the last with a pair?
What issues/successes did you run into when translating your pseudocode to code?
What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement?
We decided to implement a hash because we wanted a key/value pair. We wanted to keep track of the number of times a key was in the
array. I think we were able to pseudcode the first steps such as iterating over the hash at first to get the value. However,
we had some trouble turning it into a new array and sorting the hash by the amount of times a number was repeated. We used
the each method at first to iterate over the hash and passed in number of the array into the hash. We wanted to use the inject method,
but couldn't figure out our own initial solution. We eventually resorted to an if statement, and used push to push the key to the new array.
end
| true |
e2fb1f10d7498770408b412c64e1e68c31e08586
|
Ruby
|
ncbo/goo
|
/lib/goo/validators/implementations/superior_equal_to.rb
|
UTF-8
| 646 | 2.6875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
module Goo
module Validators
class SuperiorEqualTo < ValidatorBase
include Validator
key :superior_equal_to_
error_message ->(obj) {
"`#{@attr}` must be superior or equal to `#{@property}`"
}
validity_check -> (obj) do
target_values = self.class.attr_value(@property, @inst)
return true if target_values.nil? || target_values.empty?
return Array(@value).all? {|v| v.nil? || target_values.all?{|t_v| v >= t_v}}
end
def initialize(inst, attr, value, key)
super(inst, attr, value)
@property = self.class.property(key)
end
end
end
end
| true |
26f4bafc65e6558df356a4e31e15a99d73b28aa2
|
Ruby
|
yanshiyason/cob
|
/lib/credentials.rb
|
UTF-8
| 1,729 | 2.96875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
#
# class to handle the credentials
#
# usage:
#
# c = Credentials.new
# c.username
# c.pa_token
#
class Credentials
def initialize
@config_file = ENV['GITHUB_CREDENTIALS_FILE'] ||
"#{ENV['HOME']}/.cob/github_credentials.json"
end
def config
@config ||= parse_config
end
def username
# USERNAME
config['username'] || prompt_username
end
def pa_token
# PA_TOKEN
config['paToken'] || prompt_pa_token
end
def overwrite_config
File.write(@config_file, config.to_json)
end
def prompt_username
prompt = TTY::Prompt.new(active_color: :cyan)
username = prompt.ask('What is your github username?') do |q|
q.required true
q.modify :lowercase
end
config['username'] = username
overwrite_config
username
end
def prompt_pa_token
prompt = TTY::Prompt.new(active_color: :cyan)
token = prompt.ask('What is your github personal access token? You can get one from here: https://github.com/settings/tokens') do |q|
q.required true
end
config['paToken'] = token
overwrite_config
token
end
def reset_config_file
File.write(@config_file, '{}')
end
def ensure_config_file_is_created
return if File.exist?(@config_file)
segments = @config_file.split('/')
paths = segments[0..-2]
file = segments[-1]
dir = paths.join('/')
FileUtils.mkdir_p(dir)
FileUtils.touch(dir + '/' + file)
reset_config_file
end
private
def parse_config
JSON.parse(File.read(@config_file))
rescue StandardError => e
puts "Couldn't parse config file. Make sure the JSON is correct:\n#{@config_file}"
raise e
end
end
| true |
72732f2163f97f511ec03666bf9f2e0e7d1ada4f
|
Ruby
|
BenRKarl/WDI_work
|
/w03/d02/Corey_Leveen/yellow_submarine/app.rb
|
UTF-8
| 706 | 2.921875 | 3 |
[] |
no_license
|
require 'bundler'
Bundler.require
get '/' do
class Sailor
attr_accessor :name
def initialize(name)
@name = name
end
end
class Submarine
attr_accessor :color, :sailors
def initialize(color='yellow')
@color = color
@sailors = []
end
def accept_sailor(sailor)
@sailors << sailor
end
def torpedo_sailor
@sailors.delete(@sailors.sample)
end
end
proto = ['Jeff Winkler','John Murphy','Nessa Nguyen','Jeff Drakos','Rebecca Strong','Gardner Lonsberry' ,'Jonathan Gean','Nathaniel Tuvera','Tim Hannes','Aziz Hasanov','Chris Heuberger','Dmitry Shamis' ,'Corey Leveen','Paul Hiam','Steven Doran','Ben Karl','Kristen Tonga','Wake Lankard','Carlos Pichardo' ,'Paul Gasberra','Andrea Trapp','Heidi Williams-Foy' ]
@the_sub = Submarine.new
proto.each do |x|
@the_sub.accept_sailor(Sailor.new(x))
end
erb :index
end
| true |
a1413a91c0ebcf5ee2e3573aa239e6f6b72f9fbb
|
Ruby
|
MadBomber/experiments
|
/ruby_misc/table_read/spec_script.rb
|
UTF-8
| 8,251 | 2.875 | 3 |
[] |
no_license
|
# table_read/spec_script.rb
require 'pathname'
require_relative './db_access'
require_relative './talent_pool'
# Provides access to the contents of
# a ScenArtist (Scene Artist) script
# which stored in an SQLite database.
class SpecScript
attr_accessor :raw
attr_accessor :script
attr_accessor :characters
attr_accessor :scene_names
# a reorganized array of hashes
# each entry in the array is a scene
# a scene is a hash
# { scene_heading: 'text', says: [] }
# eachs says element is an array of hashes
# { 'action | character name' => 'text'}
attr_accessor :scenes
attr_accessor :cast
attr_accessor :talent
def initialize(a_file_path)
@db_path = a_file_path
load_script(a_file_path)
collect_scene_names
collect_characters
assign_cast(a_file_path)
build_scenes
end
def table_read(scene_number=nil)
raise "Bas Scebe Bynber. Must be between 1 and #{@scenes.size}" unless scene_number.nil? || ([email protected]).include?(scene_number)
debug_me{[ 'scene_number.class' ]}
case scene_number.class.to_s
when 'Integer'
sn = scene_number - 1
debug_me{[ '@scenes[sn][:says]', :sn ]}
@talent.screen_test(@scenes[sn][:says])
when 'Range'
scene_number.each do |sn|
@talent.screen_test(@scenes[sn-1][:says])
end
when 'NilClass'
@scenes.size.times do |sn|
@talent.screen_test(@scenes[sn][:says])
end
end
return nil
end
def assign_cast(ss_file_path)
@cast = {}
@talent = ::TalentPool.new
cast_path = ss_file_path.parent + ss_file_path.basename.to_s.gsub('kitsp','cast')
if cast_path.exist?
@cast = YAML.load cast_path.read
@talent.assign_cast @cast
else
@talent.auto_cast @characters
@talent.cast.each_pair do |character, actor|
@cast[character] = actor.name
end
end
return @cast
end
def save_script_as_xml
dir = Pathname.pwd # @db_path.parent
base = 'script' # @db_path.basename.to_s
xml_path = dir + "#{base}.xml"
xml_path.write @xml
end
def load_script(file_path)
Database.setup(file_path)
@scenarios = Scenario.all
@xml = @scenarios.first.text
@raw = Nokogiri.parse @xml
@script = @raw.elements[0]
end
def collect_scene_names
sn = 0 # scene)number
@scene_names = @script.xpath('//scene_heading/v').map{|e| "#{sn+=1} - "+e.text.strip}
end
def collect_characters
@characters = @script.xpath('//character/v').map{|e| e.text.gsub(/\(.+\)/,'').strip.upcase}.uniq
@characters << 'action'
end
def add_scene(e)
scene_heading = "#{@scenes.size + 1} - " + e.xpath('./v').text.strip
@scenes << {
'screen_header' => scene_heading,
says: [
{
'action' => "Scene Number #{scene_heading}"
}
]
}
end
# returns two index. The first is the scene_number(sn).
# The second index is the scene_says_number(ssn).
# e.g. @scenes[sn][:says][ssn]
def get_scene_indexes
sn = @scenes.size - 1
ssn = @scenes[sn][:says].size - 1
return [sn, ssn]
end
def add_action(e)
sn, ssn = get_scene_indexes
action = e.xpath('./v').text.strip
if !@scenes[sn][:says].empty? && @scenes[sn][:says].last.has_key?('action')
prev_action = @scenes[sn][:says][ssn]['action']
@scenes[sn][:says][ssn]['action'] = prev_action + "\n" + action
else
@scenes[sn][:says] << {
'action' => action
}
end
end
def add_character(e)
@current_character = e.xpath('./v').text.strip.upcase
if @current_character.include?('(')
sn, ssn = get_scene_indexes
parenthetical = @current_character.match(/(\(.+\))/)[1]
@current_character.gsub!(/\(.+\)/,'').strip!
@scenes[sn][:says] << {
'action' => sayable_parenthetical(parenthetical)
}
end
return @current_character
end
def sayable_parenthetical(parenthetical)
case parenthetical
when '(O.S)', '(O. S.)'
'from off screen'
when "(CONT'D)", "(CON'T)"
"#{@current_character} continues speaking"
else
parenthetical
end
end
def add_dialog(e)
sn, ssn = get_scene_indexes
dialog = e.xpath('./v').text.strip
if @current_character == @scenes[sn][:says][ssn].keys.first
@scenes[sn][:says][ssn][@current_character] += dialog
else
@scenes[sn][:says] << {
@current_character => dialog
}
end
end
def build_scenes
@scenes = []
scene_number = -1
@script.elements.each do |e|
if 'scene_heading' == e.name
add_scene(e)
elsif 'action' == e.name
add_action(e)
elsif 'parenthetical' == e.name
add_action(e)
elsif 'character' == e.name
add_character(e)
elsif 'dialog' == e.name
add_dialog(e)
else
# do nothing
end
end
end
def display_script
scene_number = 0
@script.elements.each do |e|
if 'character' == e.name
character_name = e.children[1].children[0].to_str
printf "\ncharacter: %s\n", character_name
elsif 'dialog' == e.name
dialog = e.children[1].children[0].to_str
printf "\ndialog: %s\n", dialog
elsif 'action' == e.name
action = e.children[1].children[0].to_str
printf "\naction: %s\n", action
elsif 'parenthetical' == e.name
parenthetical = e.children[1].children[0].to_str
printf "\nparenthetical: %s\n", parenthetical
elsif 'scene_heading' == e.name
scene_number += 1
scene_heading = e.children[1].children[0].to_str
printf "\nscene: SN-%d - %s\n", scene_number, scene_heading
else
puts
puts e.name
ap e
end
end # @script.elements.each do |e|
return nil
end
end # class SpecScript
__END__
The ScenArtist XML layout is simplistic, linear and flat.
This is found in the Scenario table, text column.
<?xml version="1.0"?>
<scenario version="1.0">
<scene_heading uuid="{000000-0000000-000000}">
<v>
<![CDATA[INT. COMPUTER ROOM]]>
</v>
</scene_heading>
<action>
<v>
<![CDATA[The writer has just installed and activateed the new script editor.]]>
</v>
</action>
<character>
<v>
<![CDATA[WRITER]]>
</v>
</character>
<dialog>
<v>
<![CDATA[What do I do now?]]>
</v>
</dialog>
<character>
<v>
<![CDATA[DIGITAL ASSISTANT]]>
</v>
</character>
<dialog>
<v>
<![CDATA[You write your screen play.]]>
</v>
</dialog>
<character>
<v>
<![CDATA[WRITER]]>
</v>
</character>
<dialog>
<v>
<![CDATA[How do I do that? ]]>
</v>
</dialog>
<parenthetical>
<v>
<![CDATA[(beat)]]>
</v>
</parenthetical>
<dialog>
<v>
<![CDATA[I have no ideas.]]>
</v>
</dialog>
<character>
<v>
<![CDATA[DIGITAL ASSISTANT]]>
</v>
</character>
<dialog>
<v>
<![CDATA[Sounds like a personal problem.]]>
</v>
</dialog>
<character>
<v>
<![CDATA[WRITER]]>
</v>
</character>
<dialog>
<v>
<![CDATA[You are not being very helpful.]]>
</v>
</dialog>
<character>
<v>
<![CDATA[DIGITAL ASSISTANT]]>
</v>
</character>
<dialog>
<v>
<![CDATA[If you wanted a helpful assistant you should have bought a macintosh.]]>
</v>
</dialog>
<scene_heading uuid="{60585259-47bf-43c1-a074-0cd9f8a4a53d}">
<v>
<![CDATA[INT. COMPUTER ROOM]]>
</v>
</scene_heading>
<action>
<v>
<![CDATA[Days have passed. The writer appears to be in the same cloths. Paper plates with half-eaten food items and pizza boxes all visible all over the office.]]>
</v>
</action>
<character>
<v>
<![CDATA[WRITER]]>
</v>
</character>
<dialog>
<v>
<![CDATA[That's the end. 130 pages of the best stuff I have ever done. I could not have done it without your help.]]>
</v>
</dialog>
<character>
<v>
<![CDATA[DIGITAL ASSISTANT]]>
</v>
</character>
<dialog>
<v>
<![CDATA[Its a good thing you did have a macintosh.]]>
</v>
</dialog>
</scenario>
| true |
ba391b330fc2d0741c41273655da2f4dd52c13b4
|
Ruby
|
zaheerkth/operators-dumbo-web-career-010719
|
/lib/operations.rb
|
UTF-8
| 154 | 3.140625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def unsafe?(speed)
if speed >60 || speed <40
true
else
false
end
end
def not_safe?(speed)
speed.between?(40,60)?false:true
end
| true |
70fc95250a7eed9b16fe0bf5c25ec776c802cb63
|
Ruby
|
proxyto/RubyTasks
|
/WarmUpWeek/digits.rb
|
UTF-8
| 316 | 3.484375 | 3 |
[] |
no_license
|
def to_digits(n)
n.to_s.chars.map {|d| d.to_i}
end
def count_digits(n)
to_digits(n).length
end
def sum_digits(n)
to_digits(n).reduce {|a,e| a+e}
end
def factorial_digits(n)
to_digits(n).reduce {|a,e| a*e}
end
puts to_digits(12345)
puts count_digits(12345)
puts sum_digits(12345)
puts factorial_digits(12345)
| true |
f2eb4a5c50436cb8dfba716e2f2e78b7b4ee1c79
|
Ruby
|
WillRadi/rental_cars
|
/app/models/rental.rb
|
UTF-8
| 1,026 | 2.671875 | 3 |
[] |
no_license
|
class Rental < ApplicationRecord
belongs_to :customer
belongs_to :car_category
has_one :car_rental
validate :end_date_must_be_greater_than_start_date
validate :start_date_is_not_past
validate :end_date_is_not_past
enum status: { scheduled: 0, ongoing: 5 }
before_create :create_code
private
def end_date_must_be_greater_than_start_date
errors.add(:end_date, 'Data final deve ser maior do que data inicial') if start_is_greater_than_end?
end
def start_date_is_not_past
errors.add(:start_date, 'Data inicial não pode ser menor do que o dia corrente') if start_date.past?
end
def end_date_is_not_past
errors.add(:end_date, 'Data final deve ser maior do que o dia corrente') if end_date_past_or_today?
end
def start_is_greater_than_end?
return if start_date.blank? || end_date.blank?
start_date >= end_date
end
def end_date_past_or_today?
end_date.today? || end_date.past?
end
def create_code
self.code = SecureRandom.alphanumeric(6).upcase
end
end
| true |
26787a0c442ca0e62145dde15345095abdaf7397
|
Ruby
|
NgariNdungu/dsa
|
/rb_bin_search.rb
|
UTF-8
| 576 | 3.453125 | 3 |
[] |
no_license
|
def bin_search(item, search_list)
found = false
return found if search_list.empty?
while !found
mid = search_list.length / 2
if search_list[mid] == item
found = true
elsif search_list[mid] < item
return bin_search(item, search_list[mid+1..-1])
else
return bin_search(item, search_list[0...mid])
end
end
return found
end
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
$\ = "\n"
print(bin_search(3, testlist))
print(bin_search(13, testlist))
# print(bin_search_no_recurse(3, testlist))
# print(bin_search_no_recurse(13, testlist))
| true |
50c707dc51d9f1385c0ca0d9cb81935de3a1d736
|
Ruby
|
soycake/ruby-examples
|
/6_1_metaprogramming_eval.rb
|
UTF-8
| 101 | 3.296875 | 3 |
[] |
no_license
|
# Simple evaluation of ruby code in a string
ruby_code = '3.times { puts "hello" }'
eval ruby_code
| true |
172b681353d007d3de790e81f19011c8f4daf13f
|
Ruby
|
Thomas008/ruby-excel-library-examples
|
/reo_example.rb
|
UTF-8
| 526 | 2.96875 | 3 |
[] |
no_license
|
require 'robust_excel_ole'
# ============================================
# =========== Read Example ===============
# ============================================
workbook = RobustExcelOle::Workbook.open './sample_excel_files/xlsx_500_rows.xlsx'
puts "Found #{workbook.worksheets_count} worksheets"
workbook.each do |worksheet|
puts "Reading: #{worksheet.name}"
num_rows = 0
worksheet.values.each do |row_vals|
row_cells = row_vals
num_rows += 1
end
puts "Read #{num_rows} rows"
end
puts 'Done'
| true |
dfec295cc2a25557b0d1e2a909aec450ba3c3e02
|
Ruby
|
johnpooley/week_2_day_2_homework
|
/river.rb
|
UTF-8
| 282 | 3.328125 | 3 |
[] |
no_license
|
class River
attr_accessor :fish
def initialize(name)
@name = name
@fish = []
end
def fishcount
return @fish.count
end
def throw_fish_in_river(new_fish)
@fish << new_fish
end
def fish_out_of_water(fish)
return @fish.delete(fish)
end
end
| true |
9232f370e1dae5b58d40764856e2007de16fb44f
|
Ruby
|
SlevinKelevra/thinknetica
|
/Lesson9/train.rb
|
UTF-8
| 1,729 | 3.203125 | 3 |
[] |
no_license
|
require_relative 'modules'
require_relative 'instance_counter'
require_relative 'validation'
class Train
include Manufacturer
include InstanceCounter
include Validation
attr_accessor :current_speed, :wagon, :numer
NUMBER_FORMAT = /^[a-z0-9]{3}-*[a-z0-9]{2}/
@@trains = {}
def self.find(numer)
@@trains[numer]
end
validate :numer, :format, NUMBER_FORMAT
def initialize(numer)
@numer = numer
validate!
@type = self.class
@wagon = []
@current_speed = 0
@@trains[numer] = self
register_instance
end
def number_train_valid?
validate!
rescue
false
end
def dial_speed(dial)
self.current_speed += dial
end
def brake_speed
self.current_speed = 0
end
def hitch_vag(wagon)
@wagon << wagon if @current_speed.zero? && type_wagon?(wagon)
end
def detach_vag(wagon)
@wagon.delete(wagon) if @current_speed.zero? && [email protected]?
end
def route_station(route)
@route = route
@index_station = 0
end
def forward
@index_station += 1 if @index_station < @route.stations.size - 1
current_station.taking_train(self)
previous_station.leave_train(self)
end
def back_station
@index_station -= 1 if @index_station > 0
current_station.taking_train(self)
next_station.leave_train(self)
end
def current_station
@route.stations[@index_station] if @route
end
def previous_station
@route.stations[@index_station - 1] if @index_station > 0
end
def next_station
@route.stations[@index_station + 1] if @index_station < @route.stations.size - 1
end
def each_wagon
wagon.each.with_index(1) { |car, index| yield(car, index) }
end
private
def type_wagon?(wagon); end
end
| true |
143b26e690adb71b767fa44c7ca9c3aac684bb16
|
Ruby
|
thomthom/SketchUp-Ruby-API-Doc
|
/lib/materialsobserver.rb
|
UTF-8
| 4,845 | 2.609375 | 3 |
[] |
no_license
|
module Sketchup
# This observer interface is implemented to react to {Material}s events.
# To implement this observer, create a Ruby class of this type, override the
# desired methods, and add an instance of the observer to the objects of
# interest. The callback onMaterialRemoveAll has been deprecated, we
# recommend using onMaterialRemove instead.
#
# @example
# # This is an example of an observer that watches the materials collection
# # for new materials and shows a messagebox.
# class MyMaterialsObserver < Sketchup::MaterialsObserver
# def onMaterialAdd(materials, material)
# UI.messagebox("onMaterialAdd: " + material.to_s)
# end
# end
#
# # Attach the observer.
# Sketchup.active_model.materials.add_observer(MyMaterialsObserver.new)
#
# @see http://www.sketchup.com/intl/en/developer/docs/ourdoc/materialsobserver MaterialsObserver Docs
#
# @since SketchUp 6.0
class MaterialsObserver
# The onMaterialAdd method is invoked whenever a {Material} is added.
#
# @example
# def onMaterialAdd(materials, material)
# UI.messagebox("onMaterialAdd: " + material.to_s)
# end
#
# @param [Sketchup::Materials] materials The materials collection
# to which the new material has been added.
#
# @param [Sketchup::Material] material The newly added material.
#
# @return [nil]
#
# @since SketchUp 6
def onMaterialAdd(materials, material)
end
# The onMaterialChange method is invoked whenever a {Material}'s texture
# image is altered.
#
# @example
# def onMaterialChange(materials, material)
# UI.messagebox("onMaterialChange: " + material.to_s)
# end
#
# @param [Sketchup::Materials] materials The materials collection
# to which the changed material belongs.
#
# @param [Sketchup::Material] material The changed material.
#
# @return [nil]
#
# @since SketchUp 6
def onMaterialChange(materials, material)
end
# The onMaterialRefChange method is invoked whenever the number of entities
# that a material is painted on changes. This could be due to the user
# manually painting something, but it could also be when faces are split,
# pasted, push-pulled, deleted, etc.
#
# @example
# def onMaterialRefChange(materials, material)
# UI.messagebox("onMaterialRefChange: " + material.to_s)
# end
#
# @param [Sketchup::Materials] materials The materials collection
# to which the changed material belongs.
#
# @param [Sketchup::Material] material The changed material.
#
# @return [nil]
#
# @since SketchUp 6
def onMaterialRefChange(materials, material)
end
# The onMaterialRemove method is invoked whenever a {Material} is deleted.
#
# @example
# def onMaterialRemove(materials, material)
# UI.messagebox("onMaterialRemove: " + material.to_s)
# end
#
# @param [Sketchup::Materials] materials The materials collection
# from which the material was removed.
#
# @param [Sketchup::Material] material The removed material.
#
# @return [nil]
#
# @since SketchUp 6
def onMaterialRemove(materials, material)
end
# @deprecated
def onMaterialRemoveAll
end
# The onMaterialSetCurrent method is invoked whenever a different {Material}
# is selected in the Materials dialog.
#
# @example
# def onMaterialSetCurrent(materials, material)
# UI.messagebox("onMaterialSetCurrent: " + material.to_s)
# end
#
# @param [Sketchup::Materials, nil] materials The materials collection
# to which the newly selected material belongs. If the selected material is
# not yet used in the Model (like from default Material Libraries), nil is
# passed instead.
#
# @param [Sketchup::Material] material The newly selected material.
#
# @return [nil]
#
# @since SketchUp 6
def onMaterialSetCurrent(materials, material)
end
# The onMaterialUndoRedo method is invoked whenever a material is altered
# and then those changes are undone or redone.
#
# @note Due to a bug, this callback does not fire in SU6 or SU7. You can use
# the ModelObserver.onTransactionStart to capture all undo events.
#
# @example
# def onMaterialUndoRedo(materials, material)
# UI.messagebox("onMaterialUndoRedo: " + material.to_s)
# end
#
# @param [Sketchup::Materials] materials The materials collection
# to which the modified material belongs.
#
# @param [Sketchup::Material] material The modified material.
#
# @return [nil]
def onMaterialUndoRedo(materials, material)
end
end
end
| true |
e33130212b029524d2f9d212ba0ff426e94b217b
|
Ruby
|
elnura15ae/Ruby_
|
/17.Comments.rb
|
UTF-8
| 74 | 2.71875 | 3 |
[] |
no_license
|
puts "Comments are fun" # This line prints comments
# this a comments
| true |
7beef2b5763abe9b70ef8e4c71948c18752c2139
|
Ruby
|
garigari-kun/til
|
/src/textbooks/poodir/ch5/overlooking.rb
|
UTF-8
| 311 | 3.03125 | 3 |
[] |
no_license
|
class Trip
attr_reader :bicycles, :customers, :vehicle
def prepare(mechanic)
return mechanic.prepare_bicycles(bicycles)
end
end
class Mechanic
def prepare_bicycles(bicycles)
return bicycles.each { |bicycle| prepare_bicycle(bicycle)}
end
def prepare_bicycle(bicycle)
end
end
| true |
797830192ef753b9744c75b9fe02e104e996fb1c
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/hamming/08797ab021c44c2c897114d3e20b3aa8.rb
|
UTF-8
| 940 | 3.890625 | 4 |
[] |
no_license
|
class Hamming
def self.compute(strand_a, strand_b)
new(strand_a, strand_b).number_of_nucleotide_differences
end
def initialize(strand_a, strand_b)
@strand_a = Strand.new(strand_a)
@strand_b = Strand.new(strand_b)
end
def number_of_nucleotide_differences
nucleotide_pairs.count do |nuc_a, nuc_b|
nuc_a != nuc_b
end
end
private
def nucleotide_pairs
strand_a, strand_b = equalise_strand_lengths
strand_a.nucleotides.zip(strand_b.nucleotides)
end
def equalise_strand_lengths
length = shortest_strand_length
[@strand_a.shorten(length), @strand_b.shorten(length)]
end
def shortest_strand_length
[@strand_a.length, @strand_b.length].min
end
end
class Strand
def initialize(string)
@string = string
end
def shorten(new_length)
Strand.new(@string[0, new_length])
end
def length
@string.length
end
def nucleotides
@string.chars
end
end
| true |
6b0cd799705c4d7e23e0fdd3125f20d1df9fe973
|
Ruby
|
dlaststark/machine-learning-projects
|
/Programming Language Detection/Experiment-2/Dataset/Train/Ruby/anonymous-recursion-1.rb
|
UTF-8
| 127 | 3.21875 | 3 |
[] |
no_license
|
def fib(n)
raise RangeError, "fib of negative" if n < 0
(fib2 = proc { |m| m < 2 ? m : fib2[m - 1] + fib2[m - 2] })[n]
end
| true |
0b93568788d221918c5b6d3a547345172276a236
|
Ruby
|
murog/hotel
|
/pseudocode_wave_2.rb
|
UTF-8
| 685 | 3.328125 | 3 |
[] |
no_license
|
require_relative 'lib/hotel.rb'
require_relative 'lib/room.rb'
require_relative 'lib/reservation.rb'
# Wave 2
# User Stories
# => As an administrator, I can view a list of rooms that are not reserved for a given date range
Hotel.available_rooms(begin_date, end_date)
#=> returns array [Room Object.available true for date range]
# => As an administrator, I can reserve an available room for a given date range
Hotel.reserve_room(begin_date, end_date)
# Constraints
# => A reservation is allowed to start on the same day that another reservation for the same room ends
# Error Handling
# => Your code should raise an exception when asked to reserve a room that is not available
| true |
b19da95b2b23733c67cd85885aa939e7d6df27f1
|
Ruby
|
genometools/genometools
|
/scripts/gc-parse.rb
|
UTF-8
| 1,410 | 2.609375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"ISC",
"BSD-2-Clause",
"LicenseRef-scancode-mit-old-style",
"Zlib",
"MIT",
"BSD-3-Clause",
"bzip2-1.0.6"
] |
permissive
|
#!/usr/bin/env ruby
GC_code = Struct.new("GC_code",:name,:idnum,:aa,:start)
def gc_code_pretty(gc)
l = [" {\"#{gc.name}\"",
"(unsigned int) #{gc.idnum}",
"\"#{gc.aa}\"",
"\"#{gc.start}\"}"]
return l.join(",\n ")
end
def transnum_idx_pretty(idx_map,idx)
if idx_map.has_key?(idx)
return " #{idx_map[idx]}U"
else
return " GT_UNDEFTRANSNUM"
end
end
start_parse = false
current = nil
codelist = Array.new()
idx_map = Hash.new()
maxnum = nil
idx = 0
STDIN.each_line do |line|
if start_parse
if m = line.match(/name \"([^\"]*)\"/)
if not m[1].match(/SGC[0-9]/)
if not current.nil?
codelist.push(current)
end
current = GC_code.new(m[1],nil,nil,nil)
end
elsif m = line.match(/id (\d+)/)
current.idnum = m[1].to_i
idx_map[current.idnum] = idx
idx += 1
maxnum = current.idnum
elsif m = line.match(/sncbieaa \"([^\"]*)\"/)
current.start = m[1]
elsif m = line.match(/ncbieaa \"([^\"]*)\"/)
current.aa = m[1]
end
elsif line.match(/^Genetic-code-table/)
start_parse = true
end
end
codelist.push(current)
puts "static GtTranslationScheme schemetable[] = {"
puts codelist.map {|gc| gc_code_pretty(gc)}.join(",\n")
puts "};"
puts "\nstatic unsigned int transnum2index[] =\n{"
puts (0..maxnum).to_a.map {|idx| transnum_idx_pretty(idx_map,idx)}.join(",\n")
puts "};"
| true |
63fa106962a34f65e9fe7edd49634dc053ab2d73
|
Ruby
|
moeabdol/design-patterns-in-ruby
|
/iterator/internal_iterator/for_each_element.rb
|
UTF-8
| 139 | 3.359375 | 3 |
[] |
no_license
|
def for_each_element(array)
array = array.clone
index = 0
while index < array.length
yield array[index]
index += 1
end
end
| true |
9c41caca3953fdb72d8b23522a70408b8b87002b
|
Ruby
|
nebolsin/oj
|
/test/test_parser_saj.rb
|
UTF-8
| 5,638 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# encoding: UTF-8
$: << File.dirname(__FILE__)
require 'helper'
$json = %{{
"array": [
{
"num" : 3,
"string": "message",
"hash" : {
"h2" : {
"a" : [ 1, 2, 3 ]
}
}
}
],
"boolean" : true
}}
class AllSaj < Oj::Saj
attr_accessor :calls
def initialize()
@calls = []
end
def hash_start(key)
@calls << [:hash_start, key]
end
def hash_end(key)
@calls << [:hash_end, key]
end
def array_start(key)
@calls << [:array_start, key]
end
def array_end(key)
@calls << [:array_end, key]
end
def add_value(value, key)
@calls << [:add_value, value, key]
end
def error(message, line, column)
@calls << [:error, message, line, column]
end
end # AllSaj
class SajTest < Minitest::Test
def test_nil
handler = AllSaj.new()
json = %{null}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:add_value, nil, nil]], handler.calls)
end
def test_true
handler = AllSaj.new()
json = %{true}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:add_value, true, nil]], handler.calls)
end
def test_false
handler = AllSaj.new()
json = %{false}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:add_value, false, nil]], handler.calls)
end
def test_string
handler = AllSaj.new()
json = %{"a string"}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:add_value, 'a string', nil]], handler.calls)
end
def test_fixnum
handler = AllSaj.new()
json = %{12345}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:add_value, 12345, nil]], handler.calls)
end
def test_float
handler = AllSaj.new()
json = %{12345.6789}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:add_value, 12345.6789, nil]], handler.calls)
end
def test_float_exp
handler = AllSaj.new()
json = %{12345.6789e7}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal(1, handler.calls.size)
assert_equal(:add_value, handler.calls[0][0])
assert_equal((12345.6789e7 * 10000).to_i, (handler.calls[0][1] * 10000).to_i)
end
def test_array_empty
handler = AllSaj.new()
json = %{[]}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:array_start, nil],
[:array_end, nil]], handler.calls)
end
def test_array
handler = AllSaj.new()
json = %{[true,false]}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:array_start, nil],
[:add_value, true, nil],
[:add_value, false, nil],
[:array_end, nil]], handler.calls)
end
def test_hash_empty
handler = AllSaj.new()
json = %{{}}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:hash_start, nil],
[:hash_end, nil]], handler.calls)
end
def test_hash
handler = AllSaj.new()
json = %{{"one":true,"two":false}}
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([[:hash_start, nil],
[:add_value, true, 'one'],
[:add_value, false, 'two'],
[:hash_end, nil]], handler.calls)
end
def test_full
handler = AllSaj.new()
Oj.saj_parse(handler, $json)
assert_equal([[:hash_start, nil],
[:array_start, 'array'],
[:hash_start, nil],
[:add_value, 3, 'num'],
[:add_value, 'message', 'string'],
[:hash_start, 'hash'],
[:hash_start, 'h2'],
[:array_start, 'a'],
[:add_value, 1, nil],
[:add_value, 2, nil],
[:add_value, 3, nil],
[:array_end, 'a'],
[:hash_end, 'h2'],
[:hash_end, 'hash'],
[:hash_end, nil],
[:array_end, 'array'],
[:add_value, true, 'boolean'],
[:hash_end, nil]], handler.calls)
end
def test_multiple
handler = AllSaj.new()
json = %|[true][false]|
p = Oj::Parser.new(:saj)
p.handler = handler
p.parse(json)
assert_equal([
[:array_start, nil],
[:add_value, true, nil],
[:array_end, nil],
[:array_start, nil],
[:add_value, false, nil],
[:array_end, nil],
], handler.calls)
end
def test_io
handler = AllSaj.new()
json = %| [true,false] |
p = Oj::Parser.new(:saj)
p.handler = handler
p.load(StringIO.new(json))
assert_equal([
[:array_start, nil],
[:add_value, true, nil],
[:add_value, false, nil],
[:array_end, nil],
], handler.calls)
end
def test_file
handler = AllSaj.new()
p = Oj::Parser.new(:saj)
p.handler = handler
p.file('saj_test.json')
assert_equal([
[:array_start, nil],
[:add_value, true, nil],
[:add_value, false, nil],
[:array_end, nil],
], handler.calls)
end
def test_default
handler = AllSaj.new()
json = %|[true]|
Oj::Parser.saj.handler = handler
Oj::Parser.saj.parse(json)
assert_equal([
[:array_start, nil],
[:add_value, true, nil],
[:array_end, nil],
], handler.calls)
end
end
| true |
42d181650d117ce8cea367b058c05a37584a1195
|
Ruby
|
szTheory/ruby_speech
|
/spec/support/dtmf_helper.rb
|
UTF-8
| 403 | 3.140625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# encoding: utf-8
# frozen_string_literal: true
#
# Convert a simple DTMF string from "1 star 2" to "dtmf-1 dtmf-star dtmf-2".
#
# @param [Array] sequence A set of DTMF keys, such as `%w(1 star 2)`.
#
# @return [String] A string with "dtmf-" prefixed for each DTMF element.
# Example: "dtmf-1 dtmf-star dtmf-2".
#
def dtmf_seq(sequence)
sequence.map { |d| "dtmf-#{d}" }.join ' '
end
| true |
02617e87e56b2bf4193a4675ab740f2b1e8804d1
|
Ruby
|
vpatel90/rr_mvc_blog
|
/app/models/comment.rb
|
UTF-8
| 508 | 2.640625 | 3 |
[] |
no_license
|
$id_c = 1
class Comment
attr_accessor :id, :time, :author_fn, :author_ln, :user, :body
def initialize(user, body, post)
@id = $id_c
$id_c += 1
@time = GetTime.now
@user = user
@author_fn = user.first_name
@author_ln = user.last_name
@body = body
@post_id = post.id
post.comments.unshift(self)
end
def to_json( _ = nil)
{
id: id,
post_id: @post_id,
author_fn: author_fn,
author_ln: author_ln,
body: body,
}.to_json
end
end
| true |
c69fdb25432dea046890485ce2a3bfcddd7ca792
|
Ruby
|
tylercollier/rpn_calc
|
/app/rpn/math.rb
|
UTF-8
| 1,236 | 3.421875 | 3 |
[] |
no_license
|
module RPN
class InvalidOperatorError < StandardError; end
class Math
def numeric_cast(input)
# We'd use the i18n library if internationalization is needed, e.g. to
# look for commas as the decimal separator.
# Casting to an integer, as opposed to always a float, is one simple way
# to output an integer when the input is an integer (i.e. no decimal
# shown), as the example gist does.
if /\./ =~ input
Float input rescue nil
else
Integer input rescue nil
end
end
def arity(operator)
case operator
when '++', '--'
1
when '+', '-', '*', '/'
2
else
raise InvalidOperatorError.new "Unable to handle operator: #{operator}"
end
end
def compute(operator, *operands)
case operator
when '++', '--'
if operator == '++'
result = operands[0] += 1
else
result = operands[0] -= 1
end
when '+', '-', '*'
result = operands[0].send operator, operands[1]
when '/'
result = operands[0].to_f / operands[1]
else
raise InvalidOperatorError.new "Unable to handle operator: #{operator}"
end
end
end
end
| true |
8cb1e994daabda6715d1fa3fadd0aaf0322323b2
|
Ruby
|
natedog/sportent
|
/vendor/plugins/semantify/lib/semantify.rb
|
UTF-8
| 1,462 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
# Semantify
require 'open-uri'
require 'nokogiri'
module Semantify
class Semantify
def self.fetch(url)
# WORK OUT HOW TO MAKE THESE CONSTANTS
openamplify_API_key = "eup9b9epknxn6fvumtdxqprc3x4d58vr"
alchemy_API_key = "a3bbc19ddac62cf366b45c1f6f83584bbca312e2"
alchemy_API_url_entity = "http://access.alchemyapi.com/calls/url/URLGetRankedNamedEntities"
alchemy_API_url_keyword = "http://access.alchemyapi.com/calls/url/URLGetKeywords"
#puts alchemy_API_url+"?url="+url+"&apikey="+alchemy_API_key
document = Nokogiri::XML(open(alchemy_API_url_entity+"?url="+url+"&apikey="+alchemy_API_key))
entities = document.css("entity")
semantic_entities = []
entities.each do |entity|
type = entity.css("type")
text = entity.css("text")
count = entity.css("count")
semantic_entities << {:tag=> text.text,:type=>type.text,:count=>count.text}
end
document = Nokogiri::XML(open(alchemy_API_url_keyword+"?url="+url+"&apikey="+alchemy_API_key))
keywords = document.css("keyword")
semantic_keywords = []
keywords.each do |keyword|
semantic_keywords << keyword.text
end
results ={:entities=> semantic_entities,:keywords=>semantic_keywords}
results
end
def send(text)
end
end
end
| true |
b6484efd4c9ca53902607ca9a0535a485790b32d
|
Ruby
|
maguirpa/Tealeaf_exercises
|
/chapter7_hashes/2.rb
|
UTF-8
| 449 | 3.046875 | 3 |
[] |
no_license
|
my_fam = {brother: "Colin", sister: "Katie", mom: "Patti", dad: "John"}
her_fam = {cousin: "Tashay", uncle: "Melvin", aunt: "Betty"}
p my_fam.merge(her_fam)
p my_fam
p my_fam.merge!(her_fam)
p my_fam
# merge without the bang operater will merge the documents in place but will not permanently alter the original hash. If you include the bang operater, it changes the original array into the new array excluding any duplicates as seen above.
| true |
9ddf573d8cd6dd6b1a984573f81cb12627099313
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/grains/d7b69a76e76a44a58c3204144a577efd.rb
|
UTF-8
| 76 | 2.859375 | 3 |
[] |
no_license
|
class Grains
def square(a)
2**(a-1)
end
def total
(2**64)-1
end
end
| true |
70a3f3ac6a15b4cb05d7df3df66a3fb11f410ac4
|
Ruby
|
avalonmediasystem/hyrax
|
/lib/wings/services/custom_queries/find_file_metadata.rb
|
UTF-8
| 5,032 | 2.75 | 3 |
[
"Apache-2.0",
"AGPL-3.0-or-later"
] |
permissive
|
# Custom query override specific to Wings for finding Hydra::PCDM::File and converting to Hyrax::FileMetadata.
# @example
# Hyrax.custom_queries.find_file_metadata_by(id: valkyrie_id, use_valkyrie: true)
# Hyrax.custom_queries.find_file_metadata_by_alternate_identifier(alternate_identifier: id, use_valkyrie: true)
require 'wings/services/file_converter_service'
module Wings
module CustomQueries
class FindFileMetadata
def self.queries
[:find_file_metadata_by,
:find_file_metadata_by_alternate_identifier,
:find_many_file_metadata_by_ids,
:find_many_file_metadata_by_use]
end
def initialize(query_service:)
@query_service = query_service
end
attr_reader :query_service
delegate :resource_factory, to: :query_service
# WARNING: In general, prefer find_by_alternate_identifier over this
# method.
#
# Hyrax uses a shortened noid in place of an id, and this is what is
# stored in ActiveFedora, which is still the storage backend for Hyrax.
#
# If you do not heed this warning, then switch to Valyrie's Postgres
# MetadataAdapter, but continue passing noids to find_by, you will
# start getting ObjectNotFoundErrors instead of the objects you wanted
#
# Find a file metadata using a Valkyrie ID, and map it to a Hyrax::FileMetadata or Hydra::PCDM::File, if use_valkyrie is true or false, respectively.
# @param id [Valkyrie::ID, String]
# @param use_valkyrie [boolean] defaults to true; optionally return ActiveFedora::File objects if false
# @return [Hyrax::FileMetadata, Hydra::PCDM::File] - when use_valkyrie is true, returns FileMetadata resource; otherwise, returns ActiveFedora PCDM::File
# @raise [Hyrax::ObjectNotFoundError]
def find_file_metadata_by(id:, use_valkyrie: true)
find_file_metadata_by_alternate_identifier(alternate_identifier: id, use_valkyrie: use_valkyrie)
end
# Find a file metadata using an alternate ID, and map it to a Hyrax::FileMetadata or Hydra::PCDM::File, if use_valkyrie is true or false, respectively.
# @param alternate_identifier [Valkyrie::ID, String]
# @param use_valkyrie [boolean] defaults to true; optionally return ActiveFedora::File objects if false
# @return [Hyrax::FileMetadata, Hydra::PCDM::File] - when use_valkyrie is true, returns FileMetadata resource; otherwise, returns ActiveFedora PCDM::File
# @raise [Hyrax::ObjectNotFoundError]
def find_file_metadata_by_alternate_identifier(alternate_identifier:, use_valkyrie: true)
alternate_identifier = ::Valkyrie::ID.new(alternate_identifier.to_s) if alternate_identifier.is_a?(String)
raise Hyrax::ObjectNotFoundError unless Hydra::PCDM::File.exists?(alternate_identifier.to_s)
object = Hydra::PCDM::File.find(alternate_identifier.to_s)
return object if use_valkyrie == false
Wings::FileConverterService.af_file_to_resource(af_file: object)
end
# Find an array of file metadata using Valkyrie IDs, and map them to Hyrax::FileMetadata maintaining order based on given ids
# @param ids [Array<Valkyrie::ID, String>]
# @param use_valkyrie [boolean] defaults to true; optionally return ActiveFedora::File objects if false
# @return [Array<Hyrax::FileMetadata, Hydra::PCDM::File>] or empty array if there are no ids or none of the ids map to Hyrax::FileMetadata
# NOTE: Ignores non-existent ids and ids for non-file metadata resources.
def find_many_file_metadata_by_ids(ids:, use_valkyrie: true)
results = []
ids.each do |alt_id|
begin
# For Wings, the id and alt_id are the same, so just use alt id querying.
file_metadata = query_service.custom_queries.find_file_metadata_by_alternate_identifier(alternate_identifier: alt_id, use_valkyrie: use_valkyrie)
results << file_metadata
rescue Hyrax::ObjectNotFoundError
next
end
end
results
end
##
# Find file metadata for files within a resource that have the requested use.
# @param use [RDF::URI] uri for the desired use Type
# @param use_valkyrie [boolean] defaults to true; optionally return ActiveFedora::File objects if false
# @return [Array<Hyrax::FileMetadata, Hydra::PCDM::File>] or empty array if there are no files with the requested use
# @example
# Hyrax.query_service.find_file_metadata_by_use(use: ::RDF::URI("http://pcdm.org/ExtractedText"))
def find_many_file_metadata_by_use(resource:, use:, use_valkyrie: true)
pcdm_files = find_many_file_metadata_by_ids(ids: resource.file_ids, use_valkyrie: false)
pcdm_files.select! { |pcdm_file| pcdm_file.metadata_node.type.include?(use) }
return pcdm_files if use_valkyrie == false
pcdm_files.collect { |pcdm_file| Wings::FileConverterService.af_file_to_resource(af_file: pcdm_file) }
end
end
end
end
| true |
f53561547f9bf0292fbb464ebccc5fb1f1954567
|
Ruby
|
matiasleidemer/validates_captcha
|
/lib/validates_captcha/image_generator/simple.rb
|
UTF-8
| 3,399 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
module ValidatesCaptcha
module ImageGenerator
# This class is responsible for creating the captcha image. It internally
# uses ImageMagick's +convert+ command to generate the image bytes. So
# ImageMagick must be installed on the system for it to work properly.
#
# In order to deliver the captcha image to the user's browser,
# Validate Captcha's Rack middleware calls the methods of this class
# to create the image, to retrieve its mime type, and to construct the
# path to it.
#
# The image generation process is no rocket science. The chars are just
# laid out next to each other with varying vertical positions, font sizes,
# and weights. Then a slight rotation is performed and some randomly
# positioned lines are rendered on the canvas.
#
# Sure, the created captcha can easily be cracked by intelligent
# bots. As the name of the class suggests, it's rather a starting point
# for your own implementations.
#
# You can implement your own (better) image generator by creating a
# class that conforms to the method definitions of the example below.
#
# Example for a custom image generator:
#
# class AdvancedImageGenerator
# def generate(captcha_text)
# # ... do your magic here ...
#
# return string_containing_image_bytes
# end
#
# def mime_type
# 'image/png'
# end
#
# def file_extension
# '.png'
# end
# end
#
# Then assign an instance of it to ValidatesCaptcha::Provider::DynamicImage#image_generator=.
#
# ValidatesCaptcha::Provider::DynamicImage.image_generator = AdvancedImageGenerator.new
# ValidatesCaptcha.provider = ValidatesCaptcha::Provider::DynamicImage.new
#
# Or to ValidatesCaptcha::Provider::StaticImage#image_generator=.
#
# ValidatesCaptcha::Provider::StaticImage.image_generator = AdvancedImageGenerator.new
# ValidatesCaptcha.provider = ValidatesCaptcha::Provider::StaticImage.new
#
class Simple
MIME_TYPE = 'image/gif'.freeze
FILE_EXTENSION = '.gif'.freeze
# Returns a string containing the image bytes of the captcha.
# As the only argument, the cleartext captcha text must be passed.
def generate(captcha_code)
image_width = captcha_code.length * 20 + 10
cmd = []
cmd << "convert -size #{image_width}x40 xc:grey84 -background grey84 -fill black "
captcha_code.split(//).each_with_index do |char, i|
cmd << " -pointsize #{rand(8) + 15} "
cmd << " -weight #{rand(2) == 0 ? '4' : '8'}00 "
cmd << " -draw 'text #{5 + 20 * i},#{rand(10) + 20} \"#{char}\"' "
end
cmd << " -rotate #{rand(2) == 0 ? '-' : ''}5 -fill grey40 "
captcha_code.size.times do
cmd << " -draw 'line #{rand(image_width)},0 #{rand(image_width)},60' "
end
cmd << " gif:-"
image_magick_command = cmd.join
`#{image_magick_command}`
end
# Returns the image mime type. This is always 'image/gif'.
def mime_type
MIME_TYPE
end
# Returns the image file extension. This is always '.gif'.
def file_extension
FILE_EXTENSION
end
end
end
end
| true |
bcfe9544cd6bb9efb17d0cfeb469c19567b9fe42
|
Ruby
|
Friindel33/RubyLessons
|
/MyApp1/hwapp16.rb
|
UTF-8
| 221 | 3.6875 | 4 |
[] |
no_license
|
print "How many years planning to do savings: "
x = gets.to_f
print "How much every month: "
n = gets.to_i
s = 0
1.upto (x) do |mm|
1.upto (12) do |pp|
s = s + n
puts "Year #{mm} month #{pp}: #{s}"
end
end
| true |
287aa612c84da11a8320ac5e71f385c7718c42bb
|
Ruby
|
jherre/gexf.rb
|
/lib/gexf/json_serializer.rb
|
UTF-8
| 687 | 2.71875 | 3 |
[] |
no_license
|
require 'json'
class GEXF::JsonSerializer
def initialize(graph)
@graph = graph
end
def serialize!
JSON.pretty_unparse document
end
private
def nodes
@nodes ||= @graph.nodes.values
end
def document
{
'nodes' => build_nodes,
'links' => build_links,
}
end
def build_nodes
nodes.map{ |node|
h = {'label' => node.label}
h.update(node.attributes)
}
end
def build_links
@graph.edges.map{ |edge|
h = {
'source' => nodes.index(edge.source),
'target' => nodes.index(edge.target),
'weight' => edge.weight,
}
h.update(edge.attributes)
}
end
end
| true |
d699a0cd6763edbb430b5a2a99aaf65c3377090f
|
Ruby
|
nikolasco/project_euler
|
/036.rb
|
UTF-8
| 247 | 2.84375 | 3 |
[] |
no_license
|
MAX = 10**6
s = (0..MAX).inject(0) do |sum, n|
ns10 = n.to_s
ns10l = ns10.length/2
ns2 = n.to_s(2)
ns2l = ns2.length/2
(ns10[0,ns10l] == ns10[-ns10l,ns10l].reverse and
ns2[0,ns2l] == ns2[-ns2l,ns2l].reverse)? sum + n : sum
end
puts s
| true |
15b4b03d700e4548ff728de71e0d96117cf1f892
|
Ruby
|
Sumbhodi1618/operators-online-web-prework
|
/lib/operations.rb
|
UTF-8
| 119 | 2.953125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def unsafe?(speed = 60)
if speed >= 60
true
elsif speed <= 40
true
else
speed == 40..60
false
end
end
| true |
93911d70b31b057545b65f04f7f8165b7a853808
|
Ruby
|
surjit/Chats-REST-Server
|
/test/controllers/users_controller_test.rb
|
UTF-8
| 2,886 | 2.53125 | 3 |
[] |
no_license
|
require 'test_helper'
class UsersTest < ChatsTest
def test_users_get
get '/users'
assert_return /\A\[\{"id":1,"name":\{"first":"Matt","last":"Di Pasquale"\},"picture_id":"[0-9a-f]{32}"\}\]\z/
end
def test_users_post
# Create code
phone = '2102390603'
Chats::TextBelt.mock({'success' => true}) do
post '/codes', {phone: phone}
end
code = get_code(phone)
# Create key
post '/keys', {phone: phone, code: code}
key = get_key(phone)
valid_auth = {phone: phone, key: key}
valid_fields = {first_name: 'John', last_name: 'Appleseed', email: '[email protected]'}
unauthorized_response = [
401,
{'WWW-Authenticate' => 'Basic realm="Chats"'},
'{"message":"Incorrect phone or key."}'
]
# Test no phone or key
post '/users'
assert_return unauthorized_response
# Test invalid phone
post '/users', {phone: '123', key: key}.merge(valid_fields)
assert_return unauthorized_response
# Test invalid key
post '/users', {phone: phone, key: 'abc123'}.merge(valid_fields)
assert_return unauthorized_response
# Test invalid phone & key
post '/users', {phone: '123', key: 'abc123'}.merge(valid_fields)
assert_return unauthorized_response
# Test incorrect phone
post '/users', {phone: '2345678902', key: key}.merge(valid_fields)
assert_return unauthorized_response
# Test incorrect key
post '/users', {phone: phone, key: SecureRandom.hex}.merge(valid_fields)
assert_return unauthorized_response
# Test incorrect phone & key
post '/users', {phone: '2345678902', key: SecureRandom.hex}.merge(valid_fields)
assert_return unauthorized_response
### Test correct phone & key
# Test no first_name
post '/users', valid_auth
assert_return [400, '{"message":"First name must be between 1 & 50 characters."}']
# Test empty first_name
post '/users', valid_auth.merge(first_name: '')
assert_return [400, '{"message":"First name must be between 1 & 50 characters."}']
# Test no last_name
post '/users', valid_auth.merge(first_name: 'Matt')
assert_return [400, '{"message":"Last name must be between 1 & 50 characters."}']
# Test empty last_name
post '/users', valid_auth.merge({first_name: 'Matt', last_name: ''})
assert_return [400, '{"message":"Last name must be between 1 & 50 characters."}']
# Test correct valid params
post '/users', valid_auth.merge(valid_fields)
assert_return [201, /\A\{"access_token":"2\.[0-9a-f]{32}"\}\z/]
# Confirm previous user creation
get '/users'
assert_return /\A\[\{"id":1,"name":\{"first":"Matt","last":"Di Pasquale"\},"picture_id":"[0-9a-f]{32}"\},\{"id":2,"name":\{"first":"John","last":"Appleseed"\}\}\]\z/
# Test that key only works once
post '/users', valid_auth.merge(valid_fields)
assert_return unauthorized_response
end
end
| true |
1290228e470d71f717a89e8da9f24eb6e2da8184
|
Ruby
|
toptal/archfiend
|
/lib/archfiend/logging.rb
|
UTF-8
| 2,124 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
require 'logger'
module Archfiend
class Logging
class << self
DEFAULT_FORMATTERS = {
file: 'JSONFormatter',
stdout: 'DefaultFormatter'
}.freeze
# @param environment [String|Symbol] Current running environment, ex. :development
# @param log_directory [String,Pathname] Directory in which the logfile is supposed to live
# @param quiet [Boolean] Whether the STDOUT development output should be suppressed
# @return [MultiLogger] A multiplexer for up to two loggers
def create(environment, log_directory, quiet = false)
environment = environment.to_sym
loggers = [file_logger(environment, log_directory)]
loggers << stdio_logger if environment == :development && !quiet
MultiLogger.new(*loggers)
end
private
def file_logger(environment, log_directory)
log_name = File.join(log_directory, "#{environment}.log")
file_logger = Logger.new(log_name, 'daily')
file_logger.formatter = formatter_from_settings(:file)
file_logger
end
def stdio_logger
stdout_io = IO.try_convert(STDOUT)
stdout_io.sync = true
stdout_logger = Logger.new(stdout_io)
stdout_logger.formatter = formatter_from_settings(:stdout)
stdout_logger
end
# @param type [Symbol] :file or :stdout
# @return [Logging::BaseFormatter] a formatter instance
def formatter_from_settings(type)
formatter_name = Settings.logger.dig(:formatter, type) || DEFAULT_FORMATTERS.fetch(type)
instantiate_formatter(formatter_name)
end
def instantiate_formatter(name)
return Archfiend::Logging.const_get(name).new if Archfiend::Logging.const_defined?(name)
possible_formatter_source = File.join('logging', name.underscore)
require_relative(possible_formatter_source)
Archfiend::Logging.const_get(name).new
rescue StandardError, LoadError => e
puts "Unable to load log formatter #{name.inspect}."
puts "\nException: #{e.message}"
exit 1
end
end
end
end
| true |
cea5a3adc4dbeb6570a64c851e5708343b8bda12
|
Ruby
|
christ4sam/my_recipe_app
|
/app/controllers/recipes_controller.rb
|
UTF-8
| 4,407 | 2.953125 | 3 |
[] |
no_license
|
class RecipesController < ApplicationController
before_action :set_recipe, only: [:edit, :update, :show, :like]
#here users that are NOT logged in can browse only the index (list recipe page)and the show recipe page
before_action :require_user, except: [:show, :index, :like]
#here for a user to like a recipe user must log in
before_action :require_user_like, only: [:like]
# Here we want to make sure sure that chef can only edit the reicpes they create them self
# here we want this require_same_user method befor_action to be executed or run first before
# edit and update actions to verify that the current logged in user owns the recipe they want to edit or update
# and that this actions can not be done through the browser as well
before_action :require_same_user, only: [:edit, :update]
#here we are saying the log in user has to be admin user for them to be able to destroy any recipe
before_action :admin_user, only: :destroy
#here we are paginating the recipe listing index page
def index
@recipes = Recipe.paginate(page: params[:page], per_page: 4)
end
def show
#@recipe = Recipe.find(params[:id])
end
def new
@recipe = Recipe.new
end
# here create a new recipe and save, if you are able to save you will be redirected to list and a
# flash message that recipe was created
# of recipes but if cant save the create a new form again will vghwbe displayed again.
# with a chef object to ensure every recipe is created by a registered chef so each
# recipe created is assigned to a chef
def create
@recipe = Recipe.new(recipe_params)
@recipe.chef = current_user #must log in to be able to create a recipe
if @recipe.save
flash[:success] = "Your recipe was created successfully!"
redirect_to recipes_path
else
render :new
end
end
# to this point
# here we are retriving a particular recipe we want to edit using the params which has the id
def edit
#@recipe = Recipe.find(params[:id])
end
# after the recipe is edited and submited we redirect user back to the edited
#recipe show page else we render the edit form again
def update
#@recipe = Recipe.find(params[:id])
if @recipe.update(recipe_params)
flash[:success] = "Your recipe was updated successfully!"
redirect_to recipe_path(@recipe)
else
render :edit
end
end
#this is our like action for our recipe conotroller that gives
#chef the ability to find and like recipe
def like
#@recipe = Recipe.find(params[:id])
#to like a recipe chef must be logged in as current_user(befor_action) the befor action is to log in
like = Like.create(like: params[:like], chef: current_user, recipe:@recipe)
if like.valid?
flash[:success] = "Your selection was successful"
redirect_to :back
else
flash[:danger] = "You can only like/dislike a recipe once"
redirect_to :back
end
end
def destroy
Recipe.find(params[:id]).destroy
flash[:success] = "Recipe Deleted"
redirect_to recipes_path
end
# here we are whitelisting or writting out the peramiters our app can permit to flow through
# for creating a new recipe with our new form
private
def recipe_params
params.require(:recipe).permit(:name, :summary, :description, :picture, style_ids: [], ingredient_ids: [])
end
#this set_recipe method for params(:id) will be executed before the edit, update and show actions
def set_recipe
@recipe = Recipe.find(params[:id])
end
# Here we want to make sure sure that chef can only edit the reicpes they create them self or they are admin
def require_same_user
if current_user != @recipe.chef and !current_user.admin?
flash[:danger] = "You can only edit your own recipes"
redirect_to recipes_path
end
end
# requre_user action is defind in our application controller because is a method we will be
#using in all our controllers
def require_user_like
if !logged_in?
flash[:danger] = "You must be logged in to perform that action"
redirect_to :back
end
end
#this is the action that allows only the admin user to delete recipe
def admin_user
redirect_to recipes_path unless current_user.admin?
end
end
| true |
3391adf8c63f2922662ce1ca02c7806878b08074
|
Ruby
|
Jliv316/module_3_diagnostic
|
/app/models/station.rb
|
UTF-8
| 327 | 2.8125 | 3 |
[] |
no_license
|
class Station
attr_reader :station_name, :street_address, :fuel_types, :distance, :access_times
def initialize(info)
@station_name = info[:station_name]
@street_address = info[:street_address]
@fuel_types = info[:fuel_type_code]
@distance = rand(5..20)
@access_times = info[:access_days_times]
end
end
| true |
481f2e779c2a31be9c07159184dd736173087209
|
Ruby
|
jaw772/enigma
|
/lib/decrypt.rb
|
UTF-8
| 454 | 2.9375 | 3 |
[] |
no_license
|
require_relative './enigma'
message_file = File.open(ARGV[0], "r")
key_1 = "82648"
date_1 = "240818"
encrypted_message = message_file.read
message_file.close
enigma = Enigma.new
decrypted = enigma.decrypt(encrypted_message, key_1, date_1)
decrypted_message = decrypted[:decryption]
decrypted_file = File.open(ARGV[1], "w")
decrypted_file.write(decrypted_message)
decrypted_file.close
puts "Created '#{ARGV[1]}' with the key #{key_1} and date #{date_1}"
| true |
0c112f04973a8c290b1f97f322bd6480f3d62014
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/roman-numerals/fefbe03f79d649ed8db2c26297908892.rb
|
UTF-8
| 816 | 3.375 | 3 |
[] |
no_license
|
module Roman
ROMAN_NUMERALS = %w(I V X L C D M)
def to_roman
return '' if zero?
highest_digit, remaining = to_s.split(//, 2).map(&:to_i)
place = to_s.length - 1
highest_digit.digit_to_roman(place) + remaining.to_roman
end
protected
# Roman numeral for (self * 10**place).
# Precondition: 0 <= self <= 9
def digit_to_roman(place)
numerals_offset = place * 2
one, five, ten = ROMAN_NUMERALS[numerals_offset..numerals_offset + 3]
case self # Example for place==0:
when 0..3 then one * self # I..III
when 4 then one + five # IV
when 5..8 then five + one * (self - 5) # V..VIII
when 9 then one + ten # IX
else raise ArgumentError
end
end
end
Fixnum.send(:include, Roman)
| true |
35021b374861915c0401ca1df2c41e2c698a8fa1
|
Ruby
|
Macaroni2629/Launch-School
|
/120_object_oriented_programming/120_exercises/debugging/wish_you_were_here.rb
|
UTF-8
| 2,031 | 4.3125 | 4 |
[] |
no_license
|
# Wish You Were Here
# On lines 37 and 38 of our code, we can see that grace and ada are located at the same coordinates. So why does line 39 output false? Fix the code to produce the expected output.
class Person
attr_reader :name
attr_accessor :location
def initialize(name)
@name = name
end
def teleport_to(latitude, longitude)
@location = GeoLocation.new(latitude, longitude)
end
end
class GeoLocation
attr_reader :latitude, :longitude
def initialize(latitude, longitude)
@latitude = latitude
@longitude = longitude
end
def to_s
"(#{latitude}, #{longitude})"
end
end
# Example
ada = Person.new('Ada')
ada.location = GeoLocation.new(53.477, -2.236)
grace = Person.new('Grace')
grace.location = GeoLocation.new(-33.89, 151.277)
ada.teleport_to(-33.89, 151.277)
puts ada.location # (-33.89, 151.277)
puts grace.location # (-33.89, 151.277)
puts ada.location == grace.location # expected: true
# actual: false
# Discussion
# On line 39 of our original code, we invoke the == method to compare the equality of two locations. Since our GeoLocation class does not implement ==, Ruby invokes the method from the BasicObject class. BasicObject#==, however, returns true only if the two objects being compared are the same object, or in other words, if they have the same object id.
# In order to compare the equality of instances of our custom class based on the value of their attributes, we need to define a == method in our custom class, which overrides BasicObject#== (thanks to Ruby's method lookup path). GeoLocation#== does exactly that: it compares two locations based on their latitude and longitude values.
class GeoLocation
attr_reader :latitude, :longitude
def initialize(latitude, longitude)
@latitude = latitude
@longitude = longitude
end
def ==(other)
latitude == other.latitude && longitude == other.longitude
end
def to_s
"(#{latitude}, #{longitude})"
end
end
| true |
34a38255720f9ddaa5bdd5fc6e98e0b36019c961
|
Ruby
|
HerbCSO/Episode3
|
/models/book.rb
|
UTF-8
| 219 | 2.921875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Book < ActiveRecord::Base
has_many :characters
validates_presence_of :title
def to_s
"#{title}, written by #{author} has #{pages} pages, characters: [#{characters.map { |c| c.to_s }.join(', ')}]"
end
end
| true |
5b2ad62523f53973598a0bd246ae664b7f5db3ca
|
Ruby
|
karlhe/pmanagr
|
/app/models/user.rb
|
UTF-8
| 3,579 | 2.578125 | 3 |
[] |
no_license
|
require 'digest/sha1'
class User < ActiveRecord::Base
has_many :memberships
has_many :projects, :through => :memberships
has_many :assignments
has_many :tasks, :through => :assignments, :uniq => true
has_many :posts
include Authentication
include Authentication::ByPassword
include Authentication::ByCookieToken
validates_presence_of :login
validates_length_of :login, :within => 3..40
validates_uniqueness_of :login
validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
validates_presence_of :name
validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true
validates_length_of :name, :maximum => 100
validates_presence_of :email
validates_length_of :email, :within => 6..100 #[email protected]
validates_uniqueness_of :email
validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message
attr_accessible :login, :email, :name, :password, :password_confirmation, :public, :has_registered
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
#
# uff. this is really an authorization, not authentication routine.
# We really need a Dispatch Chain here or something.
# This will also let us return a human error message.
#
def self.authenticate(login, password)
return nil if login.blank? || password.blank?
u = find_by_login(login.downcase) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
def login=(value)
write_attribute :login, (value ? value.downcase : nil)
end
def email=(value)
write_attribute :email, (value ? value.downcase : nil)
end
def register_from_invitation (n, e)
arr = [('0'..'9'),('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten
self.login = (0...40).map{arr[rand(arr.length)]}.join
self.name = n
self.email = e
self.crypted_password = (0...40).map{arr[rand(arr.length)]}.join
self.salt = (0...40).map{arr[rand(arr.length)]}.join
self.has_registered = false
capitalize_name
end
def capitalize_name
self.name = self.name.split(' ').map {|w| w.capitalize }.join(' ')
end
def is_public?
return !!public
end
def has_registered?
return !!self.has_registered
end
def is_owner?(project)
membership = project.memberships.find(:first, :conditions => { :user_id => self.id })
!membership.blank? and membership.is_owner?
end
def is_manager?(task)
self == task.manager
end
def can_complete_assignment?(assignment)
assignment.user == self || self.is_manager?(assignment.task) || self.is_owner?(assignment.task.project)
end
def is_user?(project)
membership = project.memberships.find(self)
!membership.blank? and membership.is_user?
end
def is_approved?(project)
membership = project.memberships.find(self)
!membership.blank? and membership.is_approved?
end
def is_pending?(project)
membership = project.memberships.find(self)
!membership.blank? and membership.is_pending?
end
def is_request?(project)
membership = project.memberships.find(self)
!membership.blank? and membership.is_request?
end
def full_memberships
return self.memberships.select { |m| m.level == "user" or m.level == "owner" }
end
def pending_memberships
return self.memberships.select { |m| m.level == "pending" }
end
end
| true |
25e78913245932a0c0a7c088f835e37998ad13a9
|
Ruby
|
quantitare/quantitare-categories
|
/lib/quantitare/categories/tv.rb
|
UTF-8
| 1,017 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Quantitare
module Categories
##
# A representation of an episode of television watched by a user. Contains basic information about the episode,
# as well as a pointer with which Quantitare can gather more metadata about it.
#
class TV < Quantitare::Category
specification do
# The name of the source from which you wish to retrieve the episode's metadata, such as The TV DB
# ("tvdb") or Trakt ("trakt"). The episode and show identifiers can be used to pull more data from that source
# about the media.
required(:service_source).maybe(:string)
required(:episode_title).filled(:string)
required(:episode_identifier).maybe(:string)
required(:show_title).filled(:string)
required(:show_identifier).maybe(:string)
optional(:show_year).maybe(:integer)
required(:season_number).maybe(:integer)
required(:episode_number).maybe(:integer)
end
end
end
end
| true |
e8a57e7b4861f3a528bd398389d22e75517c0496
|
Ruby
|
errbit/hoptoad_zmq_notifier
|
/lib/hoptoad_zmq_notifier/configuration.rb
|
UTF-8
| 1,252 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
# encoding: utf-8
module HoptoadZmqNotifier
# Used to set up and modify settings for the notifier.
class Configuration
OPTIONS = [:mailbox_size, :uri].freeze
# Size of outgoing messages queue. All messages over this value will be dropped.
attr_accessor :mailbox_size
# The uri to connect to (0MQ socket)
attr_accessor :uri
def initialize
@mailbox_size = 200
end
def zmq_context
@zmq_context ||= ZMQ::Context.new
end
def socket
@socket ||= begin
s = zmq_context.socket ZMQ::PUB
s.connect @uri
s.setsockopt(ZMQ::HWM, mailbox_size)
at_exit { s.close }
s
end
end
# Allows config options to be read like a hash
#
# @param [Symbol] option Key for a given attribute
def [](option)
send(option)
end
# Returns a hash of all configurable options
def to_hash
OPTIONS.inject({}) do |hash, option|
hash.merge(option.to_sym => send(option))
end
end
# Returns a hash of all configurable options merged with +hash+
#
# @param [Hash] hash A set of configuration options that will take precedence over the defaults
def merge(hash)
to_hash.merge(hash)
end
end
end
| true |
c1633b5e2ec83307ba68ed40d9ea45bc64c3046c
|
Ruby
|
irwinchan/object_oriented_programming
|
/people.rb
|
UTF-8
| 595 | 4.59375 | 5 |
[] |
no_license
|
# Object Oriented Programming Assignments
# Exercise 1
class Person
def initialize(name)
@name = name
end
def greet
puts "Hi, my name is #{@name}"
end
end
class Student < Person
def learn
puts "I get it!"
end
end
class Instructor < Person
def teach
puts "Everything in Ruby is an Object"
end
end
instructor_a = Instructor.new("Chris")
instructor_a.greet
student_a = Student.new("Cristina")
student_a.greet
instructor_a.teach
student_a.learn
student_a.teach # This does not work because student_a is a Student object and the Student class does not have the teach method.
| true |
fc753dce29160c907a1eab84929eee3458c2295c
|
Ruby
|
BreahnaDavid/pulse_music
|
/app/lib/best_track.rb
|
UTF-8
| 396 | 3.0625 | 3 |
[] |
no_license
|
class BestTrack
def initialize(emotion)
@emotion = emotion
end
def search
if ['happiness'].include? @emotion
songs = HuineaTrack.all_happy
songs[rand(songs.count)]
elsif ['neutral', 'surprise'].include? @emotion
songs = HuineaTrack.all
songs[rand(songs.count)]
else
songs = HuineaTrack.all_sad
songs[rand(songs.count)]
end
end
end
| true |
6d08204326edb88be1fdbf114f7f6dda9d368de3
|
Ruby
|
DmitryKey/nlp-spam
|
/src/bin/classify
|
UTF-8
| 481 | 3.3125 | 3 |
[] |
no_license
|
#! /usr/bin/env ruby
#
# Classify a given text file based on a training set.
#
require_relative '../lib/classifier'
abort "Usage: #{File.basename(__FILE__)} CLASSIFIER_OBJ TEST_OBJ" if ARGV.size < 2
classifier = Classifier.load(ARGV.shift)
testing = Classifier.load(ARGV.shift)
testing.each do |sample|
pred = classifier.classify(sample.value)
if pred == sample.kind
puts "TRUE (#{pred} == #{sample.kind})"
else
puts "FALSE (#{pred} != #{sample.kind})"
end
end
| true |
70f1a41c12eb20ce6d592849bafa66101600ddc1
|
Ruby
|
jordanhudgens/ruby-fundamentals
|
/datastructures/arrays.rb
|
UTF-8
| 150 | 2.96875 | 3 |
[] |
no_license
|
my_int_arr = [1, 2, 3, 4, 5, 6]
my_other_arr = Array.new
range_arry = (1..25).to_a
my_nested_arr = [my_int_arr, 4, 2, 5, "Hey"]
p my_nested_arr[0][3]
| true |
2f53dccb69a1ec71626ad3e2ce96646b7649caee
|
Ruby
|
keomony/learn-to-program
|
/chap09/ex1_one_billion_seconds.rb
|
UTF-8
| 592 | 3.390625 | 3 |
[] |
no_license
|
# One billion seconds...
# Find out the exact second you were born (if you can).
# Figure out when you will turn (or perhaps when you did turn?) one billion seconds old.
# Then go mark your calendar.
puts "Please, tell me your date of birth."
puts "Which year were you born?"
birth_year = gets.chomp
puts "Which month were you born?"
birth_month = gets.chomp
puts "Which day of the month were you born?"
birth_day = gets.chomp
years_old = Time.now.year - Time.new(birth_year,birth_month,birth_day).year
puts "SPANK! ".* years_old
puts "-".* 20
puts Time.new(1982,3,4,19,5,31)+1000000000
| true |
8d820c28eedb0f23921a7995c16242a7becfe27a
|
Ruby
|
hirao19/ruby
|
/ruby1.rb
|
UTF-8
| 1,832 | 3.796875 | 4 |
[] |
no_license
|
name = "佐藤"
puts "こんにちは#{name}さん"
age = 33
puts "#{age}歳です"
puts "Hello Ruby"
puts "-----------------"
puts 33
puts 2 + 9
puts "2+9"
puts 2 - 2
puts 2 * 2
puts 2 / 2
puts 2 % 2
puts "-----------------"
puts "今日もRubyを" + "勉強します"
puts "10" + "10"
puts "-----------------"
name = "hirao"
puts name
puts "-----------------"
text = "プログラミングを学んだら、"
puts text + "世界が広がる"
num = 10
num1 = 23
puts num + num1
puts num * num1
puts "----------------"
text = "をマスターしよう"
puts "HTML" + text
puts "CSS" + text
puts "Ruby" + text
num = num + 10
puts num
num1 *= 10
puts num1
puts "----------------"
puts "#{name}と申します"
puts "#{num}歳とみせかけて違います"
puts "---------------"
score = 97
if score > 80
puts "よく出来ました"
end
if score > 99
puts "よく出来ました"
end
puts "---------------"
score = 90
puts score > 80
puts score < 70
puts score >= 60
puts score <= 90
puts "---------------"
puts score == 90
puts score == 80
puts score != 90
puts score != 80
name = "shiki"
puts name == "shiki"
puts name != "siki"
score = 100
if score != 90
puts "満点ではありません"
end
puts "---------------"
score = 70
if score > 80
puts "よく出来ました"
else
puts "頑張りましょう"
end
puts "---------------"
score = 70
if score > 80
puts "よく出来ました"
elsif score > 66
puts "まずまずです"
else
puts "頑張りましょう"
end
puts "---------------"
score = 90
if score >= 95 && score <= 85
puts "高得点です。次は満点を目指しましょう"
else
puts "自己管理をし、しっかりと学習しましょう!"
end
if score >=90 || score <=88
puts "高得点です。あと少し!"
end
puts "----------------"
| true |
93d1b44b278f3f45780a70bab362c642e63477e3
|
Ruby
|
cawhyte/oo-basics-v-000
|
/lib/book.rb
|
UTF-8
| 391 | 3.53125 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Book
attr_accessor :author, :page_count, :genre
attr_reader :title
def initialize(title)
@title = title
end
def turn_page
puts "Flipping the page...wow, you read fast!"
end
end
class Shoe
attr_accessor :color, :size, :material, :condition
attr_reader :brand
def initialize(brand)
@brand = brand
end
def cobble
puts "Your shoe is as good as new!"
end
end
| true |
0b707aec05f16741c0c2bab03f6db2e0a07047d0
|
Ruby
|
MichelleMik/TIcTacToe_BV
|
/lib/gameboard.rb
|
UTF-8
| 2,365 | 3.59375 | 4 |
[] |
no_license
|
require_relative 'game.rb'
require_relative 'cell.rb'
require_relative 'player.rb'
require 'pry'
class GameBoard
attr_reader :grid, :length
attr_accessor :available_spaces
def initialize
reset_board
@length = @grid.length
end
def get_cell_coordinates(x,y)
@grid[x][y]
end
def set_cell(x,y, char)
cell = get_cell_coordinates(x,y)
cell.val = char
end
def winner?
diagonal_wins? || anti_diagonal_wins? || column_or_row_wins?("row") || column_or_row_wins?("column")
end
def tie?
@available_spaces.size == 0
end
def game_done?
winner? || tie? ? true : false
end
def reset_board
@grid = default
@available_spaces = grid_hash.keys
end
def grid_hash
moves = {
1 => [0,0],
2 => [0,1],
3 => [0,2],
4 => [1,0],
5 => [1,1],
6 => [1,2],
7 => [2,0],
8 => [2,1],
9 => [2,2]
}
end
def default
new_moves = grid_hash.keys.map{|move|Cell.new(move)}
newest = new_moves.each_slice(3).to_a
end
def diagonal_wins
diag_chars = Array.new(@length).each_with_index.map do |char, i|
@grid[i][i].val
end
diag_chars
end
def diagonal_wins?
if diagonal_wins
diagonal = diagonal_wins.reject{|item| item.is_a? Integer}
end
diagonal.size == @length && diagonal.uniq.size == 1
end
def anti_diagonal_wins
anti_diag_chars = Array.new(@length).each_with_index.map do |char, i|
@grid[i][(@length-1)-i].val
end
anti_diag_chars
end
def anti_diagonal_wins?
if anti_diagonal_wins
anti_diagonal = anti_diagonal_wins.reject{|item| item.is_a? Integer}
end
anti_diagonal.size == @length && anti_diagonal.uniq.size == 1
end
def block_row_wins
rows = []
@grid.each_with_index do |row,i|
char_row = row.map{|item| item.val}
rows << char_row
end
rows
end
def block_column_wins
columns = []
(0..@length-1).each do |i|
char_column = @grid.map{|item|item[i].val}
columns << char_column
end
columns
end
def column_or_row_wins?(type)
method = self.send("block_#{type}_wins")
wins = method.find{|item| item.uniq.size == 1}
if wins
non_int_wins = wins.reject{|item|item.is_a? Integer}
non_int_wins ? true : false
else
false
end
end
end
| true |
cb5725c13fe5c333ab8a858ddc952fc61f769812
|
Ruby
|
rbk/ruby_class
|
/examples/More_Method_Tricks/variable_parameter_lists.rb
|
UTF-8
| 916 | 3.203125 | 3 |
[] |
no_license
|
# variable_parameter_lists
def method_test( p1, p2, *p3 )
puts "p1 is #{p1}"
puts "p2 is #{p2}"
puts "p3 is #{p3.inspect}"
puts '-' * 30
end
method_test( 'a', 'b' )
method_test( 'a', 'b', 'c' )
method_test( 'a', 'b', 'c', 'd', 'e' )
method_test( 'a', 'b', 'c', 'd', 'e', 'f', 'g' )
def tag_writer(tag, content, *css)
puts "<#{tag} style=\"#{css.join( '; ' )}\">#{content}</#{tag}>"
end
tag_writer( 'div', 'hello', 'color: red', 'font-size: 16px' )
tag_writer( 'p', 'This is a test' )
def many_params( p1, p2, p3, p4, p5, p6, p7 )
puts "p1 is #{p1}"
puts "p2 is #{p2}"
puts "p3 is #{p3}"
puts "p4 is #{p4}"
puts "p5 is #{p5}"
puts "p6 is #{p6}"
puts "p7 is #{p7}"
puts '-' * 30
end
a = ["red","green","blue","purple","orange","yellow"]
many_params("white",a[0],a[1],a[2],a[3],a[4],a[5])
many_params("white", *a)
# many_params(*a)
| true |
3091837885b37fd524587d5f74ba51702d31079e
|
Ruby
|
isundaylee/clips_to_html
|
/item.rb
|
UTF-8
| 131 | 2.65625 | 3 |
[] |
no_license
|
class Item
attr_accessor :datetime, :type
def initialize(datetime, type)
@datetime = datetime
@type = type
end
end
| true |
e035dbc41d7f3f3b0621ece25345cf100d7f5d7b
|
Ruby
|
stevehvaughn/coffee-shop
|
/app/models/customer.rb
|
UTF-8
| 737 | 2.6875 | 3 |
[] |
no_license
|
class Customer < ActiveRecord::Base
has_many :orders, dependent: :destroy
has_many :coffees, through: :orders
def self.names
pluck(:name)
end
def order_coffee(coffee_title, price)
coffee = Coffee.find_or_create_by(title: coffee_title)
order = Order.create(customer_id: id, coffee_id: coffee.id, price: price)
order.receipt
end
def total_purchases_amount
orders.sum(:price)
end
def dislike_coffee(coffee_title)
coffee = Coffee.find_by(title: coffee_title)
last_coffee_order = orders.where("coffee_id = ?", coffee.id).last
last_coffee_order.destroy
puts "#{name} has been refunded $#{order.price}"
end
end
| true |
c81a2b18a464e0ccaeef49775a3b8b835c2f5e13
|
Ruby
|
d-actor/lunch_lady
|
/lunclady.rb
|
UTF-8
| 5,727 | 3.5 | 4 |
[] |
no_license
|
require 'pry'
@total = []
@wallet = 10
class Dish
attr_reader :name, :price
def initialize(name, price)
@name = name
@price = price
end
def info
puts "#{@name} -- #{@price}"
end
end
@meat_loaf = Dish.new('Meatloaf', '3.50')
@hamsandwich = Dish.new('Ham Sandwich', '2.25')
@mysterymeat = Dish.new("Mystery Meat", '4.75')
### sides
@chips = Dish.new('Chips', '0.75')
@carrots = Dish.new('Carrots', '1.00')
@apple = Dish.new('Apple', '0.75')
@toast = Dish.new('Toast', '1.00')
def menu
puts "---DIGITAL LUNCH LADY---"
puts "1) Menu"
puts "2) Total"
puts "3) Clear"
puts "\n--Type 'Quit' at any time to quit-- \n \n"
print "WALLET = "
print @wallet.to_f - @order_total.to_f
print " USD \n \n"
puts "Please make a selection: "
selection = gets.strip.to_s
end
def choose_lunch
def main_dish
puts "Select ONE Main dish: "
puts "1)"
puts "#{@meat_loaf.info}"
puts "2)"
puts "#{@hamsandwich.info}"
puts "3)"
puts "#{@mysterymeat.info}"
choice = gets.strip.to_s
case choice
when "1"
puts "Meatloaf added!"
@total << @meat_loaf
when "2"
puts "Ham Sandwich added!"
@total << @hamsandwich
when "3"
puts "Mystery Meat added!"
@total << @mysterymeat
when "Quit", "quit", "q", "QUIT", "Q"
total
puts "Goodbye!"
exit
else
puts "Invalid choice, try again"
main_dish
end
end
def side_one
puts "Select a side: "
puts "1)"
puts "#{@chips.info}"
puts "2)"
puts "#{@carrots.info}"
puts "3)"
puts "#{@apple.info}"
puts "4)"
puts "#{@toast.info}"
choice1 = gets.strip.to_s
case choice1
when "1"
puts "Chips added!"
@total << @chips
when "2"
puts "Carrots added!"
@total << @carrots
when "3"
puts "Apple added!"
@total << @apple
when "4"
puts "Toast added!"
@total << @toast
when "Quit", "quit", "q", "QUIT", "Q"
total
puts "Goodbye!"
exit
else
puts "Invalid choice, try again"
side_one
end
end
def side_two
puts "Choose one more: "
puts "1)"
puts "#{@chips.info}"
puts "2)"
puts "#{@carrots.info}"
puts "3)"
puts "#{@apple.info}"
puts "4)"
puts "#{@toast.info}"
choice2 = gets.strip.to_s
case choice2
when "1"
puts "Chips added!"
@total << @chips
when "2"
puts "Carrots added!"
@total << @carrots
when "3"
puts "Apple added!"
@total << @apple
when "4"
puts "Toast added!"
@total << @toast
when "Quit", "quit", "q", "QUIT", "Q"
total
puts "Goodbye!"
exit
else
puts "Invalid choice, try again"
side_two
end
end
def add_ons
puts "Add Another item?"
puts "1) YES"
puts "2) NO"
puts "\n--Type 'Quit' at any time to quit-- \n \n"
puts "Choose an option: "
opt = gets.strip.to_s
case opt
when "1"
puts "Choose an item:"
puts "1)"
puts "#{@meat_loaf.info}"
puts "2)"
puts "#{@hamsandwich.info}"
puts "3)"
puts "#{@mysterymeat.info}"
puts "4)"
puts "#{@chips.info}"
puts "5)"
puts "#{@carrots.info}"
puts "6)"
puts "#{@apple.info}"
puts "7)"
puts "#{@toast.info}"
opt2 = gets.strip.to_s
case opt2
when "1"
puts "Meatloaf added!"
@total << @meat_loaf
add_ons
when "2"
puts "Ham Sandwich added!"
@total << @hamsandwich
add_ons
when "3"
puts "Mystery Meat added!"
@total << @mysterymeat
add_ons
when "4"
puts "Chips added!"
@total << @chips
add_ons
when "5"
puts "Carrots added!"
@total << @carrots
add_ons
when "6"
puts "Apple added!"
@total << @apple
add_ons
when "7"
puts "Toast added!"
@total << @toast
add_ons
when "Quit", "quit", "q", "QUIT", "Q"
total
puts "Goodbye!"
exit
else
puts "Invalid choice, try again"
add_ons
end
when "2"
puts "OK"
total
when "Quit", "quit", "q", "QUIT", "Q"
total
puts "Goodbye!"
exit
else
puts "Invalid selection, try again"
add_ons
end
end
main_dish
side_one
side_two
add_ons
end
def total
puts "Your order is: "
@order_total = 0
@total.each do |item|
puts "#{item.name} -- #{item.price}"
@order_total += item.price.to_f
end
puts "Your order total is:"
print @order_total
print " USD\n\n"
@remaining = @wallet.to_f - @order_total.to_f
if @remaining >= 0
puts "Your change is:"
print @remaining.to_f
print " USD.\n"
else
puts "Not enough cash!"
clear
end
end
def clear
puts "Clear current selections?"
puts "1) YES"
puts "2) NO"
puts "\n--Type 'Quit' at any time to quit-- \n \n"
puts "Choose an option: "
choice = gets.strip.to_s
case choice
when "1"
puts "Clearing selections..."
@total.clear
total
when "2"
puts "Keeping selections..."
when "Quit", "quit", "q", "QUIT", "Q"
total
puts "Goodbye!"
exit
else
puts "Invalid Selection"
clear
end
end
loop do
case menu
when "1"
choose_lunch
when "2"
total
when "3"
clear
when "Quit", "quit", "q", "QUIT", "Q"
total
puts "Goodbye!"
break
else
puts "Invalid selection, try again my dude"
end
end
| true |
32c226cee166258faaa60066a3fc7e1722189c3a
|
Ruby
|
avalanche123/sinatra-rabbit
|
/lib/sinatra/rabbit/validation.rb
|
UTF-8
| 1,880 | 3.046875 | 3 |
[
"Apache-2.0"
] |
permissive
|
module Sinatra
module Rabbit
module Validation
class Failure < StandardError
attr_reader :param
def initialize(param, msg='')
super(msg)
@param = param
end
def name
param.name
end
end
class Param
attr_reader :name, :klass, :type, :options, :description
def initialize(args)
@name = args[0]
@klass = args[1] || :string
@type = args[2] || :optional
@options = args[3] || []
@description = args[4] || ''
end
def required?
type.eql?(:required)
end
def optional?
type.eql?(:optional)
end
end
def param(*args)
raise RabbitDuplicateParamException if params[args[0]]
p = Param.new(args)
params[p.name] = p
end
def params
@params ||= {}
@params
end
# Add the parameters in hash +new+ to already existing parameters. If
# +new+ contains a parameter with an already existing name, the old
# definition is clobbered.
def add_params(new)
# We do not check for duplication on purpose: multiple calls
# to add_params should be cumulative
new.each { |p| @params[p.name] = p }
end
def each_param(&block)
params.each_value { |p| yield p }
end
def validate(values)
each_param do |p|
if p.required? and not values[p.name]
raise Failure.new(p, "Required parameter #{p.name} not found")
end
if values[p.name] and not p.options.empty? and
not p.options.include?(values[p.name])
raise Failure.new(p, "Parameter #{p.name} has value #{values[p.name]} which is not in #{p.options.join(", ")}")
end
end
end
end
end
end
| true |
69dd8ca273a237ff8b984b1067fb9c42cfb8c964
|
Ruby
|
tonyr729/backend_prework
|
/day_7/fizzbuzz/fizzbuzz.rb
|
UTF-8
| 146 | 3.65625 | 4 |
[] |
no_license
|
(1..100).each { |num|
string = ''
string += 'Fizz' if num % 3 == 0
string += 'Buzz' if num % 5 == 0
puts(string.empty? ? num : string);
}
| true |
0aed1cb3a17e7c5e7361bc41408b1193414de9f9
|
Ruby
|
p/stint-video-assembly
|
/stint-video-assembly
|
UTF-8
| 7,493 | 2.71875 | 3 |
[
"curl"
] |
permissive
|
#!/usr/bin/env ruby
# Smartycam puts a keyframe in every second at the second.
# May be using 30 fps to make this work.
# This means as long as I am splitting & joining videos on whole seconds
# I should be splitting and joining on keyframes.
#
# ffprobe info: https://stackoverflow.com/questions/11400248/using-ffmpeg-to-get-video-info-why-do-i-need-to-specify-an-output-file
#
# ffmpeg video cutting:
# https://stackoverflow.com/questions/43890/crop-mp3-to-first-30-seconds
# https://superuser.com/questions/138331/using-ffmpeg-to-cut-up-video#704118
# http://trac.ffmpeg.org/wiki/Seeking
# https://superuser.com/questions/554620/how-to-get-time-stamp-of-closest-keyframe-before-a-given-timestamp-with-ffmpeg#554679
require 'byebug'
require 'tempfile'
require 'fileutils'
require 'json'
require 'open3'
require 'yaml'
require 'optparse'
class Hash
def stringify_keys
out = {}
each do |k, v|
out[k.to_s] = v
end
out
end
def deep_stringify_keys
out = {}
each do |k, v|
if v.is_a?(Hash)
v = v.deep_stringify_keys
end
out[k.to_s] = v
end
out
end
end
options = {}
OptionParser.new do |opts|
opts.on('-s', '--skeleton', 'Create a skeleton configuration file') do
options[:skeleton] = true
end
opts.on('-b', '--build-meta', 'Build video meta info') do
options[:build_meta] = true
end
opts.on('-j', '--auto-join', 'Automatically join part files') do
options[:auto_join] = true
end
end.parse!
def video_file?(path)
%w(mov mkv).include?(path.sub(/.*\./, '').downcase)
end
$size_cache = {}
def cached_file_size(path)
$size_cache[path] ||= File.stat(path).size
end
def size_reasonable?(path)
cached_file_size(path) > 50_000_000
end
class Generator
attr_reader :root
def initialize(root)
@root = root
end
private def video_file_paths
paths = []
Dir["#{root}/*"].sort.each do |path|
filename = File.basename(path)
if video_file?(filename) && size_reasonable?(path)
paths << path
end
end
end
end
class SkeletonGenerator < Generator
def generate
skeleton = {}
video_file_paths.each do |path|
filename = File.basename(path)
skeleton[filename] = {
split: nil,
join: nil,
size: human_size(path),
}
end
skeleton
end
private def human_size(path)
(cached_file_size(path) / 1024 / 1024).round.to_s + ' MB'
end
end
class MetaGenerator < Generator
def generate
video_file_paths.each do |path|
key_frame_times = FfProbe.new(path).key_frame_times
open("#{path}.keyframes.json", 'w') do |f|
f << JSON.dump(key_frame_times)
end
end
end
end
class Splitter
def initialize(config)
@config = config
end
attr_reader :config
def run
plan = []
@groups = {}
config.each do |filename, subconfig|
splits = subconfig['split']
if splits.nil? || splits == 'none'
puts "Ignore #{filename}"
next
end
if splits.is_a?(Hash) && splits.size == 1 && splits.values == [nil]
splits = splits.keys.first
end
if splits.is_a?(String)
# single split, do we need to change file format?
if splits =~ /-p\d+$/ || splits.include?('.')
# yes
splits = {splits => {}}
else
new_name = make_new_name(filename, splits)
puts "Copy #{filename} -> #{new_name}"
plan << ['cp', filename, new_name]
group(new_name)
next
end
end
splits.each do |target, split_config|
if split_config == {}
# format conversion only
new_name = make_new_name(filename, target, 'mkv')
puts "Convert all #{filename} -> #{new_name}"
FileUtils.rm_f(new_name)
plan << ['ffmpeg', '-i', filename, '-c', 'copy', new_name]
group(new_name)
else
puts "Split #{filename} -> #{target}"
# ranged conversion
#info = FfProbe.new(filename)
pre_opts = []
post_opts = []
if split_config['start']
pre_opts += ['-ss', split_config['start'].to_s]
end
if split_config['end']
post_opts += ['-to', split_config['end'].to_s]
end
args = pre_opts + ['-i', filename] + post_opts
target_path = make_new_name(filename, target, 'mkv')
FileUtils.rm_f(target_path)
cmd = ['ffmpeg'] + args + ['-c', 'copy', target_path]
plan << cmd
group(target_path)
end
end
end
plan.each do |cmd|
execute(cmd)
end
@groups.each do |group_name, paths|
next if paths.size <= 1
target_path = make_new_name(paths.first, group_name)
Tempfile.open('stint-video-assembly') do |f|
paths.each do |path|
f << "file '#{File.realpath(path)}'\n"
end
f.flush
FileUtils.rm_f(target_path)
cmd = ['ffmpeg', '-f', 'concat', '-safe', '0', '-i', f.path, '-c', 'copy', target_path]
#execute(['cat',f.path])
execute(cmd)
end
end
end
private def group(path)
group_name = path.sub(/-p\d+(\.\w+)?$/, '')
if group_name != path
@groups[group_name] ||= []
@groups[group_name] << path
end
end
private def make_new_name(filename, target, new_ext=nil)
if target.include?('.')
target
else
if new_ext.nil?
unless filename =~ /\.(\w+)$/
raise "Can't figure out the extension for #{filename}"
end
new_ext = $1.downcase
end
"#{target}.#{new_ext}"
end
end
private def execute(cmd)
pid = fork do
puts "Executing #{cmd.join(' ')}"
exec(*cmd)
end
Process.waitpid(pid)
end
end
module Utils
module_function def duration_to_length(duration)
unless duration =~ /^(((\d+):)?(\d+):)?(\d+)(\.\d+)$/
raise "Bad duration format: #{duration}"
end
h, m, s, ms = $3, $4, $5, $6
h.to_i * 3600 + m.to_i * 60 + s.to_i + "0#{ms}".to_f
end
end
class FfProbe
def initialize(path)
@path = path
end
attr_reader :path
def info
@info ||= JSON.parse(get_output(
'ffprobe', '-v', 'quiet', '-print_format', 'json',
'-show_format', path))
end
def length
info['format']['duration'].to_f
end
def key_frame_times
@key_frame_times ||= begin
info = JSON.parse(get_output(
'ffprobe', '-v', 'quiet', '-print_format', 'json',
path,
'-select_streams', 'v', '-show_frames', '-show_entries', 'frame=pkt_pts_time,pict_type'))
info = info['frames']
key_frame_times = []
info.each do |frame_info|
if frame_info['pict_type'] == 'I'
key_frame_times << frame_info['pkt_pts_time'].to_f
end
end
key_frame_times
end
end
private def get_output(*cmd)
output, status = Open3.capture2(*cmd)
if status.exitstatus != 0
raise "Command failed: #{cmd.join(' ')}: #{status.exitstatus}"
end
output
end
end
if File.basename($0) == File.basename(__FILE__)
if options[:skeleton]
payload = SkeletonGenerator.new(Dir.pwd).generate.deep_stringify_keys
puts YAML.dump(payload)
exit
elsif options[:build_meta]
MetaGenerator.new(Dir.pwd).generate
exit
end
config = YAML.load(File.open(ARGV.first).read)
Splitter.new(config).run
end
| true |
46d912bb00d9918ed48b2214001e565031662d25
|
Ruby
|
PiyushNankar12/Ruby_Training
|
/Yash Mekhe/Day3/email_validate.rb
|
UTF-8
| 224 | 2.96875 | 3 |
[] |
no_license
|
def mail_validate(mail)
if /[a-zA-Z0-9\.\-\_]{1,}@[a-zA-Z].[a-z]{2,}/ =~ mail
print "Valid email id!!!\n"
else
print "Invalid email id!!!\n"
end
end
print "Enter the email - id : \n"
mail = gets
mail_validate(mail)
| true |
66dcdc55d00b85cc344b71c911c272151c9ab5a8
|
Ruby
|
trizen/sidef
|
/scripts/json.sf
|
UTF-8
| 243 | 2.859375 | 3 |
[
"Artistic-2.0"
] |
permissive
|
#!/usr/bin/ruby
var json = require('JSON::PP').new;
# Parse JSON
var data = json.decode('{"blue": [1, 2], "ocean": "water"}');
say data;
# Change JSON
data{:ocean} = Hash.new(water => %w[fishy salty]);
# Encode JSON
say json.encode(data);
| true |
cc67314293b4c54a2296d7bc65c98fd30860067c
|
Ruby
|
lhwitherspoon/ls_rb100
|
/variables/play-file.rb
|
UTF-8
| 78 | 3 | 3 |
[] |
no_license
|
# scope.rb
a = 5
3.times do |n|
a = 3
b = 5
end
puts a
puts b
| true |
c4101f08a35859e2ef2d192f540cfb871d5f32ff
|
Ruby
|
JumpstartLab/problem_solving
|
/solutions/mitchell_will/lib/ex2.rb
|
UTF-8
| 292 | 3.53125 | 4 |
[] |
no_license
|
class Reverse
def self.execute(to_reverse)
if to_reverse.length == 1
to_reverse
else
to_reverse[-1] + execute(to_reverse[0..-2])
end
end
end
class String
# lol confusing much?
def reverse
length == 1 ? self : self[-1] + self[0..-2].reverse
end
end
| true |
c5b50bf4623c98b3859755a161cb1b5874f03792
|
Ruby
|
Green-stripes/key-for-min-value-001-prework-web
|
/key_for_min.rb
|
UTF-8
| 615 | 3.796875 | 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)
lowest = []
name_hash.each do |key, value|
lowest << value
end
low = []
if lowest[0] == nil
nil
elsif lowest[0] < lowest[1] && lowest[0] < lowest[2]
low << lowest[0]
elsif lowest[1] < lowest[0] && lowest[1] < lowest[2]
low << lowest[1]
elsif lowest[2] < lowest[0] && lowest[2] < lowest[1]
low << lowest [2]
else nil
end
winner = []
name_hash.each do |key, value|
if value == low[0]
winner << key
end
end
winner[0]
end
| true |
d02b25e23a30e09742c0f5ea0962c1a0f1d15634
|
Ruby
|
benrodenhaeuser/LS_100
|
/02_variables/test.rb
|
UTF-8
| 60 | 3.03125 | 3 |
[] |
no_license
|
(1..3).each do |i|
end
for j in (1..3)
j += 1
end
puts j
| true |
68a1cd2c6ddeb3aba899c076dee4507c1b532dd8
|
Ruby
|
iwashi/cloudn-cli
|
/lib/cloudn_cli/shell.rb
|
UTF-8
| 8,022 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
require "readline"
require "pp"
require "termcolor" # for simple colorize
require "coderay" # for syntax highlight
require "rexml/document"
require "erb"
require "open-uri"
require "cgi"
require_relative "client"
module Cloudn
class User
def initialize(name, opt)
@name = name.freeze
@api_key = opt[:api_key].freeze
@secret_key = opt[:secret_key].freeze
url = opt[:url]
@url = url.is_a?(URI::HTTP) ? url : URI.parse(url)
@url.freeze
@api_location = opt[:api_location].freeze
end
attr_reader :name, :api_key, :secret_key, :url, :api_location
end
class Shell
class SyntaxError < StandardError; end
def initialize(config_path)
@config_path = config_path.freeze
@xml_formatter = REXML::Formatters::Pretty.new(2)
@xml_formatter.compact = true
load_config
create_client
input_loop
end
attr_reader :config_path, :url, :json, :raw, :users, :current_user
alias user current_user
def json=(bool)
@json = bool
update_client
return @json
end
def raw=(bool)
@raw = bool
update_client
return @raw
end
def current_user=(user)
user = user.to_sym
@current_user = @users[user]
update_client
return @current_user
end
alias user= current_user=
private
def create_client
@client = Cloudn::Client.new(
url: @current_user.url,
api_key: @current_user.api_key,
secret_key: @current_user.secret_key,
api_location: @current_user.api_location,
json: @json
)
end
alias update_client create_client
def load_config
@config = YAML.load_file(@config_path)
@url = URI.parse(@config[:url])
@json = @config[:json]
@raw = @config[:raw_output]
users = @config[:users]
@users = {}
users.each do |name_sym, opt|
@users[name_sym] = User.new(name_sym.to_s, opt)
end
@current_user = @users.values.first
end
def make_param_hash(line)
command, *params = line.split
param_hash = { command: command }
unless params.empty?
opt_key_value = params.map do |param|
key, value = param.split("=", 2)
raise SyntaxError, "Invalid Parameter: #{param}" unless value
#[key.to_sym, CGI.escape(value)]
[key.to_sym, value]
#[key.to_sym, ERB::Util.u(value)]
end
opt_hash = Hash[opt_key_value]
param_hash.merge!(opt_hash)
end
return param_hash
end
def syntax_highlight(str, lang)
CodeRay.scan(str, lang).term
end
def raw_formatted_output(response_text)
if @json
response_hash = ::JSON.parse(response_text)
pretty_json = ::JSON.pretty_generate(response_hash)
puts syntax_highlight(pretty_json, :json)
else # XML
response_xml = ::REXML::Document.new(response_text)
@xml_formatter.write(response_xml, formatted = "")
puts syntax_highlight(formatted, :xml)
end
end
def process_command(line)
param_hash = make_param_hash(line)
if @raw
response_text = @client.get_raw(param_hash)
raw_formatted_output(response_text)
else
response_hash = @client.get(param_hash)
PP.pp(response_hash, pretty_printed = "")
puts syntax_highlight(pretty_printed, :ruby)
end
end
def info(str)
puts ::TermColor.colorize(str.to_s, :green)
end
def alert(str)
warn ::TermColor.colorize(str.to_s, :red)
end
def change_format(format)
case format
when /json/i
self.json = true
when /xml/i
self.json = false
else
raise ArgumentError, "undefined format: #{format}"
end
end
def show_list_users
@users.each do |name, user|
if user == @current_user
info "#{name} *"
else
info name
end
end
end
Usage = <<-EOS
Usage: command [parameter1=value2 parameter2=value2 ...]
Cloudn Cli Command:
exit|quit:
exit the shell
config:
show current config
doc ${api_name}:
show description for the API
format (xml|json)?:
show or change current format
raw (true|false)?:
enable/disable raw output
user ${user_name}:
switch user
users:
show users
eval { # ruby code }:
eval ruby code in Cloudn::Client instance context
EOS
NON_WHITESPACE_REGEXP = %r![^\s#{[0x3000].pack("U")}]!
def process_line(line)
return if line !~ NON_WHITESPACE_REGEXP # ignore bland line
case line
when "help"
info Usage
when "exit", "quit"
exit
when "config"
PP.pp(@config, pretty_printed = "")
puts syntax_highlight(pretty_printed, :ruby)
when /^doc (.+)$/
query = $1
raise ArgumentError, "command not specified" unless query
regexp = /^#{query}/i
commands = APIList.select {|command| regexp =~ command }
commands.each do |command|
info command
info APIParams[command][1]
puts
end
when /^format ?(.+)?$/
format_to_change = $1
change_format(format_to_change.to_s) if format_to_change
info "Current format is: #{@json ? "JSON" : "XML"}"
when /^raw ?(.+)?$/
raw = $1
self.raw = (raw == "true") if raw
info (@raw ? "Raw Output" : "Ruby's Hash Output")
when /^user (.+)?$/
user_to_change = $1
self.user = $1 if $1
info "Current user is: #{@current_user.name}"
when "users"
show_list_users
when /^eval \{(.+)\}$/
raise ArgumentError, "code is not specified" unless $1
code = $1
instance_eval(code)
else
process_command(line)
end
end
# API infomation for completion
APIParamsPath = File.expand_path("../api_list.json", __FILE__).freeze
APIParams = JSON.parse(File.read(APIParamsPath)).freeze
APIList = APIParams.keys.freeze
# libedit(editline) in Mac OS X is broken.
# its #line_buffer(rl_line_buffer) is not line buffer but a mere last line.
CompletionProc = lambda do |line|
words = line.split
word = words.last
case words.size
when 0, 1 # command completion
Readline.completion_append_character = " "
regexp = /^#{word}/i
return APIList.select {|key| regexp =~ key }
else # params completion
Readline.completion_append_character = "="
command = words.first
completing_param = words.pop
regexp = /^#{completing_param}/i
api_params = APIParams[command]
return nil unless api_params
no_required_params = api_params.first
completed_params = no_required_params.select {|param| regexp =~ param }
return completed_params.map {|param| (words + [param]).join(" ") }
end
end
def init_readline_completion
Readline.basic_word_break_characters = "" # disable readline's word break
Readline.completion_proc = CompletionProc
end
STTY = `stty -g`.chomp rescue nil
TrapINT = lambda do |signum|
trap(:INT) do
(system("stty", STTY) rescue nil) if STTY # reset stty
exit
end
puts "Interrupt again to exit"
end
def register_trap
trap(:INT, &TrapINT)
end
PaddingLen = 10
Padding = (" " * PaddingLen).freeze
def input_loop
init_readline_completion
register_trap
while line = Readline.readline("> ", true)
register_trap if trap(:INT, nil) != TrapINT
begin
process_line(line)
rescue => ex
alert "Exception #{ex.class}: #{ex.message}"
ex.backtrace.each {|trace| alert(Padding + trace) }
end
end
end
end
end
if $PROGRAM_NAME == __FILE__
p Cloudn::Shell.new("../../config.yml")
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.