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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
523ae47ac1d4c2158eaf5b269809bbf0b00f1e19 | Ruby | samwize/fastlane | /fastlane_core/spec/fastlane_runner_spec.rb | UTF-8 | 1,510 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe Commander::Runner do
describe '#handle_unknown_error' do
class CustomError < StandardError
def preferred_error_info
['Title', 'Line 1', 'Line 2']
end
end
class NilReturningError < StandardError
def preferred_error_info
nil
end
end
it 'should reraise errors that are not of special interest' do
expect do
Commander::Runner.new.handle_unknown_error!(StandardError.new('my message'))
end.to raise_error(StandardError, '[!] my message'.red)
end
it 'should reraise errors that return nil from #preferred_error_info' do
expect do
Commander::Runner.new.handle_unknown_error!(NilReturningError.new('my message'))
end.to raise_error(StandardError, '[!] my message'.red)
end
it 'should abort and show custom info for errors that have the Apple error info provider method with $verbose=false' do
runner = Commander::Runner.new
expect(runner).to receive(:abort).with("\n[!] Title\n\tLine 1\n\tLine 2".red)
with_verbose(false) do
runner.handle_unknown_error!(CustomError.new)
end
end
it 'should reraise and show custom info for errors that have the Apple error info provider method with $verbose=true' do
with_verbose(true) do
expect do
Commander::Runner.new.handle_unknown_error!(CustomError.new)
end.to raise_error(CustomError, "[!] Title\n\tLine 1\n\tLine 2".red)
end
end
end
end
| true |
f9f4a376d6767055ce1ddd490ccfd47ca0004502 | Ruby | artsy/bearden | /app/models/slack_bot.rb | UTF-8 | 478 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class SlackBot
def self.post(message)
new(message).post
end
def initialize(message)
@message = message
end
def post
options = default_options.merge(text: @message)
client.chat_postMessage options
end
private
def client
@client ||= Slack::Web::Client.new
end
def channel
Rails.application.secrets.slack_channel
end
def default_options
{
as_user: true,
channel: channel,
link_names: true
}
end
end
| true |
a03b3d69eac0f4c5c59579971488af2924dcbf7a | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/allergies/4b6a24cf78264601ab31160fbcd8bc0e.rb | UTF-8 | 573 | 3.28125 | 3 | [] | no_license | class Allergies
attr_reader :score
LOOKUP = [["cats", 128], ["pollen", 64], ["chocolate", 32], ["tomatoes", 16],
["strawberries", 8], ["shellfish", 4], ["peanuts", 2], ["eggs", 1]]
def initialize(score)
@score = score
end
def allergic_to?(item)
list.include?(item)
end
def list
@list ||= make_list
end
private
def make_list
tally_score = score
LOOKUP.each_with_object([]) do |(item, rating), list|
if tally_score >= rating
list.unshift(item)
tally_score %= rating
end
end
end
end
| true |
c28e284a8b5580d4dc35805cb35fb176c8adfd12 | Ruby | asarialtun/sinatra_number_guess | /web_guesser.rb | UTF-8 | 740 | 3.265625 | 3 | [] | no_license | require 'sinatra'
require 'sinatra/reloader'
number = rand(100)
#@guess = ""
@message = ""
get '/' do
@guess = params["guess"].to_i if params["guess"]
message = construct_message(@guess,number) if @guess
erb :index, :locals => {:number => number, :guess => @guess,:message => message}
end
def construct_message(guess,number)
if guess > number
if guess-number >= 5
@message = "Way too high"
else
@message = "Too high!"
end
elsif guess < number
if number - guess >= 5
@message = "Way too low"
else
@message = "Too low!"
end
elsif guess == number
@message = "That's right!"
end
@message += "\n<br>The secret number is #{number}" if guess != number
return @message
end
| true |
232b0e3f0d3b401b4d731896f0b8641ff141b4bb | Ruby | alexmgr/RunTracer | /ruby/iterative_reducer.rb | UTF-8 | 4,475 | 2.734375 | 3 | [] | no_license | # Author: Ben Nagy
# Copyright: Copyright (c) Ben Nagy, 2006-2010.
# License: The MIT License
# (See README.TXT or http://www.opensource.org/licenses/mit-license.php for details.)
require 'rubygems'
require 'beanstalk-client'
require 'msgpack'
require 'oklahoma_mixer'
# As traces come in, maintain an iteratively reduced set which
# still has full coverage. Not as efficient as the greedy
# algorithm, but it's 'free' since we're processing the traces
# anyway. This reduced set can be greedily reduced further once
# we have enough coverage.
class IterativeReducer
COMPONENT="IterativeReducer"
VERSION="1.0.0"
PREFIX="#{COMPONENT}-#{VERSION}"
DEFAULTS={
:beanstalk_servers=>["127.0.0.1"],
:beanstalk_port=>11300,
:backup_file=>"ccov-reduced.tch",
:ringbuffer_size=>100,
:debug=>true
}
def debug_info( str )
warn "#{PREFIX}: #{str}" if @debug
end
def initialize( opt_hsh )
@opts=DEFAULTS.merge( opt_hsh )
@debug=@opts[:debug]
@processed=0
@loghandle=File.open( "ir.log", "wb+" ) # quick hack
@loghandle.sync=true
@coverage=Set.new
@reduced={}
servers=@opts[:beanstalk_servers].map {|srv_str| "#{srv_str}:#{@opts[:beanstalk_port]}" }
debug_info "Starting up, connecting to #{@opts[:beanstalk_servers].join(' ')}"
@stalk=Beanstalk::Pool.new servers
@stalk.watch 'compressed'
@stalk.use 'reduced'
debug_info "Initializing backup in #{@opts[:backup_file]}"
initialize_backup
debug_info "Startup done."
end
def initialize_backup
@backup=OklahomaMixer.open( @opts[:backup_file], :rcnum=>10 )
end
def close
@backup.close
@loghandle.close
end
def coverage
@coverage.size
end
def reduced_size
@reduced.size
end
def update_rolling_average( added )
@ringbuffer||=[]
@ringbuffer << added
@ringbuffer.shift if @ringbuffer.size > @opts[:ringbuffer_size]
@avg=(@ringbuffer.inject {|s,x| s+=x} / @ringbuffer.size.to_f)
end
def rolling_average
@avg
end
# This could be refactored into Reductions but it's ugly
# with the ivars we need to access.
def update_reduced( this_set, fn )
this_hsh={}
# General Algorithm
# There are two ways into the reduced set.
# 1. Add new blocks
# 2. Consolidate the blocks of 2 or more existing files
unless this_set.subset? @coverage # then we add new blocks
this_set_unique=(this_set - @coverage)
update_rolling_average( this_set_unique.size )
@coverage.merge this_set_unique
# Any old files with unique blocks that
# are covered by this set can be deleted
# and their unique blocks merged with those of this set
# (this is breakeven at worst)
@reduced.delete_if {|fn, hsh|
this_set_unique.merge( hsh[:unique] ) if hsh[:unique].subset?( this_set )
}
this_hsh[:unique]=this_set_unique
@reduced[fn]=this_hsh
else # Do we consolidate 2 or more sets of unique blocks?
update_rolling_average( 0 )
double_covered=@reduced.select {|fn,hsh|
hsh[:unique].subset? this_set
}
if double_covered.size > 1
merged=Set.new
double_covered.each {|fn,hsh|
merged.merge hsh[:unique]
@reduced.delete fn
}
this_hsh[:unique]=merged
@reduced[fn]=this_hsh
end
end
@backup['set']=@reduced.keys.to_msgpack
end
def process_next
debug_info "getting next trace"
job=@stalk.reserve # from 'compressed' tube
message=MessagePack.unpack( job.body )
deflated=Set.new( MessagePack.unpack(message['deflated']) )
debug_info "Updating reduced"
update_reduced( deflated, message['filename'])
message.delete 'deflated'
@stalk.put message.to_msgpack #into 'reduced' tube
@processed+=1
debug_info "Finished. Reduced Set: #{reduced_size} Total Cov: #{coverage}, Rolling Avg: #{rolling_average}, Processed: #{@processed}"
@loghandle.puts "#{reduced_size},#{coverage},#{rolling_average},#{@processed}"
job.delete
end
end
| true |
ab77b5537c48c65e5b86922b46f7275fbb592c17 | Ruby | khnaero/odin_project | /learn_ruby/03_simon_says/simon_says.rb | UTF-8 | 448 | 4.0625 | 4 | [] | no_license | #write your code here
def echo(word)
"#{word}"
end
def shout(word)
"#{word.upcase}"
end
def repeat(word, num=2)
[word] * num * " "
end
def start_of_word(word, num)
word[0..(num - 1)]
end
def first_word(phrase)
phrase.split(' ')[0]
end
def titleize(title)
words = title.split.map do |word|
if %w(the and over).include?(word)
word
else
word.capitalize
end
end
words.first.capitalize!
words.join(" ")
end | true |
d471fc25c8aedc6e731a216cb3b0725cb6b72d49 | Ruby | jaesypg/ar-student-schema | /app/models/student.rb | UTF-8 | 320 | 2.890625 | 3 | [] | no_license | require_relative '../../db/config'
class Student < ActiveRecord::Base
# implement your Student model here
def name
"#{self.first_name} #{self.last_name}"
end
def age
now = Time.now.utc.to_date
now.year - self.birthday.year - (self.birthday.to_date.change(:year => now.year) > now ? 1 : 0)
end
end | true |
68a1dc07d256f5ddcfa3996763392c522e7261fc | Ruby | nikhgupta/handlisted | /app/models/merit/badge_rules.rb | UTF-8 | 1,638 | 2.796875 | 3 | [] | no_license | # Be sure to restart your server when you modify this file.
#
# +grant_on+ accepts:
# * Nothing (always grants)
# * A block which evaluates to boolean (recieves the object as parameter)
# * A block with a hash composed of methods to run on the target object with
# expected values (+votes: 5+ for instance).
#
# +grant_on+ can have a +:to+ method name, which called over the target object
# should retrieve the object to badge (could be +:user+, +:self+, +:follower+,
# etc). If it's not defined merit will apply the badge to the user who
# triggered the action (:action_user by default). If it's :itself, it badges
# the created object (new user for instance).
#
# The :temporary option indicates that if the condition doesn't hold but the
# badge is granted, then it's removed. It's false by default (badges are kept
# forever).
module Merit
class BadgeRules
include Merit::BadgeRulesMethods
def initialize
award_user_who :is_alpha_user, "alpha-user"
award_user_who :is_beta_user, "beta-user"
award_user_who :is_developer, "omega"
award_user_who :is_new_user, "new-user", temporary: true
award_user_who :has_completed_profile_information, 'autobiographer', temporary: true
end
private
def award_user_who(check, badge, options = {}, &block)
actions = ['users/sessions#create', 'users#update', 'users/sessions#destroy']
actions.push [options.delete(:and_on)]
grant_on actions.flatten.compact, {
badge: badge,
model_name: "User",
to: :itself
}.merge(options) do |user|
user.send("#{check}?")
end
end
end
end
| true |
badf8ed7e53912daae3b32ae14c277b3fbab942e | Ruby | aemrich/ttt-6-position-taken-rb-q-000 | /lib/position_taken.rb | UTF-8 | 317 | 3.65625 | 4 | [] | no_license | # code your #position_taken? method here!
def position_taken?(board, position)
if board[position] == " "
then false
elsif board[position] == ""
then false
elsif board[position] == nil
then false
elsif board[position] == "X"
then true
elsif board[position] == "O"
then true
end
end | true |
668c1b77df34852aa3dcd98a2e001b0d7e87add6 | Ruby | ewoutquax/weatherapp | /lib/adafruit/sensor_reader.rb | UTF-8 | 443 | 2.515625 | 3 | [] | no_license | module Adafruit
module SensorReader
def self.invoke
reading_temperature_pressure = `/srv/python/Adafruit_Python_BMP/api.py`.split("\n")
reading_temperature_humidity = `/srv/python/Adafruit_Python_DHT/examples/api.py`.split("\n")
{
temperature: reading_temperature_pressure[0],
pressure: reading_temperature_pressure[1],
humidity: reading_temperature_humidity[1]
}
end
end
end
| true |
d2a6cde4e7558ccbfc4bf7875ad8a9df3c71ce21 | Ruby | benjlcox/drug_wars | /lib/api/city.rb | UTF-8 | 221 | 3.09375 | 3 | [] | no_license | class City
attr_reader :name
attr_accessor :drugs
def initialize(name, drugs)
@name = name
@drugs = drugs
end
def new_day
@drugs.each_pair do |name, drug|
drug.change_price
end
end
end
| true |
5079f35aa54f6bcd925db975a94ca6cc2dd4be33 | Ruby | empressofflowers/my-each-onl01-seng-ft-041320 | /my_each.rb | UTF-8 | 204 | 3.125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry'
#fruit_basket = ["mango", "peach", "orange", "apple"]
def my_each(array)
n = 0
while n < array.length
yield (array[n])
n = n + 1
end
array
end
#my_each(array)
| true |
2a4cf3ba629f5398cbd8f0bb52d8a9be13fe8a00 | Ruby | jobitoalv/Terminal_App | /Classes/confirmation.rb | UTF-8 | 1,479 | 3.53125 | 4 | [] | no_license | require_relative 'dog'
require_relative '../classes/method/header'
class Booking
attr_reader :booking, :service, :date, :add_on
def initialize(booking, service, date, add_on=nil)
@service = service
@date = date
@add_on = add_on
@booking = booking
end
def display_booking(dog, grooming)
puts HEADER_LINE
puts "#{dog.name.upcase}'S BOOKING".center(HEADER_LENGTH)
puts HEADER_LINE
puts
puts grooming.name
grooming.contact_info
puts
puts "Service type: #{service.type}"
@service.display_features
puts
puts "Booking date:"
@date.each{ |date| puts " *#{date}" }
puts
if @add_on
display_confirmation_add_on
else
puts HEADER_LINE
end
puts"Total Price : $#{'%.2f' % service.price}" .rjust(HEADER_LINE)
end
def display_booking_add_on
puts"Add Ons: "
@add_on.each { |add_on| puts" *#{add_on.name} - $#{add_on.price}"}
puts
puts HEADER_LINE
puts "#{add_on_price}".rjust(HEADER_LINE)
end
def add_on_price
add_on_total= 0
@add_on.each { |add_on|add_on_total += add_on.price.to_f}
return add_on_total
end
def booking_price
if @add_on
return @service.price.to_f + add_on_price
else
return @service.price.to_f
end
end
end | true |
6cdf1cdd02d617f9e4ae348982b12672bdcc8c4d | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/rna-transcription/dcc34914e4f645209f5bb24bbfe6abca.rb | UTF-8 | 1,232 | 3.484375 | 3 | [] | no_license | class Complement
def self.of_dna(dna_strand)
DNAStrand.new(dna_strand).rna_complement
end
def self.of_rna(rna_strand)
RNAStrand.new(rna_strand).dna_complement
end
end
class DNAStrand
attr_reader :strand
def initialize(strand)
@strand = strand
end
def rna_complement
strand.split(//).map do |nucleotide|
nucleotide_converter.dna_nucleotide_to_rna(nucleotide)
end.join
end
private
def nucleotide_converter
@nucleotide_converter ||= NucleotideConverter.new
end
end
class RNAStrand
attr_reader :strand
def initialize(strand)
@strand = strand
end
def dna_complement
strand.split(//).map do |nucleotide|
nucleotide_converter.rna_nucleotide_to_dna(nucleotide)
end.join
end
private
def nucleotide_converter
@nucleotide_converter ||= NucleotideConverter.new
end
end
class NucleotideConverter
def dna_nucleotide_to_rna(nucleotide)
case nucleotide
when 'G' then 'C'
when 'C' then 'G'
when 'T' then 'A'
when 'A' then 'U'
end
end
def rna_nucleotide_to_dna(nucleotide)
case nucleotide
when 'C' then 'G'
when 'G' then 'C'
when 'A' then 'T'
when 'U' then 'A'
end
end
end
| true |
1b0c55fb0cbd30bfe2efc80833b9943650bb7d21 | Ruby | engineyard/fragrant | /lib/fragrant/address_manager.rb | UTF-8 | 2,198 | 2.921875 | 3 | [
"MIT"
] | permissive | require 'ipaddr'
require 'json'
module Fragrant
AddressRangeExhausted = Class.new(StandardError)
class AddressManager
attr_accessor :data_location, :allocated_addresses
attr_accessor :address_range, :address_map
def initialize(data_location, address_range)
self.data_location = data_location
self.address_range = address_range
self.address_map = {}
self.allocated_addresses = []
load_address_data
end
def load_address_data
return unless File.exist?(data_location)
unless File.writable?(data_location)
raise "Unable to access IP address config file at #{data_location}"
end
File.open(data_location, 'rb') do |f|
data = JSON.parse(f.read)
self.address_range = data['address_range']
self.address_map = data['address_map']
self.allocated_addresses = data['allocated_addresses']
end
end
def address_data
{:address_range => address_range,
:allocated_addresses => allocated_addresses,
:address_map => address_map}
end
def first_available_address
ip = IPAddr.new(address_range).to_range.detect do |ip|
!allocated_addresses.include?(ip.to_s)
end
return ip.to_s if ip
raise AddressRangeExhausted, "No more addresses available in range #{address_range}"
end
def persist
dir = File.dirname(data_location)
FileUtils.mkdir_p(dir) unless File.directory?(dir)
File.open(data_location, 'wb') do |f|
f.write(address_data.to_json)
end
end
def claim_address(environment_id)
if address_map.key?(environment_id)
raise "#{environment_id} already has an address"
end
address = first_available_address
address_map[environment_id] = address
allocated_addresses << address
persist
address
end
def release_addresses(environment_id)
unless address_map.key?(environment_id)
raise "No addresses registered to environment #{environment_id}"
end
address = address_map[environment_id]
allocated_addresses.delete address
address_map.delete environment_id
persist
end
end
end
| true |
a5d1ad9347972709c93d3c9a463da34fbf2ee82f | Ruby | ari-skyler/badges-and-schedules-onl01-seng-ft-050420 | /conference_badges.rb | UTF-8 | 424 | 3.84375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def batch_badge_creator(names)
names.collect do |name|
"Hello, my name is #{name}."
end
end
def badge_maker(name)
"Hello, my name is #{name}."
end
def assign_rooms(names)
room = 0
names.collect do |name|
room+=1
"Hello, #{name}! You'll be assigned to room #{room}!"
end
end
def printer(names)
batch_badge_creator(names).each {|badge| puts badge}
assign_rooms(names).each {|room| puts room}
end | true |
a9e0e2b835452326e47c25d639dfe1a15f6dbcea | Ruby | fmlharrison/learn_to_program | /ch14-blocks-and-procs/even_better_profiling.rb | UTF-8 | 406 | 3.34375 | 3 | [] | no_license | def profile block_description, &block
#this method take a code a sees how long it takes to run.. in seconds
#the block_description is the name of the code
#&block is the code's block truned into a proc.
profiling = true
if profiling
start_time = Time.new
block.call
duration = Time.new - start_time
puts "#{block_description}: #{duration} seconds"
else
block.call
end
end
| true |
2e82c5f8466e308bb0e29764f21ea36f92e3783a | Ruby | enukane/Solution-for-PE | /SOLVED/prob17.rb | UTF-8 | 1,800 | 3.859375 | 4 | [] | no_license | $num_to_word = {
0 => "and",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
10=> "ten",
11=> "eleven",
12=> "twelve",
13=> "thirteen",
14=> "fourteen",
15=> "fifteen",
16=> "sixteen",
17=> "seventeen",
18=> "eighteen",
19=> "nineteen",
20=> "twenty",
30=> "thirty",
40=> "forty",
50=> "fifty",
60=> "sixty",
70=> "seventy",
80=> "eighty",
90=> "ninety",
100=> "hundred",
1000=> "thousand"
}
sum = 0
def word_length_of_num_in_english num
print "#{num} : "
cur = 0
# 1000
if num == 1000
print "#{$num_to_word[1]}#{$num_to_word[1000]} :#{$num_to_word[1].length+$num_to_word[1000].length}\n"
return $num_to_word[1].length + $num_to_word[1000].length
end
# 100 ~ 999
n_at_100 = num / 100
n_ex_100 = num % 100
n_at_10 = n_ex_100 / 10
n_at_1 = n_ex_100 % 10
# 100, 200, ... 900
if n_at_100 > 0 then
cur += $num_to_word[n_at_100].length
print $num_to_word[n_at_100]
cur += $num_to_word[100].length
print $num_to_word[100]
end
if n_ex_100 > 0 then
if n_at_100 > 0
cur += $num_to_word[0].length
print $num_to_word[0]
end
str = $num_to_word[n_ex_100]
if str then
cur += str.length
print "#{str} : #{cur}\n"
return cur
end
# 1 to 99 but not in n_to_word
# 21, 22 .... 99
cur += $num_to_word[n_at_10*10].length if n_at_10 > 0
print $num_to_word[n_at_10*10]
cur += $num_to_word[n_at_1].length if n_at_1 > 0
print $num_to_word[n_at_1]
end
print " : total #{cur}\n"
return cur
end
p (1..1000).inject(0){|sum, num|
sum + word_length_of_num_in_english(num)
}
p word_length_of_num_in_english(342)
p word_length_of_num_in_english(115)
| true |
039a553b3570e9d7462645f4c24d9a1793121a59 | Ruby | mandarandriam/ruby-vendredi | /exo_10.rb | UTF-8 | 187 | 3.390625 | 3 | [] | no_license | print "Peut-on avoir votre date de naissance s'il vous plaît? "
date_de_naissance = gets.chomp.to_i
operation = 2017 - date_de_naissance
puts "Votre âge, en 2017 est de #{operation}"
| true |
e05d41eb5ddd58113f61f54807afa03cecb18d6c | Ruby | Vutienbka/Ruby | /DoWhile.rb | UTF-8 | 54 | 3.09375 | 3 | [] | no_license | a = 10
loop do
puts a
a -= 1
break if a < 0
end
| true |
ba7e7d11116de0c5ba1dd57fdb17f66c4b103d45 | Ruby | alu0100003956/LPP_T_36_p4 | /lib/complejos.rb | UTF-8 | 1,079 | 3.46875 | 3 | [] | no_license | #! usr/bin/ruby
#definición de una clase complejos para trabajar con numeros complejos
class Complejos
attr_reader :real, :imaginaria
def initialize(real, imaginaria)
@real,@imaginaria = real, imaginaria
end
def to_s
"#{@real}+#{@imaginaria}i"
end
def +(other)
if (other.is_a? Complejos)
Complejos.new(@real + other.real, @imaginaria + other.imaginaria)
end
end
def -(other)
if (other.is_a? Complejos)
Complejos.new(@real - other.real, @imaginaria - other.imaginaria)
end
end
def *(other)
if (other.is_a? Complejos)
Complejos.new(@real * other.real - @imaginaria * other.imaginaria,
@real * other.imaginaria + @imaginaria * other.real)
elsif (other.is_a? Numeric)
Complejos.new( other * @real, other * @imaginaria)
end
end
def /(other)
if (other.is_a? Complejos)
denominador = (other.real * other.real - other.imaginaria * other.imaginaria).to_f
Complejos.new((@real * other.real - @imaginaria * other.imaginaria) / denominador,
(@imaginaria * other.real - @real * other.imaginaria) / denominador)
end
end
end
| true |
ded2dfcefb9f602c7957d7d015f93898c50a53ae | Ruby | nuiver/help-for-hire | /db/seeds.rb | UTF-8 | 4,561 | 2.53125 | 3 | [] | no_license | lawn_mowing = Task.create ( { name: "Lawn Mowing", category: "Gardening" } )
hedge_trimming = Task.create ( { name: "Hedge Trimming", category: "Gardening" } )
fertilizing = Task.create ( { name: "Fertilizing", category: "Gardening" } )
weeding = Task.create ( { name: "Weeding", category: "Gardening" } )
paving = Task.create ( { name: "Paving", category: "Gardening" } )
pond_construction = Task.create ( { name: "Pond Construction", category: "Gardening" } )
changing_light_bulb = Task.create ( { name: "Changing light bulb", category: "Electricity" } )
laying_cables = Task.create ( { name: "Laying cables", category: "Electricity" } )
installing_distribution = Task.create ( { name: "Installing Distribution", category: "Electricity" } )
vacuuming = Task.create ( { name: "Vacuuming", category: "Cleaning" } )
window_cleaning = Task.create ( { name: "Window cleaning", category: "Cleaning" } )
mopping = Task.create ( { name: "Mopping", category: "Cleaning" } )
dusting = Task.create ( { name: "Dusting", category: "Cleaning" } )
sanitary = Task.create ( { name: "Sanitary", category: "Cleaning" } )
house_repair = Task.create ( { name: "House repair", category: "Carpentry" } )
furniture_repair = Task.create ( { name: "Furniture repair", category: "Carpentry" } )
building_fence = Task.create ( { name: "Building fence", category: "Carpentry" } )
unclog_toilet = Task.create ( { name: "Unclog toilet", category: "Plumbing" } )
installing_new_pipes = Task.create ( { name: "Installing new pipes", category: "Plumbing" } )
shower_installation = Task.create ( { name: "Shower installation", category: "Plumbing" } )
kitchen_installation = Task.create ( { name: "Kitchen installation", category: "Plumbing" } )
computer_help = Task.create ( { name: "Computer help", category: "IT" } )
Booking.delete_all
Service.delete_all
User.delete_all
dana = User.create( { email: "dana@emailadres.com", password: "abcd1234" })
jacob = User.create( { email: "jacob@emailadres.com", password: "abcd1234" })
wouter = User.create( { email: "wouter@emailadres.com", password: "abcd1234" })
monique = User.create( { email: "monique@emailadres.com", password: "abcd1234" })
michael = User.create( {email: "michael@emailadres.com", password: "abcd1234"})
henk = User.create( {email: "henk@emailadres.com", password: "abcd1234"})
service1 = Service.create ( {
name: "Cleaning",
description: "I'm available for cleaning basically anything! I have helped out my family in needs for years and know the perfect ways how to clean best",
begin_date: "2016-08-27 00:00:00 +0200",
end_date: "2016-09-10 00:00:00 +0200",
location: "Hoorn",
price: 100.00,
category: "Cleaning",
tasks: [ vacuuming, window_cleaning, mopping, dusting, sanitary ],
user: dana
} )
service2 = Service.create ( {
name: "Gardening help",
description: "I can do your gardening for you! I have my own company for 20 years. No matter how big or small your garden is, I can make it beautifull",
begin_date: "2016-09-20 00:00:00 +0200",
end_date: "2016-09-28 00:00:00 +0200",
location: "Amsterdam",
price: 200.00,
category: "Gardening",
tasks: [ lawn_mowing, hedge_trimming, fertilizing, weeding, paving ],
user: jacob
} )
service3 = Service.create ( {
name: "Computergirl",
description: "Computer problems? I'm your girl to contact!",
begin_date: "2016-09-01 00:00:00 +0200",
end_date:"2016-09-02 00:00:00 +0200",
location: "Alkmaar",
price: 100.00,
category: "IT",
tasks: [ computer_help ],
user: monique
} )
service4 = Service.create ( {
name: "Electricity fixer",
description: "I can fix anything",
begin_date: "2016-09-01 00:00:00 +0200",
end_date:"2016-09-02 00:00:00 +0200",
location: "Amsterdam",
price: 75.00,
category: "Electricity",
tasks: [ changing_light_bulb ],
user: michael
} )
service5 = Service.create ( {
name: "Your handyman",
description: "Everything in the house I can fix",
begin_date: "2016-09-01 00:00:00 +0200",
end_date:"2016-09-02 00:00:00 +0200",
location: "Amsterdam",
price: 30.00,
category: "Carpentry",
tasks: [ house_repair ],
user: henk
} )
booking1 = Booking.create ( {
begin_date: "2016-09-01 00:00:00 +0200",
end_date: "2016-09-02 00:00:00 +0200",
service: service1,
user: wouter
})
booking2 = Booking.create ( {
begin_date: "2016-08-28 00:00:00 +0200",
end_date: "2016-08-29 00:00:00 +0200",
service: service3,
user: wouter
})
| true |
dc75f10c07bf21685943cbaa2ddd37860c1bec4d | Ruby | nayow/tests-ruby | /lib/03_basics.rb | UTF-8 | 671 | 3.4375 | 3 | [] | no_license | def who_is_bigger(a,b,c)
hash = {'a': a, 'b': b, 'c': c}
if a && b && c then return "#{hash.key(hash.values.max)} is bigger"
else return "nil detected"
end
end
def reverse_upcase_noLTA(str)
return str.gsub(/[lta]/i,'').reverse.upcase
end
def array_42(arr)
arr.each {|x| if x==42 then return true end}
return false
end
def magic_array(arr)
return arr.flatten.map{|x| x*2}.uniq.delete_if{|x| x%3==0}.sort
end
# - flattened (i.e. no more arrays in array)
# - sorted
# - with each number multiplicated by 2
# - with each multiple of 3 removed
# - with each number duplicate removed (any number should appear only once)
# - sorted | true |
b0b01475eec825ed25d691cdc25cdb12c75df434 | Ruby | Byronlee/SalesTax | /lib/salestax/basket_item.rb | UTF-8 | 227 | 2.640625 | 3 | [
"MIT"
] | permissive | module Salestax
class BasketItem
include RateCalculable
attr_accessor :goods, :amount, :price
def initialize(goods, amount=1, price)
@goods, @amount, @price = goods, amount, price
end
end
end
| true |
6917c6fd2faaf032af93c92b9ecb2a8239174116 | Ruby | standardgalactic/slideshow | /slideshow-models/attic/markup/mediawiki.rb | UTF-8 | 1,178 | 2.609375 | 3 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | # encoding: utf-8
module Slideshow
module MediawikiEngines
def setup_mediawiki_engine
return if @mediawiki_engine_setup
logger.debug 'require wikicloth -- load mediawiki library'
require 'wikicloth' # default mediawiki library
@mediawiki_engine_setup = true
rescue LoadError
puts "You're missing a library required for Mediawiki to Hypertext conversion. Please run:"
puts " $ gem install wikicloth"
# check: raise exception instead of exit e.g
# raise FatalException.new( 'Missing library dependency: wikicloth' )
exit 1
end
def mediawiki_to_html( content )
setup_mediawiki_engine()
puts " Converting Mediawiki-text (#{content.length} bytes) to HTML..."
# NB: turn off table_of_contents (TOC) auto-generation with __NOTOC__
# NB: turn off adding of edit section/markers for headings (noedit:true)
wiki = WikiCloth::Parser.new( data: "__NOTOC__\n"+content, params: {} )
content = wiki.to_html( noedit: true )
end
end # module MediawikiEngines
end # module Slideshow
class Slideshow::Gen
include Slideshow::MediawikiEngines
end
| true |
c6f916fc4ed6f693489def30707b52d72dc9e35b | Ruby | afiore/tripleloop | /spec/tripleloop/util_spec.rb | UTF-8 | 3,009 | 2.921875 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe Tripleloop::Util do
subject { Tripleloop::Util }
describe ".with_nested_fetch" do
context "when supplied argument is an array" do
it "extends it with the NestedFetch module" do
subject.with_nested_fetch({}).should respond_to(:get_in)
end
end
context "when supplied argument is an hash" do
it "extends it with the NestedFetch module" do
subject.with_nested_fetch([]).should respond_to(:get_in)
end
end
context "when supplied argument is not enumerable" do
it "returns the supplied argument" do
subject.with_nested_fetch(Object.new).should_not respond_to(:get_in)
end
end
end
describe ".module" do
module Test
module Foo
class Bar; end
end
class Baz; end
end
context "when the supplied object's class is within a nested namespace" do
it "returns the parent module as a constant" do
subject.module(Test::Foo::Bar.new).should eq(Test::Foo)
subject.module(Test::Baz.new).should eq(Test)
end
end
context "when the supplied object class is not noested within a namespace" do
it "returns the Kernel constant" do
subject.module(Object.new).should eq(Kernel)
end
end
end
describe Tripleloop::Util::NestedFetch do
describe "#get_in" do
context "when object is a hash" do
subject { Tripleloop::Util.with_nested_fetch({
:path => {
:to => {
:value => :ok
}
}
})}
it "returns the value corresponding to the supplied path" do
subject.get_in(:path, :to, :value).should eq(:ok)
end
it "returns nothing when the corresponding value cannot be found" do
subject.get_in(:wrong, :path).should be_nil
end
end
context "when object is an array" do
subject { Tripleloop::Util.with_nested_fetch([
[0,1,2,[
[:ok]
]]
])}
it "returns the value corresponding to the supplied path" do
subject.get_in(0,3,0,0).should eq(:ok)
end
it "returns nothing when no corresponding value can be found" do
subject.get_in(0,3,1).should be_nil
end
end
end
end
describe Tripleloop::Util::String do
subject { Tripleloop::Util::String }
describe ".classify" do
it "turns 'snake case' into 'camel case'" do
subject.classify("foo_bar_baz").should eq("FooBarBaz")
end
end
end
describe Tripleloop::Util::Hash do
subject { {"foo" => 1,
"bar" => 2,
"baz" => {"k" => "v"}
}.extend(Tripleloop::Util::Hash) }
describe ".symbolize_keys" do
it "returns a copy of the supplied hash replacing symbols with strings" do
subject.symbolize_keys.should eq({
:foo => 1,
:bar => 2,
:baz => {:k => "v"}
})
end
end
end
end
| true |
98d20c0d82aea87adae298c798277b4f0a263191 | Ruby | aczid/ruby_patterns | /behavioral/memento.rb | UTF-8 | 887 | 3.765625 | 4 | [] | no_license | #!/usr/bin/ruby
# This example demonstrates the memento pattern in the Ruby language.
class Originator
def initialize
@state = self.inspect
end
def set_memento(memento)
@state = memento.get_state
end
def create_memento
return Memento.new(@state)
end
end
class Memento
def initialize(state)
@state = state
end
def get_state
return @state
end
def set_state(state)
@state = state
end
end
class Caretaker
def initialize
@savedstates = Array.new
end
def add_memento(memento)
@savedstates.push(memento)
end
def get_memento(id)
return @savedstates[id]
end
end
class Client
def initialize
@caretaker = Caretaker.new
@originator = Originator.new
end
def run
@caretaker.add_memento(@originator.create_memento)
puts @caretaker.inspect
end
end
cff = Client.new
cff.run | true |
b501832ba37e1f590efcf392bafe58c76b391e1c | Ruby | vikas-reddy/misc-code | /Azri/submissions/Chakrapani_Week2_assignments/chatserver.rb | UTF-8 | 2,104 | 3.21875 | 3 | [] | no_license | require 'socket'
### Changeable variables ###
port = 6789
count_history = 30 # Number of messages to store in history & print
### --------------------###
#### Arrays to maintain connection/user/thread Details and Last 30 messages ####
client_connections = []
client_threads = {}
past_history = []
### Starting a Server on port 'port' ###
server = TCPServer.new(port)
while(session = server.accept)
client_connections << session
client_threads["#{session.to_s}"] = Thread.new(session) do |client_session|
if (past_history.length > 0)
client_session.puts "-------Past #{past_history.length} Messages from Chat Board-------"
past_history.each do |prev_mesg|
client_session.puts prev_mesg
end
end
client_session.puts "-------Welcome To Chat Board-------"
client_session.puts "SERVER: No Of Users Online :: #{client_connections.length}"
while(1)
### Getting Chat Conversation ###
in_mesg = client_session.gets
if(in_mesg.chomp == "logout")
### handling logout & removing and closing connection/thread info ###
login_name = client_session.gets.chomp
end_mesg = "SERVER: User '#{login_name}' left Chat Board"
c_t = client_threads["#{client_session}"]
client_connections.delete(client_session)
client_threads.delete("#{client_session.to_s}")
### Sending logout notification to all other users(online) in the chat board ###
client_connections.each do |clnt|
if client_session != clnt
clnt.puts end_mesg
clnt.puts "SERVER: No Of Users Online :: #{client_connections.length}"
end
end
client_session.puts "logout"
client_session.close
c_t.exit
else
### Sending Actual chat Conversations ###
client_connections.each do |clnt|
if client_session != clnt
clnt.print in_mesg
end
end
end
### Storing past history : 'count_history' conversations!!! ###
if (past_history.length < count_history)
past_history << in_mesg
elsif(past_history.length >= count_history)
past_history.delete(past_history[0])
past_history << in_mesg
end
end
end
end
| true |
272a4aa5352a110890ef1d84231976c7d7d6545c | Ruby | sabtain93/rb_101_small_problems | /debugging/08.rb | UTF-8 | 1,683 | 3.890625 | 4 | [] | no_license | =begin
The given code prompts the user to set their own password, and then prompts
them to log in with that password, but throws an error.
The problem here is that we try to access the local variable `password` from
within the `set_password` method without passing it in as an argument. The
method has it's own discreet scope, so will not be able to access the local
variable. Further, we will again need to pass the `password` variable as an argument
to the `verify_password` method, which also tries to access it while not in
scope.
Once we get the program to run without errors, we see there is another problem.
The local variable password is reassigned to the password set by the user within
the set_password method. This breaks the link between the local variable outside
the method and the method parameter password. They do not, therefore, both
reference the string object set by the user. Instead, password outside the method
will still reference `nil`, causing authentication to fail.
Fix this by initializing local variable password as an empty string, and using
a mutating method to preserve the link between it and the originally referenced
string object. We will also need to modify the conditional on ln 44 to reflect
this change.
=end
password = ''
def set_password(password)
puts 'What would you like your password to be?'
new_password = gets.chomp
password << new_password
end
def verify_password(password)
puts '** Login **'
print 'Password: '
input = gets.chomp
if input == password
puts 'Welcome to the inside!'
else
puts 'Authentication failed.'
end
end
if password.empty?
set_password(password)
end
verify_password(password)
| true |
a30e85900777e7a2fee3dd21281e74a7aae614d8 | Ruby | garethlatwork/quickbase_client_extras | /examples/cookbookfiles/recordAndFieldIterator.rb | UTF-8 | 647 | 2.6875 | 3 | [] | no_license |
require 'QuickBaseClient'
# change "username" "password" to your QuickBase username and password
qbc = QuickBase::Client.new("username","password")
qbc.doQuery("6ewwzuuj")
puts "\n --- QuickBase Formula Functions Reference ---\n\n"
recordNumber = 1
qbc.eachRecord(qbc.records){|record|
puts "\n --- Record #{recordNumber} ---"
recordNumber += 1
qbc.eachField(record){|field|
print qbc.lookupFieldNameFromID(field.attributes["id"])
print ": "
if field.has_text?
text = field.text.dup
text.gsub!("<BR/>","\n") if text.include?("<BR/>")
puts text
end
}
}
| true |
fb1e4b7fb12906861ea7c583add483db76921257 | Ruby | EliseP08/ruby | /exo_09.rb | UTF-8 | 177 | 3.328125 | 3 | [] | no_license | puts "Quel est votre prénom ?"
user_firstname = gets.chomp
puts "Merci, quel est votre nom ?"
user_lastname = gets.chomp
puts "Bonjour, #{user_firstname} #{user_lastname} " | true |
625652fbf49cac3668b8d782944e2b36bfe2e6c5 | Ruby | aklives/collections_practice_vol_2-dumbo-web-career-040119 | /collections_practice.rb | UTF-8 | 1,218 | 3.28125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def begins_with_r tools
value = true
tools.each do |t|
if t.scan(/\w/)[0] != "r"
value = false
end
end
value
end
def contain_a tools
arr = []
tools.each do |t|
for i in 0..tools.length-1
if t.scan(/\w/)[i] == 'a'
arr << t
end
end
end
arr
end
def first_wa tools
tools.each do |t|
if t.to_s.scan(/(..)(..)/)[0][0] == 'wa'
return t
end
end
end
def remove_non_strings(tools)
tools.delete_if {|tool| tool.class != String}
end
def count_elements(array)
counts = Hash.new(0)
array.map {|name_hash| counts[name_hash]+=1}
counts.map do |hash, count|
hash[:count] = count
end
counts.keys
end
def merge_data(keys, data)
keys.each do |name_hash|
data.each do |hash|
name_hash.merge!(hash[name_hash[:first_name]])
end
end
end
def find_cool cool
cool.select {|hash| hash if hash.has_value?("cool") }
end
def organize_schools(schools)
organized = {}
schools.each do |school, location_hash|
location_hash.each do |symbol, location|
if organized[location] == nil
organized[location] = [school]
else
organized[location] << school
end
end
end
organized
end
| true |
be9b6371c44c21fba5361a74bc29b5f6e69f5ae9 | Ruby | Kmbsamaurice/odin-project-basic-ruby-projects | /caeser-cipher/spec/caeser-cipher-spec.rb | UTF-8 | 714 | 3.390625 | 3 | [] | no_license | require "../lib/caeser-cipher.rb"
describe "#caeser-cipher" do
it "shifts letters 3 places to the right" do
expect(caeser_cipher("def", 3)).to eql("ghi")
end
it "shifts letters 3 places to the left" do
expect(caeser_cipher("def", -3)).to eql("abc")
end
it "wraps around the letter 'z'" do
expect(caeser_cipher("xyz", 3)).to eql("abc")
end
it "returns both uppercase and lowercase" do
expect(caeser_cipher("dEF", 3)).to eql("gHI")
end
it "returns punctuation unmodified" do
expect(caeser_cipher("?deF!", 3)).to eql("?ghI!")
end
it "handles large integers" do
expect(caeser_cipher("DEF", 34)).to eql("LMN")
end
end | true |
8ebb7a2722a161b6f3ff835c3efcaffd19dd4be0 | Ruby | TakahiroSuzukiqq/CFA-weather-challenge | /weather-challenge.rb | UTF-8 | 1,965 | 3.765625 | 4 | [] | no_license | #####################################################
require "terminal-table"
require "paint"
#####################################################
class Question
def initialize(question)
@question = question
@days = ["Monday", "Tuesday", "Wednesday", "Tursday", "Friday", "Saturday", "Sunday"]
end
attr_accessor :question
def insert_table(days, temp_c, temp_f)
@days = days.join("\n")
rows = []
rows << [@days, temp_c, temp_f]
table = Terminal::Table.new title: "Temperature", headings: %w(Days Celsius Fahrenheit),rows: rows
puts table
end
def ask(hi_progress_bar)
@answers = []
temp_c = []
temp_f = []
@question.each do |question|
system("clear")
puts "#{hi_progress_bar.title}: (#{hi_progress_bar.current_step}/#{@question.length})"
puts question
answer = gets.chomp.to_i
@answers << answer
hi_progress_bar.current_step += 1
end
@answers.each do|answer|
if answer <= 28
temp_c << Paint[answer, :blue]
temp_f << (Paint[answer * 9 / 5 + 32, :blue])
elsif answer >=28
temp_c << Paint[answer, :red]
temp_f << (Paint[answer * 9 / 5 +32, :red])
end
end
@temp_c = temp_c.join("\n")
@temp_f = temp_f.join("\n")
insert_table(@days, @temp_c, @temp_f)
end
end
#####################################################
class ProgressBar
def initialize(title)
@current_step = 1
@title = title
end
attr_accessor :current_step, :title
end
#####################################################
days = ["Monday", "Tuesday", "Wednesday", "Tursday", "Friday", "Saturday", "Sunday"]
@questions = []
days.each do |day|
@questions << "Hi, What was the temperature on #{day}?"
end
#####################################################
hi_question = Question.new(@questions)
hi_progress_bar = ProgressBar.new("Question Progress")
hi_question.ask(hi_progress_bar)
#####################################################
| true |
db7b1f075c3605310614db37f0b0e19dc526ccd3 | Ruby | GillianShanks/ecosystem_classes | /River.rb | UTF-8 | 349 | 3.546875 | 4 | [] | no_license | class River
attr_reader :name
def initialize(name, fish)
@name = name
@fish = fish #array
end
def fish_count()
return @fish.count()
end
# def add_fish(fish)
# @fish << fish
# end
def lose_fish(fish)
@fish.delete(fish)
end
def bear_hunts(bear, fish)
bear.eats_fish(fish)
lose_fish(fish)
end
end
| true |
c359c7a939bbdcab48ddb7caecdca8af1c1b1706 | Ruby | rocket-coverall/100075 | /GamePacket.rb | UTF-8 | 1,513 | 3.484375 | 3 | [] | no_license | class GamePacket # class for outgoing game packets
def initialize param = {}
@type = param[:type]
@body = ""
end
def type
@type
end
def add_utf8 param
@body += [param.length].pack('n')+param
end
def add_long param
@body += [param].pack('N')
end
def add_byte param
@body += [param].pack('n')
end
def to_s type
head = [size,type,0,0,0].pack('nnccc')
head+@body
end
def size
@body.length + 7
end
end
class ServerPacket # class for incoming game packets. it is actually just a stream, but fuck that
attr_accessor :cursor, :server
def initialize str, server
@data = str
@server = server
reset
end
def unp a,b # i honestly don't remember how this works, nor do i want to figure it out again
r = 0
@sic = @data
(a..b).each {|i| r+=@sic[i].ord*(256**(b-i)) }
r
end
def reset
@cursor = 0
end
def forward bytes
@cursor += bytes
end
def size
@data.length
end
def read_byte
return false unless size >= cursor
@cursor += 1
@data[@cursor-1].ord
end
def read_long
return false unless size >= @cursor+3
@cursor += 4
unp @cursor-4, @cursor-1
end
def type
unp 0,1
end
def read_int
return false unless size >= @cursor+1
@cursor += 2
unp @cursor-2, @cursor-1
end
def read_utf8
len = read_byte
return false unless size >= @cursor+size
@cursor += len
@data[@cursor-len .. @cursor-1]
end
end | true |
58d159114e41ae5913943c7fa795fa573533639a | Ruby | sannidhigowda/sannidhi | /backend/Ruby/animal2.rb | UTF-8 | 285 | 3.0625 | 3 | [] | no_license | class Animal
def dog_sound
puts"whoff-whoff"
end
def lion_sound
puts"roar"
end
def elephant_sound
puts"triuph"
end
def rabbbit_sound
puts"squeaks"
end
end
class Amphibians < Animal
end
dog=Amphibians.new
puts dog.dog_sound
puts dog.lion_sound
putsdog.elephant_sound
| true |
25b03e6a3801c1b4e1df6183f9eaa7cfb322828b | Ruby | croelanjr/Ruby-UPC2014-Unidad05 | /juegos_bolivarianos.rb | UTF-8 | 3,723 | 3.40625 | 3 | [] | no_license | =begin
A raíz de los recientes juegos Bolivarianos en nuestro país, se necesita implementar una aplicación
de software que ayude a los organizadores a realizar algunas tareas importantes. Para ello se le ha
solicitado lo siguiente:
a) Desarrollar un subprograma que determine el país que obtuvo mayor cantidad de medallas de oro.
b) Elaborar un subprograma que permita determinar al ganador de los juegos, para ello se sabe que
gana el que tiene mayor cantidad de medallas (oro, plata y bronce)
c) Elaborar un subprograma que determine el porcentaje de países que obtuvieron un número de medallas
menor que el total de medallas otorgadas en los juegos entre todos los países participantes (cantidad de países / total medallas)
=end
def medallasdeOro(pais,medallasOro)
mayor_medalla = medallasOro[0]
indice = 0
for i in 0...medallasOro.size
if mayor_medalla < medallasOro[i]
mayor_medalla = medallasOro[i]
indice = i
end
end
return pais[indice]
end
def encuentraGanador(pais,medallasOro,medallasPlata,medallasBronce)
@medallas = []
for i in 0...medallasOro.size
@medallas << medallasOro[i] + medallasPlata[i] + medallasBronce[i]
end
ganador = medallasdeOro(pais,@medallas)
return ganador
end
def debajoMedia(medallasOro,medallasPlata,medallasBronce)
@cantidad_medalla = []
numero_medalla = 0
porcentaje_cada_pais = []
for i in 0...medallasOro.size
@cantidad_medalla << medallasOro[i] + medallasPlata[i] + medallasBronce[i]
end
cantidad_med = @cantidad_medalla
for j in 0...cantidad_med.size
numero_medalla = numero_medalla + cantidad_med[j]
end
cada_pais = @cantidad_medalla
for h in 0...cada_pais.size
porcentaje_cada_pais << (100 - (cada_pais[h] * 100.00) / numero_medalla).round(2)
end
#print @cantidad_medalla
##print numero_medalla
#print porcentaje_cada_pais
puts (numero_medalla.to_i * cada_pais.size) / 180.0
end
#--- zona de test ----
def test_medallasdeOro
pais=["Colombia","Peru","Chile","Ecuador","Venezuela","Guatemala","Panama"]
oro1=[23,45,34,12,5,33,44]
oro2=[13,25,44,22,55,3,4]
oro3=[63,45,34,12,5,33,55]
print validate("Peru", medallasdeOro(pais,oro1))
print validate("Venezuela", medallasdeOro(pais,oro2))
print validate("Colombia", medallasdeOro(pais,oro3))
end
def test_encuentraGanador
pais=["Colombia","Peru","Chile","Ecuador","Venezuela","Guatemala","Panama"]
oro1=[23,45,34,12,5,33,44]
plata1=[13,25,44,22,55,3,4]
broce1=[63,45,34,12,5,33,55]
oro2=[33,34,3,22,25,31,41]
plata2=[13,20,42,21,5,31,14]
broce2=[14,42,36,44,45,22,77]
oro3=[13,15,14,12,11,16,18]
plata3=[43,55,64,72,55,88,48]
broce3=[63,45,34,12,5,33,55]
print validate("Peru", encuentraGanador(pais,oro1,plata1,broce1))
print validate("Panama", encuentraGanador(pais,oro2,plata2,broce2))
print validate("Guatemala", encuentraGanador(pais,oro3,plata3,broce3))
end
def test_debajoMedia
oro1=[23,45,34,12,5,33,44]
plata1=[13,25,44,22,55,3,4]
broce1=[63,45,34,12,5,33,55]
oro2=[33,34,3,22,25,31,41]
plata2=[13,20,42,21,5,31,14]
broce2=[14,42,36,44,45,22,77]
oro3=[13,15,14,12,11,16,18]
plata3=[43,55,64,72,55,88,48]
broce3=[63,45,34,12,5,33,55]
print validate(42.86, debajoMedia(oro1,plata1,broce1))
print validate(57.14, debajoMedia(oro2,plata2,broce2))
print validate(28.57, debajoMedia(oro3,plata3,broce3))
end
def validate (expected, value)
expected == value ? "." : "F"
end
def test
puts "Test de prueba del programa"
puts "---------------------------"
test_medallasdeOro
puts " "
test_encuentraGanador
puts " "
test_debajoMedia
puts " "
end
test | true |
1e96920a333a070a8c29057d70b6f21a3e121de7 | Ruby | eeeli24/building_blocks | /stock_picker.rb | UTF-8 | 562 | 3.28125 | 3 | [] | no_license | def stock_picker prices
best_days = []
best_value = 0
days_indexes = []
prices.each do |first_day|
first_day_index = prices.index(first_day)
range = prices[first_day_index..-1]
range.each do |second_day|
if second_day - first_day > best_value
best_value = second_day - first_day
best_days[0,1] = first_day, second_day
days_indexes[0] = prices.index(best_days[0])
days_indexes[1] = prices.index(best_days[1])
end
end
end
puts days_indexes
end
stock_picker([17,3,6,9,15,8,6,1,10]) | true |
a059d070205572c1afe7a87b9367874d420d15ed | Ruby | ksandy95/contributions | /iteration_3.rb | UTF-8 | 2,848 | 2.921875 | 3 | [] | no_license | require 'pry'
require 'csv'
class GameTeam
attr_reader :game_id,
:team_id,
:hoa,
:won,
:settled_in,
:head_coach,
:goals,
:shots,
:hits,
:pim,
:pp_opportunities,
:pp_goals,
:face_off_win_percentage,
:giveaways,
:takeaways
def initialize(row)
@game_id = row[:game_id]
@team_id = row[:team_id]
@hoa = row[:hoa]
@won = row[:won]
@settled_in = row[:settled_in]
@head_coach = row[:head_coach]
@goals = row[:goals].to_i
@shots = row[:shots].to_i
@hits = row[:hits].to_i
@pim = row[:pim].to_i
@pp_opportunities = row[:powerplayopportunities].to_i
@pp_goals =row[:powerplaygoals].to_i
@face_off_win_percentage = row[:faceoffwinpercentage].to_f
@giveaways = row[:giveaways].to_i
@takeaways = row[:takeaways].to_i
end
end
============================================================
def get_teams
team_ids = []
games.each do |game|
team_ids << game.away_team_id
team_ids << game.home_team_id
end
team_ids.uniq
end
def win_percentage_by_team
win_per_by_team = {}
@teams.each do |teams|
relevant_games = []
@game_teams.each do |games|
if teams.team_id == games.team_id
relevant_games << games
end
end
wins = []
relevant_games.each do |stat|
if stat.won == "TRUE"
wins << stat
end
end
final = (wins.count/relevant_games.count.to_f).round(2)
final = 0.000001 if final.nan?
win_per_by_team[teams.team_name] = final
end
win_per_by_team
end
def winningest_team
a = win_percentage_by_team.max_by{|team, percentage| percentage}
a.first
end
def fans
gamess = @game_teams.group_by{|teams| teams.team_id}
gamess.transform_values do |games|
home_wins = 0
away_wins = 0
games_played_home = 0
games_played_away = 0
games.each do |game|
home_wins += 1 if game.won == "TRUE" && game.hoa == "home"
away_wins += 1 if game.won == "TRUE" && game.hoa == "away"
games_played_home += 1 if game.hoa == "home"
games_played_away += 1 if game.hoa == "away"
end
home_win_percent = (home_wins/games_played_home.to_f).round(2)
away_win_percent = (away_wins/games_played_away.to_f).round(2)
fan_per = (home_win_percent - away_win_percent.to_f).round(2)
end
end
def worst_fans
fans.min
end
def best_fans
team_stuff = []
@game_teams.each do |game|
@teams.each do |team|
if game.team_id == team.team_id
team_stuff << [team.team_name, game.team_id]
end
end
end
a = team_stuff.uniq.last
a[0]
end
| true |
b829e06c61ee755e8bc9c732f2ec212697262854 | Ruby | mkrogemann/poller-json | /lib/matchers/json/json_path_has_value.rb | UTF-8 | 363 | 2.578125 | 3 | [
"MIT"
] | permissive | module Matchers
module JSON
class JSONPathHasValue
include JSONPath
def initialize(json_path, json_value)
@json_path = json_path
@json_value = json_value
end
def matches?(document_s)
json_hash = ::JSON.parse(document_s)
value_on_path(json_hash, @json_path) == @json_value
end
end
end
end | true |
13898cf3385275da8b80acfa6b99c57845079be0 | Ruby | auranet/asapccf | /lib/asap/utility/date_time_formatter.rb | UTF-8 | 526 | 2.875 | 3 | [] | no_license | require 'date'
module ASAP
module Utility
class DateTimeFormatter
def self.in_words(date_time)
self.in_words_without_year(date_time) + ', ' + date_time.year.to_s
end
def self.in_words_without_year(date_time)
TimeFormatter.standard(date_time) + ' on ' + DateFormatter.in_words_without_year(date_time)
end
def self.standard(date_time)
DateFormatter.standard(date_time) + ' ' + TimeFormatter.standard(date_time)
end
end
end
end
| true |
26a6ae7d089e182281eff4a1a3e5a210b02be41d | Ruby | mazamachi/hatenastar_tweet | /tweet.rb | UTF-8 | 2,266 | 2.953125 | 3 | [] | no_license | require 'rubygems'
require 'twitter'
require 'bitly'
load("./hotentry_star.rb")
class Tweet
attr_accessor :tweets
def initialize
@cli = Twitter::REST::Client.new do |config|
config.consumer_key = '******************************'
config.consumer_secret = '******************************'
config.access_token = '******************************'
config.access_token_secret = '******************************'
end
@tweets = make_tweets
end
def get_short_url(page_url)
Bitly.use_api_version_3
bitly = Bitly.new('************', '************************************')
bitly.shorten(page_url).short_url
end
def get_comment(user,url)
enrty_url = URI.escape(url)
entry_json = nil
open('http://b.hatena.ne.jp/entry/jsonlite/?url='+enrty_url) do |uri|
entry_json = JSON.parse(uri.read)
end
entry_json["bookmarks"].each do |bookmark|
if bookmark["user"] == user
return bookmark["comment"]
end
end
end
def get_infos
ranking = Hotentry.new.ranking
infos = {}
num = 1
ranking.each do |ar|
infos[num] = {}
infos[num][:user] = ar[0].match(%r{http://b.hatena.ne.jp/(.+)/})[1]
infos[num][:score] = ar[1]
infos[num][:url] = ar[2]
infos[num][:comment] = get_comment(infos[num][:user],ar[2])
num += 1
end
infos
end
def make_tweets
tweets = []
hour = Time.now.hour
self.get_infos.each do |num,hash|
tweet = "#{hour}時の#{num}位(#{hash[:score]}pts)#{hash[:user]}:#{hash[:comment]}"
shorten = get_short_url(hash[:url])
if tweet.length+shorten.length+1 <= 140
tweet = tweet[0...(140-(shorten.length+1))]
else #"…… "の分
tweet = tweet[0...(140-(shorten.length+5))]
tweet << "……"
end
tweet << " " << shorten
tweets << tweet
end
tweets
end
def hourly_tweet
Tweet.new.tweets.reverse.each do |tweet| #10位からツイートしたいのでreverse
update(tweet)
end
end
def test
t = Time.now.to_s
update(t)
end
private
def update(tweet)
return nil unless tweet
begin
@cli.update(tweet.chomp)
rescue => ex
nil
end
end
end | true |
07912aa1bb00c1e20f103e91fea1a4d7441a47ac | Ruby | htekayadi/toy_robot_simulator | /lib/toyrobot/robot.rb | UTF-8 | 596 | 3.203125 | 3 | [] | no_license | module ToyRobot
# Robot's state class
class Robot
include ToyRobot::Logging
attr_accessor :position, :placed
def initialize
@position = nil
@placed = false
end
def place(x, y, face)
@position = Position.new(x, y, Direction.find(face))
@placed = true
end
def move
@position.move
end
def left
@position.left
end
def right
@position.right
end
def to_s
if @placed
"#{@position.x},#{@position.y},#{@position.direction}"
else
'Not placed'
end
end
end
end
| true |
771aa0a397f62f4dfa8c01990f95425f2308ea80 | Ruby | bugsnag/bugsnag-ruby | /spec/utility/circular_buffer_spec.rb | UTF-8 | 2,211 | 3.171875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # encoding: utf-8
require 'spec_helper'
require 'bugsnag/utility/circular_buffer'
RSpec.describe Bugsnag::Utility::CircularBuffer do
describe "#initialize" do
it "contains no items" do
buffer = Bugsnag::Utility::CircularBuffer.new
expect(buffer.to_a).to eq([])
end
end
describe "#max_items" do
it "defaults to 25" do
buffer = Bugsnag::Utility::CircularBuffer.new
expect(buffer.max_items).to equal 25
end
it "can be set during #initialize" do
buffer = Bugsnag::Utility::CircularBuffer.new(10)
expect(buffer.max_items).to equal 10
end
end
describe "#max_items=" do
it "changes #max_items" do
buffer = Bugsnag::Utility::CircularBuffer.new(10)
buffer.max_items = 17
expect(buffer.max_items).to equal(17)
end
it "shifts any excess items when reduced" do
buffer = Bugsnag::Utility::CircularBuffer.new(10)
(0...10).each { |x| buffer << x }
buffer.max_items = 3
expect(buffer.to_a).to eq([7, 8, 9])
end
it "increases the maximum capacity" do
buffer = Bugsnag::Utility::CircularBuffer.new(3)
buffer << 1
buffer << 2
buffer << 3
expect(buffer.to_a).to eq([1, 2, 3])
buffer.max_items = 5
buffer << 4
buffer << 5
expect(buffer.to_a).to eq([1, 2, 3, 4, 5])
end
end
describe "#<<" do
it "adds items to the buffer" do
buffer = Bugsnag::Utility::CircularBuffer.new
buffer << 1
expect(buffer.to_a).to eq([1])
end
it "shifts items it #max_items is exceeded" do
buffer = Bugsnag::Utility::CircularBuffer.new(5)
(0...10).each { |x| buffer << x }
expect(buffer.to_a).to eq([5, 6, 7, 8, 9])
end
it "can be chained" do
buffer = Bugsnag::Utility::CircularBuffer.new
buffer << 1 << 2 << 3 << 4 << 5
expect(buffer.to_a).to eq([1, 2, 3, 4, 5])
end
end
describe "#each" do
it "can be iterated over" do
buffer = Bugsnag::Utility::CircularBuffer.new
buffer << 1
buffer << 2
buffer << 3
output = []
buffer.each do |x|
output << x
end
expect(output).to eq([1, 2, 3])
end
end
end | true |
eb9e2c88cb0fe520162bdf24202a5b6d914d7d06 | Ruby | zk-ruby/zookeeper | /cause-abort.rb | UTF-8 | 2,541 | 2.515625 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #!/usr/bin/env ruby
require 'zookeeper'
require File.expand_path('../spec/support/zookeeper_spec_helpers', __FILE__)
class CauseAbort
include Zookeeper::Logger
include Zookeeper::SpecHelpers
attr_reader :path, :pids_root, :data
def initialize
@path = "/_zktest_"
@pids_root = "#{@path}/pids"
@data = 'underpants'
end
def before
@zk = Zookeeper.new('localhost:2181')
rm_rf(@zk, path)
logger.debug { "----------------< BEFORE: END >-------------------" }
end
def process_alive?(pid)
Process.kill(0, @pid)
true
rescue Errno::ESRCH
false
end
def wait_for_child_safely(pid, timeout=5)
time_to_stop = Time.now + timeout
until Time.now > time_to_stop
if a = Process.wait2(@pid, Process::WNOHANG)
return a.last
else
sleep(0.01)
end
end
nil
end
def try_pause_and_resume
@zk.pause
logger.debug { "paused" }
@zk.resume
logger.debug { "resumed" }
@zk.close
logger.debug { "closed" }
end
def run_test
logger.debug { "----------------< TEST: BEGIN >-------------------" }
@zk.wait_until_connected
mkdir_p(@zk, pids_root)
# the parent's pid path
@zk.create(:path => "#{pids_root}/#{$$}", :data => $$.to_s)
@latch = Zookeeper::Latch.new
@event = nil
cb = proc do |h|
logger.debug { "watcher called back: #{h.inspect}" }
@event = h
@latch.release
end
@zk.stat(:path => "#{pids_root}/child", :watcher => cb)
logger.debug { "-------------------> FORK <---------------------------" }
@pid = fork do
rand_sleep = rand()
$stderr.puts "sleeping for rand_sleep: #{rand_sleep}"
sleep(rand_sleep)
logger.debug { "reopening connection in child: #{$$}" }
@zk.reopen
logger.debug { "creating path" }
rv = @zk.create(:path => "#{pids_root}/child", :data => $$.to_s)
logger.debug { "created path #{rv[:path]}" }
@zk.close
logger.debug { "close finished" }
exit!(0)
end
event_waiter_th = Thread.new do
@latch.await(5) unless @event
@event
end
logger.debug { "waiting on child #{@pid}" }
status = wait_for_child_safely(@pid)
raise "Child process did not exit, likely hung" unless status
if event_waiter_th.join(5) == event_waiter_th
logger.warn { "event waiter has not received events" }
end
exit(@event.nil? ? 1 : 0)
end
def run
before
run_test
# try_pause_and_resume
end
end
CauseAbort.new.run
| true |
0d3a82460fccc961d273422feed5954ba18d216b | Ruby | msoanes/project_euler | /02_even_fibonacci_numbers.rb | UTF-8 | 516 | 3.5625 | 4 | [] | no_license | def even_fibonacci_sum(maximum)
running_total = 2
latest_fibonacci_numbers = [1, 2]
loop do
3.times do
latest_fibonacci_numbers = next_fibonacci_pair(latest_fibonacci_numbers)
end
if latest_fibonacci_numbers.last > maximum
break
end
running_total += latest_fibonacci_numbers.last
end
running_total
end
def next_fibonacci_pair(fibonacci_pair)
answer = [fibonacci_pair.last]
answer << fibonacci_pair.first + fibonacci_pair.last
answer
end
puts even_fibonacci_sum(4e6)
| true |
fb75f3daeae7d883c769a44d7177ed56be526e04 | Ruby | kaneki-ken01/playground | /solutions/uri/1007/1007.rb | UTF-8 | 102 | 2.578125 | 3 | [
"MIT"
] | permissive | a = gets.to_i
b = gets.to_i
c = gets.to_i
d = gets.to_i
puts "DIFERENCA = #{'%d' % (a * b - c * d)}"
| true |
fd3934073b6c7857f8a21ceba7ccb6382541f525 | Ruby | evanrinehart/furry-dubstep | /acid.rb | UTF-8 | 3,078 | 2.84375 | 3 | [] | no_license | require 'json'
require 'fileutils'
class Acid
class LoaderError < StandardError; end
def initialize log_path, &block
@methods = {}
@read = lambda{|x| x}
@show = lambda{|x| x}
@init = lambda{ nil }
@log_path = log_path
self.instance_eval &block
begin
@state = load_log @log_path
rescue Errno::ENOENT
@state = @init[]
_checkpoint @log_path, @state
end
@log_file = File.open(@log_path, 'a')
end
def init &block
@init = block
end
def log_file path
@log_path = path
end
def serialize &block
@show = block
end
def deserialize &block
@read = block
end
def checkpoint
@log_file.close
_checkpoint @log_path, @state
@log_file = File.open(@log_path, 'a')
end
def view name, &block
define name do |*args|
yield @state, *args
end
end
def update name, &block
define '_'+name.to_s do |state, *args|
block[state, *args]
end
define name.to_s do |*args|
@log_file.puts(JSON.generate([name] + args))
@state = block[@state, *args]
nil
end
end
def update_m name, &block
define '_'+name.to_s do |state, *args|
block[state, *args]
state
end
define name.to_s do |*args|
@log_file.puts(JSON.generate([name] + args))
block[@state, *args]
nil
end
end
def update_mr name, &block
define '_'+name.to_s do |state, *args|
block[state, *args]
state
end
define name.to_s do |*args|
@log_file.puts(JSON.generate([name] + args))
retval = block[@state, *args]
retval
end
end
def method_missing name, *args
raise NoMethodError, name.to_s unless @methods[name.to_s]
@methods[name.to_s][*args]
end
private
def define name, &block
@methods[name.to_s] = block
end
def load_log log_path
log_file = File.open(log_path)
line0 = log_file.gets
begin
if line0
state = @read[JSON.parse(line0, :symbolize_names => true)[:checkpoint]]
else
log_file.close
state = @init[]
_checkpoint log_path, state
return state
end
rescue JSON::ParserError, Acid::LoaderError
raise LoaderError, "initial record in log file is busted"
end
log_file.lines do |line|
begin
name, *args = JSON.parse(line)
state, retval = self.send('_'+name, state, *args)
rescue JSON::ParserError
STDERR.puts "*** WARNING: corrupt line in log, recovering o_O ***"
log_file.close
FileUtils.copy log_path, log_path+'.original'
_checkpoint log_path, state
return state
rescue NoMethodError
log_file.close
raise LoaderError, "I don't have a way to use update method #{name.inspect}"
end
end
log_file.close
state
end
def _checkpoint log_path, state
file = File.open(log_path+'.paranoid', 'w')
image = JSON.generate({:checkpoint => @show[state]})
file.puts(image)
file.close
File.rename(log_path+'.paranoid', log_path)
end
end
| true |
c84eeb24cc06a40a71983c93eaa65ed86b0454a3 | Ruby | baccigalupi/aqua | /lib/aqua/store/couch_db/attachments.rb | UTF-8 | 7,311 | 2.71875 | 3 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Aqua
module Store
module CouchDB
# Attachments is a Hash-like container with keys that are attacment names and values that are file-type
# objects. Initializing and adding to the collection assures the types of both keys and values. The
# collection implements a lazy-loading scheme, such that when an attachment is requested and not found,
# it will try to load it from CouchDB.
class Attachments < Gnash
attr_reader :document
attr_reader :stubs
# Creates a new attachment collection with keys that are attachment names and values that are
# file-type objects. The collection manages both the key and the value types.
#
# @param [String] Document uri; used to save and retrieve attachments directly
# @param [Hash] Initialization values
#
# @api public
def initialize( doc, hash={} )
raise ArgumentError, "must be initialized with a document" unless doc.respond_to?( :retrieve )
@document = doc
self.class.validate_hash( hash ) unless hash.empty?
super( hash )
end
# Adds an attachment to the collection, checking for type. Does not add directly to the database.
#
# @param [String, Symbol] Name of the attachment as a string or symbol
# @param [File] The attachment
#
# @api public
def add( name, file )
self.class.validate_hash( name => file )
self[name] = file
end
# Adds an attachment to the collection and to the database. Document doesn't have to be saved,
# but it does need to have an id.
#
# @param [String, Symbol] Name of the attachment as a string or symbol
# @param [File] The attachment
#
# @api public
def add!( name, file )
add( name, file )
content_type = MIME::Types.type_for(file.path).first
content_type = content_type.nil? ? "text\/plain" : content_type.simplified
data = {
'content_type' => content_type,
'data' => Base64.encode64( file.read ).gsub(/\s/,'')
}
file.rewind
response = CouchDB.put( uri_for( name ), data )
update_doc_rev( response )
file
end
# Deletes an attachment from the collection, and from the database. Use #delete (from Hash) to just
# delete the attachment from the collection.
#
# @param [String, Symbol] Name of the attachment as a string or symbol
# @return [File, nil] File at that location or nil if no file found
#
# @api public
def delete!( name )
if self[name]
file = delete( name )
unless document.new?
CouchDB.delete( uri_for( name ) )
end
file
end
end
# Gets an attachment from the collection first. If not found, it will be requested from the database.
#
# @param [String, Symbol] Name of the attachment
# @return [File, nil] File for that name, or nil if not found in hash or in database
#
# @api public
def get( name, stream=false )
file = self[name]
unless file
file = get!( name, stream )
end
file.rewind if file # just in case of previous streaming
file
end
# Gets an attachment from the database. Stores it in the hash.
#
# @param [String, Symbol] Name of the attachment
# @param [true, false] Stream boolean flag indicating whether the data should be converted to
# a file or kept as a stream
# @return [File, nil] File for that name, or nil if not found in the database
# @raise Any error encountered on retrieval of the attachment, json, http_client, Aqua etc
#
# @todo make this more memory favorable, maybe streaming/saving in a max number of bytes
# @api public
def get!( name, stream=false )
file = nil
response = CouchDB.get( uri_for( name, false ), true ) rescue nil
data = response && response.respond_to?(:keys) ? Base64.decode64( response['data'] ) : nil
if data || response
file = Tempfile.new( CGI.escape( name.to_s ) )
file.binmode if file.respond_to?( :binmode )
data ? file.write( data ) : file.write( response )
file.rewind
self[name] = file
end
stream ? file.read : file
end
# Constructs the standalone attachment uri for PUT and DELETE actions.
#
# @param [String] Name of the attachment as a string or symbol
#
# @api private
def uri_for( name, include_rev = true )
raise ArgumentError, 'Document must have id in order to save an attachment' if document.id.nil? || document.id.empty?
document.uri + "/#{CGI.escape( name.to_s )}" + ( document.rev && include_rev ? "?rev=#{document.rev}" : "" )
end
# Validates and throws an error on a hash, insisting that the key is a string or symbol,
# and the value is a file.
#
# @param [Hash]
#
# @api private
def self.validate_hash( hash )
hash.each do |name, file|
raise ArgumentError, "Attachment name, #{name.inspect}, must be a Symbol or a String" unless [Symbol, String ].include?( name.class )
raise ArgumentError, "Attachment file, #{file.inspect}, must be a File-like object" unless file.respond_to?( :read )
end
end
# Goes into the document and updates it's rev to match the returned rev. That way #new? will return false
# when an attachment is created before the document is saved. It also means that future attempts to save
# the doc won't fail with a conflict.
#
# @param [Hash] response from the put request
# @api private
def update_doc_rev( response )
document[:_rev] = response['rev']
end
# Creates a hash for the CouchDB _attachments key.
# @example
# "_attachments":
# {
# "foo.txt":
# {
# "content_type":"text\/plain",
# "data": "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
# },
#
# "bar.txt":
# {
# "content_type":"text\/plain",
# "data": "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
# }
# }
def pack
pack_hash = {}
self.keys.each do |key|
file = self[key]
content_type = MIME::Types.type_for(file.path).first
content_type = content_type.nil? ? "text\/plain" : content_type.simplified
data = {
'content_type' => content_type,
'data' => Base64.encode64( file.read ).gsub(/\s/,'')
}
file.rewind
pack_hash[key.to_s] = data
end
pack_hash
end
end # Attachments
end # CouchDB
end # Store
end # Aqua | true |
c64f2c07d4a12d08049b63dea62684674390fc9c | Ruby | anwarmamat/cmsc330 | /ruby/Ruby_Lecture_4/my_collect.rb | UTF-8 | 165 | 3.546875 | 4 | [] | no_license | def my_collect(a)
b = Array.new(a.length)
0.upto(a.length-1) { |i|
b[i] = yield(a[i])
}
return b
end
b = my_collect([5, 6, 7]) { |x| x*2 }
puts b.inspect | true |
f12d2c64f961b8aa15e76151877db9ceb78d629c | Ruby | romigos/2021_RUBY_RUSH | /34_step_method.rb | UTF-8 | 181 | 3.25 | 3 | [] | no_license | puts 'I am a string'
array = ['James Bond', 'Brad Pitt', 'Dr. Who', 'House MD', 'Madonna']
puts array.to_s
array.pop
puts array.to_s
array.pop 2
puts array.to_s
time = Time.now
puts time | true |
75b1fa7b6378fa6885f1e79e8b47bbed5db4d100 | Ruby | aldhsu/algorithms | /second_lowest_number.rb | UTF-8 | 1,271 | 3.890625 | 4 | [] | no_license | class SecondLowestNumber
attr_accessor :digits, :break_point, :swap_index
# #1. Find highest index swap
# #2. Find lowest number at index
def initialize(integer)
@digits = integer.to_s
@break_point = -1 # where to stop looking and where to swap
@swap_index = nil # where to swap from
end
def find_swap_index(index_of_number)
number = digits[index_of_number]
result = nil
index_of_number.downto(break_point).each do |index|
if digits[index] < number
result = index
break
end
end
if result
if result > break_point || (result == break_point && (!swap_index || digits[index_of_number] < digits[swap_index]))
@break_point = result
@swap_index = index_of_number
end
end
end
def next_intagram
enum = (digits.length-1).downto(0).each
while (current_index = enum.next) > break_point
find_swap_index(current_index)
end
return_number
rescue StopIteration
raise "No smaller integer next"
end
def return_number
@digits[break_point], @digits[swap_index] = @digits[swap_index], @digits[break_point]
sorted_after = @digits[(break_point + 1)..-1].chars.sort.join("")
"#{@digits[0..break_point]}#{sorted_after}".to_i
end
end
| true |
6add69252fa1e56cf804fb27d24fe2a71ff75155 | Ruby | Srossmanreich/phase-0 | /week-9/ruby-review-3/r-r.rb | UTF-8 | 1,421 | 3.984375 | 4 | [
"MIT"
] | permissive | # OO Basics: Student
# I worked on this challenge [by myself, with: ].
# This challenge took me [#] hours.
# Pseudocode
# Initial Solution
students = {}
class Student
attr_accessor :scores, :first_name
def initialize(first_name,scores) #Use named arguments!
@first_name = first_name
@scores = scores
return {first_name: scores}
end
def average
@average = @scores.reduce(:+) / @scores.length
end
def letter_grade
return "A" if @average >= 90
return "B" if @average >= 80
return "C" if @average >= 70
return "D" if @average >= 60
return "F" if @average < 60
end
end
Alex = Student.new("Alex",[100,100,100,0,100])
students[0] = Alex
students[0].average
students[0].letter_grade
def linear_search(hash,name)
counter = 0
until hash[counter] = name || counter > hash.length
counter += 1
end
if counter > hash.length
return -1
else
counter
end
end
linear_search(students,"Alex")
linear_search(students, "Random")
# Refactored Solution
# DRIVER TESTS GO BELOW THIS LINE
# Initial Tests:
p students[0].first_name == "Alex"
p students[0].scores.length == 5
p students[0].scores[0] == students[0].scores[4]
p students[0].scores[3] == 0
# Additional Tests 1:
p students[0].average == 80
p students[0].letter_grade == 'B'
# Additional Tests 2:
p linear_search(students, "Alex") == 0
p linear_search(students, "NOT A STUDENT") == -1
# Reflection | true |
d19503c3b80e644b1053c2added8f5ed329af067 | Ruby | akash121kumar/Training | /Ruby/hashes_method.rb | UTF-8 | 2,142 | 4.0625 | 4 | [] | no_license | # grades = {'akash'=> 10, 'vikas' => 7}
# puts grades['akash']
# grades = Hash.new
# print grades.class
# grades["vijay"]= 10
# print grades
# grades.each{|key,values| puts "key is #{key} and value is #{values}"}
# books = {}
# books[:matz] = "The ruby language"
# books[:black] = "The well grounded Rubyist"
# print books[:black], "\n"
# a=Hash["a",100,"b",200,"c",300]
# print a,a["c"], "\n"
# h1={"a" => 1, "c" => 2}
# h2={7 =>35 ,"c" =>2, "a"=> 1}
# h3={"a"=> 1, "c" => 2}
# puts h1 == h2 #False
# puts h1==h3 #True
# h1={"a" => 1,"b" => 2, "c" =>3}
# print h1, "\n"
# h1["a"] = 5 #Assigning a new value to existing key
# print h1, "\n"
# h={"colors" => ["red","blue","green"],
# "letters" => ["a","b","c"]} #compares the object with the key
# print h.assoc("colors") ,"\n"
# h=Hash["a",1,"b",2]
# puts h
# h.clear #used to clear hash
# puts h
#compare by identity
# h1={"a" => 100,"b" =>200, :c =>"c"}
# puts h1["a"]
# puts h1.compare_by_identity?
h1={"a" => 100,"b" =>200,"d" => 500}
# h1.delete("a") #Deletes the key value pair
# print h1, "\n"
# print h1.delete("z") { |el| "#{el} not found"}, "\n"
h = {"a" => 100, "b"=> 200, "c" => 300}
# h.delete_if {|key, value| key >= "b"}
# print h,"\n"
# h.each_pair{|key,value| puts "#{key} is #{value}"} #enumerates key and values
# print h.empty? ,"\n"
# print h.eql?(h1) #compares two hashes and gives boolean value
# puts h.fetch("a") #fetch the value of key
# print h.flatten #converts into array
# print h.flatten(2)
# print h.has_key?("a")
# print h.has_value?(300)
# print h.invert #convert value as a key and key as a value
# a=h.keys #returns all the keys of a hash
# print a ,"\n"
# b=h.values #returns all the values from hash
# print b ,"\n"
# print h.merge(h1), "\n" #merges two hashes
# print h.rassoc(200) #search in values
# h.replace({"e" => 300 , "d" => 400 }) #replaces eixisting hash with new key_value pairs
# print h ,"\n"
# h.shift #deletes a key value pair from hash
# print h
# a=h.store("a",100) #stores a value
# print a.class
print h.to_a #converts the hash into an array
| true |
4919b864e48eed2eda8e6c681d96526e318fecd6 | Ruby | lbernal713/MIS4397-LuisBernal | /Assignments/Learn Ruby the Hard Way/ex.4.rb | UTF-8 | 675 | 3.40625 | 3 | [] | no_license | cars = 100 # initialize
space_in_a_car = 4.0 # initialize
drivers = 30 # initialize
passengers = 90 # initialize
cars_not_driven = cars - drivers # cars not being used
cars_driven = drivers # cars that will be driven
carpool_capacity = cars_driven * space_in_a_car # capacity
average_passengers_per_car = passengers / cars_driven # avg passenger
puts "There are #{cars} cars available."
puts "There are only #{drivers} drivers available."
puts "There will be #{cars_not_driven} empty cars today."
puts "We can transport #{carpool_capacity} people today."
puts "We have #{passengers} to carpool today."
puts "We need to put about #{average_passengers_per_car} in each car." | true |
91ec27cfa9762a8898e63662d7a7493cc8860147 | Ruby | 4rlm/dbc_onsite | /2.1_public-vs-private-interfaces/spec/bank_account_spec.rb | UTF-8 | 1,043 | 2.90625 | 3 | [] | no_license | require_relative '../bank_account'
describe BankAccount do
let(:account) { BankAccount.new("bob", "Checking", 333666999) }
it "has a readable account_number" do
expect(account.account_number).to eq("######999")
end
it "has a readable customer_name" do
expect(account.customer_name).to eq("BOB")
end
it "has a writable customer_name" do
expect{ account.customer_name = "Sara" }.to change { account.customer_name }.to "SARA"
end
it "has a readable account type" do
expect(account.account_type).to eq "Checking"
end
it "has a writable account type" do
expect { account.account_type = "Savings" }.to change { account.account_type }.to "Savings"
end
# it "has a private account_number" do #this will fail
# expect {account.account_number = 333666000 }.to change {account.account_number}.to "######000"
# end
it "it has a private account_number that can not be re - written" do
expect { account.account_number = 333666000 }.to raise_error(NoMethodError)
end
end
# NoMethodError
| true |
9101b4a443b0c7e591c5d1eca587a8d958a0b099 | Ruby | andibachmann/ad_dir | /lib/ad_dir/group.rb | UTF-8 | 4,046 | 2.828125 | 3 | [
"MIT"
] | permissive | module AdDir
# **`AdDir::Group`** models a 'Group' entry in an Active Directory.
#
# For basic CRUD operations see {AdDir::Entry}. In additon to these
# {AdDir::Group} offers methods to list and managed {AdDir::User}
# relationships.
#
# ## List users belonging to a group
#
# * **`members`** list of members' DNs
#
# ```
# mygrp = AdDir::Group.find('lpadmin')
# mygrp.members
# # => ["CN=John Doe",OU=people,ou....", "CN=Betty...", ...]
# ```
#
# * **`users`** => Array of {User} objects
#
# ```
# mygrp.users
# # => [#<AdDir::User dn: "CN=John Doe",..." ...>, <#AdDir::User dn: ..]
# ```
#
# * **`users_usernames`** lists the username of each member
#
# ```
# mygrp.users_usernames
# # => ["jdoe", "bblue", "shhinter"]
# ```
#
# ## Modify User Relationship
#
# **Note**: Contrary to modifications of 'normal' attributes
# modifications of user relationships are instantly saved!
#
# ### Add User
#
# ```
# jdoe = AdDir::User.find('jdoe')
# mygrp.add_user(jdoe)
# ```
#
# ### Removing a user
#
# ```
# jdoe = AdDir::User.find('jdoe')
# mygrp.remove_user(jdoe)
# ```
#
class Group < AdDir::Entry
self.tree_base = 'ou=groups,dc=my,dc=company,dc=com'
self.primary_key = :samaccountname
# Used to efficiently filter Group entries in ActiveDirectory.
OBJECTCATEGORY = 'group'.freeze
# Get the correct `User` class.
# When querying and managing users subclasses of this class
# have to get the correct User model.
#
# ```
# module B
# class User < AdDir::User
# end
#
# class Group < AdDir::Group
# end
# end
#
# g = B::Group.user_klass
# #=> B::User
# ```
#
# If there is no class `B::User` any group related methods will fail.
#
# If you want to override this method simply set the class instance
# variable `@user_klass` to your custom group class:
#
# ```
# module B
# class Group < AdDir::Group
# @user_klass = C::User
# end
# end
# #
# B::Group.user_klass
# # => C::User
# ```
def self.user_klass
return @user_klass if defined? @user_klass
@user_klass = sibling_klass('User')
end
# The name of the group (i.e. the samaccountname)
#
def name
samaccountname
end
# Return all users being member of this group.
def users
# members.map { |dn| User.select_dn(dn) }
members.map { |dn| self.class.user_klass.select_dn(dn) }
end
# Find the 'primary user' of the group
# If this is a normal group 'nil' is returned.
def primary_user
# @primary_user ||= AdDir::User.find_by_primarygroupid(
@primary_user ||= self.class.user_klass.find_by_primarygroupid(
objectsid_decoded.split('-').last
)
end
# Returns true if the group is a primary group.
# @return [Boolean]
def primary_group?
!primary_user.nil?
end
# Returns the DNs of all user.
# @note If the group is a **primary group** **`:member`**
# is empty (and mutually, the primary group is not present in
# the `:memberof` attribute of a {::User} object).
#
# @see http://support.microsoft.com/en-us/kb/275523
def members
return @ldap_entry[:member] if attribute_present?(:member)
@ldap_entry[:member] = []
end
# Return an array of the members' usernames.
#
def members_usernames
# users.map { |u| u.username }.sort
users.map(&:username).sort
end
alias_method :users_usernames, :members_usernames
# Adds a user to the group
#
def add_user(user)
unless members.include?(user.dn)
self[:member] += [user.dn]
save
end
users
end
# Remove a user from the group
#
def remove_user(user)
if members.include?(user.dn)
self[:member] -= [user.dn]
save
end
users
end
end
end
| true |
9f98f2e3d2ba97780d3cdccef8b7480a57a7e20f | Ruby | afleisch/study_hall | /introduction.rb | UTF-8 | 411 | 3.046875 | 3 | [] | no_license |
#Saving my friend's name
puts "Hello, what's your name?"
name = gets.chomp
#Saving number of completed assignments
puts "How many prework assignments have you completed?"
assignments = gets.chomp
puts "Hello #{name}. My name is Ashley."
puts "I see you've completed #{assignments}. I have completed all of them."
puts "In my free time I like to spend time with my family."
#commentlkjljalfjsdlfkjsdlfj | true |
54725e68878c1a55998027bb5dfa1dc800baa4c5 | Ruby | singram/euler | /problem28/problem28.rb | UTF-8 | 607 | 4.03125 | 4 | [
"MIT"
] | permissive | # Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
# 21 22 23 24 25
# 20 7 8 9 10
# 19 6 1 2 11
# 18 5 4 3 12
# 17 16 15 14 13
# It can be verified that the sum of the numbers on the diagonals is 101.
# What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
# Seq1 = 1,3,7,13,21,31,43,57,73
# Seq2 = 1,5,9,17.25.37,49,65,81
size = 1001
s1 = [1]
s2 = [1]
require 'pp'
(1..size-1).to_a.each do |r|
s1 << s1.last + 2*r
s2 << s2.last + 4 * ((r+1)/2)
end
pp (s1+s2).inject(&:+) - 1
| true |
dcf32d10afe9bd8c3a694d2f57b091bcb0a16dcd | Ruby | dguptaruby/JungleCodersDemo | /lib/v_card_handler.rb | UTF-8 | 1,525 | 2.578125 | 3 | [] | no_license | require 'multiple_vcard'
# Add new module for Vcard
module VCardHandler
def self.include(klass)
klass.extend ClassMethods
klass.send(:include, InstanceMethods)
end
# Add module for instance methods
module InstanceMethods
def v_card_multiple(contacts)
card = Vpim::Vcard::Maker.make2 do |maker|
contacts.each do |c|
maker.add_temp_begin if contacts.first != c
maker.add_name { |name| name.given = c.name }
if c.address?
maker.add_addr do |addr|
addr.location = 'home'
addr.street = c.address
end
end
maker.add_tel(c.phone)
maker.add_email(c.email)
maker.org = c.organization if c.organization?
maker.birthday = c.birthday if c.birthday?
maker.add_temp_end if contacts.last != c
end
end
send_data card.to_s, filename: 'contact.vcf'
end
def v_card_single(contact)
card = Vpim::Vcard::Maker.make2 do |maker|
maker.add_name { |name| name.given = contact.name }
if contact.address?
maker.add_addr do |addr|
addr.location = 'home'
addr.street = contact.address
end
end
maker.add_tel(contact.phone)
maker.add_email(contact.email)
maker.org = contact.organization if contact.organization?
maker.birthday = contact.birthday if contact.birthday?
end
send_data card.to_s, filename: 'contact.vcf'
end
end
end
| true |
08efaf15a4732f8b969833c557d0f11369bad95c | Ruby | googleapis/google-cloud-ruby | /google-cloud-bigtable/lib/google/cloud/bigtable/value_range.rb | UTF-8 | 7,548 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | # frozen_string_literal: true
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "google/cloud/bigtable/convert"
module Google
module Cloud
module Bigtable
##
# # ValueRange
#
# Specifies a contiguous range of string values.
#
# * from value bound : The value at which to begin the range.
# If neither field is set, interpreted as an empty string, inclusive.
# * End value bound: The value at which to end the range.
# If neither field is set, interpreted as an infinite string value, exclusive.
#
# @example
# require "google/cloud/bigtable"
#
# bigtable = Google::Cloud::Bigtable.new
# table = bigtable.table "my-instance", "my-table"
#
# # Range that includes all row keys including "value-001" to "value-005" excluding.
# table.new_value_range.from("value-001").to("value-005")
#
# # Range that includes all row keys including "value-001" up to inclusive "value-010".
# table.new_value_range.from("value-001").to("value-010", inclusive: true)
#
# # Range that includes all row keys including "value-001" up until end of the row keys.
# table.new_value_range.from "value-001"
#
# # Range that includes all row keys exclusive "value-001" up until end of the row keys.
# table.new_value_range.from "value-001", inclusive: false
#
# # Range with unbounded from and the exclusive end "value-100".
# table.new_value_range.to "value-100"
#
# # Range that includes all row keys including from and end row keys "value-001", "value-100".
# table.new_value_range.between "value-001", "value-100"
#
# # Range that includes all row keys including "value-001" up until "value-100".
# table.new_value_range.of "value-001", "value-100"
#
class ValueRange
# @private
# Creates a value range instance.
def initialize
@grpc = Google::Cloud::Bigtable::V2::ValueRange.new
end
##
# Sets the row range with the lower bound.
#
# @param value [String, Integer] The value. Required. If the argument
# is an Integer, it will be encoded as a 64-bit signed big-endian
# integer.
# @param inclusive [Boolean] Whether the value is an inclusive or
# exclusive lower bound. Default is `true`, an inclusive lower bound.
# @return [Google::Cloud::Bigtable::ValueRange]
#
# @example Inclusive lower bound.
# require "google/cloud/bigtable"
#
# bigtable = Google::Cloud::Bigtable.new
# table = bigtable.table "my-instance", "my-table"
#
# range = table.new_value_range.from "value-001"
#
# @example Exclusive lower bound.
# require "google/cloud/bigtable"
#
# bigtable = Google::Cloud::Bigtable.new
# table = bigtable.table "my-instance", "my-table"
#
# range = table.new_value_range.from "value-001", inclusive: false
#
def from value, inclusive: true
# If value is integer, covert it to a 64-bit signed big-endian integer.
value = Convert.integer_to_signed_be_64 value
if inclusive
@grpc.start_value_closed = value
else
@grpc.start_value_open = value
end
self
end
##
# Sets the value range with upper bound.
#
# @param value [String, Integer] value. Required. If the argument
# is an Integer, it will be encoded as a 64-bit signed big-endian
# integer.
# @param inclusive [Boolean] Whether the value is an inclusive or
# exclusive lower bound. Default is `false`, an exclusive lower bound.
# @return [Google::Cloud::Bigtable::ValueRange]
#
# @example Inclusive upper bound.
# require "google/cloud/bigtable"
#
# bigtable = Google::Cloud::Bigtable.new
# table = bigtable.table "my-instance", "my-table"
#
# range = table.new_value_range.to "value-010", inclusive: true
#
# @example Exclusive upper bound.
# require "google/cloud/bigtable"
#
# bigtable = Google::Cloud::Bigtable.new
# table = bigtable.table "my-instance", "my-table"
#
# range = table.new_value_range.to "value-010"
#
def to value, inclusive: false
# If value is integer, covert it to a 64-bit signed big-endian integer.
value = Convert.integer_to_signed_be_64 value
if inclusive
@grpc.end_value_closed = value
else
@grpc.end_value_open = value
end
self
end
##
# Sets the value range with inclusive lower and upper bounds.
#
# @param from_value [String, Integer] Inclusive from value. Required.
# If the argument is an Integer, it will be encoded as a 64-bit
# signed big-endian integer.
# @param to_value [String, Integer] Inclusive to value. Required.
# If the argument is an Integer, it will be encoded as a 64-bit
# signed big-endian integer.
# @return [Google::Cloud::Bigtable::ValueRange]
# Range with inclusive from and to values.
#
# @example
# require "google/cloud/bigtable"
#
# bigtable = Google::Cloud::Bigtable.new
# table = bigtable.table "my-instance", "my-table"
#
# range = table.new_value_range.between "value-001", "value-010"
#
def between from_value, to_value
from(from_value).to(to_value, inclusive: true)
end
##
# Set value range with an inclusive lower bound and an exclusive upper bound.
#
# @param from_value [String, Integer] Inclusive from value. Required.
# If the argument is an Integer, it will be encoded as a 64-bit
# signed big-endian integer.
# @param to_value [String, Integer] Exclusive to value. Required.
# If the argument is an Integer, it will be encoded as a 64-bit
# signed big-endian integer.
# @return [Google::Cloud::Bigtable::ValueRange]
# Range with an inclusive from value and an exclusive to value.
#
# @example
# require "google/cloud/bigtable"
#
# bigtable = Google::Cloud::Bigtable.new
# table = bigtable.table "my-instance", "my-table"
#
# range = table.new_value_range.of "value-001", "value-010"
#
def of from_value, to_value
from(from_value).to(to_value)
end
# @private
#
# @return [Google::Cloud::Bigtable::V2::ValueRange]
#
def to_grpc
@grpc
end
end
end
end
end
| true |
965f355d0c58d6debff4c3807ac69609a1ed39d5 | Ruby | tommylees112/match-market | /lib/tasks/odds.rake | UTF-8 | 653 | 2.640625 | 3 | [] | no_license | namespace :odds do
task seed: :environment do
OUTCOME = ["Home", "Away", "Draw"]
tommy = User.find(1) #_by_email("thomas.lees@chch.ox.ac.uk")
hamish = User.find(3) #_by_email("hachall@hotmail.com")
adrian = User.find(2) #_by_email("walkerrrrrrr@gmail.com")
USER = [tommy, hamish, adrian]
def generate_odd_params(odd)
odd.user = USER.sample
odds_number = rand(1.1..2.0).round(2)
odd.odds = odds_number
odd.save!
end
Match.all.each do |match|
OUTCOME.each do |outcome|
3.times do
odd = Odd.new(match: match)
odd.outcome = outcome
generate_odd_params(odd)
end
end
end
end
end
| true |
87d3f2722b88bfa88ac737df166fef025e81892f | Ruby | justinw827/oo-cash-register-nyc-web-080618 | /lib/cash_register.rb | UTF-8 | 734 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class CashRegister
attr_accessor :total, :discount, :title
def initialize(discountIn = 0.0)
@total = 0.0
@discount = discountIn
@itemList = []
@priceList = []
end
def add_item(titleIn, priceIn, quantityIn=1)
for i in 1..quantityIn
@total += priceIn
@itemList.push(titleIn)
@priceList.push(priceIn)
end
end
def apply_discount
if discount == 0.0
return "There is no discount to apply."
else
@total -= @total * (@discount / 100.0)
#binding.pry
return "After the discount, the total comes to $#{@total.round}."
end
end
def items
return @itemList
end
def void_last_transaction
@total -= @priceList[-1]
end
end
| true |
8786ebfd47f91c7447906ad5c5795354714f52dd | Ruby | hildebrandosegundo/cursoruby | /herança.rb | UTF-8 | 175 | 2.71875 | 3 | [] | no_license | class Pessoa
attr_accessor :nome
private
def telefone
end
end
class PessoaFisica < Pessoa
attr_accessor :cpf
end
pessoa = PessoaFisica.new
puts pessoa.nome = "hilde"
| true |
74b6e3ac3ac3d66ca2b90a24acdef6db0db9282a | Ruby | johnhattori/shelter_w_classes | /main.rb | UTF-8 | 2,004 | 3.625 | 4 | [] | no_license | require "pry"
require_relative "shelter"
require_relative "pet"
require_relative "client"
shelter = nil
s1 = Shelter.new("414 Brannan St.", {}, {})
c1 = Client.new("John", "m", 49)
c2 = Client.new("Guy", "m", 25)
c3 = Client.new("Sumeet", "m", 28)
c4 = Client.new("Connie", "f", 21)
p1 = Pet.new("Tomale", "cat", "m", 2, ["string"])
p2 = Pet.new("Torta", "cat", "f", 2, ["feather"])
p3 = Pet.new("Hector", "dog", "m", 8, ["bone"])
p4 = Pet.new("Billie", "bird", "m", 4, ["bell"])
p5 = Pet.new("Lucy", "dog", "f", 1, ["ball"])
s1.pet["Tomale"] = p1
s1.pet["Torta"] = p2
s1.pet["Hector"] = p3
s1.pet["Billie"] = p4
s1.pet["Lucy"] = p5
s1.client["John"] = c1
s1.client["Guy"] = c2
s1.client["Sumeet"] = c3
s1.client["Connie"] = c4
print "Would you like to (l)ist available pets, (a)dopt a pet, (g)ive up a pet for adoption or (q)uit?"
input = gets.chomp.downcase
while input != "q"
if input == "l"
s1.pet.each do |x,y|
if y.available?
puts "#{y.name} is available"
else
puts "#{y.name} is unavailable"
end
end
elsif input == "a"
puts "What is the name of the pet you'd like to adopt?"
pet_name = gets.chomp
puts "What's your name?"
owner_name =gets.chomp
if s1.pet[pet_name].available?
s1.pet[pet_name].owner = owner_name
s1.client[owner_name].pet = pet_name
puts "Congratulations. Your new friend's name is #{s1.client[owner_name].pet}"
else
puts "Unfortunately, #{s1.client[owner_name].pet} isn't available for adoption. "
end
elsif input == "g"
puts "What's the name of the pet you want to give up for adoption?"
adopt_pet = gets.chomp
if s1.pet[adopt_pet].available? == false
currentowner = s1.pet[pet_name].owner
s1.pet[pet_name].owner = nil
s1.client[currentowner].pet = nil
puts "Thank you for your adoption."
end
end
print "Would you like to (l)ist available pets, (a)dopt a pet, (g)ive up a pet for adoption or (q)uit?"
input = gets.chomp.downcase
end
| true |
6cbb2d2d36a28bff07af7eb4778d00e09ae41ced | Ruby | dev-asadhameed/Salesloft-API-Integration | /app/services/string_matcher.rb | UTF-8 | 912 | 2.671875 | 3 | [] | no_license | # frozen_string_literal: true
require 'fuzzystringmatch'
class StringMatcher
attr_reader :records, :errors, :matching_strings, :fuzzy_string_matcher
def initialize(records)
@records = records
@errors = []
@matching_strings = {}
@fuzzy_string_matcher = FuzzyStringMatch::JaroWinkler.create(:pure)
check_errors
end
def generate
return errors.to_sentence if errors.any?
records.each_with_index do |record, outer_index|
@matching_strings[record] = []
records.each_with_index do |rec, inner_index|
next if outer_index == inner_index
@matching_strings[record] << rec if fuzzy_string_matcher.getDistance(record, rec) >= 0.9
end
end
@matching_strings
end
private
def check_errors
errors << I18n.t('errors.missing_records') unless records.any?
error << I18n.t('errors.data_type') unless records.is_a?(Array)
end
end
| true |
d312f7e2628e9e2a43c635bf526b5330666f26c9 | Ruby | ogawatti/hiddeste | /app/models/event.rb | UTF-8 | 949 | 2.546875 | 3 | [] | no_license | class Event < ActiveRecord::Base
attr_accessible :date, :description, :name, :organizer_id, :place
has_many :user_events, :dependent => :destroy
has_many :users, :through => :user_events
has_many :notices, :order => 'created_at DESC', :dependent => :destroy
validates :name, :presence => true, :length => {:maximum => 255}
validates :organizer_id, :presence => true
after_create :create_user_event
def organizer
User.find_by_id(self.organizer_id)
end
def organizer?(user)
!!(organizer == user)
end
def organizer_name
User.find_by_id(self.organizer_id).name
end
def notice_users
users.where(notice: true)
end
def og_description
[ "Place: #{place}", "Date: #{date}", "Description: #{description}" ].join(", ")
end
private
def create_user_event
user_event = UserEvent.new
user_event.user_id = self.organizer_id
user_event.event_id = self.id
user_event.save
end
end
| true |
96f384e27e947dd6bd58ad665a59a4a13c269e46 | Ruby | europ/lunch | /lunch/app/controllers/restaurants/RestauraceAPizzerieNaPlace.rb | UTF-8 | 484 | 2.828125 | 3 | [] | no_license | require 'nokogiri'
require 'restclient'
class RestauraceAPizzerieNaPlace
def initialize
@url = 'https://www.pizzerienaplace.cz/denni-menu/'
@css_selector = '.widget-body'
end
def load
{
id: self.class.to_s,
name: 'Restaurace a Pizzerie Na Place',
url: @url,
content: parse(scrape)
}
end
def scrape
page = Nokogiri::HTML.parse(RestClient.get(@url))
page.css(@css_selector).text
end
def parse(text)
text
end
end
| true |
2605e6d028f5d4ca77151839807abddb215ea4ef | Ruby | kasia-kaleta/project_1_shop_inventory_app | /models/brands.rb | UTF-8 | 1,184 | 3.203125 | 3 | [] | no_license | require_relative('../db/sql_runner')
class Brand
attr_reader :id
attr_accessor :name, :info, :img
def initialize(options)
@id = options['id'].to_i if options['id']
@name = options['name']
@info = options['info']
@img = options['img']
end
def save()
sql = "INSERT INTO brands (name, info, img) VALUES ($1, $2, $3) RETURNING id"
values = [@name, @info, @img]
result = SqlRunner.run(sql, values)
@id = result.first['id']
end
def self.all()
sql = "SELECT * FROM brands"
brands = SqlRunner.run(sql)
result = brands.map { |brand| Brand.new(brand) }
return result
end
def update()
sql = "UPDATE brands SET (name, info, img) = ($1, $2, $3)
WHERE id = $4"
values = [@name, @info, @img, @id]
SqlRunner.run(sql, values)
end
def delete()
sql = "DELETE FROM brands
WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def self.delete_all()
sql = "DELETE FROM brands"
SqlRunner.run(sql)
end
def self.find(id)
sql = "SELECT * FROM brands WHERE id = $1"
values = [id]
result = SqlRunner.run(sql, values).first
return Brand.new(result)
end
end
| true |
a81af3b4e9f80471022ad91588fa683906f44238 | Ruby | jake-007/rxruby | /test/rx/concurrency/test_scheduled_item.rb | UTF-8 | 1,167 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | # Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
require 'test_helper'
class DummyScheduler
end
class TestScheduledItem < Minitest::Test
def setup
@state = []
@item = Rx::ScheduledItem.new(DummyScheduler.new, @state, 5) do |_, state|
state << 1
end
end
def test_cancel
assert_equal(false, @item.cancelled?)
@item.cancel
assert_equal(true, @item.cancelled?)
end
def test_invocation
less = Rx::ScheduledItem.new(DummyScheduler.new, @state, 0)
more = Rx::ScheduledItem.new(DummyScheduler.new, @state, 10)
same = Rx::ScheduledItem.new(DummyScheduler.new, @state, 5)
assert(less < @item)
assert(more > @item)
assert_equal(same, @item)
end
def test_invoke
@item.invoke
assert_equal([1], @state)
end
def test_invoke_raises_on_subsequent_calls
@item.invoke
assert_raises(RuntimeError) { @item.invoke }
end
def test_cancel_and_invoke
assert_equal(false, @item.cancelled?)
@item.cancel
assert_equal(true, @item.cancelled?)
@item.invoke
assert_equal([], @state)
end
end
| true |
58fb1b9d7543834a7f049508df00164a506b5e68 | Ruby | fdreith/square_array | /square_array.rb | UTF-8 | 182 | 3.15625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def square_array(array)
new_array = []
array.each {|x| new_array << x ** 2}
new_array
end
# don't use any built-in array methods other than
# .each (e.g. .collect, .inject). | true |
9de157a516d8a433d04c54ec1c570fc24578d920 | Ruby | dfl/open_flash_chart | /lib/open_flash_chart/pie.rb | UTF-8 | 663 | 2.59375 | 3 | [
"MIT"
] | permissive | module OpenFlashChart
class PieValue < Base
def initialize(value, label, args={})
@value = value
@label = label
super args
end
def set_label(label, label_color, font_size)
self.label = label
self.label_colour = label_color
self.font_size = font_size
end
def on_click(event)
@on_click = event
end
end
class Pie < Base
def initialize args={}
@type = "pie"
@colours = ["#d01f3c","#356aa0","#C79810"]
@border = 2
super
end
def set_no_labels
self.no_labels = true
end
def on_click(event)
@on_click = event
end
end
end | true |
b8683a3fb105629809a29adbd19477ec9c194bc3 | Ruby | kjjgibson/Morokufy | /lib/hip_chat/room_notification.rb | UTF-8 | 1,956 | 2.671875 | 3 | [] | no_license | module HipChat
class RoomNotification
include ActiveModel::Validations
include ActiveModel::Serialization
# Valid values for the 'color' attribute
module Color
YELLOW = 'yellow'
GREEN = 'green'
RED = 'red'
PURPLE = 'purple'
GRAY = 'gray'
RANDOM = 'random'
end
# Valid values for the 'message_format' attribute
# html - Message is rendered as HTML and receives no special treatment.
# Must be valid HTML and entities must be escaped (e.g.: '&' instead of '&').
# May contain basic tags: a, b, i, strong, em, br, img, pre, code, lists, tables.
# text - Message is treated just like a message sent by a user.
# Can include @mentions, emoticons, pastes, and auto-detected URLs (Twitter, YouTube, images, etc).
module MessageFormat
HTML = 'html'
TEXT = 'text'
end
# A label to be shown in addition to the sender's name. Valid length range: 0 - 64.
attr_accessor :from
# Determines how the message is treated by the server and rendered inside HipChat applications
attr_accessor :message_format
# Background color for message
attr_accessor :color
# Whether this message should trigger a user notification (change the tab color, play a sound, notify mobile phones, etc). Each recipient's notification preferences are taken into account.
attr_accessor :notify
# The message body
attr_accessor :message
# An optional card object
attr_accessor :card
validates :from, length: { minimum: 0, maximum: 64}, allow_nil: true
validates_presence_of :message
validates_inclusion_of :color, in: lambda { |_| Color.constants.map { |c| Color.const_get(c) } }, allow_nil: true
validates_inclusion_of :message_format, in: lambda { |_| MessageFormat.constants.map { |c| MessageFormat.const_get(c) } }, allow_nil: true
def initialize(message: nil)
@message = message
end
end
end
| true |
f483dda605622b72fdd0879fb1e3f673ba06ab2e | Ruby | terut/goodluck | /app/notifier.rb | UTF-8 | 3,753 | 3 | 3 | [
"MIT"
] | permissive | require 'hipchat'
require 'faraday'
module Goodluck
class Notifier
attr_accessor :repo, :url, :environment
def self.build(repo, url, environment)
case ENV["NOTIFIER"]
when "slack"
SlackNotifier.new(repo, url, environment)
when "hipchat"
HipChatNotifier.new(repo, url, environment)
else
NullNotifier.new(repo, url, environment)
end
end
def initialize(repo, url, environment)
@repo = repo
@url = url
@environment = environment
end
def pending
raise NotImplementedError, "You must implement #{self.class}##{__method__}"
end
def success
raise NotImplementedError, "You must implement #{self.class}##{__method__}"
end
def failure
raise NotImplementedError, "You must implement #{self.class}##{__method__}"
end
private
def pending_msg
"[deploy] #{repo}: goodluck is shipping to #{environment}.\n#{url}"
end
def success_msg
"[deploy] #{repo}: goodluck shipped successfully to #{environment}.\n#{url}"
end
def failure_msg
"[deploy] #{repo}: what's the hell. goodluck couldn't ship to #{environment}."
end
end
class HipChatNotifier < Notifier
attr_accessor :room, :token
def initialize(repo, url, environment)
super
@room = ENV['HIPCHAT_ROOM']
@token = ENV['HIPCHAT_API_TOKEN']
end
def pending
notify(pending_msg)
end
def success
notify(success_msg, color: 'green')
end
def failure
notify(failure_msg, color: 'red')
end
private
def notify(message, options = {})
default_options = { message_format: 'text' }
client[room].send("goodluck", message, default_options.merge(options))
end
def client
@client ||= HipChat::Client.new(token, api_version: 'v1')
end
end
class SlackNotifier < Notifier
attr_accessor :hook_url, :channel, :default_payload
def initialize(repo, url, environment)
super
@hook_url = ENV['SLACK_HOOK_URL']
@channel = ENV['SLACK_CHANNEL']
@default_payload = {
channel: channel,
username: "goodluck",
icon_emoji: ":angel:"
}
end
def pending
payload = {
text: "Deployment process started.",
attachments: [
{
color: "warning",
title: "#{environment.capitalize}: Deploy #{repo}",
text: "Shipping to #{environment}.",
}
]
}
notify(default_payload.merge(payload))
end
def success
payload = {
text: "Deployment process finished.",
attachments: [
{
color: "good",
title: "#{environment.capitalize}: Deploy #{repo}",
text: "Shipped successfully to #{environment}.",
fields: [
{
title: "URL",
value: url,
short: true
}
]
}
]
}
notify(default_payload.merge(payload))
end
def failure
payload = {
text: "Deployment process stopped.",
attachments: [
{
color: "danger",
title: "#{environment.capitalize}: Deploy #{repo}",
text: "What's the hell. Something has gone wrong with #{environment}.",
}
]
}
notify(default_payload.merge(payload))
end
private
def notify(payload)
Faraday.post hook_url, { payload: payload.to_json }
end
end
class NullNotifier < Notifier
def pending
puts pending_msg
end
def success
puts success_msg
end
def failure
puts failure_msg
end
end
end
| true |
fccc8f3b13e4dea5ed183ac764bbf0744445a635 | Ruby | gkarolyi/what-the-hell | /app/services/tmdb.rb | UTF-8 | 2,461 | 2.703125 | 3 | [] | no_license | require "open-uri"
require "benchmark"
class Tmdb
class << self
def top_actors(movie_id, top_n = 4)
movie_cast(movie_id).sort { |b, a| a["popularity"] - b["popularity"] }
.first(top_n)
end
def movie_details(movie_id)
details = read_and_parse(movie_url(movie_id))
important_details(details)
end
def each_movie_details(array_of_movie_ids)
array_of_movie_ids.map do |id|
Thread.new do
movie_details(id)
end
end.map(&:value)
end
def matching_cast(movie_ids)
movie_ids.last(2)
.map do |id|
Thread.new do
movie_cast(id.to_i).map { |actor| actor["id"] }
end
end.map(&:value)
.reduce(&:&)
end
def actor_details(actor_id)
url = "https://api.themoviedb.org/3/person/#{actor_id}?#{api_params}"
read_and_parse(url)
rescue OpenURI::HTTPError
actor_not_found
end
def movie_cast(movie_id)
url = "https://api.themoviedb.org/3/movie/#{movie_id}/credits?#{api_params}"
cast = read_and_parse(url)["cast"]
cast.select { |c| c["known_for_department"] == "Acting" }
end
def search_actor_name(query)
url = "https://api.themoviedb.org/3/search/person?#{api_params}&query=#{query}&page=1"
actor_id = read_and_parse(url)['results'][0]['id']
actor_details(actor_id)
end
def recommendation_details(recommendations)
recommendations.first(3).map do |rec|
Thread.new do
url = movie_search_url(rec)
details = read_and_parse(url)['results'].first
important_details(details)
end
end.map(&:value)
end
private
def key
ENV['TMDB_KEY']
end
def api_params
"api_key=#{key}&language=en-US&include_adult=false"
end
def movie_url(movie_id)
"https://api.themoviedb.org/3/movie/#{movie_id.to_i}?#{api_params}"
end
def movie_search_url(query)
"https://api.themoviedb.org/3/search/movie?#{api_params}&query=#{query}"
end
def read_and_parse(url)
JSON.parse(URI.parse(url).read)
end
def important_details(hash)
{
title: hash["title"],
img_path: hash["poster_path"],
description: hash["overview"],
year: hash["release_date"]
}
end
def actor_not_found
{ name: "NOT FOUND" }
end
end
end
| true |
0a392bff10aee76b94a30a4b55d5303dde9e69d1 | Ruby | thatkahunaguy/sample_app | /app/models/user.rb | UTF-8 | 2,189 | 2.828125 | 3 | [] | no_license | class User < ActiveRecord::Base
# dependent destroy below ensures if the user is destroyed so are the microposts
has_many :microposts, dependent: :destroy
# validate presence of name - note the code below is the same as
# validates(:name, {presence: true}) - parens optional and {} opt on hash last arg
validates :name, presence: true, length: {maximum: 50}
# checking for valid email uses a regular expression (regex) to define format
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
# rails infers true for uniqueness since the case_sensitive flag is set
uniqueness: { case_sensitive: false }
# ensure email is lowercase before saving to database to ensure dbase uniqueness
before_save { self.email = email.downcase }
# callback to ensure a remember token is created prior to saving
before_create :create_remember_token
# validate password min length - has_secure_password validates matching, presence,
# and adds an authenticate method to put the hash in password_digest
validates :password, length: { minimum: 6 }
has_secure_password
# this is the user feed method which will allow following posts, initially users own
def feed
# This is preliminary. See "Following users" for the full implementation.
Micropost.where("user_id = ?", id)
end
# new token and encrypt are attached to the User class because they are used
# outside the User model and don't require a user instance to function
def User.new_remember_token
SecureRandom.urlsafe_base64
end
# the SHA encryption is used because it is much faster than bcrypt and needs to
# be used on every page/often. to_s is used because sometimes in test environments
# there will be a nil token(?)
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
#no need to expose this to the outside as its only used in User model
private
# extra indentation to clearly show which methods are private is good practice
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
| true |
498f6bac16653c63c327b6384c448c5601edb64d | Ruby | tgxworld/coursemology2 | /spec/libraries/time_bounded_spec.rb | UTF-8 | 3,011 | 2.546875 | 3 | [
"MIT"
] | permissive | require 'rails_helper'
RSpec.describe 'time_bounded', type: :model do
class TimeBoundedTest < ActiveRecord::Base
end
temporary_table(:time_bounded_tests) do |t|
t.time_bounded
end
with_temporary_table(:time_bounded_tests) do
before(:context) do
[
[nil, nil],
[nil, 1.day],
[-1.day, nil],
[-1.day, 1.day]
].each do |pair|
options = {}
options[:valid_from] = DateTime.now + pair[0] unless pair[0].nil?
options[:valid_to] = DateTime.now + pair[1] unless pair[1].nil?
TimeBoundedTest.create!(options)
end
end
it 'gets records which are still valid' do
matching_entries = TimeBoundedTest.currently_valid
expect(matching_entries).to_not be_empty
matching_entries.each do |record|
expect(record).to be_currently_valid
expect(record.valid_from).to satisfy { |v| v.nil? || v <= DateTime.now }
expect(record.valid_to).to satisfy { |v| v.nil? || v >= DateTime.now }
end
end
context 'when the records have neither valid_from nor valid_to' do
subject { TimeBoundedTest.new }
it { is_expected.to be_currently_valid }
end
context 'when the records do not have valid_from' do
context 'when the records expire after today' do
subject { TimeBoundedTest.new(valid_to: DateTime.now + 1.day) }
it { is_expected.to be_currently_valid }
end
context 'when the records expire before today' do
subject { TimeBoundedTest.new(valid_to: DateTime.now - 1.day) }
it { is_expected.to_not be_currently_valid }
end
end
context 'when the records do not have valid_to' do
context 'when the records become valid after today' do
subject { TimeBoundedTest.new(valid_from: DateTime.now + 1.day) }
it { is_expected.not_to be_currently_valid }
end
context 'when the records become valid before today' do
subject { TimeBoundedTest.new(valid_from: DateTime.now - 1.day) }
it { is_expected.to be_currently_valid }
end
end
context 'when the records have both valid_from and valid_to' do
context 'when the records have expired' do
subject do
TimeBoundedTest.new(valid_from: DateTime.now - 1.week,
valid_to: DateTime.now - 1.day)
end
it { is_expected.not_to be_currently_valid }
end
context 'when the records have not become valid' do
subject do
TimeBoundedTest.new(valid_from: DateTime.now + 1.day,
valid_to: DateTime.now + 1.week)
end
it { is_expected.not_to be_currently_valid }
end
context 'when the records are become valid' do
subject do
TimeBoundedTest.new(valid_from: DateTime.now - 1.week,
valid_to: DateTime.now + 1.week)
end
it { is_expected.to be_currently_valid }
end
end
end
end
| true |
9e0460d8221957628d5c3cb7493dbed429b2a33b | Ruby | spigo/MI-RUB | /Semestralka/lib/Knapsack.rb | UTF-8 | 2,431 | 3.40625 | 3 | [] | no_license |
class Array
def power_set
yield [] if block_given?
self.inject([[]]) do |ps, elem|
r = []
ps.each do |i|
r << i
new_subset = i + [elem]
yield new_subset if block_given?
r << new_subset
end
r
end
end
end
class Knapsack
KnapsackItem = Struct.new(:name, :weight, :value)
def knapsack_bruteforce(file)
instances_count = File.foreach(file).inject(0) {|c, line| c+1}
def knap(potential_items, knapsack_capacity)
fval = 0
maxval = 0
solutions = []
potential_items.power_set do |subset|
weight = subset.inject(0) {|w, elem| w += elem.weight}
next if weight > knapsack_capacity
value = subset.inject(0) {|v, elem| v += elem.value}
if value == maxval
solutions << subset
elsif value > maxval
maxval = value
solutions = [subset]
end
end
#puts "#{maxval}"
#puts "full value: #{fval}"
solutions.each do |set|
items = []
wt = 0
set.each {|elem| wt += elem.weight; items << elem.name}
#puts "weight: #{wt}"
#puts "items: #{items.join(',')}"
puts "cena: #{maxval}"
return maxval
end
end
fval = 0
p = 0
while p < instances_count do
data = IO.readlines(file)[p].split
items = Array.new;
id = data[0]; data.shift;
items_count = data[0].to_i; data.shift;
knapsack_capacity = data[0].to_i; data.shift;
i = -1
j = 0;
i.upto(items_count-2) do
items << KnapsackItem.new("#{j}", data[i+1].to_i, data[i+2].to_i)
i +=2
j +=1
end
fval += knap(items, knapsack_capacity)
p +=1
#puts fval
end
end
def knapsack_heuristic(file)
instances_count = File.foreach(file).inject(0) {|c, line| c+1}
fval = 0
p = 0;
while p < instances_count do
data = IO.readlines(file)[p].split
items = Array.new;
id = data[0]; data.shift; #read instance id
items_count = data[0].to_i; data.shift; #read instance items
knapsack_capacity = data[0].to_i; data.shift; #read knapsack capacity
i = 0
x = 0;
while x < items_count do
koef = data[i+1].to_i/data[i].to_i
items << [koef, data[i].to_i, data[i+1].to_i]
i += 2;
x += 1;
end
total = 0
mval = 0
items.sort.reverse.each do |item|
break if (total+item[1] > knapsack_capacity)
total += item[1]
mval += item[2]
end
puts "cena: #{mval}"
#fval += mval
p +=1
#puts fval
end
end
end
| true |
7d9e0f0b641190de8bc7371efe9d792673ef5c12 | Ruby | sidapa/super_settings | /lib/super_settings/rule_key_parser.rb | UTF-8 | 566 | 2.875 | 3 | [
"MIT"
] | permissive | module SuperSettings
# RuleKeyParser parses rule keys. It takes in either a symbol
# or an array of symbols and parses through them, returning
# an array of symbols for registration
class RuleKeyParser
attr_accessor :keys
def initialize(params)
arr_params = Array(params)
valid_params = %w(String Symbol)
@keys = arr_params.map do |param|
unless valid_params.include? param.class.to_s
fail SuperSettings::Error, 'Invalid Parameter'
end
param.to_sym
end
@keys.uniq!
end
end
end
| true |
e979e2ecc8dfdf6751f4cd4999ad47461bddc528 | Ruby | progpyftk/learn_to_code_with_ruby_udemy | /Section 12/count_values.rb | UTF-8 | 137 | 3.4375 | 3 | [] | no_license | custom_count (my_hash, number)
count = 0
my_hash.each do |key, value|
count += 1 if value == number
end
count
end | true |
811fb681b61e33c29afecd6bca752b0af01afc14 | Ruby | CarlosCanizal/blackjack_web | /main.rb | UTF-8 | 6,961 | 2.96875 | 3 | [] | no_license | require 'rubygems'
require 'sinatra'
set :sessions, true
helpers do
def start_game
suits = ["clubs", "diamonds", "hearts", "spades"]
values = ["A","2","3","4","5","6","7","8","9","10","Q","K"]
deck = suits.product(values)
decks = [deck,deck,deck,deck]
end
def show_cards(hand)
cards = ""
hand.each do |card|
cards += "<img class='card' alt='#{card[0]}_#{card[1]}' src='/images/cards/#{card[0]}_#{card[1]}.jpg' />"
end
cards
end
def close_game
session[:player_name] = nil
session[:player_label] = nil
session[:bet] = nil
session[:decks] = nil
session[:money] = nil
session[:user_hand] = nil
session[:dealer_hand] = nil
session[:game_step] = nil
session[:game_step] = nil
end
def hit_card
@decks = session[:decks]
rand_deck = rand(@decks.length)
rand_card = rand(@decks[rand_deck].length)
card = @decks[rand_deck][rand_card]
@decks[rand_deck].delete_at(rand_card)
end
def hand_total(hand)
values = {"A"=>11,"2"=>2,"3"=>3,"4"=>4,"5"=>5,"6"=>6,"7"=>7,"8"=>8,"9"=>9,"10"=>10,"J"=>10,"Q"=>10,"K"=>10}
hand_total = 0
aces = []
hand.each do |card|
card[1]
if card[1] == "A"
aces << card
else
hand_total += values[card[1]]
end
end
aces.each do |card|
hand_total += hand_total+values[card[1]] > 21 ? 1 : values[card[1]]
end
hand_total
end
def results(user_hand, dealer_hand, money, bet)
user_total = hand_total(user_hand)
dealer_total = hand_total(dealer_hand)
if user_total > 21
result = "lose"
money -= bet
else
if user_total == dealer_total
result = "draw"
else
if user_total == 21 && user_hand.length == 2
result = "blackjack"
money += (bet*1.5)
else
if user_total > dealer_total || dealer_total > 21
result = "win"
money += bet
else
result = "lose"
money -= bet
end
end
end
end
session[:result] = result
session[:money] = money
{result:result, money:money}
end
end
before '/game/*' do
unless session[:player_name]
close_game
redirect '/new_player?access=no_access'
end
@player_name = session[:player_name]
@player_label = session[:player_label]
@money = session[:money]
end
before '/game/results/*' do
redirect '/game' if session[:game_step] == :playing
@player_name = session[:player_name]
@player_label = session[:player_label]
@money = session[:money]
end
before '/new_player' do
redirect '/back_to_game' if session[:game_step]
end
get '/' do
erb :index
end
get '/close_game' do
close_game
redirect "/"
end
get '/game/results/take_my_money' do
@money = session[:money]
close_game
erb :take_my_money
end
post '/game/hit' do
session[:user_hand] << hit_card
@user_hand = session[:user_hand]
@user_total = hand_total(@user_hand)
if @user_total >21
result = results(session[:user_hand], session[:dealer_hand], session[:money], session[:bet])
session[:game_step] = nil
redirect '/game/results/results'
elsif @user_total == 21
session[:game_step] = :dealer_turn
end
redirect '/game'
end
post '/game/stay' do
session[:game_step] = :dealer_turn
redirect '/game'
end
get '/game/results/results' do
session[:bet] = nil
@user_hand = session[:user_hand]
@user_total = hand_total(session[:user_hand])
@dealer_hand = session[:dealer_hand]
@dealer_total = hand_total(@dealer_hand)
@message = case session[:result]
when "lose" then "Sorry #{@player_label} #{@player_name} You Lose #{@bet}"
when "win" then "Congratulations! #{@player_label} #{@player_name} You Win #{@bet}"
when "draw" then "This is a Draw"
when "blackjack" then "Blackjack! #{@player_label} #{@player_name} You Win #{@bet}"
end
session[:user_hand] = nil
session[:dealer_hand] = nil
erb :results
end
post '/game/hit_dealer' do
session[:dealer_hand] << hit_card
@dealer_hand = session[:dealer_hand]
@dealer_total = hand_total(@dealer_hand)
if @dealer_total >16
result =results(session[:user_hand], session[:dealer_hand], session[:money], session[:bet])
session[:game_step] = nil
redirect '/game/results/results'
end
session[:game_step] = :dealer_turn
redirect '/game'
end
get '/game' do
redirect '/game/bet' unless session[:bet]
@dealer_turn = false
@player_name = session[:player_name]
@player_label = session[:player_label]
@bet = session[:bet]
@user_hand = session[:user_hand]
@user_total = hand_total(@user_hand)
@dealer_hand = session[:dealer_hand]
if session[:game_step] == :dealer_turn
@dealer_turn = true
@dealer_total = hand_total(@dealer_hand)
if @dealer_total >16
result =results(session[:user_hand], session[:dealer_hand], session[:money], session[:bet])
session[:game_step] = nil
redirect '/game/results/results'
end
end
erb :game
end
post '/game' do
@bet = params["bet"].to_i
session[:bet] = @bet
redirect '/game' if session[:user_hand]
redirect '/game/bet?bet=invalid' if @bet < 1
redirect '/game/bet?bet=greater' if @bet > session[:money]
session[:game_step] = :playing
session[:decks] = start_game
session[:user_hand] = []
session[:dealer_hand] = []
@player_name = session[:player_name]
@player_label = session[:player_label]
2.times { session[:user_hand] << hit_card }
2.times { session[:dealer_hand] << hit_card }
@user_hand = session[:user_hand]
@user_total = hand_total(@user_hand)
if @user_total == 21
session[:game_step] = :dealer_turn
redirect '/game'
end
@dealer_hand = session[:dealer_hand]
erb :game
end
get '/game/bet' do
redirect '/game' if session[:game_step] == :playing
redirect '/close_game' if session[:money] < 1
@error = "Please type a valid bet numeric greater than 0" if params["bet"] == "invalid"
@error = "Your bet must be lower or equal than #{session[:money]}" if params["bet"] == "greater"
erb :bet
end
get '/new_player' do
redirect '/back_to_game' if session[:player_name]
@error = "Sorry, You have no acccess to the CASINO. Please register!" if params["access"] == "no_access"
@error = "Please let me know your name" if params["name"] == "empty"
@error = "Please select a valid label" if params["label"] == "invalid"
erb :new_player
end
get '/back_to_game' do
erb :back_to_game
end
post '/new_player' do
labels = ['Mrs.', 'Miss', 'Mr.']
player_name = params["player_name"].capitalize
player_label = params["player_label"]
redirect "/new_player?label=invalid" unless labels.include? player_label
redirect "/new_player?name=empty" if player_name.empty?
session[:player_name] = player_name
session[:player_label] = player_label
session[:game_step] = :bet
session[:money] = 500
redirect '/game/bet'
end
| true |
5d4b2ce129bfbf8979eae586c4a30b0893ecd95f | Ruby | jinp6301/appacademy-exercises | /w1d3/merge_sort.rb | UTF-8 | 544 | 3.515625 | 4 | [] | no_license | def merge_sort(array)
if array.length < 2
return array
end
left, right = split_array(array)
result = combine(merge_sort(left), merge_sort(right))
end
def split_array(array)
middle = array.length/2
[array.take(middle), array.drop(middle)]
end
def combine(array1, array2)
if array1.empty? || array2.empty?
if array2.empty?
return array1
else
return array2
end
else
nil
end
smallest = array1.first <= array2.first ? array1.shift : array2.shift
combine(array1, array2).unshift(smallest)
end | true |
c5cda2a79431975f255d08c663f4877e8690e500 | Ruby | olistik/rsc-arena | /lib/rsc-arena/bot.rb | UTF-8 | 757 | 2.984375 | 3 | [
"MIT"
] | permissive | module Rsc::Arena
class Bot
attr_accessor :chips, :card, :bet
attr_reader :name
include Comparable
def initialize(name, klass)
@name, @bot = name, klass.new
@card = nil
@bet = 0
@chips = 0
end
def chips=(amount)
@chips = amount
@bot.chips = amount
end
def active?
@chips > 0
end
def <=>(other)
@chips <=> other.chips
end
def notify_ante_payed(amount)
@bot.notify_ante_payed(amount)
end
def to_s
"#{@name} -> #{@chips}"
end
def see_opponent_card(opponent)
@bot.see_opponent_card(opponent.name, opponent.card)
end
def method_missing(name, *args, &block)
@bot.send(name, *args, &block)
end
end
end
| true |
da4d90e22b221a0a5d3dda011f5809c43954085a | Ruby | rorycforster/project_euler | /problem9.rb | UTF-8 | 1,002 | 4 | 4 | [] | no_license | def special_pythagorean_triplet(a, b, c)
if a < b
if b < c
if (a**2) + (b**2) == (c**2)
if (a + b + c) == 1000
puts "This is the special pythagorean triplet"
else puts "This is not the special pythagorean triplet"
end
end
end
end
end
def pyth_triplet(num)
if num.is_a?(Float) == false
end
end
#what do we know about a
a = Math.sqrt(c**2 - b**2)
a < b
a = 1000 - b - c
#what do we know about b
b = Math.sqrt(c**2 - a**2)
b < c
b = 1000 - a - c
#what do we know about c
c = Math.sqrt(a**2 + b**2)
c>b
c = 1000 - a - b
def test_for_a(a)
a < 997
end
#
#a < b
#a**2 + b**2 = c**2
#a + b < 1000
a*b*c =
a+b+c =1000
a**2 + b**2 = c**2
a**2+b**2 = 1000 - a - b
a**2 + b**2 + b + a = 1000
a*(a+1) + b*(b+1) = 1000
Math.sqrt(a**2 + b**2) =
def pyth_triplet(a, b, c)
if a < b
if b < c
if (a**2) + (b**2) == (c**2)
puts "This is a pythagorean triplet"
else puts "This is not a pythagorean triplet"
end
end
end
end | true |
f66c92e5627010211acd4279410be2948cd4e34b | Ruby | ahmedelmahalawey/sablon | /test/html/node_properties_test.rb | UTF-8 | 4,109 | 2.625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
require "test_helper"
class NodePropertiesTest < Sablon::TestCase
def setup
# struct to simplify prop whitelisting during tests
@inc_props = Struct.new(:props) do
def include?(*)
true
end
end
end
def test_empty_node_properties_converison
# test empty properties
props = Sablon::HTMLConverter::NodeProperties.new('w:pPr', {}, @inc_props.new)
assert_equal props.inspect, ''
assert_nil props.to_docx
end
def test_simple_node_property_converison
props = { 'pStyle' => 'Paragraph' }
props = Sablon::HTMLConverter::NodeProperties.new('w:pPr', props, @inc_props.new)
assert_equal props.inspect, 'pStyle=Paragraph'
assert_equal props.to_docx, '<w:pPr><w:pStyle w:val="Paragraph" /></w:pPr>'
end
def test_node_property_with_nil_value_converison
props = { 'b' => nil }
props = Sablon::HTMLConverter::NodeProperties.new('w:rPr', props, @inc_props.new)
assert_equal props.inspect, 'b'
assert_equal props.to_docx, '<w:rPr><w:b /></w:rPr>'
end
def test_node_property_with_hash_value_converison
props = { 'shd' => { color: 'clear', fill: '123456', test: nil } }
props = Sablon::HTMLConverter::NodeProperties.new('w:rPr', props, @inc_props.new)
assert_equal props.inspect, 'shd={:color=>"clear", :fill=>"123456", :test=>nil}'
assert_equal props.to_docx, '<w:rPr><w:shd w:color="clear" w:fill="123456" /></w:rPr>'
end
def test_node_property_with_array_value_converison
props = { 'numPr' => [{ 'ilvl' => 1 }, { 'numId' => 34 }] }
props = Sablon::HTMLConverter::NodeProperties.new('w:pPr', props, @inc_props.new)
assert_equal props.inspect, 'numPr=[{"ilvl"=>1}, {"numId"=>34}]'
assert_equal props.to_docx, '<w:pPr><w:numPr><w:ilvl w:val="1" /><w:numId w:val="34" /></w:numPr></w:pPr>'
end
def test_complex_node_properties_conversion
props = {
'top1' => 'val1',
'top2' => [
{ 'mid0' => nil },
{ 'mid1' => [
{ 'bottom1' => { key1: 'abc' } },
{ 'bottom2' => 'xyz' }
] },
{ 'mid2' => 'val2' }
],
'top3' => { key1: 1, key2: '2', key3: nil, key4: true, key5: false }
}
output = <<-DOCX.gsub(/^\s*/, '').delete("\n")
<w:pPr>
<w:top1 w:val="val1" />
<w:top2>
<w:mid0 />
<w:mid1>
<w:bottom1 w:key1="abc" />
<w:bottom2 w:val="xyz" />
</w:mid1>
<w:mid2 w:val="val2" />
</w:top2>
<w:top3 w:key1="1" w:key2="2" w:key4="true" />
</w:pPr>
DOCX
props = Sablon::HTMLConverter::NodeProperties.new('w:pPr', props, @inc_props.new)
assert_equal props.to_docx, output
end
def test_setting_property_value
props = {}
props = Sablon::HTMLConverter::NodeProperties.new('w:pPr', props, @inc_props.new)
props['rStyle'] = 'FootnoteText'
assert_equal({ 'rStyle' => 'FootnoteText' }, props.instance_variable_get(:@properties))
end
def test_properties_filtered_on_init
props = { 'pStyle' => 'Paragraph', 'rStyle' => 'EndnoteText' }
props = Sablon::HTMLConverter::NodeProperties.new('w:rPr', props, %w[rStyle])
assert_equal({ 'rStyle' => 'EndnoteText' }, props.instance_variable_get(:@properties))
end
def test_transferred_properties
props = { 'pStyle' => 'Paragraph', 'rStyle' => 'EndnoteText' }
props = Sablon::HTMLConverter::NodeProperties.new(nil, props, %w[pStyle])
trans = props.transferred_properties
assert_equal({ 'rStyle' => 'EndnoteText' }, trans)
end
def test_node_properties_paragraph_factory
props = { 'pStyle' => 'Paragraph' }
props = Sablon::HTMLConverter::NodeProperties.paragraph(props)
assert_equal 'pStyle=Paragraph', props.inspect
assert_equal props.to_docx, '<w:pPr><w:pStyle w:val="Paragraph" /></w:pPr>'
end
def test_node_properties_run_factory
props = { 'color' => 'FF00FF' }
props = Sablon::HTMLConverter::NodeProperties.run(props)
assert_equal 'color=FF00FF', props.inspect
assert_equal '<w:rPr><w:color w:val="FF00FF" /></w:rPr>', props.to_docx
end
end
| true |
35862442f7aa901ca6ba769341786bf941a154b0 | Ruby | wribln/pmodbase | /app/models/base_item_list.rb | UTF-8 | 4,627 | 2.71875 | 3 | [] | no_license | # BaseItemList is shown on the base page having NO_OF_COLUMNS_ON_BASE_PAGE
# columns (defined in config/initializers/basic_settings.rb)
class BaseItemList
# return all features and associated headings in an array to be passed on
# to the BaseController; the array is multi-dimensional, the first index
# is over the columns to be shown; the second index contains the feature
# category heading and another array with the feature_names and their
# controller.
def self.all( current_user )
# determine which feature groups will be shown to the user; for this
# I define a structure to hold feature group specific information
a_category = Struct.new( :item_count, :features, :seqno, :label, :column_no )
all_features = Feature.includes([ :feature_category, :permission4_groups ]).select( :id, :code, :label, :feature_category_id, :access_level ).order( :seqno ).all
all_categories = Hash.new
all_features.each_with_index do |f, fi|
if f.feature_category_id.nil? || f.feature_category_id <= 0 then
Rails.logger.debug( "BaseItemList: FeatureCategory #{ f.feature_category_id } referenced in Feature #{ f.id } is invalid!" )
next
end
next if f.no_direct_access?
if f.access_to_index? || current_user.permission_to_index?( f.id ) then
if all_categories[ f.feature_category_id ].nil? then # new group - initialize
all_categories[ f.feature_category_id ] = a_category.new( 1, [ fi ], f.feature_category.seqno, f.feature_category.label, nil )
else # existing group - increment count, add new feature to list
all_categories[ f.feature_category_id ].item_count += 1
all_categories[ f.feature_category_id ].features << fi
end
end
end
# pick up data for feature groups, increment item cound by one
# (for the group title, compute maximum of all groups, and
# total count over all groups
total_no_items = 0
no_items_per_col = 0
all_categories.each_value do |tgv|
tgv.item_count += 1.5
total_no_items += tgv.item_count
no_items_per_col = tgv.item_count if tgv.item_count > no_items_per_col
end
# if there is nothing to display, return nil
return nil if total_no_items == 0
# remove all empty groups
all_categories.delete_if{ |tgi,tgv| tgv.item_count == 0 }
# hash is not useful from now on - continue with all_categories as array,
# sort into seqno order
all_categories = all_categories.to_a
all_categories.sort! { |ag1, ag2| ag1[ 1 ].seqno <=> ag2[ 1 ].seqno }
# adjust approximate number of items in each column:
# [no_items_per_col, total_no_items.fdiv(NO_OF_COLUMNS_ON_BASE_PAGE).ceil].max
no_items_per_col = total_no_items.fdiv( NO_OF_COLUMNS_ON_BASE_PAGE ).ceil unless
( no_items_per_col * NO_OF_COLUMNS_ON_BASE_PAGE ) > total_no_items
# ready for first loop: distribute groups to columns
# column_item_count holds total of items assigned to column,
# total_no_items will be the number of items left to distribute
column_item_count = Array.new( NO_OF_COLUMNS_ON_BASE_PAGE, 0 )
all_categories.each do |tgv|
column_item_count.each_index do |ci|
if( column_item_count[ ci ] + tgv[ 1 ].item_count ) <= no_items_per_col then
column_item_count[ ci ] += tgv[ 1 ].item_count
total_no_items -= tgv[ 1 ].item_count
tgv[ 1 ].column_no = ci
break
end # if
end # column_item_count do
end # all_categories do
# distribute remaining items to colum, largest group to shortest column first
while total_no_items > 0
ci = column_item_count.index(column_item_count.min)
g_max = 0
i_max = nil
all_categories.each_with_index do | tgv, tgi |
if tgv[ 1 ].column_no.nil? and tgv[ 1 ].item_count > g_max then
g_max = tgv[ 1 ].item_count
i_max = tgi
end
end
column_item_count[ ci ] += all_categories[ i_max ][ 1 ].item_count
total_no_items -= all_categories[ i_max ][ 1 ].item_count
all_categories[ i_max ][ 1 ].column_no = ci
end
# final stage: collect output into array for controller
result = Array.new( NO_OF_COLUMNS_ON_BASE_PAGE ){ Array.new }
all_categories.each do |tgv|
result[ tgv[ 1 ].column_no ] << [ 0, tgv[ 1 ].label ] # header
tgv[ 1 ].features.each do | t |
result[ tgv[ 1 ].column_no ] << [ 1, all_features[ t ].label, all_features[ t ].code ] # detail
end
result[ tgv[ 1 ].column_no ] << [ 2 ] # end of group
end
return result
end # def
end
| true |
4d958a96bed27a725750969954ab83fcc04282f0 | Ruby | elaineparie/triangle-classification-v-000 | /lib/triangle.rb | UTF-8 | 764 | 3.484375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Triangle
attr_accessor :length_1, :length_2, :length_3
def initialize(length_1, length_2, length_3)
@length_1 = length_1
@length_2 = length_2
@length_3 = length_3
end
def kind
if @length_1 == 0 || @length_2 == 0 || @length_3 == 0
raise TriangleError
elsif @length_1 < 0 || @length_2 < 0 || @length_3 < 0
raise TriangleError
elsif @length_1 + @length_2 < @length_3 || @length_1 + @length_3 == @length_2 || @length_2 + @length_3 < @length_1
raise TriangleError
elsif @length_1 == @length_2 && @length_1 == @length_3
:equilateral
elsif @length_1 == @length_2 || @length_1 == @length_3 || @length_2 == @length_3
:isosceles
else
:scalene
end
end
class TriangleError < StandardError
# triangle error code
end
end
| true |
be755949733618fb3c887ff1f51f28960f59439b | Ruby | udaykadaboina/rabbitmq-tutorial | /send.rb | UTF-8 | 398 | 2.984375 | 3 | [] | no_license | require 'bunny'
# connect to RabbitMQ server
conn = Bunny.new
conn.start
# create a channel, where most of the API for getting things done resides
ch = conn.create_channel
# declare a queue, then pubhish a msg to the queue:
q = ch.queue("hello")
ch.default_exchange.publish("Hello world! from Bunny World!", :routing_key => q.name)
puts "[x] Sent 'Hello World!'"
# close the connection
conn.close
| true |
f23c615cdeb3eb8b20037bfd81d44a7a84466a07 | Ruby | ThoughtGang/BGO | /lib/bgo/application/commands/image-create.rb | UTF-8 | 3,178 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env ruby
# :title: Bgo::Commands::CreateImage
=begin rdoc
BGO command to create a new Image object.
Copyright 2013 Thoughtgang <http://www.thoughtgang.org>
=end
require 'bgo/application/command'
require 'bgo/application/commands/shared/data_model_options'
require 'bgo/application/commands/shared/pipeline'
require 'bgo/application/commands/shared/standard_options'
require 'bgo/image'
module Bgo
module Commands
=begin rdoc
A command to create an Image in a project or stream.
=end
class CreateImageCommand < Application::Command
# ----------------------------------------------------------------------
disable_plugins
summary 'Create a BGO Image'
usage "#{Commands.data_model_usage} [-c str] [-xo] STRING"
help "Create an Image object in a Project or stream.
Category: plumbing
This creates a BGO Image object whose contents are STRING. By default, STRING
is the name of a file to read as the Image contents. The -x and -o arguments
can be used to treat STRING as a hex or octal representation of the Image
contents (instead of as a filename).
Options:
-c, --comment string Comment for Image object
-o, --octal Data string is in ASCII octal bytes ('0377 0001'...)
-x, --hex Data string is in ASCII hex bytes ('FF 01'...)
#{Commands.standard_options_help}
#{Commands.data_model_options_help}
#{Commands.data_model_help}
Examples:
# Add a binary image for the file 'memdump.bin'
bgo image-create memdump.bin
# Add a binary image consisting of 8 0xCC (int3 in x86) bytes:
bgo image-create -x 'CC CC CC CC CC CC CC CC'
See also: file-create, image, image-create-remote, image-create-virtual,
image-delete, image-edit"
# ----------------------------------------------------------------------
def self.invoke_with_state(state, options)
options.images.each { |path| create_image(options, state, path) }
state.save("Image added by cmd IMAGE-CREATE" )
true
end
def self.create_image(options, state, str)
buf = ''
if options.hex
buf = str.split(' ').collect { |c| c.hex }.pack('C*')
elsif options.octal
buf = str.split(' ').collect { |c| c.oct }.pack('C*')
else
buf = File.binread(str)
end
img = state.add_image buf
img.comment = options.comment if img && options.comment
end
def self.get_options(args)
options = super
options.hex = options.octal = false
options.comment = nil # image comment attribute
options.images = []
opts = OptionParser.new do |opts|
opts.on( '-c', '--comment string' ) { |str| options.comment = cmt }
opts.on( '-x', '--hex' ) { options.hex = true }
opts.on( '-o', '--octal' ) { options.octal = true }
Commands.data_model_options(options, opts)
Commands.standard_options(options, opts)
end
opts.parse!(args)
raise "Insufficient arguments" if args.count < 1
while args.length > 0
options.images << args.shift
end
return options
end
end
end
end
| true |
8a4e3e8bfc12257213640461b0a4c4bea2308dc9 | Ruby | bravoaggie/Electron | /features/step_definitions/edittimesheet_steps.rb | UTF-8 | 1,325 | 2.5625 | 3 | [] | no_license | require 'uri'
require 'cgi'
require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "app", "models", "employee"))
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths"))
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors"))
module WithinHelpers
def with_scope(locator)
locator ? within(*selector_for(locator)) { yield } : yield
end
end
World(WithinHelpers)
def employee
@employee = FactoryGirl.create(:employee)
@employee.save
return @employee
end
Given(/^(?:|I )am viewing my (.+)$/) do |page_name|
visit path_to(page_name, @employee)
end
When(/^(?:|I )double-click a time cell$/) do
expect(find(:xpath, "(//td[2])[1]")['contenteditable']).to eq('false')
find(:xpath, "(//td[2])[1]").double_click
end
When(/^(?:|I )double-click the last time cell of a day$/) do
find(:xpath, "(//td[2])[1]").double_click
end
When(/^(?:|I )edit a time cell to (.+)$/) do |input|
cell = "(//td[2])[1]"
find(:xpath, cell).set(input)
end
When(/^(?:|I )edit another time cell to (.+)$/) do |input|
cell = "(//td[3])[1]"
find(:xpath, cell).set(input)
end
Then(/^(?:|The )cell should be editable$/) do
expect(find(:xpath, "(//td[2])[1]")['contenteditable']).to eq('true')
end
Then(/^A new row should appear below it$/) do
end | true |
a866a61009e395cf9864272a808acad0fa53af01 | Ruby | trikitrok/careerbuilder-2013-nov | /lib/bottles.rb | UTF-8 | 437 | 3.296875 | 3 | [] | no_license | require './lib/beer_verse'
class BottlesSong
def sing
verses(99, 0)
end
def verses(starting, ending = 0)
starting.downto(ending).map { |n| verse(n) }.join("\n") + "\n"
end
def verse(starting_bottle_count)
number = starting_bottle_count.to_bottlenum
"#{number} of beer on the wall, #{number.to_s.downcase} of beer.\n" +
number.action + ", #{number.next.to_s.downcase} of beer on the wall.\n"
end
end | true |
a4a71fe15c5c157c724b4810d14b9d6eadb8f684 | Ruby | treacher/payslip_generator | /lib/payslip_generator/employee_readers/csv_reader.rb | UTF-8 | 389 | 2.6875 | 3 | [] | no_license | module PayslipGenerator
module EmployeeReaders
class CsvReader < CSV
def each(&block)
super { |row| yield(convert(row)) }
end
def convert(row)
{
first_name: row[0],
last_name: row[1],
salary: BigDecimal.new(row[2]),
super_rate: row[3].to_f,
pay_period: row[4]
}
end
end
end
end
| true |
fcdd49fb86117571e24eaf7632650f4867abb035 | Ruby | dhoffens/week-1 | /day-1/student_cities.rb | UTF-8 | 237 | 3.421875 | 3 | [] | no_license | cities = [ "boca raton", "bronx", "miami", "bloomington" ]
cities_capitalize = cities.map do |city|
if city.include? " "
city.split(" ").each do |c|
c.capitalize!
end.join(" ")
else
city.capitalize
end
end
p cities_capitalize | true |
bba4bd4101c72a86cc2f84cfbc8ebb5e33614ab0 | Ruby | TechnicallyAustin/reverse-each-word-online-web-pt-120919 | /reverse_each_word.rb | UTF-8 | 131 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def reverse_each_word(sentence = "")
new_arr = sentence.split(" ")
new_arr.collect { |element| element.reverse}.join(" ")
end
| true |
b79d25ea14a61de15979e22dde14bfb1e8c35e5d | Ruby | irevived1/ruby-object-initialize-lab-wdf-000 | /lib/dog.rb | UTF-8 | 227 | 3.0625 | 3 | [] | no_license | class Dog
def initialize(names,breeds="Mut")
@name = names
@breed = breeds
end
def name= (names)
@name = names
end
def breed= (breeds)
@breed = breeds
end
def name
@name
end
def breed
@breeds
end
end
| true |
d6f5d6ef3093c8ab644d3d0da4162a18c84d5631 | Ruby | takayuki-ochiai/CodePractice | /RubyPractice/repeat_practice/itodenwa2.rb | UTF-8 | 166 | 3.171875 | 3 | [] | no_license | n = 16
pair = Array.new(n / 2 + 1)
pair[0] = 1
1.upto(n/2) do |i|
pair[i] = 0
i.times do |j|
pair[i] += pair[j] * pair[i - j - 1]
end
end
puts pair[n/2]
| true |
11eae715fdac06cc1a6e1edbf38c2e5664ee6ca9 | Ruby | stumpy224/grid_pool | /app/models/game.rb | UTF-8 | 2,182 | 2.6875 | 3 | [] | no_license | class Game
attr_accessor(
:game_id,
:bracket_position_id,
:game_state,
:game_is_live,
:game_over,
:round,
:team_on_top_seed,
:team_on_top_name_short,
:team_on_top_name_full,
:team_on_top_score,
:team_on_top_is_winner,
:team_on_bottom_seed,
:team_on_bottom_name_short,
:team_on_bottom_name_full,
:team_on_bottom_score,
:team_on_bottom_is_winner,
:square_winner,
:square_winner_id,
:current_period,
:time_clock,
:network,
:game_status
)
def initialize(attributes = {})
@game_id = attributes[:game_id]
@bracket_position_id = attributes[:bracket_position_id]
@game_state = attributes[:game_state]
@game_is_live = attributes[:game_is_live]
@game_over = attributes[:game_over]
@round = attributes[:round]
@team_on_top_seed = attributes[:team_on_top_seed]
@team_on_top_name_short = attributes[:team_on_top_name_short]
@team_on_top_name_full = attributes[:team_on_top_name_full]
@team_on_top_score = attributes[:team_on_top_score]
@team_on_top_is_winner = attributes[:team_on_top_is_winner]
@team_on_bottom_seed = attributes[:team_on_bottom_seed]
@team_on_bottom_name_short = attributes[:team_on_bottom_name_short]
@team_on_bottom_name_full = attributes[:team_on_bottom_name_full]
@team_on_bottom_score = attributes[:team_on_bottom_score]
@team_on_bottom_is_winner = attributes[:team_on_bottom_is_winner]
@square_winner = attributes[:square_winner]
@square_winner_id = attributes[:square_winner_id]
@current_period = attributes[:current_period]
@time_clock = attributes[:time_clock]
@network = attributes[:network]
@game_status = attributes[:game_status]
end
def game_is_live?
!!@game_is_live
end
def game_over?
!!@game_over
end
def team_on_bottom_is_winner?
!!@team_on_bottom_is_winner
end
def team_on_top_is_winner?
!!@team_on_top_is_winner
end
def self.exists?
self.count > 0 ? true : false
end
def self.all
ObjectSpace.each_object(self).to_a
end
def self.count
all.count
end
def self.clean_up
ObjectSpace.garbage_collect
end
end
| true |
e4ef8f9c616825cc591449dce74df46f5e578ff6 | Ruby | maegus/Learn | /Book/Introduction-To-Algorithms/direct_address.rb | UTF-8 | 175 | 2.984375 | 3 | [] | no_license | class DirectAddressTable
def initialize
@table = []
end
def search(k)
@table[k]
end
def insert(x)
@table[x] = x
end
def delete(x)
@table[x] = nil
end
end
| true |
439e9dae296c15d613c498da70447b8d5a0172cd | Ruby | kirirotha/sinatra-mvc-lab-hou01-seng-ft-071320 | /models/piglatinizer.rb | UTF-8 | 1,131 | 3.703125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
class PigLatinizer
attr_accessor :phrase
def initialize
@phrase = phrase
end
def piglatinize(phrase)
split_phrase = phrase.split(" ")
piglat_phrase = []
split_phrase.each do |word|
letters = word.split("")
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
vowel_ = false
index = 0
if vowels.include?(letters[0])
letters.push("w")
vowel_ = true
end
while vowel_ == false && index < letters.count
this_letter = letters.shift
vowels.each do |x|
if this_letter == x
letters.unshift(this_letter)
vowel_ = true
end
end
if vowel_ == false
letters.push(this_letter)
end
index +=1
end
finished_word = letters.join + "ay"
piglat_phrase << finished_word
end
piglat_phrase.join(" ")
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.