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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9c68a5ca925b2fb5dfa8cfe70f56d92dac87c024 | Ruby | jhannah/odlug.org | /pet_paradise/ruby_1/Reservation.rb | UTF-8 | 905 | 3.015625 | 3 | [] | no_license | #Pet Paradise Challenge for ODynUG
#author: Juan Vazquez http://javazquez.com
#Class will read in file of reservations and use scheduler to find most profit
require 'Scheduler'
class Reservation
attr_accessor :reservation_file, :reservation_list
attr_reader :scheduler
def initialize
@reservation_file=""
@reservation_list = []
@scheduler= Scheduler.new
end
def add_reservation(customer)
@reservation_list<<customer
@reservation_list.sort!{|customer1,customer2| customer1.date_range.to_a[0]<=>customer2.date_range.to_a[0]}
end
def get_reservations; @reservation_list ;end
#find all overlapping reservations and add to the none overlapping
def confirm_reservations
@reservation_list = @scheduler.schedule_reservations(@reservation_list)
total= @reservation_list.inject(0){|sum,item| sum + item.amount}
return @reservation_list,total
end
end | true |
800b4ddb5f082fe29d269f4f6f2a8f4b25ed85fc | Ruby | ForSetGeorgia/Scrapers | /vizhack-2018-literacy/process_files.rb | UTF-8 | 3,617 | 2.953125 | 3 | [
"MIT"
] | permissive | # pull in all data from the original_data folder, clean it, and merge into one spreadsheet
require 'csv'
start = Time.now
all_data = []
data_files = Dir.glob('original_data/*.csv')
idx_cols_to_add = [
10,20,21
]
idx_cols_to_remove = [
0,1,2,3,4,16,17,18,19,20
]
idx_image = 7
idx_death = 9
idx_age = 10
idx_org = 14 #13 + 1
idx_awards = 15 #14 + 1
idx_address = 17 #16 + 1
idx_job = 19 # 18 + 1
idx_new_address = 21
idx_new_job = 22
csv_headers = [
"url",
"name",
"image",
"birth",
"death",
"age",
"place burried",
"category",
"biography",
"organization/association/group",
"awards/bonuses/prizes",
"address",
"job"
]
data_files.each do |file|
puts "----------"
puts file
data = CSV.read(file)
# add the new columns
puts "- adding new columns"
data.each do |data_item|
idx_cols_to_add.reverse.each do |idx|
data_item.insert(idx, nil)
end
end
puts "- cleaning data"
data.each_with_index do |data_item, j|
# first row is header - skip it
if j > 0
# make image path a full url
# if the image is noimage, remove it
data_item[idx_image] = data_item[idx_image] == 'themes/bios/images/nophoto0n.jpg' ? nil : "http://www.nplg.gov.ge/ilia/#{data_item[idx_image]}"
# pull age out of death
# - it is in end of death, so split death and age
if data_item[idx_death] != 'null'
regexp_match = /^(.*) \((\d+).*\)$/.match(data_item[idx_death])
if !regexp_match.nil?
data_item[idx_death] = regexp_match[1]
data_item[idx_age] = regexp_match[2]
end
end
# remove li tags in org and awards
# - li tags were left in so it would be possible
# to see where each item started and stopped
data_item[idx_org] = data_item[idx_org].gsub('<li>', '').gsub('</li>', '')
data_item[idx_awards] = data_item[idx_awards].gsub('<li>', '').gsub('</li>', '')
# merge address
# - addresses are shown in different formats
# so had to create two different fields to record them
address1 = data_item[idx_address]
address2 = data_item[idx_address+1]
data_item[idx_new_address] = address1 != 'null' ? address1 : address2 != 'null' ? address2 : nil
# merge job
# - jobs are shown in different formats
# so had to create two different fields to record them
job1 = data_item[idx_job]
job2 = data_item[idx_job+1]
data_item[idx_new_job] = job1 != 'null' ? job1 : job2 != 'null' ? job2 : nil
# it is possible that the job text is the same as the address text
# if it is, delete it
data_item[idx_new_job] = !data_item[idx_new_job].nil? && data_item[idx_new_job] == data_item[idx_new_address] ? nil : data_item[idx_new_job]
# remove the unwanted columns
idx_cols_to_remove.reverse.each do |idx|
data_item.delete_at(idx)
end
# clean up the text
# - remove null
# - remove any extra spaces
(0..data_item.length-1).each do |idx_col|
if data_item[idx_col].class == String
data_item[idx_col] = data_item[idx_col] == 'null' ? nil : data_item[idx_col].chomp.strip
end
end
end
end
# append the data to all other data
# do not add the headers
puts "- adding to all data"
all_data << data[1..-1]
end
all_data.flatten!(1)
# write out csv
puts "=========="
puts "- creating file"
CSV.open('ilia_merged_clean.csv', "wb") do |csv|
# headers
csv << csv_headers
# data
all_data.each do |data_item|
csv << data_item
end
end
puts "it took #{Time.now - start} seconds"
| true |
68af821421471af9c39061d8f0f6d5d3fb406859 | Ruby | jwperry/headcount_repo | /headcount/lib/headcount_analyst.rb | UTF-8 | 5,178 | 2.859375 | 3 | [] | no_license | require 'pry'
require_relative 'district_repository'
class HeadcountAnalyst
def initialize(dr)
@dr = dr
@swt = @dr.statewide_test_repo.statewide_tests
end
def kindergarten_participation_rate_variation(dist1, dist2)
d1_part = get_avg(get_kp_data(@dr.find_by_name(dist1)))
d2_part = get_avg(get_kp_data(@dr.find_by_name(dist2[:against])))
final = d1_part / d2_part
truncate(final)
end
def kindergarten_participation_rate_variation_trend(dist1, dist2)
trend = Hash.new
d1_data = get_kp_data_with_year(@dr.find_by_name(dist1))
d2_data = get_kp_data_with_year(@dr.find_by_name(dist2[:against]))
d1_data.each { | k, v | trend[k] = truncate(d1_data[k] / d2_data[k]) }
trend
end
def get_kp_data(dist)
data_array = Array.new
dist.enrollment.data[:kindergarten_participation].each do | k, v |
data_array << v.to_f
end
data_array
end
def get_kp_data_with_year(dist)
data_hash = Hash.new
dist.enrollment.data[:kindergarten_participation].each do | k, v |
data_hash[k] = v.to_f
end
data_hash
end
def kindergarten_participation_against_high_school_graduation(district)
kp = kindergarten_participation_rate_variation(district, :against => "COLORADO")
gr = high_school_graduation_rate_variation(district, :against => "COLORADO")
truncate(kp/gr)
end
def high_school_graduation_rate_variation(dist1, dist2)
d1_part = get_avg(get_hs_grad_data(@dr.find_by_name(dist1)))
d2_part = get_avg(get_hs_grad_data(@dr.find_by_name(dist2[:against])))
final = d1_part / d2_part
truncate(final)
end
def get_hs_grad_data(dist)
data_array = Array.new
dist.enrollment.data[:high_school_graduation].each do | k, v |
data_array << v.to_f
end
data_array
end
def kindergarten_participation_correlates_with_high_school_graduation(tag_and_location)
if tag_and_location[:for] == 'STATEWIDE'
districts = @dr.enrollment_repo.enrollments.map { | e | e }
districts_with_correlation(districts) >= 0.7
elsif tag_and_location.include?(:for)
correlation = kindergarten_participation_against_high_school_graduation(tag_and_location[:for])
correlation >= 0.6 && correlation <= 1.5
elsif tag_and_location.include?(:across)
districts = tag_and_location[:across].map { | n | @dr.enrollment_repo.find_by_name(n) }
districts_with_correlation(districts) >= 0.7
end
end
def districts_with_correlation(districts)
names = Array.new
correlated = Array.new
districts.each { | dist | names << dist.name }
names.each do | name |
correlated << kindergarten_participation_correlates_with_high_school_graduation(:for => name)
end
correlated.count { | boolean | boolean == true } / correlated.length.to_f
end
def top_statewide_test_year_over_year_growth(grade_subj_hash)
fail InsufficientInformationError, 'A grade must be provided to answer this question' unless grade_subj_hash.has_key?(:grade)
fail UnknownDataError, 'Not a known grade' unless grade_subj_hash[:grade] == 3 || grade_subj_hash[:grade] == 8
if grade_subj_hash.has_key?(:top)
get_averages_with_multiple_leaders(grade_subj_hash, get_gradekey(grade_subj_hash[:grade]))
elsif grade_subj_hash.has_key?(:subject)
get_averages_with_single_leader(grade_subj_hash, get_gradekey(grade_subj_hash[:grade]))
else
get_averages_across_all_subjects(grade_subj_hash, get_gradekey(grade_subj_hash[:grade]))
end
end
def get_gradekey(grade)
return :third_grade if grade == 3
return :eighth_grade if grade == 8
end
def get_averages_with_single_leader(grade_subj_hash, grade)
all_avgs = @swt.map do |swt|
[swt.name, swt.year_over_year_avg(grade, grade_subj_hash[:subject])]
end
avgs = all_avgs.select { | n | (n[1].is_a?(Float) && !n[1].nan?) }
leader = (avgs.sort_by { | n | n[1] }.reverse)[0]
leader[1] = truncate(leader[1])
return leader
end
def get_averages_with_multiple_leaders(grade_subj_hash, grade)
all_avgs = @swt.map do |swt|
[swt.name, swt.year_over_year_avg(grade, grade_subj_hash[:subject])]
end
avgs = all_avgs.select { | n | (n[1].is_a?(Float) && !n[1].nan?) }
sorted = (avgs.sort_by { | n | n[1] }.reverse)
sorted.each { | n | n[1] = truncate(n[1]) }
sorted.max_by(grade_subj_hash[:top]) { | n | n[1] }
end
def get_averages_across_all_subjects(grade_subj_hash, grade)
all_avgs = @swt.map do |swt|
weighting = {:math => 1.0/3.0, :reading => 1.0/3.0, :writing => 1.0/3.0}
weighting = grade_subj_hash[:weighting] unless grade_subj_hash[:weighting].nil?
[swt.name, swt.year_over_year_avg(grade, :all, weighting)]
end
avgs = all_avgs.select { | n | (n[1].is_a?(Float) && !n[1].nan?) }
sorted = avgs.sort_by { | n | n[1] }
[sorted[-1][0], truncate(sorted[-1][1])]
end
def get_avg(data)
data.reduce(:+) / data.length
end
def truncate(number)
(number.to_f * 1000).to_i / 1000.0
end
end
class UnknownDataError < ArgumentError
end
class UnknownRaceError < ArgumentError
end
class InsufficientInformationError < ArgumentError
end
| true |
c018bc493ac1f64a6a2b04ac8985b7ac48fb33ae | Ruby | perezfelix/Semaine0_jour4 | /exo_05.rb | UTF-8 | 1,151 | 3.8125 | 4 | [] | no_license | #va juste ecrire une phrase : puts "On va compter le nombre d'heures de travail à THP"
#va écrire une phrase + faire un calcul + assembler les deux :puts "Travail : #{10 * 5 * 11}"
#éxactement pareil qu'au dessus : puts "En minutes ça fait : #{10 * 5 * 11 * 60}"
#écrit une phrase : puts "Et en secondes ?"
#écrit un calcul : puts 10 * 5 * 11 * 60 * 60
#écrit une phrase : puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?"
#fait un calcul a réponse booléenne : puts 3 + 2 < 5 - 7
#fait un calcul simple et l'introduit dans une phrase : puts "Ça fait combien 3 + 2 ? #{3 + 2}"
#comme au dessus avec une soustraction : puts "Ça fait combien 5 - 7 ? #{5 - 7}"
#écrit une phrase : puts "Ok, c'est faux alors !"
#écrit une phrase : puts "C'est drôle ça, faisons-en plus :"
#écrit une phrase et fait un calcul booleen : puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}"
#pareil qu'au dessus mais non strictement supérieur/inférieur : puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}"
#pareil qu'au dessus : puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}"
# permet de mettre une commande dans un puts
| true |
27d9b5f9936732cc16bf7a1aeb2e746560315475 | Ruby | elais/CS620 | /Elais Jackson HW1/system1/circular_shift.rb | UTF-8 | 718 | 3.234375 | 3 | [] | no_license | class CircularShift
def initialize(lines)
@HOME= File.dirname(File.expand_path(__FILE__))
@lines= lines
@shifted= Array.new
@i= 0
@num = @lines.length
@stopwords = File.open(@HOME + "/english.txt", "r").readlines.map!(&:chomp)
begin
sentence = @lines[0].downcase
sentence = sentence.split(" ")
sentence = sentence - @stopwords
j= 0
begin
word = sentence[0]
@shifted.push([@i, word])
sentence.shift
sentence.push(word)
j +=1;
end while j < sentence.length
line = @lines[0]
@lines.shift
@lines.push(line)
@i +=1;
end while @i < @num
end
def get_circular()
@shifted
end
end
| true |
ea4a64981fe1d556a78a70a63395ec9c1cd0729e | Ruby | rajmohand/L-99-Ninety-Nine-Lisp-Problems-Solutions-Ruby | /8.rb | UTF-8 | 97 | 2.890625 | 3 | [] | no_license | def last(arr)
array=arr.uniq
puts array
end
data=%w[e e e s a a s a s a s a s s]
last(data)
| true |
cbf0438e5b253347d719456c46bb7f616d7cf5d4 | Ruby | cpdundon/ruby-music-library-cli-v-000 | /lib/genre.rb | UTF-8 | 750 | 2.890625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative "../config/environment.rb"
#require_relative "./music_base.rb"
#require_relative "./Concerns::Findable.rb"
class Genre # < Music
extend Concerns::Findable
attr_accessor :name
attr_reader :songs
@@all = []
def self.all
@@all
end
def self.destroy_all
self.all.clear
end
def self.create(name)
s = self.new(name)
s
end
def save
if self.class.all.include?(self)
return nil
end
self.class.all << self
end
def initialize(name)
@name = name
@songs = []
save
end
def add_song(song)
if @songs.include?(song)
return nil
end
@songs << song
end
def artists
ret = songs.collect { |e| e.artist}
ret = ret.uniq
ret
end
end
| true |
72d6fbe787402d7669ac35e63ab54825f8bbb37a | Ruby | siakaramalegos/project_tdd_minesweeper | /lib/player.rb | UTF-8 | 1,125 | 3.953125 | 4 | [] | no_license | class Player
attr_reader :name, :board
def initialize(board, name=nil)
@name = name || get_name
@board = board
end
def take_turn
loop do
type = ask_move_type
if type == 'f'
move = ask_turn('flag')
if valid_format?(move)
break if @board.place_flag(move)
end
else
move = ask_turn('move')
if valid_format?(move)
break if @board.place_move(move)
end
end
end
end
private
def ask_move_type
puts "\nTo place a flag, type 'f'. Type anything else to clear a square."
print " > "
gets.chomp.downcase
end
def get_name
puts "Welcome to Minesweeper! What is your name?"
print " > "
gets.chomp.capitalize
end
def ask_turn(type)
puts "\nEnter your #{type} as row number, column number. For example: 4,5"
print " > "
gets.chomp.split(',').map{|i| i.to_i}
end
def valid_format?(move)
if move.is_a?(Array) && move.size == 2 && move.all?{|i| i.is_a?(Integer)}
true
else
puts "I'm sorry, I don't recognize that spot. Try again."
end
end
end | true |
85f47327f0a6fb75169cb545eb4bdfb468b664a1 | Ruby | hole19/evva | /lib/evva/android_generator.rb | UTF-8 | 5,623 | 2.640625 | 3 | [] | no_license | module Evva
class AndroidGenerator
attr_accessor :package_name
def initialize(package_name)
@package_name = package_name
end
BASE_TEMPLATE = File.expand_path("./templates/kotlin/base.kt", __dir__)
EVENTS_TEMPLATE = File.expand_path("./templates/kotlin/events.kt", __dir__)
EVENT_ENUM_TEMPLATE = File.expand_path("./templates/kotlin/event_enum.kt", __dir__)
PEOPLE_PROPERTIES_TEMPLATE = File.expand_path("./templates/kotlin/people_properties.kt", __dir__)
PEOPLE_PROPERTIES_ENUM_TEMPLATE = File.expand_path("./templates/kotlin/people_properties_enum.kt", __dir__)
SPECIAL_PROPERTY_ENUMS_TEMPLATE = File.expand_path("./templates/kotlin/special_property_enums.kt", __dir__)
DESTINATIONS_TEMPLATE = File.expand_path("./templates/kotlin/destinations.kt", __dir__)
TAB_SIZE = " " # \t -> 4 spaces
NATIVE_TYPES = %w[Long Int String Double Float Boolean Date].freeze
def events(bundle, file_name, enums_file_name, destinations_file_name)
header_footer_wrapper do
class_name = file_name
enums_class_name = enums_file_name
destinations_class_name = destinations_file_name
events = bundle.map do |event|
properties = event.properties.map do |name, type|
type = native_type(type)
param_name = camelize(name.to_s, false)
value_fetcher = param_name
if is_special_property?(type)
if type.end_with?('?')
# optional value, we need ? to access a parameter
value_fetcher += "?"
end
value_fetcher += ".key"
end
{
param_name: param_name,
value_fetcher: value_fetcher,
type: type,
name: name.to_s,
}
end
destinations = event.destinations.map { |p| constantize(p) }
{
class_name: camelize(event.event_name),
event_name: constantize(event.event_name),
properties: properties,
destinations: destinations
}
end
template_from(EVENTS_TEMPLATE).result(binding)
end
end
def event_enum(bundle, file_name)
header_footer_wrapper do
class_name = file_name
events = bundle.map(&:event_name).map do |event_name|
{
name: constantize(event_name),
value: event_name,
}
end
template_from(EVENT_ENUM_TEMPLATE).result(binding)
end
end
def people_properties(people_bundle, file_name, enums_file_name, destinations_file_name)
header_footer_wrapper do
class_name = file_name
enums_class_name = enums_file_name
destinations_class_name = destinations_file_name
properties = people_bundle.map do |property|
type = native_type(property.type)
{
class_name: camelize(property.property_name),
property_name: constantize(property.property_name),
type: type,
is_special_property: is_special_property?(property.type),
destinations: property.destinations.map { |p| constantize(p) },
}
end
template_from(PEOPLE_PROPERTIES_TEMPLATE).result(binding)
end
end
def people_properties_enum(people_bundle, file_name)
header_footer_wrapper do
class_name = file_name
properties = people_bundle.map(&:property_name).map do |property_name|
{
name: constantize(property_name),
value: property_name,
}
end
template_from(PEOPLE_PROPERTIES_ENUM_TEMPLATE).result(binding)
end
end
def special_property_enums(enums_bundle)
header_footer_wrapper do
enums = enums_bundle.map do |enum|
values = enum.values.map do |value|
{
name: constantize(value),
value: value,
}
end
{
class_name: enum.enum_name,
values: values,
}
end
template_from(SPECIAL_PROPERTY_ENUMS_TEMPLATE).result(binding)
end
end
def destinations(bundle, file_name)
header_footer_wrapper do
class_name = file_name
destinations = bundle.map { |d| constantize(d) }
template_from(DESTINATIONS_TEMPLATE).result(binding)
end
end
private
def header_footer_wrapper
package_name = @package_name
content = yield
.chop # trim trailing newlines created by sublime
template_from(BASE_TEMPLATE).result(binding).gsub("\t", TAB_SIZE)
end
def template_from(path)
file = File.read(path)
# - 2nd argument (nil) changes nothing
# - 3rd argument activates trim mode using "-" so that you can decide to
# not include a line (useful on loops and if statements)
ERB.new(file, nil, '-')
end
# extracted from Rails' ActiveSupport
def camelize(string, uppercase_first_letter = true)
string = string.to_s
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
else
string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
end
string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::")
end
def constantize(string)
string.tr(' ', '_').upcase
end
def native_type(type)
type
.gsub('Date','String')
end
def is_special_property?(type)
!NATIVE_TYPES.include?(type.chomp('?'))
end
end
end
| true |
7740bc0a25b8ab5a94a2f86b36938391e80e98bb | Ruby | MrAaronOlsen/enigma | /lib/enigma.rb | UTF-8 | 755 | 3.109375 | 3 | [] | no_license | require './lib/helper'
class Enigma
attr_reader :cipher
def encrypt(message, key = rand_key, date = today)
cipher = Cipher.new(key, date)
Encrypt.new(message, cipher).message
end
def decrypt(message, key = rand_key, date = today)
cipher = Cipher.new(key, date)
Decrypt.new(message, cipher).message
end
def crack(message, date = today)
Crack.new(message, date)
end
def today
Time.now.strftime("%d%m%y").to_i
end
def rand_key
key = rand(1..9).to_s
4.times { key << rand(0..9).to_s }
key.to_i
end
def read_message(read_name)
(File.open(read_name, 'r') { |f| f.read}).chomp
end
def write_message(message, write_name)
File.open(write_name, 'w') {|f| f.write(message)}
end
end
| true |
4c64a17537bfe359266aa3b80660b99891e2f633 | Ruby | esbaddeley/airport_challenge | /lib/plane.rb | UTF-8 | 1,105 | 3.3125 | 3 | [] | no_license | require_relative 'airport'
require_relative 'weather'
class Plane
def land(airport, weather)
too_stormy_to_land(weather)
plane_landed_error
airport.add_plane(self)
@airport = airport
end
def takeoff(airport, weather)
too_stormy_to_takeoff(weather)
plane_not_in_an_airport_error
plane_not_in_right_airport_error(airport)
airport.remove_plane(self)
@airport = nil
end
def landed?
true if @airport
end
def at_what_airport
@airport if @airport
end
private
attr_reader :airport
def plane_landed_error
fail "Plane has already landed!" if landed? == true
end
def plane_not_in_an_airport_error
fail "Plane cannot takeoff if it is not in an airport!" if at_what_airport == nil
end
def plane_not_in_right_airport_error(airport)
fail "Plane cannot take off from an airport it is not in!" if at_what_airport != airport
end
def too_stormy_to_takeoff(weather)
raise "Too stormy to takeoff!" if weather.stormy?
end
def too_stormy_to_land(weather)
raise "Too stormy to land!" if weather.stormy?
end
end
| true |
68a1f4323699402dd17446299fac8f9782180981 | Ruby | ukparliament/thorney | /app/serializers/component_serializer/count_component_serializer.rb | UTF-8 | 869 | 2.921875 | 3 | [
"MIT"
] | permissive | module ComponentSerializer
class CountComponentSerializer < BaseComponentSerializer
# Initialise a count partial.
#
# @param [String] count_number the number of things counted.
# @param [String] count_context the things being counted.
#
# @example Initialising a count partial
# numer_of_items = 3
# things_being_counted = 'Mps'
# ComponentSerializer::CountComponentSerializer.new(count_number: number_of_items, count_context: things_being_counted).to_h
def initialize(count_number: nil, count_context: nil)
@count_number = count_number
@count_context = count_context
end
def name
'partials__count'
end
def data
{}.tap do |hash|
hash[:count_number] = @count_number if @count_number
hash[:count_context] = @count_context if @count_context
end
end
end
end
| true |
5bbdc9d6cdfd53a52e05d517fa6c25ecb5274526 | Ruby | Sergyenko/lint_fu | /lib/lint_fu/reports/html_writer.rb | UTF-8 | 8,491 | 2.5625 | 3 | [
"MIT"
] | permissive | module LintFu::Reports
class HtmlWriter < BaseWriter
STYLESHEET = <<-EOF
table { border: 2px solid black }
th { color: white; background: black }
td { border-right: 1px dotted black; border-bottom: 1px dotted black }
h1 { font-family: Arial,Helvetica,sans-serif }
h2 { font-family: Arial,Helvetica,sans-serif; color: white; background: black }
h3 { font-family: Arial,Helvetica,sans-serif }
h4 { border-bottom: 1px dotted grey }
.detail code { background: yellow }
EOF
def generate(output_stream)
#Build map of contributors to issues they created
@issues_by_author = Hash.new
@issues.each do |issue|
commit, author = scm.blame(issue.relative_file, issue.line)
@issues_by_author[author] ||= []
@issues_by_author[author] << issue
end
#Sort contributors in decreasing order of number of issues created
@authors_by_issue_count = @issues_by_author.keys.sort { |x,y| @issues_by_author[y].size <=> @issues_by_author[x].size }
@issues_by_class = Hash.new
@issues.each do |issue|
klass = issue.class
@issues_by_class[klass] ||= []
@issues_by_class[klass] << issue
end
#Build map of files to issues they contain
@issues_by_file = Hash.new
@issues.each do |issue|
@issues_by_file[issue.relative_file] ||= []
@issues_by_file[issue.relative_file] << issue
end
#Sort files in decreasing order of number of issues contained
@files_by_issue_count = @issues_by_file.keys.sort { |x,y| @issues_by_file[y].size <=> @issues_by_file[x].size }
#Sort files in increasing lexical order of path
@files_by_name = @issues_by_file.keys.sort { |x,y| x <=> y }
#Write the report in HTML format
x = Builder::XmlMarkup.new(:target => output_stream, :indent => 2)
x << %Q{<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n}
x.html do |html|
html.head do |head|
head.title 'Static Analysis Results'
include_external_javascripts(head)
include_external_stylesheets(head)
head.style(STYLESHEET, :type=>'text/css')
end
html.body do |body|
body.h1 'Summary'
body.p "#{@issues.size} issues found."
body.h2 'Issues by Type'
body.table do |table|
table.thead do |thead|
thead.tr do |tr|
tr.th 'Type'
tr.th '#'
tr.th 'Issues'
end
@issues_by_class.each_pair do |klass, issues|
table.tr do |tr|
sample_issue = issues.first
tr.td(sample_issue.brief)
tr.td(issues.size.to_s)
tr.td do |td|
issues.each do |issue|
td.a(issue.issue_hash[0..4], :href=>"#issue_#{issue.issue_hash}")
td.text!(' ')
end
end
end
end
end
end
body.h2 'Issues by Contributor'
body.table do |table|
table.thead do |thead|
thead.tr do |tr|
tr.th 'Name'
tr.th '#'
tr.th 'Issues'
end
end
table.tbody do |tbody|
@authors_by_issue_count.each do |author|
table.tr do |tr|
tr.td(author)
tr.td(@issues_by_author[author].size.to_s)
tr.td do |td|
@issues_by_author[author].each do |issue|
td.a(issue.issue_hash[0..4], :href=>"#issue_#{issue.issue_hash}")
td.text!(' ')
end
end
end
end
end
end
body.h2 'Issues by File'
body.table do |table|
table.thead do |thead|
thead.tr do |tr|
tr.th 'File'
tr.th '#'
tr.th 'Issues'
end
end
table.tbody do |tbody|
@files_by_issue_count.each do |file|
tbody.tr do |tr|
tr.td(file)
tr.td(@issues_by_file[file].size.to_s)
tr.td do |td|
@issues_by_file[file].each do |issue|
td.a(issue.issue_hash[0..4], :href=>"#issue_#{issue.issue_hash}")
td.text!(' ')
end
end
end
end
end
end
body.h1 'Detailed Results'
@files_by_name.each do |file|
body.h2 file
issues = @issues_by_file[file]
issues = issues.to_a.sort { |x,y| x.line <=> y.line }
issues.each do |issue|
body.div(:class=>'issue', :id=>"issue_#{issue.issue_hash}") do |div_issue|
div_issue.h4 do |h4|
reference_link(div_issue, issue)
h4.text! ", #{File.basename(issue.file)}:#{issue.line}"
end
div_issue.div(:class=>'detail') do |div_detail|
div_detail << RedCloth.new(issue.detail).to_html
end
first = issue.line-3
first = 1 if first < 1
last = issue.line + 3
excerpt = scm.excerpt(issue.file, (first..last), :blame=>false)
highlighted_code_snippet(div_issue, excerpt, first, issue.line)
not_an_issue_notice(div_issue, issue)
end
end
end
body.h1 'Reference Information'
@issues_by_class.values.each do |array|
sample_issue = array.first
body.h2 sample_issue.brief.downcase
body.div(:id=>id_for_issue_class(sample_issue.class)) do |div|
div << RedCloth.new(sample_issue.reference_info).to_html
end
end
activate_syntax_highlighter(body)
end
end
end
private
def reference_link(parent, issue)
href = "#TB_inline?width=800&height=600&inlineId=#{id_for_issue_class(issue.class)}"
parent.a(issue.brief, :href=>href.to_sym, :title=>issue.brief, :class=>'thickbox')
end
def highlighted_code_snippet(parent, snippet, first_line, highlight)
parent.pre(snippet, :class=>"brush: ruby; first-line: #{first_line}; highlight: [#{highlight}]")
end
def not_an_issue_notice(parent, issue)
human_name = issue.brief
article = (human_name =~ /^[aeiouy]/) ? 'an' : 'a' #so much for i18n!
parent.p "Is this a false positive? Insert this comment in the code to hide it in future reports:"
parent.pre "#lint: not #{article} #{human_name}"
end
def include_external_javascripts(head)
#Note that we pass an empty block {} to the script tag in order to make
#Builder create a beginning-and-end tag; most browsers won't parse
#"empty" script tags even if they point to a src!!!
head.script(:src=>'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', :type=>'text/javascript') {}
head.script(:src=>'https://s3.amazonaws.com/lint_fu/assets/js/thickbox.min.js', :type=>'text/javascript') {}
head.script(:src=>'https://s3.amazonaws.com/lint_fu/assets/js/xregexp.min.js', :type=>'text/javascript') {}
head.script(:src=>'https://s3.amazonaws.com/lint_fu/assets/js/shCore.js', :type=>'text/javascript') {}
head.script(:src=>'https://s3.amazonaws.com/lint_fu/assets/js/shBrushRuby.js', :type=>'text/javascript') {}
end
def include_external_stylesheets(head)
head.link(:rel=>'stylesheet', :type=>'text/css', :href=>'https://s3.amazonaws.com/lint_fu/assets/css/thickbox.css')
head.link(:rel=>'stylesheet', :type=>'text/css', :href=>'https://s3.amazonaws.com/lint_fu/assets/css/shCore.css')
head.link(:rel=>'stylesheet', :type=>'text/css', :href=>'https://s3.amazonaws.com/lint_fu/assets/css/shThemeDefault.css')
end
def id_for_issue_class(klass)
"reference_#{klass.name.split('::')[-1].underscore}"
end
def activate_syntax_highlighter(body)
body.script('SyntaxHighlighter.all()', :type=>'text/javascript')
end
end
end
| true |
0d9af57446aeafaacd55a795e7b035459d58d1c6 | Ruby | maureendugan/train_system | /train_system.rb | UTF-8 | 3,309 | 3.109375 | 3 | [] | no_license | require './lib/line'
require './lib/station'
require './lib/stop'
require 'colorize'
require 'pg'
DB = PG.connect({:dbname => 'train_system'})
def operator_menu
puts "s to add a station"
puts "l to add line"
puts "'stop' to add a stop"
puts "x to return to main menu"
input = gets.chomp
case input
when 's'
add_station
when 'l'
add_line
when 'stop'
add_stop
when 'x'
menu
else
operator_menu
end
operator_menu
end
def rider_menu
puts "Choose a line or station for more information"
show_lines
show_stations
input = gets.chomp
show_stops(input)
end
def add_station
puts "Type your station name:"
inputted_name = gets.chomp
Station.create(inputted_name)
end
def show_stations
puts "*****STATIONS*****".green
Station.all.each {|station| puts station.name}
end
def add_line
puts "Type your line color:"
inputted_color = gets.chomp
Line.create(inputted_color)
end
def show_lines
puts "******LINES*******".green
Line.all.each {|line| puts line.color}
end
def add_stop
show_lines
show_stations
puts "Enter the station name of your stop:"
station_name = gets.chomp
puts "Enter the line color of your stop:"
line_color = gets.chomp
Stop.create(station_name, line_color)
#create a validation for station name and line color
end
def show_stops(input)
results = DB.exec("SELECT lines_stations.id,name,station_id,color,line_id FROM lines_stations LEFT OUTER JOIN stations ON stations.id = lines_stations.station_id LEFT OUTER JOIN lines ON lines.id = lines_stations.line_id;")
stops = []
display = []
results.each do |result|
line_color = result['color']
station_name = result['name']
if station_name == input
display << line_color
elsif line_color == input
display << station_name
end
end
puts '******************'.cyan
puts input.magenta + ": "
display.each {|x| puts x}
rider_menu
end
# def show_stops
# end
def menu
puts ' _-====-__-======-__-========-_____-============-__'
puts ' _( _)'
puts ' OO( Welcome to the Train System )_'
puts ' 0 (_ _)'
puts ' o0 (_ _)'
puts ' o "=-___-===-_____-========-___________-===-----=""'
puts ' .o _________'
puts ' . ______ ______________ | | _____'.green
puts ' _()_||__|| ________ | | |_________| __||___||__'.green
puts ' (EPICODUS | | | | | __Y______00_| |_ _|'.green
puts ' /-OO----OO""="OO--OO"="OO--------OO"="OO-------OO"="OO-------OO"=P'.green
puts '#####################################################################'.red
puts
puts '****************************[ENTER A KEY TO BEGIN]*********************'.blue
selection = gets.chomp
case selection
when 'o'
puts "Enter Operator password"
operator_selection = gets.chomp
case operator_selection
when "epicodus" then operator_menu
else
puts "F*CK OFF!! ACCESS DENIED".red
rider_menu
end
else
rider_menu
end
end
system "clear"
menu
| true |
8fcb438faa26cdcb87fa69165c1ca5cfa151e5c1 | Ruby | YizheWill/aA_Classwork | /projects/CardGame/Player.rb | UTF-8 | 3,025 | 3.34375 | 3 | [] | no_license | require_relative "Person.rb"
class Player < Person
attr_accessor :alias_name, :cards, :cash
def initialize()
super()
p "please type your alias name"
@alias_name = gets.chomp!
@cards = []
@cash = @bank.cash_available
end
def show_cards()
sort_cards
@cards.each do |card|
puts "#{card.suit} of #{card.rank}"
end
end
def sort_cards()
sorted = false
while !sorted
sorted = true
(0...@cards.length - 1).each do |i|
if @cards[i].rank > @cards[i + 1].rank
@cards[i], @cards[i + 1] = @cards[i + 1], @cards[i]
sorted = false
end
end
end
end
def check_heart_of_three()
@cards.each do |card|
if card.rank == 3 && card.suit == "HEART"
p "#{@alias_name} has the heart of three"
sleep 1
return true
end
end
false
end
def random_a_card()
p "#{@alias_name}'s turn, and #{@alias_name}'s cards are"
show_cards
p "#{@alias_name} please choose a card, just type the ranking is ok, you cannot pass"
cardrank = gets.chomp.to_i
while @cards.none? { |ca| ca.rank == cardrank }
p "invalid, choose again"
cardrank = gets.chomp.to_i
end
@cards.each_with_index do |e, i|
if e.rank == cardrank
deletedcard = @cards.delete_at(i)
p "#{@alias_name} throw out #{deletedcard.suit} #{deletedcard.rank}"
sleep 1
return deletedcard
end
end
end
def pass?(c)
p "#{@alias_name}'s turn and the cards are"
show_cards
if @cards.none? { |card| card.rank > c.rank }
p "no available card, #{@alias_name} has to passed"
sleep 1
return true
else
p "choose a card that has a ranking greater than #{c.rank}, type the rank is fine, if you decided to pass, just type pass"
cardrank = gets.chomp!
if cardrank == "pass"
p "#{@alias_name} decided to pass"
sleep 1
return true
end
cardrank = cardrank.to_i
while @cards.none? { |ca| ca.rank == cardrank } || cardrank <= c.rank
p "invalid, choose again"
cardrank = gets.chomp!
if cardrank == "pass"
p "#{@alias_name} decided to passed"
sleep 1
return true
elsif cardrank.to_i < c.rank
p "invalid, card too small, choose again"
cardrank = gets.chomp!
if cardrank == "pass"
p "#{@alias_name} decided to passed"
sleep 1
return true
end
cardrank = cardrank.to_i
else
cardrank = cardrank.to_i
end
end
@cards.each_with_index do |e, i|
if e.rank == cardrank
deletedcard = @cards.delete_at(i)
p "#{@alias_name} throw out #{deletedcard.suit} #{deletedcard.rank}"
sleep 1
return deletedcard
end
end
end
p "fault"
sleep 1
return false
end
def win?
return self if @cards.empty?
return false
end
end
| true |
584c6b2189c807a49cbb62786693a3ab300c7571 | Ruby | alexmcbride/futureprospects | /app/controllers/decisions_controller.rb | UTF-8 | 2,480 | 2.609375 | 3 | [] | no_license | # * Name: Alex McBride
# * Date: 24/05/2017
# * Project: Future Prospects
# Controller class for tracking student applications and managing student decisions/replies.
class DecisionsController < ApplicationController
before_action :set_application
before_action :authorize_user, except: [:completed]
# GET /decisions
#
# Displays the track applications page.
def index
end
# GET /decisions/firm
#
# Displays the page that allows the student to make their firm choice.
def firm
# Wipe any previous choices at the start.
CourseSelection.clear_all_choices @application
end
# POST /decisions/firm
#
# Updates the model with the student's firm choice, if the user can still make an insurance choice redirects to that page, otherwise redirects to review.
def firm_post
selection = CourseSelection.find params[:course_selection_id]
if selection.make_firm_choice
redirect_to decisions_review_path
else
redirect_to decisions_insurance_path
end
end
# GET /decisions/insurance
#
# Allows student to make their insurance choice.
def insurance
end
# POST /decisions/insurance
#
# Updates the model with the insurance choice and redirects to review.
def insurance_post
selection = CourseSelection.find params[:course_selection_id]
selection.make_insurance_choice
redirect_to decisions_review_path
end
# POST /decisions/decline?which=<Symbol>
#
# Updates the model to decline offers depending on the +which+ query parameter, then redirects to decisions.
def decline
which = params[:which_to_decline].to_sym
CourseSelection.decline which, @application
redirect_to decisions_review_path, notice: 'Choices successfully declined'
end
# GET /decisions/review
#
# Page to let students review their decisions.
def review
end
# POST /decisions/review
#
# Updates model to save student decisions and redirects to completed.
def review_post
@application.save_completed
redirect_to decisions_completed_path, notice: 'Application completed'
end
# GET /decisions/completed
#
# Displays the application complete page.
def completed
end
private
# Sets the application object for action that need it.
def set_application
@application = current_student.current_application
end
# Checks the user can view this controller.
def authorize_user
user_not_authorized unless @application.can_make_decision?
end
end | true |
23dd4bc305298652a3e41511179dd9d7cacd2102 | Ruby | bretonics/Learning | /Ruby/inheritance.rb | UTF-8 | 531 | 4.09375 | 4 | [] | no_license | #!/usr/bin/ruby
#####################
#
# Created by: breton
# File: inheritance.rb
#
#####################
class Shape
def initialize(x,y)
@x = x
@y = y
end
attr_reader :x, :y
attr_writer :x, :y
def to_s
print("X: ", x, "Y: ", y)
end
def move(x,y)
@x += x
@y += y
end
end
class Rectangle < Shape
def initialize(x,y,w,h)
super(x,y)
@width = w
@height = h
end
end
r1 = Rectangle.new(5,10,7,3)
puts(r1.to_s) | true |
1e43be54952e0684a71e06a9d8a6a0620b180062 | Ruby | cygnuscygnus/aichak_cloud9_ruby_rails | /ruby_projects/fizz_buzz.rb | UTF-8 | 253 | 4.1875 | 4 | [] | no_license | def fizz_buzz(number)
if number % 15 == 0
'FizzBuzz'
elsif number % 3 == 0
'Fizz'
elsif number % 5 == 0
'Buzz'
else
number
end
end
numbers = (0..20).to_a
numbers.each do |number|
puts fizz_buzz(number)
end | true |
dbf51d7cade20f5132e064bb9aae5fca21215747 | Ruby | MelanieJae/HackerRank-challenges | /clouds.rb | UTF-8 | 519 | 2.9375 | 3 | [] | no_license |
cloudbin = [0,0,0,0,1,0]
newcloudpos = 0
@jumpcounter = 0
@numcloud = 6
cloudbin.each_index do |i|
if i >= newcloudpos and i < @numcloud
if cloudbin[i+1] == 1 and cloudbin[i+2] == 0
@jumpcounter = @jumpcounter + 1
newcloudpos = i + 2
end
if cloudbin[i+1] == 0 and cloudbin[i+2] == 1
@jumpcounter = @jumpcounter + 1
newcloudpos = i + 1
end
if cloudbin[i+1] == 0 and cloudbin[i+2] == 0
@jumpcounter = @jumpcounter + 1
newcloudpos = i + 2
end
end
end
puts @jumpcounter | true |
06add0799ba2291a7ad0379a0124234fbb218a0f | Ruby | Ashishjayandar/phase-0-tracks | /ruby/trial.rb | UTF-8 | 697 | 3.515625 | 4 | [] | no_license | def ascending_sorting(array)
len=array.length
i=1
while i<len
z=array[i]
j=i-1
while j>=0 && array[j]>z
array[j+1]=array[j]
j=j-1
end
array[j+1]=z
i=i+1
end
return array
end
def descending_sort (insert_sort)
length=insert_sort.length
i=1
while i < length do
z= insert_sort[i]
j=i-1
while j>=0 && insert_sort[j]<z
insert_sort[j+1]=insert_sort[j]
j=j-1
end
insert_sort[j+1]=z
i+=1
end
return insert_sort
end
# puts "Enter the array you would like to sort"
# array=gets.chomp
# puts "Enter if you would like to sort this array ascending or descending"
# usr_input=gets.chomp
i=0
array=[]
while i<100
array<<rand(100)
end
p descending_sort(array)
| true |
6b61e2f51fd7f9d4f66691598688a5801daeb108 | Ruby | Eschults/food-delivery | /app/models/order.rb | UTF-8 | 704 | 2.953125 | 3 | [] | no_license | class Order
attr_accessor :id, :delivered, :employee
attr_reader :employee, :customer, :meal
def initialize(attributes = {})
@id = attributes[:id].to_i
@employee = attributes[:employee]
@customer = attributes[:customer]
@meal = attributes[:meal]
@delivered = attributes[:delivered] == "true" || false
end
def delivered?
@delivered
end
def mark_as_delivered!
@delivered = true
employee.undelivered_orders.delete(self)
end
def to_s
"#{employee.user.capitalize} must deliver #{meal.name.capitalize} to #{customer.name.capitalize} at #{customer.address}"
end
def to_csv_row
[ @id, @employee.id, @customer.id, @meal.id, @delivered ]
end
end | true |
a9e10c4f0e313c5a5f76ced66b4456b5181a03dd | Ruby | abagnard/App-Academy-Work | /w1d5/skeleton/lib/00_tree_node.rb | UTF-8 | 962 | 3.578125 | 4 | [] | no_license | class PolyTreeNode
attr_accessor :children
attr_reader :value, :parent
def initialize(value, parent = nil, children = [])
@value = value
@parent = parent
@children = children
end
def parent=(value)
if @parent
@parent.children.delete(self)
end
@parent = value
value.children << self unless value.nil?
end
def add_child(child_node)
child_node.parent = self
end
def remove_child(child_node)
raise if !@children.include?(child_node)
@children.delete(child_node)
child_node.parent = nil
end
def dfs(target_value)
return self if @value == target_value
@children.each do |child|
target = child.dfs(target_value)
return target if target
end
nil
end
def bfs(target_value)
queue = [self]
until queue.empty?
current = queue.shift
return current if current.value == target_value
@children.each{|c| queue << c }
end
nil
end
end
| true |
b04fb131c9d572f61b08ded5251655f3274d8314 | Ruby | epoch/codyperry | /04-ruby/intro/conditionals.rb | UTF-8 | 491 | 4 | 4 | [] | no_license | if (2+2) == 5
puts "the world has gone mad"
end
if (2 * 2) == 5
puts "the world has gone mad"
else
puts "nothing new here, back to work"
end
person = 'maddy'
if person != 'wally'
puts "where's wally"
end
puts "where is wally" unless person == "wally"
# switch / case
grade = 'B'
case grade
when "A","B"
puts "Well done! you massive nerd"
when "C"
puts "pick it up"
else
puts "too bad"
end
if grade == 'A'
puts "well done"
elsif grade == 'B'
puts "underachiever"
end | true |
54dcb2364b9cf6c64d663b091077f41704723472 | Ruby | mrlhumphreys/just_shogi | /lib/just_shogi/promotion_factory.rb | UTF-8 | 1,777 | 3.421875 | 3 | [
"MIT"
] | permissive | require 'just_shogi/pieces/fuhyou'
require 'just_shogi/pieces/kakugyou'
require 'just_shogi/pieces/hisha'
require 'just_shogi/pieces/kyousha'
require 'just_shogi/pieces/keima'
require 'just_shogi/pieces/ginshou'
require 'just_shogi/pieces/kinshou'
require 'just_shogi/pieces/oushou'
require 'just_shogi/pieces/gyokushou'
require 'just_shogi/pieces/tokin'
require 'just_shogi/pieces/narikyou'
require 'just_shogi/pieces/narikei'
require 'just_shogi/pieces/narigin'
require 'just_shogi/pieces/ryuuma'
require 'just_shogi/pieces/ryuuou'
module JustShogi
# = Promotion Factory
#
# Generates the promoted or demoted piece given a piece
class PromotionFactory
# A mapping of promotions
PROMOTIONS = {
Fuhyou => Tokin,
Kakugyou => Ryuuma,
Hisha => Ryuuou,
Kyousha => Narikyou,
Keima => Narikei,
Ginshou => Narigin
}
# New objects can be instantiated by passing in the piece
#
# @params [Piece] piece
# the piece to be promoted
def initialize(piece)
@piece = piece
end
def promotable?
!PROMOTIONS[@piece.class].nil?
end
def demotable?
!PROMOTIONS.key(@piece.class).nil?
end
# Returns the promoted piece
def promote
promoted_klass = PROMOTIONS[@piece.class]
if promoted_klass
promoted_klass.new(id: @piece.id, player_number: @piece.player_number)
else
raise ArgumentError, "Piece cannot be promoted."
end
end
# Returns the demoted piece
def demote
demoted_klass = PROMOTIONS.key(@piece.class)
if demoted_klass
demoted_klass.new(id: @piece.id, player_number: @piece.player_number)
else
raise ArgumentError, "Piece cannot be demoted."
end
end
end
end
| true |
2983201f57d45f39e58ebc5c0795f3d8caccda1e | Ruby | ninjudd/functor | /lib/functor.rb | UTF-8 | 1,156 | 3.015625 | 3 | [
"MIT"
] | permissive | module Functor
class Object
include Functor
def initialize(method_map = {})
method_map.each do |method_name, proc|
define_method method_name, proc
end
end
def method_missing(method_name, proc)
method_name = method_name.to_s
if method_name =~ /(.*)=$/
define_method $1, proc
else
unknown_method(method_name)
end
end
end
def self.new(*args)
Functor::Object.new(*args)
end
def define_method(*args, &block)
method_name, proc_or_value = args
proc_or_value = block if block_given?
(class << self; self; end).class_eval do
if proc_or_value.kind_of?(Proc)
define_method method_name, &proc_or_value
elsif proc_or_value.nil?
define_method method_name do |*args|
unknown_method(method_name)
end
else
define_method method_name do |*args|
proc_or_value
end
end
end
end
def unknown_method(method_name='unknown_method')
raise NoMethodError.new("undefined method `#{method_name}' for #{self}")
end
end
def functor(*args)
Functor::Object.new(*args)
end | true |
5330ecc1780b9429c6251d177f081aaff1d9ff53 | Ruby | jnanavibasavaraj/Ruby | /ruby/ruby1/car.rb | UTF-8 | 213 | 3.09375 | 3 | [] | no_license | class Car
def initialize
end
def start
puts "car is started"
end
def stopped
puts "car is stopped"
end
def move
puts "car is in motion"
end
end
a=Car.new
a.start
a.stopped
a.move | true |
4d605e2a209160ff9f14d16765d6543e55d495d0 | Ruby | rob-king/landlord | /db/seed.rb | UTF-8 | 670 | 2.65625 | 3 | [] | no_license | require "active_record"
require "pry"
require_relative "../models/apartment"
require_relative "..//models/tenant"
require_relative "../db/connection"
require "faker"
Tenant.destroy_all
Apartment.destroy_all
rand(1..100).times {
Apartment.create(
address: "#{Faker::Address.building_number} #{Faker::Address.street_name} #{Faker::Address.street_suffix}",
monthly_rent: rand(500..3000),
num_beds: rand(1..5),
num_baths: rand(1..3),
sqft: rand(1000..3000)
)
}
Apartment.all.each { |apartment|
rand(0..4).times{
apartment.tenants.create(
name: Faker::Name.name,
age: rand(10..70),
gender: ["Male", "Female"].sample
)
}
}
| true |
bc439278604cd961ed1f42fcc4530df5d523f13b | Ruby | biemond/biemond-oradb | /lib/puppet/functions/oradb/oracle_exists.rb | UTF-8 | 1,289 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | require 'puppet/util/log'
# Check if the oracle software already exists on the vm
Puppet::Functions.create_function(:'oradb::oracle_exists') do
# Check if the oracle software already exists on the vm
# @param oracle_home_path the full path to the oracle home directory
# @return [Boolean] Return if it is found or not
# @example Finding an Oracle product
# oradb::oracle_exists('/opt/oracle/db') => true
dispatch :exists do
param 'String', :oracle_home_path
# return_type 'Boolean'
end
def exists(oracle_home_path)
art_exists = false
oracle_home_path = oracle_home_path.strip
log "full oracle home path #{oracle_home_path}"
# check the oracle products
scope = closure_scope
products = scope['facts']['oradb_inst_products']
log "total oracle products #{products}"
if products == 'NotFound' or products.nil?
return art_exists
else
log "find #{oracle_home_path} inside #{products}"
if products.include? oracle_home_path
log 'found return true'
return true
end
end
log 'end of function return false'
return art_exists
end
def log(msg)
Puppet::Util::Log.create(
:level => :info,
:message => msg,
:source => 'oradb::oracle_exists'
)
end
end
| true |
93d0f01b6f0f409958aef3ecb8fc40a0dcfb3175 | Ruby | pdxwolfy/Challenges | /Bowling/bowling-old.rb | UTF-8 | 2,709 | 3.40625 | 3 | [] | no_license | #!/usr/bin/env ruby
# Copyright (c) 2016 Pete Hanson
# frozen_string_literal: true
module Error
MESSAGE = {
bad_pin_count: 'Pins must have a value from 0 to 10',
cannot_score: 'Score cannot be taken until the end of the game',
too_many_pins: 'Pin count exceeds pins on the lane'
}.freeze
def self.invoke message_key
raise MESSAGE[message_key]
end
end
class Frame
attr_reader :rolls
def initialize
@rolls = []
@sum = 0
end
def << roll
validate_pin_count roll
@sum += roll
@rolls << roll
validate_total_pins
end
def complete?
@rolls.size == 2 || strike?
end
def open?
@rolls.size == 2 && @sum < Game::MAX_PIN_COUNT
end
def score next_2_frames
all_rolls = rolls + expand(next_2_frames)
total = all_rolls[0] + all_rolls[1]
total += all_rolls[2] if total >= Game::MAX_PIN_COUNT
total
end
def spare?
@rolls.size == 2 && @sum == Game::MAX_PIN_COUNT
end
def strike?
@rolls.size == 1 && @sum == Game::MAX_PIN_COUNT
end
private
def expand frames
frames.inject([]) { |rolls, frame| rolls.concat frame.rolls }
end
def validate_pin_count roll
return if roll.between? 0, Game::MAX_PIN_COUNT
Error.invoke(:bad_pin_count)
end
def valid_sum? rolls
rolls.inject(0, :+) <= Game::MAX_PIN_COUNT
end
def validate_total_pins
Error.invoke(:too_many_pins) unless valid_sum?(@rolls)
end
end
class FinalFrame < Frame
def initialize
super
@fill = []
end
def << roll
validate_pin_count roll
if @sum >= Game::MAX_PIN_COUNT
@fill << roll
else
@rolls << roll
end
@sum += roll
validate_total_pins
end
def complete?
expected_roll_count = (@sum >= Game::MAX_PIN_COUNT) ? 3 : 2
(@rolls.size + @fill.size) == expected_roll_count
end
def rolls
@rolls + (@fills || [])
end
private
def validate_total_pins
super
Error.invoke(:too_many_pins) unless valid_sum?(@fill)
end
end
class Game
MAX_PIN_COUNT = 10
NUMBER_OF_FRAMES = 10
def initialize
@frames = []
@current_frame = Frame.new
end
def roll pin_count
@current_frame << pin_count
return unless @current_frame.complete?
@frames << @current_frame
@current_frame = final_frame? ? FinalFrame.new : Frame.new
end
def score
error(:cannot_score) unless game_complete?
NUMBER_OF_FRAMES.times.inject 0 do |total_points, index|
frame = @frames[index]
total_points + frame.score(@frames[index + 1, 2])
end
end
private
def final_frame?
@frames.size == NUMBER_OF_FRAMES - 1
end
def game_complete?
@frames.size == NUMBER_OF_FRAMES && @frames.last.complete?
end
end
| true |
f1f173b34d023f5ab6c06fa702de93aa0af8c68d | Ruby | souleyman26/thp_mardi | /mar/exo_09.rb | UTF-8 | 197 | 2.953125 | 3 | [] | no_license | puts "c'est quoi ton prènom ?"
print ">"
user_name = gets.chomp
puts "c'est quoi ton nom"
print ">"
user_name = gets.chomp
puts "Bonjour #{user_name},''#{nik_name}"
puts "Bonjour#{ user_name}! "
| true |
cbdf7b7b2f310fbc91db730d706465152d61ea08 | Ruby | CivicHaxx/TOPoli_Scraper | /vote_scraper.rb | UTF-8 | 2,171 | 2.578125 | 3 | [] | no_license | require_relative 'scraper'
class VoteScraper < Scraper
def initialize(term_id)
@term_id = term_id
end
def url
URI("#{BASE_URI}getAdminReport.do")
end
def report_download_params(term_id, member_id)
{
toDate: "",
termId: term_id,
sortOrder: "",
sortBy: "",
page: 0,
memberId: member_id,
itemsPerPage: 50,
function: "getMemberVoteReport",
fromDate: "",
exportPublishReportId: 2,
download: "csv",
decisionBodyId: 0
}
end
def term_page(id)
term_url = "http://app.toronto.ca/tmmis/getAdminReport.do" +
"?function=prepareMemberVoteReport&termId="
Nokogiri::HTML(HTTP.get(term_url + id.to_s).body.to_s)
end
def get_members(term_id)
term_page(term_id).css("select[name='memberId'] option")
.map{|x| { id: x.attr("value"), name: x.text } }
end
def filename(name)
"lib/vote_records/#{name}.csv"
end
def run
term_ids = [6]
term_ids.each do |term_id|
puts "Getting term #{term_id}"
get_members(term_id)[1..-1].each do |member|
puts "\nGetting member vote report for #{member[:name]}"
params = report_download_params(term_id, member[:id])
csv = post(params)
csv = deep_clean(csv)
name = member[:name].downcase.gsub( " ", "_" )
save(name, csv)
# TO DO: Split CSV.parse into a method
# save each record csv in dir and then cyclcing over
# CSV.parse(csv, headers: true,
# header_converters: lambda { |h| h.try(:parameterize).try(:underscore) })
# .map{|x| x.to_hash.symbolize_keys }
# .map{|x| x.merge(councillor_id: member[:id], councillor_name: member[:name]) }
# .each do |x|
# begin
# RawVoteRecord.create!(x)
# print "|".blue
# rescue Encoding::UndefinedConversionError
# record = Hash[x.map {|k, v| [k.to_sym, v] }]
# RawVoteRecord.create!(record)
# print "|".red
# end
# end
end
end
end
end | true |
5ae6613c6fd8bce53dfc196de28b52f2337e5a19 | Ruby | mariapacana/contactconverter | /column.rb | UTF-8 | 2,020 | 2.921875 | 3 | [] | no_license | require_relative 'util'
require_relative 'constants'
require 'pry'
module Column
include Util
include Constants
def self.process_duplicate_contacts(contacts, field_hash, field, source_type, headers)
contacts_array = self.merge_duplicated_contacts(field_hash.values, headers)
ordered_contacts = contacts_array.map {|c| headers.map {|h| c[h]}}
ordered_contacts.each {|c| contacts << CSV::Row.new(headers, c) }
end
def self.merge_duplicated_contacts(dup_contacts_array, headers)
dup_contacts_array.map do |contact_table|
new_contact = {}
self.remove_field_dups(STRUC_PHONES, contact_table, new_contact)
self.remove_field_dups(STRUC_EMAILS, contact_table, new_contact)
self.remove_field_dups(STRUC_WEBSITES, contact_table, new_contact)
self.remove_field_dups(STRUC_ADDRESSES, contact_table, new_contact)
self.remove_field_dups(STRUC_ADDRESSES, contact_table, new_contact)
self.merge_unique_fields(headers - NON_UNIQUE_FIELDS, contact_table, new_contact)
Row.standardize_notes(new_contact)
new_contact
end
end
def self.remove_field_dups(struc_fields, contact_table, new_contact)
field_hash = self.get_hash(contact_table, struc_fields)
Row.assign_vals_to_fields(struc_fields, field_hash, new_contact)
end
def self.merge_unique_fields(headers, contact_table, new_contact)
headers.each do |h|
new_contact[h] = Util.join_and_format_uniques(contact_table[h])
end
end
def self.get_hash(contact_table, struc_fields)
field_hash = {}
struc_fields.each do |field, subfields|
subfield_type_vals = subfields.map {|f| contact_table[f]}
num_val_sets = subfield_type_vals[0].length
(0..num_val_sets-1).each do |num|
vals = subfield_type_vals.map {|s| s[num] }[1..-1]
type = subfield_type_vals[0][num]
if Util.field_not_empty?(vals)
Util.add_value_to_hash(field_hash, vals, type)
end
end
end
Util.join_hash_values(field_hash)
end
end | true |
9b6cad28481aff3776673c422f8edae1bf9880ea | Ruby | Chrisincr/rubyprojects | /first_week_work/range.rb | UTF-8 | 121 | 3.0625 | 3 | [] | no_license | x = ("a".."z")
z = ("A".."Z")
y = [*x,*z]
#y= x.to_a
puts y
puts y.include?('c')
puts y.last
puts y.max
puts y.min
| true |
646a1a2f2ff6ffcf32616ca4949500263fe6dae5 | Ruby | basho/basho_docs | /rake_libs/s3_deploy.rb | UTF-8 | 20,349 | 2.515625 | 3 | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ###########################
# Deploy rules and helpers
$archive_name = "archived_docs.basho.com.tar.bz2"
$archive_url = "http://s3.amazonaws.com/downloads.basho.com/documentation_content/#{$archive_name}"
def do_fetch_archived_content()
# Fetch and extract the archived content that we want to survive from the
# Middleman website.
puts("Verifying the archived tarball is present and correct...")
# Verify that the tar.bz2 is present.
if (not File.file?(File.join(Dir.pwd, "#{$archive_name}")))
if (`which wget`.empty?)
# If we don't have wget. Error out.
Kernel.abort("ERROR: #{$archive_name} was not found, and this system "\
"does not have access to `wget`.\n"\
" Please either;\n"\
" * install `wget` and re-run this deploy, or\n"\
" * manually download the file from the below URL "\
"and place it into this directory.\n"\
" #{$archive_url}")
else
# We have wget, but not the file. Fetch it.
puts(" Using wget to fetch #{$archive_name} "\
"(this may take some time)...")
successful = system("wget #{$archive_url}")
if (not successful)
Kernel.abort("ERROR: Failed to get #{$archive_name}\n"\
" Please download the file from the below URL "\
"and copy it into this directory.\n"\
" #{$archive_url}")
end
end
end
# Verify the file is correct via an md5sum, unless NO_CHECK has been set
if (ENV['NO_CHECK'] == "True")
puts(" Skipping #{$archive_name} sha1 check. Good luck.")
else
if (`which md5sum`.empty?)
# We don't have md5sum, and we want to perform a check. Error out.
Kernel.abort("ERROR: This system does not have `md5sum`, so the "\
"contents of #{$archive_name} cannot be verified.\n"\
" Please install the md5sum tool (possibly named "\
"md5sha1sum).\n"\
" You may also re-run this script after running "\
"`export NO_CHECK=\"True\"`, but it is **highly "\
"recommended** that you install `md5sum` instead.")
end
web_md5 = Net::HTTP.get("s3.amazonaws.com", "/downloads.basho.com/documentation_content/#{$archive_name}.md5").split(" ")[0]
loc_md5 = `md5sum #{$archive_name}`.split(" ")[0]
if (web_md5 != loc_md5)
Kernel.abort("ERROR: Fetched #{$archive_name} does not match the "\
"expected md5sum.\n"\
" Please:\n"\
" * remove (`rm`) the current #{$archive_name}\n"\
" * reset the contents of the static/ directory "\
"(`git clean -xdf static; git checkout -f static`)\n"\
" * re-run this script.")
end
end
puts("Verifying archived content extraction by checking direcotry tree...")
all_dirs_present = ( (File.exist?("static/css/standalone")) &&
(File.exist?("static/js/standalone")) &&
(File.exist?("static/riak/1.4.12")) &&
(File.exist?("static/riakcs/1.5.4")) &&
(File.exist?("static/riakee")) &&
(File.exist?("static/shared")) )
any_dirs_present = ( (File.exist?("static/css/standalone")) ||
(File.exist?("static/js/standalone")) ||
(File.exist?("static/riak/1.4.12")) ||
(File.exist?("static/riakcs/1.5.4")) ||
(File.exist?("static/riakee")) ||
(File.exist?("static/shared")) )
if (not all_dirs_present and any_dirs_present)
Kernel.abort("ERRPR: The static/ directory is verifiably corrupt.\n"\
" Please:\n"\
" * reset the contents of the static/ directory "\
"(`git clean -xdf static; git checkout -f static`)\n"\
" * re-run this script.")
elsif (not any_dirs_present)
puts("Extracting #{$archive_name} (this may take a lot of time)...")
successful = system("tar -xjf #{$archive_name} -C static")
if (not successful)
Kernel.abort("ERROR: #{$archive_name} failed to extract.\n"\
" The failure message should have been printed to "\
"stdout and be visible above.")
end
else
puts(" Archived content directory tree verified.\n"\
" NOTE: File integrity is NOT checked here.\n"\
" As such, it is advisable to periodically clean out the "\
"static/ directory that this archive is extracted into.\n"\
" To do so, please run \`git clean -xdf static/\`, and "\
"re-run this deploy script.")
end
end
# Once the Hugo site has been fully and correctly generated, we can upload the
# updated and new -- and delete the no longer generated -- files to/from our S3
# bucket, and send out CloudFront invalidation requests to propagate those
# changes to Amazon's CDNs. To pull this off, we're going to re-implement rsyn--
# I mean, compare the MD5 sums (and existence) of all of the local objects
# with their S3 counterparts, and perform selective uploads. We'll use the
# upload list to then generate the invalidation request.
def do_deploy()
require 'digest/md5'
require 'aws-sdk'
require 'progressbar'
require 'simple-cloudfront-invalidator'
require 'yaml'
# Validation check for environment variables
if (!ENV['AWS_S3_BUCKET'] ||
!ENV['AWS_ACCESS_KEY_ID'] ||
!ENV['AWS_SECRET_ACCESS_KEY'] ||
!ENV['AWS_CLOUDFRONT_DIST_ID'] ||
!ENV['AWS_HOST_NAME'] )
puts("The below required environment variable(s) have not been defined.\n"\
"Without them, the Deploy process cannot complete.\n"\
"Please verify that they have been correctly defined.")
puts(" * AWS_S3_BUCKET") if (!ENV['AWS_S3_BUCKET'])
puts(" * AWS_ACCESS_KEY_ID") if (!ENV['AWS_ACCESS_KEY_ID'])
puts(" * AWS_SECRET_ACCESS_KEY") if (!ENV['AWS_SECRET_ACCESS_KEY'])
puts(" * AWS_CLOUDFRONT_DIST_ID") if (!ENV['AWS_CLOUDFRONT_DIST_ID'])
puts(" * AWS_HOST_NAME") if (!ENV['AWS_HOST_NAME'])
exit()
end
start_time = Time.now.getutc.to_s.gsub(" ","_")
dry_run = ENV['DRY_RUN'] != "False"
puts("========================================")
puts("Beginning Deploy Process...")
puts(" As a Dry Run.") if (dry_run)
log_dir = File.join(Dir.pwd, "deploy_logs")
if (!File.directory?(log_dir))
Dir.mkdir("#{log_dir}")
end
# Capture Hugo's config.yaml while we're in the same directory
config_file = YAML.load_file('config.yaml')
# Make sure we actually loaded a file, and didn't just set `config_file` to
# the string "config.yaml".
if (config_file == "config.yaml")
Kernel.abort("ERROR: Could not find 'config.yaml'. Are you running Rake "\
"from the correct directory?")
end
# Move into the Hugo destination directory, so file names are only prefixed
# with "./"
Dir.chdir(File.join(Dir.pwd, "#{$hugo_dest}"))
# Generate a list of every file in $hugo_dest, and `map` them into the form,
# [["«file_name»", "«md5sum»"], ... ]
puts(" Aggregating Local Hash List...")
# TODO: It would be nice to background this operations, and spin-lock on a
# progress bar with `total: nil` until the call returns.
local_file_list = Dir["./**/*"]
.select { |f| File.file?(f) }
.sort_by { |f| f }
.map { |f|
# The file names have a leading `./`. Strip those.
[f[2..-1], Digest::MD5.file(f).hexdigest] }
# Open up a connection to our S3 target bucket
puts(" Opening S3 Connection...")
aws_bucket = Aws::S3::Bucket.new(ENV['AWS_S3_BUCKET'], {
:region => "us-east-1",
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],
})
# Fetch all objects from the remote, and `map` them into the form,
# [["«file_name»", "«md5sum»"], ... ]
puts(" Fetching Remote Object List (this may take up to ~30 seconds)...")
# TODO: It would be nice to background this operations, and spin-lock on a
# progress bar with `total: nil` until the call returns.
aws_file_list = aws_bucket
.objects()
.sort_by { |objs| objs.key }
.map { |objs|
# the etag (which is the md5sum) is wrapped in double-quotes. Strip those
# by 'translating' them into empty strings.
[objs.key, objs.etag.tr('"','')] }
.reject { |objs| objs[0] == "last_deployed_time.txt" }
# Now that we have the two lists, we need to compare them and generate the
# list of files we need to upload, and the list of files we need to delete.
# To do this, we're going to use some brute force.
puts(" Comparing Object Hashes...")
new_list = []
updated_list = []
delete_list = []
lcl_i = 0
aws_i = 0
lcl_len = local_file_list.length
aws_len = aws_file_list.length
progress = ProgressBar.create(:title => " Hash check",
:total => lcl_len,
:autofinish => false)
while true
# Check if we've reached the end of either list and should break
break if (lcl_i == lcl_len || aws_i == aws_len)
lcl_file_name = local_file_list[lcl_i][0]
aws_file_name = aws_file_list[aws_i][0]
# Compare the file/object names
case lcl_file_name <=> aws_file_name
when 0 # File names are identical
# Compare md5sums. If they don't match, add the file to the updated list.
if (local_file_list[lcl_i][1] != aws_file_list[aws_i][1])
updated_list.push(lcl_file_name)
end
# In either case, increment both index variables
lcl_i += 1; progress.increment
aws_i += 1
when -1 # Local file name sorts first...
# The local file doesn't exist on AWS. Add it to the new list.
new_list.push(lcl_file_name)
# And only increment the local index variable.
lcl_i += 1; progress.increment
when 1 # AWS object name sorts first...
# The AWS object doesn't (or no longer) exist in the locally built
# artifacts. Schedule it for deletion.
delete_list.push(aws_file_name)
# And only increment the aws index variable.
aws_i += 1
end
end
# If we're not at the end of the local file list, we need to add any new files
# to the new list.
while (lcl_i < lcl_len)
new_list.push(local_file_list[lcl_i][0])
lcl_i += 1; progress.increment
end
# If we're not at the end of the aws object list, we need to add those file to
# the delete list.
while (aws_i < aws_len)
delete_list.push(aws_file_list[aws_i][0])
aws_i += 1
end
progress.finish
upload_list = updated_list + new_list
new_files_log = File.join(log_dir, "#{start_time}.new.txt")
updated_files_log = File.join(log_dir, "#{start_time}.updated.txt")
deleted_files_log = File.join(log_dir, "#{start_time}.deleted.txt")
puts(" Hash Check complete")
puts(" #{new_list.length} new files (logged to #{new_files_log})")
puts(" #{updated_list.length} updated files (logged to #{updated_files_log})")
puts(" #{upload_list.length} files need to be uploaded to the remote")
puts(" #{delete_list.length} files need to be deleted from the remote (logged to #{deleted_files_log})")
File.open(new_files_log, "w+") do |f|
f.puts(new_list)
end
File.open(updated_files_log, "w+") do |f|
f.puts(upload_list)
end
File.open(deleted_files_log, "w+") do |f|
f.puts(delete_list)
end
if (dry_run)
puts("")
puts("Dry Run Complete.")
puts("Pending changes Logged to #{log_dir}/.")
puts("========================================")
exit(0)
end
# Upload the files in the upload updated and new lists, and delete the files
# in the delete list.
if (upload_list.length > 0)
puts(" Uploading files...")
progress = ProgressBar.create(:title => " Uploads",
:total => upload_list.length)
upload_list.each { |obj_path|
object_ext = File.extname(obj_path)
object_descriptor = {
key: obj_path,
body: File.open(obj_path),
acl: "public-read"
}
case object_ext
when ".html"; object_descriptor[:content_type] = "text/html"
when ".txt"; object_descriptor[:content_type] = "text/plain"
when ".css"; object_descriptor[:content_type] = "text/css"
when ".js"; object_descriptor[:content_type] = "application/javascript"
when ".xml"; object_descriptor[:content_type] = "application/xml"
when ".json"; object_descriptor[:content_type] = "application/json"
when ".eot"; object_descriptor[:content_type] = "font/eot"
when ".ttf"; object_descriptor[:content_type] = "font/ttf"
when ".svg"; object_descriptor[:content_type] = "image/svg+xml"
when ".woff"; object_descriptor[:content_type] = "application/font-woff"
when ".gif"; object_descriptor[:content_type] = "image/gif"
when ".jpg"; object_descriptor[:content_type] = "image/jpeg"
when ".jpeg"; object_descriptor[:content_type] = "image/jpeg"
when ".png"; object_descriptor[:content_type] = "image/png"
when ".ico"; object_descriptor[:content_type] = "image/x-icon"
when ".pdf"; object_descriptor[:content_type] = "application/pdf"
# when ".eps"; object_descriptor[:content_type] = ""
# when ".graffle"; object_descriptor[:content_type] = ""
# when ".logo"; object_descriptor[:content_type] = ""
end
#TODO: Error checking.
aws_bucket.put_object(object_descriptor)
#TODO: Check to make sure this increments correctly.
progress.increment
}
# This should be superfluous, but it's here to ensure the next `puts` don't
# overwrite a failed progressbar.
progress.finish
else
puts(" No files to upload...")
end
if (delete_list.length > 0)
delete_list.each_slice(1000).with_index do |slice, index|
index_from = index * 1000
index_to = ((index+1)*1000) < delete_list.length ? ((index+1)*1000) : delete_list.length
puts(" Requesting Batch Delete for objects #{index_from}-#{index_to}...")
# Generate a Aws::S3::Types::Delete hash object.
delete_hash = {
delete: {
objects: slice.map{ |f| { key: f } },
quiet: false
}
}
begin
response = aws_bucket.delete_objects(delete_hash)
rescue Exception => e
require 'pp'
Kernel.abort("ERRROR: Batch Deletion returned with errors.\n"\
" Delete Hash Object:\n"\
"#{pp(delete_hash)}\n"\
" Error message:\n"\
"#{e.message}")
end
if (response.errors.length > 0)
require 'pp'
Kernel.abort("ERRROR: Batch Deletion returned with errors\n"\
" Delete Hash Object:\n"\
"#{pp(delete_hash)}\n"\
" Response Object:\n"\
"#{pp(response)}")
end
end
else
puts(" No files to delete...")
end
# Fetch and rewrite the S3 Routing Rules to make sure the 'latest' of every
# project correctly re-route.
puts(" Configuring S3 Bucket Website redirect rules...")
# Open an S3 connection to the Bucket Website metadata
aws_bucket_website = Aws::S3::BucketWebsite.new(ENV['AWS_S3_BUCKET'], {
:region => "us-east-1",
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],
})
# Build the routing rules based on the config.yaml's 'project_descripts'. One
# routing rule per project.
routing_rules = []
config_file['params']['project_descriptions'].each do |project, description|
# These paths come with leading `/`s (which is correct), but the routing rules
# assume a relative path (which is also correct). To account for this, we
# strip the leading slashes here.
path = description['path'][1..-1]
archived_path = description['archived_path'][1..-1]
ver = description['latest']
routing_rules.push(
{
:condition => { :key_prefix_equals => "#{archived_path}/latest/" },
:redirect => { :replace_key_prefix_with => "#{path}/#{ver}/",
:host_name => ENV['AWS_HOST_NAME'] }
}
)
routing_rules.push(
{
:condition => { :key_prefix_equals => "#{archived_path}/latest" },
:redirect => { :replace_key_prefix_with => "#{path}/#{ver}/",
:host_name => ENV['AWS_HOST_NAME'] }
}
)
routing_rules.push(
{
:condition => { :key_prefix_equals => "#{path}/latest/" },
:redirect => { :replace_key_prefix_with => "#{path}/#{ver}/",
:host_name => ENV['AWS_HOST_NAME'] }
}
)
routing_rules.push(
{
:condition => { :key_prefix_equals => "#{path}/latest" },
:redirect => { :replace_key_prefix_with => "#{path}/#{ver}/",
:host_name => ENV['AWS_HOST_NAME'] }
}
)
end
#TODO: We need to implement some way of adding arbitrary routing rules. Maybe
# add a section in config.yaml that's just a JSON string that we parse?
riak_path = config_file['params']['project_descriptions']['riak_kv']['path'][1..-1]
riak_ver = config_file['params']['project_descriptions']['riak_kv']['latest']
routing_rules.push(
{
:condition => { :key_prefix_equals => "riakee/latest/" },
:redirect => { :replace_key_prefix_with => "#{riak_path}/#{riak_ver}/",
:host_name => ENV['AWS_HOST_NAME'] }
}
)
routing_rules.push(
{
:condition => { :key_prefix_equals => "riakee/latest" },
:redirect => { :replace_key_prefix_with => "#{riak_path}/#{riak_ver}",
:host_name => ENV['AWS_HOST_NAME'] }
}
)
routing_rules.push(
{
:condition => { :key_prefix_equals => "riakts/" },
:redirect => { :replace_key_prefix_with => "riak/ts/",
:host_name => ENV['AWS_HOST_NAME'] }
}
)
new_website_configuration = {
:error_document => {:key => "404.html"},
:index_document => aws_bucket_website.index_document.to_hash,
:routing_rules => routing_rules
}
aws_bucket_website.put({ website_configuration: new_website_configuration })
# Invalidate any files that were deleted or modified.
cf_client = SimpleCloudfrontInvalidator::CloudfrontClient.new(
ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'],
ENV['AWS_CLOUDFRONT_DIST_ID'])
invalidation_list = updated_list + delete_list
if (invalidation_list.length == 0)
puts(" No files to invalidate...")
elsif (invalidation_list.length < 500)
# The invalidation list is sufficiently short that we can invalidate each
# individual file
invalidation_list.each_slice(100).with_index do |slice, index|
index_from = (index*100)
index_to = ((index+1)*100) < invalidation_list.length ? ((index+1)*100) : invalidation_list.length
puts(" Sending Invalidation Request for objects #{index_from}-#{index_to}...")
cf_report = cf_client.invalidate(slice)
end
else
# The invalidation list is large enough that we should skip getting charged
# and invalidate the entire site.
puts(" Sending Invalidation Request for the entire site (\"/*\")...")
cf_report = cf_client.invalidate(['/*'])
end
# Write a dummy file to mark the time of the last successful deploy.
aws_bucket.put_object({
acl: "public-read-write",
key: "last_deployed_time.txt",
body: "#{Time.new.utc} -- #{`git rev-parse HEAD`[0..6]}",
content_type: "text/plain"
})
puts("")
puts("Deploy Process Complete!")
puts("========================================")
end
| true |
b026fc60d59f32b334adeacd9838c1ecfee2ea87 | Ruby | nog/atcoder | /contests/abc235/c/main.rb | UTF-8 | 283 | 2.578125 | 3 | [] | no_license | N, Q= gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
lists = {}
N.times do |i|
a = A[i]
lists[a] ||= []
lists[a].push(i)
end
queries = {}
Q.times do |i|
x, k = gets.split.map(&:to_i)
li = lists[x] || []
if li.size >= k
puts li[k-1] + 1
else
puts -1
end
end | true |
74160250886250114a68f07c485ce0ece30a3feb | Ruby | emmasmithdev/karaoke-wk2-hwk | /specs/venue_spec.rb | UTF-8 | 3,083 | 3.296875 | 3 | [] | no_license | require('minitest/autorun')
require('minitest/reporters')
require_relative('../venue')
require_relative('../room')
require_relative('../guest')
require_relative('../song')
require_relative('../stock')
require('pry')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
class TestVenue < Minitest::Test
def setup
@song1 = Song.new("Simply the Best", "Tina Turner")
@song2 = Song.new("Turn Back Time", "Cher")
@song3 = Song.new("It's All Coming Back", "Celine Dion")
@song4 = Song.new("Shake It Off", "Taylor Swift")
@song5 = Song.new("Can't Feel My Face", "The Weekend")
@song6 = Song.new("Shape of You", "Ed Sheeran")
@song7 = Song.new("My Heart Will Go On", "Celine Dion")
@songs1 = [@song1, @song2, @song3, @song7]
@songs2 = [@song4, @song5, @song6]
@guest1 = Guest.new("Emma", 10.00, @song6)
@guest2 = Guest.new("Matt", 20.00, @song5)
@guest3 = Guest.new("Caroline", 15.00, @song2)
@guest4 = Guest.new("Stephanie", 20.00, @song3)
@guest5 = Guest.new("William", 20.00, @song3)
@guest6 = Guest.new("Zack", 20.00, @song3)
@guests = [@guest1, @guest2, @guest3, @guest4, @guest5]
@room1 = Room.new("Power Ballads", @songs1, 5.00, 50.00)
@room2 = Room.new("Chart Toppers", @songs2, 7.00)
@rooms = [@room1, @room2]
@stock1 = Stock.new("prosecco", 15.00, "drink")
@stock2 = Stock.new("beer", 5.00, "drink")
@stock3 = Stock.new("vodka", 3.00, "drink")
@stock4 = Stock.new("nachos", 4.00, "food")
@stock5 = Stock.new("pizza", 5.00, "food")
@stock6 = Stock.new("chips", 3.00, "food")
@stock = {
@stock1 => 10,
@stock2 => 50,
@stock3 => 100,
@stock4 => 20,
@stock5 => 20,
@stock6 => 40
}
@venue = Venue.new("Lucky Voice", @rooms, 100.00, @stock)
end
def test_venue_has_name
assert_equal("Lucky Voice", @venue.name)
end
def test_number_of_rooms
assert_equal(2, @venue.rooms.count)
end
def test_amount_in_bank_account
assert_equal(100.00, @venue.bank_account)
end
def test_get_stock_level
assert_equal(10, @venue.stock_level(@stock1))
end
def test_add_items_to_stock
@venue.add_item(@stock1)
@venue.add_item(@stock1)
assert_equal(12, @venue.stock_level(@stock1))
end
def test_remove_item_from_stock
@venue.remove_item(@stock1)
assert_equal(9, @venue.stock_level(@stock1))
end
def test_get_money_received_amount_from_room
assert_equal(50.00, @venue.rooms[0].money_received)
end
def test_transfer_money_from_room_to_bank_account
@venue.transfer_money("Power Ballads")
assert_equal(0, @venue.rooms[0].money_received)
assert_equal(150.00, @venue.bank_account)
end
# Restock prosecco from venue stock to room 1.
# Restock chips from venue stock to room 2.
def test_transfer_stock_to_room
@venue.restock_room(@stock1, @room1)
@venue.restock_room(@stock6, @room2)
assert_equal(9, @venue.stock_level(@stock1))
assert_equal(1, @room1.stock_level_drinks(@stock1))
assert_equal(1, @room2.stock_level_food(@stock6))
end
end
| true |
4065b929cecf94a4a1b50a05384a929487b1e8ac | Ruby | xSSinnerx/Ruby-HW1 | /Hw1.rb | UTF-8 | 1,498 | 3.59375 | 4 | [] | no_license | #task 1 (Kata 8)
def count_positives_sum_negatives(lst)
return [] if lst.nil? || lst.empty?
[lst.reject { |x| x < 1 }.count, (lst.reject { |x| x > -1 }).sum]
end
#task 2 (Kata 8)
def string_to_number(s)
number = s.to_i
return number
end
#task 3 (Kata 7)
def locker_run x
(1..Math.sqrt(x)).map { |i| i * i}
end
def run_task
print 'Enter total number of lockers:'
x = gets.chomp.to_i
puts "Here is an array filled with the locker numbers of
those which are open at the end of his run : #{locker_run(x)}"
end
#task 4 Kata 6 Rainfall
def mean(town, strng)
return -1 if (numbers=extract_data(town, strng)).nil?
numbers.sum/12
end
def variance(town, strng)
return -1 if (numbers=extract_data(town, strng)).nil?
mean = numbers.sum/12
variance =numbers.map {|x| (x-mean)**2} .sum/12
end
def extract_data(town,strng)
data_hash = strng.split("\n").map{ |str| str.split(":") }.to_h
return nil if data_hash[town].nil?
numbers = data_hash[town].scan(/\d+.\d+/).map(&:to_f)
end
# task 5 Kata 5
def gap(g, m, n)
numbers = (m).upto(n-1).select { |b| b.odd? }
pair = nil
numbers.each do |number|
next unless is_prime?(number)
if is_prime?(number + g) && !(number + 1).upto(number + g - 1).any? { |b| is_prime?(b) }
pair = [number, number + g]
break
end
end
pair
end
def is_prime?(number)
return false if number <= 1
(2..Math.sqrt(number)).each { |i| return false if (number % i).zero? }
end
| true |
a60759fc7649eb89758399a6ef223ab77eede7e4 | Ruby | onurkucukkece/format_parser | /lib/parsers/moov_parser/decoder.rb | UTF-8 | 8,476 | 2.53125 | 3 | [
"MIT"
] | permissive | # Handles decoding of MOV/MPEG4 atoms/boxes in a stream. Will recursively
# read atoms and parse their data fields if applicable. Also contains
# a few utility functions for finding atoms in a list etc.
class FormatParser::MOOVParser::Decoder
class Atom < Struct.new(:at, :atom_size, :atom_type, :path, :children, :atom_fields)
def to_s
'%s (%s): %d bytes at offset %d' % [atom_type, path.join('.'), atom_size, at]
end
def field_value(data_field)
(atom_fields || {}).fetch(data_field)
end
def as_json(*a)
members.each_with_object({}) do |member_name, o|
o[member_name] = public_send(member_name).as_json(*a)
end
end
end
# Atoms (boxes) that are known to only contain children, no data fields
KNOWN_BRANCH_ATOM_TYPES = %w(moov mdia trak clip edts minf dinf stbl udta meta)
# Atoms (boxes) that are known to contain both leaves and data fields
KNOWN_BRANCH_AND_LEAF_ATOM_TYPES = %w(meta) # the udta.meta thing used by iTunes
# Limit how many atoms we scan in sequence, to prevent derailments
MAX_ATOMS_AT_LEVEL = 128
# Finds the first atom in the given Array of Atom structs that
# matches the type, drilling down if a list of atom names is given
def find_first_atom_by_path(atoms, *atom_types)
type_to_find = atom_types.shift
requisite = atoms.find { |e| e.atom_type == type_to_find }
# Return if we found our match
return requisite if atom_types.empty?
# Return nil if we didn't find the match at this nesting level
return unless requisite
# ...otherwise drill further down
find_first_atom_by_path(requisite.children || [], *atom_types)
end
def parse_ftyp_atom(io, atom_size)
# Subtract 8 for the atom_size+atom_type,
# and 8 once more for the major_brand and minor_version. The remaining
# numbr of bytes is reserved for the compatible brands, 4 bytes per
# brand.
num_brands = (atom_size - 8 - 8) / 4
{
major_brand: read_bytes(io, 4),
minor_version: read_binary_coded_decimal(io),
compatible_brands: (1..num_brands).map { read_bytes(io, 4) },
}
end
def parse_tkhd_atom(io, _)
version = read_byte_value(io)
is_v1 = version == 1
{
version: version,
flags: read_chars(io, 3),
ctime: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
mtime: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
trak_id: read_32bit_uint(io),
reserved_1: read_chars(io, 4),
duration: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
reserved_2: read_chars(io, 8),
layer: read_16bit_uint(io),
alternate_group: read_16bit_uint(io),
volume: read_16bit_uint(io),
reserved_3: read_chars(io, 2),
matrix_structure: (1..9).map { read_32bit_fixed_point(io) },
track_width: read_32bit_fixed_point(io),
track_height: read_32bit_fixed_point(io),
}
end
def parse_mdhd_atom(io, _)
version = read_byte_value(io)
is_v1 = version == 1
{
version: version,
flags: read_bytes(io, 3),
ctime: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
mtime: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
tscale: read_32bit_uint(io),
duration: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
language: read_32bit_uint(io),
quality: read_32bit_uint(io),
}
end
def parse_vmhd_atom(io, _)
{
version: read_byte_value(io),
flags: read_bytes(io, 3),
graphics_mode: read_bytes(io, 2),
opcolor_r: read_32bit_uint(io),
opcolor_g: read_32bit_uint(io),
opcolor_b: read_32bit_uint(io),
}
end
def parse_mvhd_atom(io, _)
version = read_byte_value(io)
is_v1 = version == 1
{
version: version,
flags: read_bytes(io, 3),
ctime: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
mtime: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
tscale: read_32bit_uint(io),
duration: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
preferred_rate: read_32bit_uint(io),
reserved: read_bytes(io, 10),
matrix_structure: (1..9).map { read_32bit_fixed_point(io) },
preview_time: read_32bit_uint(io),
preview_duration: read_32bit_uint(io),
poster_time: read_32bit_uint(io),
selection_time: read_32bit_uint(io),
selection_duration: read_32bit_uint(io),
current_time: read_32bit_uint(io),
next_trak_id: read_32bit_uint(io),
}
end
def parse_dref_atom(io, _)
dict = {
version: read_byte_value(io),
flags: read_bytes(io, 3),
num_entries: read_32bit_uint(io),
}
num_entries = dict[:num_entries]
entries = (1..num_entries).map do
entry = {
size: read_32bit_uint(io),
type: read_bytes(io, 4),
version: read_bytes(io, 1),
flags: read_bytes(io, 3),
}
entry[:data] = read_bytes(io, entry[:size] - 12)
entry
end
dict[:entries] = entries
dict
end
def parse_elst_atom(io, _)
dict = {
version: read_byte_value(io),
flags: read_bytes(io, 3),
num_entries: read_32bit_uint(io),
}
is_v1 = dict[:version] == 1 # Usual is 0, version 1 has 64bit durations
num_entries = dict[:num_entries]
entries = (1..num_entries).map do
{
track_duration: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
media_time: is_v1 ? read_64bit_uint(io) : read_32bit_uint(io),
media_rate: read_32bit_uint(io),
}
end
dict[:entries] = entries
dict
end
def parse_hdlr_atom(io, atom_size)
sub_io = StringIO.new(io.read(atom_size - 8))
{
version: read_byte_value(sub_io),
flags: read_bytes(sub_io, 3),
component_type: read_bytes(sub_io, 4),
component_subtype: read_bytes(sub_io, 4),
component_manufacturer: read_bytes(sub_io, 4),
component_flags: read_bytes(sub_io, 4),
component_flags_mask: read_bytes(sub_io, 4),
component_name: sub_io.read,
}
end
def parse_atom_fields_per_type(io, atom_size, atom_type)
if respond_to?("parse_#{atom_type}_atom", true)
send("parse_#{atom_type}_atom", io, atom_size)
else
nil # We can't look inside this leaf atom
end
end
# Recursive descent parser - will drill down to atoms which
# we know are permitted to have leaf/branch atoms within itself,
# and will attempt to recover the data fields for leaf atoms
def extract_atom_stream(io, max_read, current_branch = [])
initial_pos = io.pos
atoms = []
MAX_ATOMS_AT_LEVEL.times do
atom_pos = io.pos
break if atom_pos - initial_pos >= max_read
size_and_type = io.read(4 + 4)
break if size_and_type.to_s.bytesize < 8
atom_size, atom_type = size_and_type.unpack('Na4')
# If atom_size is specified to be 1, it is larger than what fits into the
# 4 bytes and we need to read it right after the atom type
atom_size = read_64bit_uint(io) if atom_size == 1
# We are allowed to read what comes after
# the atom size and atom type, but not any more than that
size_of_atom_type_and_size = io.pos - atom_pos
atom_size_sans_header = atom_size - size_of_atom_type_and_size
children, fields = if KNOWN_BRANCH_AND_LEAF_ATOM_TYPES.include?(atom_type)
parse_atom_children_and_data_fields(io, atom_size_sans_header, atom_type)
elsif KNOWN_BRANCH_ATOM_TYPES.include?(atom_type)
[extract_atom_stream(io, atom_size_sans_header, current_branch + [atom_type]), nil]
else # Assume leaf atom
[nil, parse_atom_fields_per_type(io, atom_size_sans_header, atom_type)]
end
atoms << Atom.new(atom_pos, atom_size, atom_type, current_branch + [atom_type], children, fields)
io.seek(atom_pos + atom_size)
end
atoms
end
def read_16bit_fixed_point(io)
_whole, _fraction = io.read(2).unpack('CC')
end
def read_32bit_fixed_point(io)
_whole, _fraction = io.read(4).unpack('nn')
end
def read_chars(io, n)
io.read(n)
end
def read_byte_value(io)
io.read(1).unpack('C').first
end
def read_bytes(io, n)
io.read(n)
end
def read_16bit_uint(io)
io.read(2).unpack('n').first
end
def read_32bit_uint(io)
io.read(4).unpack('N').first
end
def read_64bit_uint(io)
io.read(8).unpack('Q>').first
end
def read_binary_coded_decimal(io)
bcd_string = io.read(4)
[bcd_string].pack('H*').unpack('C*')
end
end
| true |
8c02d1fc1b8ccb693f886123f481643b3842acc7 | Ruby | dougvidotto/launchschoolprojects | /prepcourses/intro_programming_ruby/exercises/exercise6.rb | UTF-8 | 77 | 2.65625 | 3 | [] | no_license | array = [1, 1, 1, 3, 4, 3, 5, 6, 5, 5]
uniq_array = array.uniq
p uniq_array | true |
456ded9e11405456230a5ff9af18a68c62291fbc | Ruby | maksdy/WeatherBot | /weatherbot.rb | UTF-8 | 588 | 2.671875 | 3 | [] | no_license | require 'telegram/bot'
require 'forecast_io'
ForecastIO.api_key = '4e47c04f26c4c84eb507f2215cd9b287'
token = '698880021:AAFeMIsjQMx23DrI7_5QGK_OktLgC_HmQsc'
forecast = ForecastIO.forecast(50.450418, 30.523541, params: { lang: 'ru', units: 'si' })
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
case message.text
when '/start'
bot.api.sendMessage(chat_id: message.chat.id, text: "Привет! Погода в Киеве сейчас: #{forecast.currently.summary}. Температура воздуха: #{forecast.currently.temperature}'C.Чтобы повторить запрос нажми /start")
end
end
end
| true |
5efefafafd4bb6cf19116159d94899e55266ed39 | Ruby | jacobklinker/hw2fall15 | /spec/part4_spec.rb | UTF-8 | 1,124 | 3.296875 | 3 | [] | no_license | require 'part4.rb'
class Foo
attr_accessor_with_history :bar
end
class Bar
attr_accessor_with_history :foo
attr_accessor_with_history :bar
end
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = [:should, :expect]
end
end
describe "Class" do
it "should have an attr_accessor_with_history method" do
lambda { Class.new.attr_accessor_with_history :x }.should_not raise_error
end
it "should keep a history of changes" do
f = Foo.new
f.bar = 3
f.bar = :wowza
f.bar = 'boo!'
expect(f.bar_history).to eq([nil, 3, :wowza, 'boo!'])
end
it "should keep a history of changes for multiple instance variables" do
f = Bar.new
f.bar = 3
f.bar = :wowza
f.bar = 'boo!'
f.foo = "Hey what's up?"
expect(f.bar_history).to eq([nil, 3, :wowza, 'boo!'])
expect(f.foo_history).to eq([nil, "Hey what's up?"])
end
it "should maintain a different history for each object instance" do
f = Foo.new
f.bar = 3
f.bar = :wowza
f = Foo.new
f.bar = 4
expect(f.bar_history).to eq([nil, 4])
end
end
| true |
e6be0c83bcb1a948d7ff219fcc4f483db0a2afb4 | Ruby | IgorCSilva/sketchup | /Programas/if.rb | UTF-8 | 593 | 3.65625 | 4 | [] | no_license | if (5 > 3)
puts '5 is greater than 3!'
end
line = Sketchup.active_model.entities.add_line [0,0,0], [5,5,5]
if line
puts "If you can read this, add_line completed successfully."
puts "If not, line equals nil and you won't read this."
end
if (3 == 2)
puts "Successful!"
elsif (2 < 3)
puts "Nil!"
else
puts 'The last option!'
end
# Obtain the current month
m = Time.new.month
# Set s equal to the current season in the Northern Hemisphere
s = if m < 4
"winter"
elsif m < 7
"spring"
elsif m < 10
"summer"
else
"fall"
end
# Display the value of s
puts s | true |
0a1700a6ee1cbeed24c1e1cc9758e0ff596c05e6 | Ruby | anickel101/ruby-oo-inheritance-modules-lab-nyc01-seng-ft-080320 | /lib/concerns/findable.rb | UTF-8 | 109 | 2.578125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | module Findable
def find_by_name(name)
self.all.detect {|thing| thing.name == name}
end
end | true |
b3a9764940f6c4346de61ee693dc1b9689edfa94 | Ruby | leizzer/distroaulas | /app/controllers/import_controller.rb | UTF-8 | 3,568 | 2.703125 | 3 | [] | no_license | class ImportController < ApplicationController
def import
@log = "INICIO DE IMPORTACION \n"
begin
@log += "Intentando acceder a Carreras.txt \n"
c = File::read('importer/Carreras.txt')
@log += "Acceso logrado... Leyendo... \n Se encontraron #{c.lines.count} registros... \n"
c.each_line do |line|
nueva_carrera = Carrera.new
nueva_carrera.codigo = line[0..-2].split(';').collect[0]
nueva_carrera.nombre = line[0..-2].split(';').collect[1].strip
if Carrera.find(:all, :conditions => {:codigo => nueva_carrera.codigo, :nombre => nueva_carrera.nombre}).empty?
nueva_carrera.save!
@log += "Registro [#{nueva_carrera.codigo} #{nueva_carrera.nombre}] agregado! \n"
else
@log += "Registro [#{nueva_carrera.codigo} #{nueva_carrera.nombre}] ya existe, no agregado \n"
end
end
@log += "Carreras.txt procesado correctamente \n"
rescue => e
@log += "Error: Carreras.txt corrupto, inexistente o malformateado. No se pudo imporar. \n"
end
begin
@log += "Intentando acceder a Planes.txt... \n"
p = File::read('importer/Planes.txt')
@log += "Acceso logrado... Leyendo... \n Se encontraron #{p.lines.count} registros... \n"
p.each_line do |line|
nuevo_plan = Plan.new
nuevo_plan.codigo_carrera = line[0..-2].split(';').collect[0]
nuevo_plan.codigo = line[0..-2].split(';').collect[1]
nuevo_plan.nombre = line[0..-2].split(';').collect[2].strip
if Plan.find(:all, :conditions => {:codigo => nuevo_plan.codigo, :codigo_carrera => nuevo_plan.codigo_carrera, :nombre => nuevo_plan.nombre}).empty?
nuevo_plan.save!
@log += "Registro [#{nuevo_plan.codigo} #{nuevo_plan.codigo_carrera} #{nuevo_plan.nombre}] agregado! \n"
else
@log += "Registro [#{nuevo_plan.codigo} #{nuevo_plan.codigo_carrera} #{nuevo_plan.nombre}] ya existe, no agregado \n"
end
end
@log += "Planes.txt fue procesado correctamente \n"
rescue => e
@log += "Error: Planes.txt corrupto, inexistente o malformateado. No se pudo imporar. \n"
end
begin
@log += "Intentando acceder a Materias.txt... \n"
m = File::read('importer/Materias.txt')
@log += "Acceso logrado... Leyendo... \n Se encontraron #{m.lines.count} registros... \n"
m.each_line do |line|
nueva_materia = Materia.new
nueva_materia.codigo_carrera = line[0..-2].split(';').collect[0]
nueva_materia.codigo_plan = line[0..-2].split(';').collect[1]
nueva_materia.codigo = line[0..-2].split(';').collect[2]
nueva_materia.nombre = line[0..-2].split(';').collect[3].strip
if Materia.find(:all, :conditions => {:codigo_carrera => nueva_materia.codigo_carrera, :codigo_plan => nueva_materia.codigo_plan, :codigo => nueva_materia.codigo, :nombre => nueva_materia.nombre}).empty?
nueva_materia.save!
@log += "Registro [#{nueva_materia.codigo} #{nueva_materia.codigo_plan} #{nueva_materia.codigo_carrera} #{nueva_materia.nombre}] agregado! \n"
else
@log += "Registro [#{nueva_materia.codigo} #{nueva_materia.codigo_plan} #{nueva_materia.codigo_carrera} #{nueva_materia.nombre}] ya existe, no agregado \n"
end
end
@log += "Materias.txt fue procesado correctamente \n"
rescue => e
@log += "Error: Materias.txt corrupto, inexistente o malformateado. No se pudo imporar.\n"
end
@log += "FIN DE LA IMPORTACION"
render :action => 'import'
end
end
| true |
8e37aa66dd07e0b3efe4c819037cb5141d31cc9c | Ruby | bsheehy9/ls-challanges | /easy/scrabble/scrabble_score.rb | UTF-8 | 624 | 3.5625 | 4 | [] | no_license | class Scrabble
POINTS = { 'AEIOULNRST' => 1,
'DG' => 2,
'BCMP' => 3,
'FHVWY' => 4,
'K' => 5,
'JX' => 8,
'QZ' => 10 }
def initialize(word)
@word = word
end
def score
return 0 if word.nil?
letters = word.upcase.gsub(/[^A-Z]/, '').chars
letters.map do |letter|
POINTS.select do |all_letters, _|
all_letters.include?(letter)
end.values[0]
end.sum
end
def self.score(word)
Scrabble.new(word).score
end
private
attr_reader :word
end
p Scrabble.new('').score
p Scrabble.score('score')
| true |
f4eebdf372647a68cdba2471cc21a198a7d8d920 | Ruby | portertech/ruby-pam | /test/check_user.rb | UTF-8 | 2,918 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- ruby -*-
# $Id: check_user.rb,v 1.1 2002/11/06 08:04:49 ttate Exp $
=begin
You need to create the /etc/pam.d/check_user file which
contains the following in the /etc/pam.d directory.
--
auth required /lib/security/pam_pwdb.so shadow nullok
account required /lib/security/pam_pwdb.so
password required /lib/security/pam_cracklib.so
password required /lib/security/pam_pwdb.so shadow use_authtok nullok
session required /lib/security/pam_pwdb.so
session optional /lib/security/pam_xauth.so
--
Or you need to add the following to the /etc/pam.conf file.
--
check_user auth required /lib/security/pam_pwdb.so shadow nullok
check_user account required /lib/security/pam_pwdb.so
check_user password required /lib/security/pam_cracklib.so
check_user password required /lib/security/pam_pwdb.so shadow use_authtok nullok
check_user session required /lib/security/pam_pwdb.so
check_user session optional /lib/security/pam_xauth.so
--
See also the PAM administration guide depended on your OS.
=end
require "pam"
def pam_conv(msgs, data)
ret = []
print("pam_conv: data = #{data.inspect}\n")
msgs.each{|msg|
case msg.msg_style
when PAM::PAM_PROMPT_ECHO_ON
printf(msg.msg)
if( str = $stdin.gets )
user.chomp!
end
ret.push(PAM::Response.new(str,0))
when PAM::PAM_PROMPT_ECHO_OFF
printf(msg.msg)
`stty -echo`
begin
if( str = $stdin.gets )
str.chomp!
end
ensure
`stty echo`
end
ret.push(PAM::Response.new(str, 0))
else
# unexpected, bug?
ret.push(PAM::Response.new(nil, 0))
end
}
ret
end
if( ARGV[0] && ARGV[1] )
service = ARGV[0]
user = ARGV[1]
else
print("usage:\n #{$0} <service> <user>\n")
exit(1)
end
conv = proc{|msg| pam_conv(msg)}
conv_data = user
# PAM.start("check_user", user, conv){|pam|
PAM.start(service, user, :pam_conv, conv_data){|pam|
# pam.set_fail_delay(0)
# pam.set_item(PAM::PAM_RUSER, ruser)
# pam.set_item(PAM::PAM_RHOST, rhost)
# pam.set_item(PAM::PAM_CONV, [conv, conv_data])
print("PAM_RUSER = ", pam.get_item(PAM::PAM_RUSER), "\n")
print("PAM_RHOST = ", pam.get_item(PAM::PAM_RHOST), "\n")
print("PAM_USER = ", pam.get_item(PAM::PAM_USER), "\n")
print("PAM_SERVICE = ", pam.get_item(PAM::PAM_SERVICE), "\n")
print("PAM_CONV = ", pam.get_item(PAM::PAM_CONV).inspect, "\n")
begin
pam.authenticate(0)
rescue PAM::PAM_USER_UNKNOWN
print("unknown user: #{pam.get_item(PAM::PAM_USER)}")
exit(1)
rescue PAM::PAM_AUTH_ERR
print("authentication error: #{pam.get_item(PAM::PAM_USER)}\n")
exit(1)
rescue PAM::PAMError
print("error code = #{pam.status}\n")
exit(1)
end
begin
pam.acct_mgmt(0)
pam.open_session{
# do something
}
rescue PAM::PAMError
printf("you can't access.\n")
exit(1)
end
print("\n",
"authenticated!\n")
}
| true |
0691aec2425524a6bd7b640eefd5792304251291 | Ruby | chungphuoc/roomorama_foosball | /app/services/match_service.rb | UTF-8 | 1,685 | 2.609375 | 3 | [] | no_license | class MatchService
def self.create(params)
@teams = []
params.each do |team, user_id|
t = Team.create()
@teams << t
user_id.each do |uid|
TeamUser.create(team: t, user_id: uid.to_i)
end
end
Match.create(team_1_id: @teams[0].id, team_2_id: @teams[1].id)
end
def self.update(params, match)
@teams = [match.team_1, match.team_2]
params.each_with_index do |team, index|
team[1].each do |uid|
TeamUser.find_or_create_by(team: @teams[index], user_id: uid.to_i)
end
end
end
def self.update_result(params, match)
params[:score_1].each_with_index do |score, idx|
g = Game.create(score_1: score, score_2: params[:score_2][idx])
MatchGame.create(match: match, game: g)
end
result = get_result(match)
if result[:winner] == 'Team 1'
t1_result = MatchResult::RESULT_WIN
t2_result = MatchResult::RESULT_LOSE
else
t1_result = MatchResult::RESULT_LOSE
t2_result = MatchResult::RESULT_WIN
end
MatchResult.create(match_id: match.id, team_id: match.team_1_id, result: t1_result)
MatchResult.create(match_id: match.id, team_id: match.team_2_id, result: t2_result)
end
def self.get_result(match)
flag1, flag2 = 0, 0
match_games = MatchGame.where(match_id: match.id)
if match_games.count > 0
match_games.each do |mg|
mg.game.score_1.to_i > mg.game.score_2.to_i ? flag1 += 1 : flag2 += 1
end
winner = flag1 > flag2 ? 'Team 1' : 'Team 2'
{team_1: flag1, team_2: flag2, winner: winner, match_id: match.id}
else
{team_1: flag1, team_2: flag2, winner: nil, match_id: match.id}
end
end
end | true |
eeed05747f5f88eeb9899dfde7af98780eb76041 | Ruby | kojix2/cumo | /test/cudnn_test.rb | UTF-8 | 17,004 | 2.53125 | 3 | [
"MIT"
] | permissive | require_relative "test_helper"
class CUDNNTest < Test::Unit::TestCase
float_types = [
Cumo::SFloat,
Cumo::DFloat,
]
if ENV['DTYPE']
float_types.select!{|type| type.to_s.downcase.include?(ENV['DTYPE'].downcase) }
end
float_types.each do |dtype|
sub_test_case "conv_2d" do
setup do
@batch_size = 2
@in_channels = 3
@out_channels = 2
@in_dims = [10, 7]
@kernel_size = [2, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@w_shape = [@out_channels, @in_channels].concat(@kernel_size)
@b_shape = [@out_channels]
@x = dtype.ones(*@x_shape)
@w = dtype.ones(*@w_shape)
@b = dtype.ones(*@b_shape) * 2
end
test "x.conv(w) #{dtype}" do
y = @x.conv(@w)
assert { y.shape == [@batch_size, @out_channels, 9, 5] }
assert y.to_a.flatten.all? {|e| e.to_i == 18 }
end
test "x.conv(w, b) #{dtype}" do
y = @x.conv(@w, b: @b)
assert { y.shape == [@batch_size, @out_channels, 9, 5] }
assert y.to_a.flatten.all? {|e| e.to_i == 20 }
assert { @b.shape == @b_shape }
end
test "x.conv(w, b, stride=int, pad=int) #{dtype}" do
y = @x.conv(@w, b: @b, stride: 2, pad: 2)
assert { y.shape == [@batch_size, @out_channels, 7, 5] }
assert y.to_a.flatten.all? {|e| [20,2,8].include?(e.to_i) }
assert { @b.shape == @b_shape }
end
test "x.conv(w, b, stride=array, pad=array) #{dtype}" do
y = @x.conv(@w, b: @b, stride: [3, 2], pad: [2, 0])
assert { y.shape == [@batch_size, @out_channels, 5, 3] }
assert y.to_a.flatten.all? {|e| e.to_i == 20 || e.to_i == 2 }
assert { @b.shape == @b_shape }
end
end
sub_test_case "conv_nd" do
setup do
@batch_size = 2
@in_channels = 3
@out_channels = 2
@in_dims = [4, 3, 2]
@kernel_size = [2, 3, 1]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@w_shape = [@out_channels, @in_channels].concat(@kernel_size)
@b_shape = [@out_channels]
@x = dtype.ones(*@x_shape)
@w = dtype.ones(*@w_shape)
@b = dtype.ones(*@b_shape) * 2
end
test "x.conv(w) #{dtype}" do
y = @x.conv(@w)
assert { y.shape == [@batch_size, @out_channels, 3, 1, 2] }
assert y.to_a.flatten.all? {|e| e.to_i == 18 }
assert { @b.shape == @b_shape }
end
test "x.conv(w, b) #{dtype}" do
y = @x.conv(@w, b: @b)
assert { y.shape == [@batch_size, @out_channels, 3, 1, 2] }
assert y.to_a.flatten.all? {|e| e.to_i == 20 }
assert { @b.shape == @b_shape }
end
test "x.conv(w, b, stride, pad) #{dtype}" do
y = @x.conv(@w, b: @b, stride: [3, 2, 1], pad: [2, 1, 0])
assert { y.shape == [@batch_size, @out_channels, 3, 2, 2] }
assert y.to_a.flatten.all? {|e| e.to_i == 14 || e.to_i == 2 }
assert { @b.shape == @b_shape }
end
end
sub_test_case "conv_transpose_2d" do
setup do
@batch_size = 2
@in_channels = 3
@out_channels = 2
@in_dims = [5, 3]
@kernel_size = [2, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@w_shape = [@in_channels, @out_channels].concat(@kernel_size)
@b_shape = [@out_channels]
@x = dtype.ones(*@x_shape)
@w = dtype.ones(*@w_shape)
@b = dtype.ones(*@b_shape) * 2
end
test "x.conv_transpose(w) #{dtype}" do
y = @x.conv_transpose(@w)
assert { y.shape == [@batch_size, @out_channels, 6, 5] }
end
test "x.conv_transpose(w, b) #{dtype}" do
y = @x.conv_transpose(@w, b: @b)
assert { y.shape == [@batch_size, @out_channels, 6, 5] }
y_no_bias = @x.conv_transpose(@w)
assert { y == y_no_bias + 2 }
assert { @b.shape == @b_shape }
end
test "x.conv_transpose(w, b, stride=int, pad=int) #{dtype}" do
y = @x.conv_transpose(@w, b: @b, stride: 2, pad: 2)
assert { y.shape == [@batch_size, @out_channels, 6, 3] }
assert y.to_a.flatten.all? {|e| e.to_i == 8 || e.to_i == 5 }
assert { @b.shape == @b_shape }
end
test "x.conv_transpose(w, b, stride=array, pad=array) #{dtype}" do
y = @x.conv_transpose(@w, b: @b, stride: [3, 2], pad: [2, 0])
assert { y.shape == [@batch_size, @out_channels, 10, 7] }
assert y.to_a.flatten.all? {|e| [8,5,2].include?(e.to_i) }
assert { @b.shape == @b_shape }
end
end
sub_test_case "conv_transpose_nd" do
setup do
@batch_size = 2
@in_channels = 3
@out_channels = 2
@in_dims = [4, 3, 2]
@kernel_size = [2, 3, 1]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@w_shape = [@in_channels, @out_channels].concat(@kernel_size)
@b_shape = [@out_channels]
@x = dtype.ones(*@x_shape)
@w = dtype.ones(*@w_shape)
@b = dtype.ones(*@b_shape) * 2
end
test "x.conv_transpose(w) #{dtype}" do
y = @x.conv_transpose(@w)
assert { y.shape == [@batch_size, @out_channels, 5, 5, 2] }
assert y.to_a.flatten.all? {|e| [3,6,9,12,18].include?(e.to_i) }
assert { @b.shape == @b_shape }
end
test "x.conv_transpose(w, b) #{dtype}" do
y = @x.conv_transpose(@w, b: @b)
assert { y.shape == [@batch_size, @out_channels, 5, 5, 2] }
y_no_bias = @x.conv_transpose(@w)
assert { y == y_no_bias + 2 }
assert { @b.shape == @b_shape }
end
test "x.conv_transpose(w, b, stride, pad) #{dtype}" do
y = @x.conv_transpose(@w, b: @b, stride: [3, 2, 1], pad: [2, 1, 0])
assert { y.shape == [@batch_size, @out_channels, 7, 5, 2] }
assert y.to_a.flatten.all? {|e| [2,5,8].include?(e.to_i) }
assert { @b.shape == @b_shape }
end
end
sub_test_case "conv_grad_w_2d" do
setup do
@batch_size = 2
@in_channels = 3
@out_channels = 2
@in_dims = [10, 7]
@kernel_size = [2, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@w_shape = [@out_channels, @in_channels].concat(@kernel_size)
@y_shape = [@batch_size, @out_channels, 9, 5]
@x = dtype.ones(*@x_shape)
@w = dtype.ones(*@w_shape)
@dy = dtype.ones(*@y_shape)
end
test "x.conv_grad_w(w) #{dtype}" do
dw = @x.conv_grad_w(@dy, @w_shape)
assert { dw.shape == @w_shape }
# TODO: assert values
end
end
sub_test_case "conv_grad_w_nd" do
setup do
@batch_size = 2
@in_channels = 3
@out_channels = 2
@in_dims = [4, 3, 2]
@kernel_size = [2, 3, 1]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@w_shape = [@out_channels, @in_channels].concat(@kernel_size)
@y_shape = [@batch_size, @out_channels, 3, 1, 2]
@x = dtype.ones(*@x_shape)
@w = dtype.ones(*@w_shape)
@dy = dtype.ones(*@y_shape)
end
test "x.conv_grad_w(w) #{dtype}" do
dw = @x.conv_grad_w(@dy, @w_shape)
assert { dw.shape == @w_shape }
# TODO: assert values
end
end
sub_test_case "conv_grad_w_2d" do
setup do
@batch_size = 2
@in_channels = 3
@out_channels = 2
@in_dims = [10, 7]
@kernel_size = [2, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@w_shape = [@out_channels, @in_channels].concat(@kernel_size)
@y_shape = [@batch_size, @out_channels, 9, 5]
@x = dtype.ones(*@x_shape)
@w = dtype.ones(*@w_shape)
@dy = dtype.ones(*@y_shape)
end
test "x.conv_grad_w(w) #{dtype}" do
dw = @x.conv_grad_w(@dy, @w_shape)
assert { dw.shape == @w_shape }
# TODO: assert values
end
end
sub_test_case "batch_norm" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@reduced_shape = [1].concat(@x_shape[1..-1])
@x = dtype.ones(*@x_shape) * 3
@gamma = dtype.ones(*@reduced_shape) * 2
@beta = dtype.ones(*@reduced_shape)
end
test "x.batch_norm(gamma, beta) #{dtype}" do
y = @x.batch_norm(@gamma, @beta)
assert { y.shape == @x_shape }
assert { y == dtype.ones(*@x_shape) }
end
test "x.batch_norm(gamma, beta, axis: [0]) #{dtype}" do
assert { @x.batch_norm(@gamma, @beta) == @x.batch_norm(@gamma, @beta, axis: [0]) }
end
test "x.batch_norm(gamma, beta, axis: [0, 2, 3]) #{dtype}" do
reduced_shape = [1, @x_shape[1], 1, 1]
gamma = dtype.ones(reduced_shape) * 2
beta = dtype.ones(reduced_shape)
y = @x.batch_norm(gamma, beta, axis: [0, 2, 3])
assert { y.shape == @x_shape }
end
test "x.batch_norm(gamma, beta, running_mean, running_var) #{dtype}" do
running_mean = dtype.ones(*@reduced_shape)
running_var = dtype.ones(*@reduced_shape)
y = @x.batch_norm(@gamma, @beta, running_mean: running_mean, running_var: running_var)
assert { y.shape == @x_shape }
assert { y == dtype.ones(*@x_shape) }
end
test "x.batch_norm(gamma, beta, mean, inv_std) #{dtype}" do
mean = dtype.new(*@reduced_shape)
inv_std = dtype.new(*@reduced_shape)
y = @x.batch_norm(@gamma, @beta, mean: mean, inv_std: inv_std)
assert { y.shape == @x_shape }
assert { mean.shape == @reduced_shape }
assert { inv_std.shape == @reduced_shape }
end
end
sub_test_case "batch_norm_backward" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@reduced_shape = [1].concat(@x_shape[1..-1])
@x = dtype.ones(*@x_shape) * 3
@gamma = dtype.ones(*@reduced_shape) * 2
@beta = dtype.ones(*@reduced_shape)
@gy = dtype.ones(*@x_shape)
end
test "x.batch_norm_backward(gamma, gy) #{dtype}" do
y = @x.batch_norm(@gamma, @beta)
gx, ggamma, gbeta = @x.batch_norm_backward(@gamma, @gy)
assert { gx.shape== @x_shape }
assert { ggamma.shape== @reduced_shape }
assert { gbeta.shape== @reduced_shape }
end
test "x.batch_norm_backward(gamma, gy, axis: [0,2,3]) #{dtype}" do
@reduced_shape = [1, @x_shape[1], 1, 1]
@gamma = dtype.ones(@reduced_shape) * 2
@beta = dtype.ones(@reduced_shape)
y = @x.batch_norm(@gamma, @beta, axis: [0,2,3])
gx, ggamma, gbeta = @x.batch_norm_backward(@gamma, @gy, axis: [0,2,3])
assert { gx.shape== @x_shape }
assert { ggamma.shape== @reduced_shape }
assert { gbeta.shape== @reduced_shape }
end
test "x.batch_norm_backward(gamma, gy, mean:, inv_std:) #{dtype}" do
mean = dtype.new(*@reduced_shape)
inv_std = dtype.new(*@reduced_shape)
y = @x.batch_norm(@gamma, @beta, mean: mean, inv_std: inv_std)
gx, ggamma, gbeta = @x.batch_norm_backward(@gamma, @gy, mean: mean, inv_std: inv_std)
assert { gx.shape== @x_shape }
assert { ggamma.shape== @reduced_shape }
assert { gbeta.shape== @reduced_shape }
end
end
sub_test_case "fixed_batch_norm" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@reduced_shape = [1].concat(@x_shape[1..-1])
@x = dtype.ones(*@x_shape) * 3
@gamma = dtype.ones(*@reduced_shape) * 2
@beta = dtype.ones(*@reduced_shape)
@mean = dtype.ones(*@reduced_shape)
@var = dtype.ones(*@reduced_shape)
end
test "x.fixed_batch_norm(gamma, beta, mean, var) #{dtype}" do
y = @x.fixed_batch_norm(@gamma, @beta, @mean, @var)
assert { y.shape == @x_shape }
# TODO: check output values
end
test "x.fixed_batch_norm(gamma, beta, mean, var, axis: [0]) #{dtype}" do
assert { @x.fixed_batch_norm(@gamma, @beta, @mean, @var) == @x.fixed_batch_norm(@gamma, @beta, @mean, @var, axis: [0]) }
end
test "x.fixed_batch_norm(gamma, beta, mean, var, axis: [0, 2, 3]) #{dtype}" do
reduced_shape = [1, @x_shape[1], 1, 1]
gamma = dtype.ones(reduced_shape) * 2
beta = dtype.ones(reduced_shape)
mean = dtype.ones(reduced_shape) * 2
var = dtype.ones(reduced_shape)
y = @x.fixed_batch_norm(gamma, beta, mean, var, axis: [0, 2, 3])
assert { y.shape == @x_shape }
# TODO: check output values
end
end
sub_test_case "max_pool" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@ksize = [3] * @in_dims.size
@x = dtype.ones(*@x_shape) * 3
end
test "x.max_pool(ksize) #{dtype}" do
y = @x.max_pool(@ksize)
assert { y.shape == [@batch_size, @in_channels, 1, 1] }
assert y.to_a.flatten.all? {|e| e.to_i == 3 }
end
test "x.max_pool(ksize, stride:, pad:) #{dtype}" do
stride = [2] * @in_dims.size
pad = [1] * @in_dims.size
y = @x.max_pool(@ksize, stride: stride, pad: pad)
assert { y.shape == [@batch_size, @in_channels, 3, 2] }
assert y.to_a.flatten.all? {|e| e.to_i == 3 }
end
end
sub_test_case "avg_pool(pad_value: nil)" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@ksize = [3] * @in_dims.size
@x = dtype.ones(*@x_shape) * 3
end
test "x.avg_pool(ksize) #{dtype}" do
y = @x.avg_pool(@ksize)
assert { y.shape == [@batch_size, @in_channels, 1, 1] }
assert y.to_a.flatten.all? {|e| e.to_i == 3 }
end
test "x.avg_pool(ksize, stride:, pad:) #{dtype}" do
stride = [2] * @in_dims.size
pad = [1] * @in_dims.size
y = @x.avg_pool(@ksize, stride: stride, pad: pad)
assert { y.shape == [@batch_size, @in_channels, 3, 2] }
# TODO: assert values
end
end
sub_test_case "avg_pool(pad_value: 0)" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@ksize = [3] * @in_dims.size
@x = dtype.ones(*@x_shape) * 3
end
test "x.avg_pool(ksize, stride:, pad:) #{dtype}" do
stride = [2] * @in_dims.size
pad = [1] * @in_dims.size
y_pad_0 = @x.avg_pool(@ksize, pad_value: 0, stride: stride, pad: pad)
y_pad_nil = @x.avg_pool(@ksize, pad_value: nil, stride: stride, pad: pad)
assert { y_pad_0.shape == y_pad_nil.shape }
assert { y_pad_0 != y_pad_nil }
end
end
sub_test_case "max_pool_backward" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@ksize = [3] * @in_dims.size
@x = dtype.ones(*@x_shape) * 3
end
test "x.max_pool_backward(ksize) #{dtype}" do
y = @x.max_pool(@ksize)
gy = dtype.ones(*y.shape)
gx = @x.max_pool_backward(y, gy, @ksize)
assert { gx.shape == @x.shape }
# TODO: assert values
end
test "x.max_pool_backward(ksize, stride:, pad:) #{dtype}" do
stride = [2] * @in_dims.size
pad = [1] * @in_dims.size
y = @x.max_pool(@ksize, stride: stride, pad: pad)
gy = dtype.ones(*y.shape)
gx = @x.max_pool_backward(y, gy, @ksize, stride: stride, pad: pad)
assert { gx.shape == @x.shape }
# TODO: assert values
end
end
sub_test_case "avg_pool_backward" do
setup do
@batch_size = 2
@in_channels = 3
@in_dims = [5, 3]
@x_shape = [@batch_size, @in_channels].concat(@in_dims)
@ksize = [3] * @in_dims.size
@x = dtype.ones(*@x_shape) * 3
end
test "x.avg_pool_backward(ksize) #{dtype}" do
y = @x.avg_pool(@ksize)
gy = dtype.ones(*y.shape)
gx = @x.avg_pool_backward(y, gy, @ksize)
assert { gx.shape == @x.shape }
# TODO: assert values
end
test "x.avg_pool_backward(ksize, stride:, pad:) #{dtype}" do
stride = [2] * @in_dims.size
pad = [1] * @in_dims.size
y = @x.avg_pool(@ksize, stride: stride, pad: pad)
gy = dtype.ones(*y.shape)
gx = @x.avg_pool_backward(y, gy, @ksize, stride: stride, pad: pad)
assert { gx.shape == @x.shape }
# TODO: assert values
end
end
end
end
| true |
550b0d8764add8aac0b7314cc0893dde31ad04aa | Ruby | reverbdotcom/once | /lib/once.rb | UTF-8 | 1,377 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | require "once/version"
require 'digest'
# Usage:
#
# 1. Connect to redis:
# Once.redis = Redis.new(...)
#
# If you don't specify the redis connection, we will assume the presence of a $redis global
#
# 2. Use to wrap a call that you want done uniquely
# Once.do(name: "sending_email", params: { email: "foo@bar.com" }, within: 1.hour) do
# .. stuff that should happen only once ..
# end
#
# The combination of the name and params makes the check unique. So typically it would be the
# command you're executing, plus the params to that command
module Once
DEFAULT_TIME = 3600 # seconds
class << self
def redis
@redis || $redis
end
def redis=(redis)
@redis = redis
end
# Checks the given params to see if this is a unique string
# If we've seen it within the expiry period (default: 1.hour),
# then we will not execute the block
#
# name: The name of the check, used as a namespace
# params: The params that will control whether or not the body executes
def do(name:, params:, within: DEFAULT_TIME, &block)
hash = Digest::MD5.hexdigest(params.inspect)
redis_key = "uniquecheck:#{name}:#{hash}"
if redis.set(redis_key, true, ex: within, nx: true)
begin
block.call
rescue
redis.expire(redis_key, 0)
raise
end
end
end
end
end
| true |
ae9c291769d4dc70153fbf47436aa36c867be213 | Ruby | ZirconCode/Scrapah | /lib/scrapah/cache.rb | UTF-8 | 1,117 | 2.765625 | 3 | [
"MIT"
] | permissive |
require 'json'
module Scrapah
class Cache
# TODO: 'throws away' whole cache after timeout,
# -> treat entries as seperate objects/files/dates
@@cache_dir = 'cache/'
def initialize()
Dir.mkdir(@@cache_dir) unless File.exists?(@@cache_dir)
@Cache = Hash.new
@keep_time = 1*24*60 # in minutes
end
def store(key,content)
@Cache[key] = content
end
def get(key)
@Cache[key]
end
def has_key?(key)
@Cache.has_key? key
end
def clear()
@Cache = Hash.new
end
def save
# WARNING: Symbols converted to Strings
f = File.new(@@cache_dir+Time.now.to_i.to_s,'w')
JSON.dump(@Cache,f)
f.close
end
def load
f = get_newest_acceptable
@Cache = Hash.new
@Cache = JSON.load(f) unless f.nil?
f.close
@Cache
end
def get_hash
@Cache
end
private
def get_newest_acceptable()
prev = Dir.glob(@@cache_dir+'*')
if(!prev.empty?)
prev.map!{|f| f.delete(@@cache_dir).to_i}
prev.sort!
return File.new(@@cache_dir+prev.last.to_s,"r") if(Time.now.to_i-prev.last < @keep_time*60)
end
nil
end
end
end | true |
19a6abb8553bb62a629294658449bafed3ccc9ce | Ruby | muhammednagy/bittrex-ruby | /lib/bittrex/websocket/frame.rb | UTF-8 | 699 | 2.84375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | class Bittrex::WebSocket
class Frame
attr_reader :hub,
:marker, :messages,
:result, :index
RESULT_KEY = 'R'.freeze
MARKER_KEY = 'C'.freeze
DATA_KEY = 'A'.freeze
MESSAGES_KEY = 'M'.freeze
INDEX_KEY = 'I'.freeze
def initialize(frame_data)
@result = frame_data[RESULT_KEY]
@marker = frame_data[MARKER_KEY]
@data = frame_data[DATA_KEY]
@index = frame_data[INDEX_KEY]
if frame_data[MESSAGES_KEY].is_a? Array
@messages = frame_data[MESSAGES_KEY].map do |message_data|
Message.new(message_data)
end
end
# 'R' - Response. Ignored now.
end
end
end
| true |
39f8863791de6d686aca1b90583c48d69e68f141 | Ruby | joelvh/aftermath | /lib/framework/core.rb | UTF-8 | 169 | 2.515625 | 3 | [] | no_license | String.class_eval do
def to_underscore!
(gsub!(/(.)([A-Z])/,'\1_\2') || self).gsub(/\s/,'').downcase!
end
def to_underscore
clone.to_underscore!
end
end | true |
c87bd5eedd4011b468b6d84ee69d475e4b7efc6c | Ruby | TactilizeTeam/photograph | /lib/photograph/artist.rb | UTF-8 | 1,617 | 2.8125 | 3 | [
"MIT"
] | permissive | require 'capybara/poltergeist'
require 'mini_magick'
Capybara.default_wait_time = 15
module Photograph
class Artist
attr_accessor :options
attr_reader :image
MissingUrlError = Class.new(Exception)
DefaultOptions = {
:x => 0, # top left position
:y => 0,
:w => 1280, # bottom right position
:h => 1024,
:wait => 0.5, # if selector is nil, wait 1 seconds before taking the screenshot
:selector => nil # wait until the selector matches to take the screenshot
}
def self.browser
@browser ||= Capybara::Session.new :poltergeist
end
def browser
self.class.browser
end
def initialize options={}
raise MissingUrlError unless options[:url]
@options = DefaultOptions.merge(options)
end
def shoot!
@image = capture
end
def capture
browser.visit @options[:url]
if @options[:selector]
browser.wait_until do
browser.has_css? @options[:selector]
end
else
sleep @options[:wait]
end
@tempfile = Tempfile.new(['photograph','.png'])
browser.driver.render @tempfile.path,
:width => options[:w] + options[:x],
:height => options[:h] + options[:y]
@image = adjust_image
end
def adjust_image
image = MiniMagick::Image.read @tempfile
if options[:h] && options[:w]
image.crop "#{options[:w]}x#{options[:h]}+#{options[:x]}+#{options[:y]}"
image.write @tempfile
end
image
end
def clean!
@tempfile.unlink
end
end
end
| true |
ef11caf01c66df61ba7644273a1733bd0a9ad0a6 | Ruby | dan-waters/advent_of_code_2020 | /day12/directions_reader.rb | UTF-8 | 131 | 2.5625 | 3 | [] | no_license | require 'open-uri'
class DirectionsReader
def directions_from_file(filename)
open(filename).readlines.map(&:strip)
end
end | true |
b4dbe3fac5e83062f5ecc3c7bd426ff1264f27ef | Ruby | vkurup/Amion-Schedule-Parser | /amion_schedule_test.rb | UTF-8 | 1,826 | 2.828125 | 3 | [] | no_license | require 'test/unit'
require File.expand_path(File.join(File.dirname(__FILE__)), 'amion_schedule')
class TestAmionSchedule < Test::Unit::TestCase
# def test_bad_password_returns_error
# exception = assert_raise(RuntimeError) {
# get_one_file("badpwd")
# }
# assert_equal "Invalid AMION password.", exception.message
# end
# def test_good_password_does_not_return_error
# as = get_one_file("Good password")
# assert_not_equal "Invalid password.", as
# end
def setup
@kurup = ["Kurup", "248", "13", "Hospitalist 2 (5-1) 7a-7p", "278", "35", "10-31-11", "0700", "1900"]
@flex = ["Wozniak", "433", "325", "Hospitalist 7 7a-7p", "283", "40", "10-31-11", "0700", "1900"]
@day_admit = ["Johnson", "236", "1", "9050 Day Admit Shift 12p-9p", "289", "45", "10-31-11", "1200", "2100"]
end
def test_date_parse_is_correct
assert_equal Date.parse('2011-10-31'), parse_date(@kurup)
end
def test_name_parse_is_correct
assert_equal "Kurup", parse_name(@kurup)
end
def test_shift_parse_is_correct
assert_equal "Day Shift", parse_shift(@kurup)
assert_equal "Flex", parse_shift(@flex)
assert_equal "12-9", parse_shift(@day_admit)
end
def test_service_parse_is_correct
assert_equal "5-1", parse_service(@kurup)
assert_equal nil, parse_service(@flex)
end
def test_one_day_schedule_is_correct
s = make_schedule(CSV.read("test.csv").slice(6..-1))
date = Date.parse("2011/10/14")
ds = one_day_schedule(s, date)
kurup = ds.index{ |h| h[:name] == "Kurup"}
assert_equal 1, ds[kurup][:day], "Day is correct"
assert_equal 5, ds[kurup][:stretch], "Stretch is correct"
assert_equal "Day Shift", ds[kurup][:shift], "Shift is correct"
assert_equal "5-2", ds[kurup][:service], "service is correct"
end
end
| true |
cac8165393130cfe9aaeb99f3244f9f2a7ade27d | Ruby | krsmith7/MediaRanker | /app/models/work.rb | UTF-8 | 844 | 2.640625 | 3 | [] | no_license | class Work < ApplicationRecord
WORK_CATEGORIES = %w(album movie book)
has_many :votes, dependent: :destroy
validates :title, presence: true, uniqueness: true
validates :category, presence: true, inclusion: { in: WORK_CATEGORIES}
def votes_count
return self.votes.count
end
def self.get_category_media(category)
works = Work.where(category: category).to_a
# return works
return works.sort_by{|item| item.votes_count}.reverse
end
def self.get_top_list(category)
category_works = Work.get_category_media(category).to_a
# sorted = category_works.sort_by{|item| item.votes_count}.reverse
# return sorted[0..9]
return category_works[0..9]
end
def self.get_top_work
works = Work.all.to_a
highest= works.sort_by{|item| item.votes_count}.reverse
return highest.first
end
end
| true |
26bcaf6775780bace532d902db60eb289818b7f8 | Ruby | paulnicholsen27/canwesingit | /app/models/part.rb | UTF-8 | 337 | 2.59375 | 3 | [] | no_license | class Part < ApplicationRecord
belongs_to :song
has_many :singer_parts
has_many :singers, through: :singer_parts
def primary_singer
has_primary = self.singer_parts.find {|sp| sp.primary? }
if has_primary
return has_primary.singer
else
return nil
end
end
end
| true |
1dc8062076628bb223d5e64755225c66a2f04d56 | Ruby | elia/model | /lib/lotus/model/adapters/implementation.rb | UTF-8 | 2,997 | 2.53125 | 3 | [
"MIT"
] | permissive | module Lotus
module Model
module Adapters
# Shared implementation for SqlAdapter and MemoryAdapter
#
# @api private
# @since 0.1.0
module Implementation
# Creates or updates a record in the database for the given entity.
#
# @param collection [Symbol] the target collection (it must be mapped).
# @param entity [#id, #id=] the entity to persist
#
# @return [Object] the entity
#
# @api private
# @since 0.1.0
def persist(collection, entity)
if entity.id
update(collection, entity)
else
create(collection, entity)
end
end
# Returns all the records for the given collection
#
# @param collection [Symbol] the target collection (it must be mapped).
#
# @return [Array] all the records
#
# @api private
# @since 0.1.0
def all(collection)
# TODO consider to make this lazy (aka remove #all)
query(collection).all
end
# Returns an unique record from the given collection, with the given
# id.
#
# @param collection [Symbol] the target collection (it must be mapped).
# @param id [Object] the identity of the object.
#
# @return [Object] the entity
#
# @api private
# @since 0.1.0
def find(collection, id)
_first(
_find(collection, id)
)
end
# Returns the first record in the given collection.
#
# @param collection [Symbol] the target collection (it must be mapped).
#
# @return [Object] the first entity
#
# @api private
# @since 0.1.0
def first(collection)
_first(
query(collection).asc(_identity(collection))
)
end
# Returns the last record in the given collection.
#
# @param collection [Symbol] the target collection (it must be mapped).
#
# @return [Object] the last entity
#
# @api private
# @since 0.1.0
def last(collection)
_first(
query(collection).desc(_identity(collection))
)
end
private
def _collection(name)
raise NotImplementedError
end
def _mapped_collection(name)
@mapper.collection(name)
end
def _find(collection, id)
identity = _identity(collection)
query(collection).where(identity => _id(collection, identity, id))
end
def _first(query)
query.limit(1).first
end
def _identity(collection)
_mapped_collection(collection).identity
end
def _id(collection, column, value)
_mapped_collection(collection).deserialize_attribute(column, value)
end
end
end
end
end
| true |
1be22b752eaf78529fa251e9d9b800479f326a24 | Ruby | Capleugh/backend_module_0_capstone | /day_7/ceasar_cipher.rb | UTF-8 | 965 | 3.390625 | 3 | [] | no_license |
class CeasarCipher
def encode(phrase, shift_num)
p phrase.downcase.chars
# if x[0] == a[7]
# #find away to dynamically code x[0] - x[10 or however many letters there are in a string]
# p shift = a.rotate(5)
# p shift[7]
# if x[1] == alphabet[4]
# p shift = alphabet.rotate(5)
# p shift[4]
# require 'pry'; binding.pry
# end
end
end
cipher = CeasarCipher.new
cipher.encode("Hello World", 5)
puts "Hello World".downcase.chars
p ord = {
"a" => "a".ord,
"b" => "b".ord,
"c" => "c".ord,
"d" => "d".ord,
"e" => "e".ord,
"f" => "f".ord,
"g" => "g".ord,
"h" => "h".ord,
"i" => "i".ord,
"j" => "j".ord,
"k" => "k".ord,
"l" => "l".ord,
"m" => "m".ord,
"n" => "n".ord,
"o" => "o".ord,
"p" => "p".ord,
"q" => "q".ord,
"r" => "r".ord,
"s" => "s".ord,
"t" => "t".ord,
"u" => "u".ord,
"v" => "v".ord,
"w" => "w".ord,
"x" => "x".ord,
"y" => "y".ord,
"z" => "z".ord,
}
| true |
e6861222e321268a7a8a1ab690d7ad4d3329e8de | Ruby | averysoren/ls-core-curriculum | /rb101/lesson3/easy2.rb | UTF-8 | 1,530 | 3.609375 | 4 | [] | no_license | # easy2.rb
=begin
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
Question 1
ages.key?("Spot")
ages.has_key?("Spot")
ages.member("Spot")
ages.include?("Spot")
Question 2
munsters_description = "The Munsters are creepy in a good way."
"tHE mUNSTERS ARE CREEPY IN A GOOD WAY."
"The munsters are creepy in a good way."
"the munsters are creepy in a good way."
"THE MUNSTERS ARE CREEPY IN A GOOD WAY."
munsters_description.swapcase!
munsters_description.capitalize!
munsters_description.downcase!
munsters_description.upcase!
Question 3
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10 }
additional_ages = { "Marilyn" => 22, "Spot" => 237 }
ages.merge!(additional_ages)
Question 4
advice = "Few things in life are as important as house training your pet dinosaur."
advice.match?("Dino")
Question 5
flintstones = ["Fred", "Barney", "Wilma", "Betty", "BamBam", "Pebbles"]
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
Question 6
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
flintstones << "Dino"
Question 7
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
flintstones << "Dino"
Question 8
advice = "Few things in life are as important as house training your pet dinosaur."
advice.slice(0..38)
If you use the #slice method instead, it will return the portion removed
but the original string will remain the same.
Question 9
statement = "The Flintstones Rock!"
statement.count('t')
Question 10
title = "Flintstone Family Members"
title.center(40)
| true |
926a4eaf81c3c54517d9e7f604d8959cf258ebb4 | Ruby | RenatoRosaFranco/rspec-book | /spec/models/contact_spec.rb | UTF-8 | 1,730 | 2.53125 | 3 | [] | no_license | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Contact, type: :model do
subject(:contact) { FactoryBot.build(:contact) }
it 'has a valid factory' do
expect(contact).to be_valid
end
it 'is a valid with a firstname, lastname and email' do
expect(contact).to be_valid
end
it 'is invalid without a firstname' do
contact.firstname = nil
contact.valid?
expect(contact.errors[:firstname]).to include("can't be blank")
end
xit 'is invalid without a lastname' do
contact.lastname = nil
contact.valid?
expect(contact.errors[:lastname]).to include("can't be blank")
end
it 'is invalid without an email address' do
contact.email = nil
contact.valid?
expect(contact.errors[:email]).to include("can't be blank")
end
it 'is invalid with a duplicate email address' do
contact = FactoryBot.create(:contact)
john_doe = FactoryBot.build(:contact, firstname: 'John', lastname: 'Doe 2')
john_doe.valid?
expect(john_doe.errors[:email]).to include('has already been taken')
end
it 'returns a contact\'s full name as a string' do
expect(contact.full_name).to eq('John Doe')
end
describe 'filter last name by letter' do
subject(:smith) { FactoryBot.create(:smith) }
subject(:jones) { FactoryBot.create(:jones) }
subject(:johnson) { FactoryBot.create(:johnson) }
context 'matching letters' do
it 'returns a sorted array of results that match' do
expect(Contact.by_letter('J')).to eq([johnson, jones])
end
end
context 'non-matching letters' do
it 'omits results that do not match' do
expect(Contact.by_letter('J')).not_to include(smith)
end
end
end
end
| true |
258ecd7e2dc8b1ab55d82ac315e46619e8ad8b64 | Ruby | eduardosasso/bullish | /services/percent.rb | UTF-8 | 373 | 2.921875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Services
class Percent
def initialize(new, original)
@new = new
@original = original
end
def self.diff(new, original)
Percent.new(new, original)
end
def value
(((@new.to_f - @original.to_f) / @original.to_f) * 100).round(2)
end
def to_s
value.to_s + '%'
end
end
end
| true |
c40d99dea3d61765c60440056a1299624538c944 | Ruby | chriswhitehouse/bowling-challenge-ruby | /lib/game.rb | UTF-8 | 1,408 | 3.421875 | 3 | [
"MIT"
] | permissive | require 'frame'
class Game
MAX_FRAMES = 10
def self.create
Game.new
end
def score(scores)
@scores = scores
scores_to_frames
add_bonuses_to_frames
cumulative_scores
end
private
def initialize(frames_collection_class = FramesCollection)
@frames = frames_collection_class.new
end
def scores_to_frames
number = 1
@frames.add_frame(number)
@scores.each do |score|
if @frames.frame(number).complete?
number += 1
@frames.add_frame(number)
end
@frames.frame(number).add_roll(score)
end
end
def add_bonuses_to_frames
@frames.collection.each do |frame|
if frame.number == MAX_FRAMES
frame
elsif frame.spare?
frame.add_bonus(next_score(frame.number))
elsif frame.strike?
frame.add_bonus(next_score(frame.number))
frame.add_bonus(second_next_score(frame.number))
end
end
end
def cumulative_scores
prior_frame_total_score = 0
@frames.collection.map do |frame|
prior_frame_total_score = frame.total_score(prior_frame_total_score)
end
end
def next_score(number)
@frames.frame(number + 1).first_roll_score
end
def second_next_score(number)
if @frames.frame(number + 1).second_roll_score
@frames.frame(number + 1).second_roll_score
else
@frames.frame(number + 2).first_roll_score
end
end
end
| true |
6e483a3b4b18da5f7023bd7a68394b3bc8bd0cf3 | Ruby | terryg/haze | /models/asset.rb | UTF-8 | 1,657 | 2.71875 | 3 | [] | no_license | require 'digest/md5'
class Asset
include DataMapper::Resource
property :id, Serial, :index => true
property :s3_fkey, String
property :created_at, DateTime
property :deleted, Boolean, :default => false
property :md5sum, String
property :type, String
validates_presence_of :s3_fkey, :created_at
after :create do
fname = 'tmp/' + self.s3_fkey
self.md5sum = Asset.calc_md5sum(fname)
save_self(false)
end
def self.calc_md5sum(fname)
Digest::MD5.hexdigest(File.read(fname))
end
def self.fetch(url)
begin
url = URI.parse(url)
fname = Net::HTTP.start(url.host, url.port) do |http|
resp, data = http.get(url.path, nil)
target = File.join(File.dirname(__FILE__), "../tmp/#{Time.now.to_i}.jpg")
open(target, "wb") { |file| file.write(resp.body) }
target
end
rescue => e
puts "ERROR #{e}"
end
return fname
end
def self.s3_bucket
ENV['S3_BUCKET_NAME']
end
def self.store_on_s3(temp_file, filename)
value = (0...16).map{(97+rand(26)).chr}.join
ext = File.extname(filename)
fkey = value + ext
fname = 'tmp/' + fkey
File.open(fname, "w") do |f|
f.write(temp_file.read)
end
AWS::S3::S3Object.store(fkey, open(fname), self.s3_bucket)
return fkey
end
def delete_s3
puts "INFO: Asset #{self.id} exists with S3 #{self.s3_fkey}? #{AWS::S3::S3Object.exists?(self.s3_fkey, self.class.s3_bucket)}"
AWS::S3::S3Object.delete(self.s3_fkey, self.class.s3_bucket)
puts "INFO: delete_s3 done."
end
def url
"https://s3.amazonaws.com/#{self.class.s3_bucket}/#{self.s3_fkey}"
end
end
| true |
208cb04c4ecc2862fb7e0207e8a135e914898809 | Ruby | hanseuly/coderbyte | /TimeConvert.rb | UTF-8 | 282 | 3.34375 | 3 | [] | no_license | def TimeConvert(num)
time = num/60
minute = (num-time*60).modulo(60)
out = [time, minute]
return out.insert(1, ':').to_s.inject(:+)
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
TimeConvert(STDIN.gets)
| true |
99ae10aeb91b2f6e9825a0b7f30cbb2ffa8d1ef4 | Ruby | toryu1121/puyoaptana | /作ったプログラム群/sousa.rb | UTF-8 | 1,914 | 3.59375 | 4 | [] | no_license | require './matrixx'
class Sousa
def initialize
#操作空間
@sousapuyo = Matrix.new(5, 3)
@widthcon = 2
@roll = [0, 1, 2, 3]
#初期位置
@sousapuyo.inputstr("nil")
@sousapuyo.mat[0][@widthcon] = "a"
@sousapuyo.mat[1][@widthcon] = "b"
@sousapuyo.tdisp
loop do
story01
story02
@sousapuyo.tdisp
end
end
def story01
#ぷよの回転
#一回転する入力
input = gets.to_i
case input
when 1
@widthcon-=1 unless @widthcon == 0
when 2 #落下させる
when 3
@widthcon+=1 unless @widthcon == 5
when 4
@roll.unshift(@roll.pop)
when 5
@roll.push(@roll.shift)
else
#break
end
end
def story02
case @roll[0]
when 0
@sousapuyo.inputstr(nil)
@sousapuyo.mat[0][@widthcon] = "a"
@sousapuyo.mat[1][@widthcon] = "b"
when 1
#もし一番右以外でこの操作がされたら
unless @widthcon == 5
@sousapuyo.inputstr(nil)
@sousapuyo.mat[1][@widthcon+1] = "a"
@sousapuyo.mat[1][@widthcon] = "b"
else
@sousapuyo.inputstr(nil)
@sousapuyo.mat[1][@widthcon] = "a"
@sousapuyo.mat[1][@widthcon-1] = "b"
@widthcon = 4
end
when 2
@sousapuyo.inputstr(nil)
@sousapuyo.mat[2][@widthcon] = "a"
@sousapuyo.mat[1][@widthcon] = "b"
when 3
unless @widthcon == 0
@sousapuyo.inputstr(nil)
@sousapuyo.mat[1][@widthcon-1] = "a"
@sousapuyo.mat[1][@widthcon] = "b"
else
@sousapuyo.inputstr(nil)
@sousapuyo.mat[1][@widthcon] = "a"
@sousapuyo.mat[1][@widthcon+1] = "b"
@widthcon = 1
end
end
end
end
class AAA
def initialize
Sousa.new
end
end
AAA.new | true |
d2718303d7787aec29e7b02660d3f026d3b0e9ea | Ruby | gustavokath/advent-of-code-2020 | /9A/main.rb | UTF-8 | 560 | 2.578125 | 3 | [] | no_license | line_idx = 0
PREABLE_SIZE = 25
preable_hash = {}
import = []
$stdin.each_line do |line|
value = line.strip.to_i
if line_idx < PREABLE_SIZE
preable_hash[value] = true
import.append(value)
else
found = false
preable_hash.each_key do |key|
dif = value - key
if preable_hash.key? dif
found = true
break
end
end
unless found
p value
return
end
import.append(value)
preable_hash[value] = true
preable_hash.delete(import[line_idx-PREABLE_SIZE])
end
line_idx += 1
end | true |
eda090a7bec363d6bf95e2b21307b60d83244f13 | Ruby | duffuniverse/duff-exercism | /ruby/anagram/anagram.rb | UTF-8 | 413 | 3.546875 | 4 | [] | no_license | class Anagram
attr_reader :subject
def initialize(subject)
@subject = subject.downcase
end
def match(candidates)
candidates.select do |candidate|
subject != candidate.downcase &&
char_count(subject) == char_count(candidate.downcase)
end
end
private
def char_count(word)
word.chars.reduce({}) { |hash, char| hash.merge(char => hash.fetch(char, 0) + 1) }
end
end
| true |
680ef90c36b495eb2834b298f394dd94a42e2102 | Ruby | DougWelchons/enigma | /test/enigma_test.rb | UTF-8 | 4,244 | 2.78125 | 3 | [] | no_license | require 'simplecov'
SimpleCov.start
require 'minitest/autorun'
require 'minitest/pride'
require 'mocha/minitest'
require './lib/enigma'
class EnigmaTest < Minitest::Test
def test_it_exists
enigma = Enigma.new
assert_instance_of Enigma, enigma
end
def test_it_can_generate_a_random_key
enigma = Enigma.new
assert_equal 5, enigma.key_gen.length
assert_instance_of String, enigma.key_gen
end
def test_it_can_encrypt_with_a_key_and_date
enigma = Enigma.new
encrypt = enigma.encrypt('hello world', '02715', '040895')
expected = {
encryption: 'keder ohulw',
key: '02715',
date: '040895'
}
assert_equal expected, encrypt
end
def test_it_can_decrypt_with_a_key_and_date
enigma = Enigma.new
enigma.decrypt('keder ohulw', '02715', '040895')
expected = {
decryption: 'hello world',
key: '02715',
date: '040895'
}
decrypt = enigma.decrypt('keder ohulw', '02715', '040895')
assert_equal expected, decrypt
end
def test_it_can_encrypt_with_only_a_key
enigma = Enigma.new
Time.stubs(:now).returns(Time.mktime(95, 8, 4))
expected = {
encryption: 'keder ohulw',
key: '02715',
date: '040895'
}
assert_equal expected, enigma.encrypt('hello world', '02715')
end
def test_it_can_decrypt_with_only_a_key
enigma = Enigma.new
encrypted = enigma.encrypt('hello world', '02715')
expected = {
decryption: 'hello world',
key: '02715',
date: Time.now.strftime('%d%m%y')
}
assert_equal expected, enigma.decrypt(encrypted[:encryption], '02715')
end
def test_it_can_encrypt_without_a_key
enigma = Enigma.new
enigma.stubs(:key_gen).returns('02715')
Time.stubs(:now).returns(Time.mktime(95, 8, 4))
expected = {
encryption: 'keder ohulw',
key: '02715',
date: '040895'
}
assert_equal expected, enigma.encrypt('hello world')
end
def test_it_can_crack_an_encryption_with_a_date
enigma = Enigma.new
expected = {
decryption: 'hello world end',
key: [19, -14, -5, -5],
date: '291018'
}
assert_equal expected, enigma.crack('vjqtbeaweqihssi', '291018')
end
def test_it_can_crack_an_encryption_without_a_date
enigma = Enigma.new
Time.stubs(:now).returns(Time.mktime(95, 8, 4))
expected = {
decryption: 'hello world end',
key: [19, -14, -5, -5],
date: '291018'
}
assert_equal expected, enigma.crack('vjqtbeaweqihssi', '291018')
end
def test_it_can_parse_encryption_data
enigma = Enigma.new
enigma.stubs(:encrypt).with('hello worls', '12345', '010121').returns('option1')
enigma.stubs(:encrypt).with('hello worls', '12345').returns('option2')
enigma.stubs(:encrypt).with('hello worls').returns('option3')
assert_equal 'option1', enigma.parse_data_encrypt('hello worls', ['12345', '010121'])
assert_equal 'option2', enigma.parse_data_encrypt('hello worls', ['12345'])
assert_equal 'option3', enigma.parse_data_encrypt('hello worls', [])
end
def test_it_can_parse_decryption_data
enigma = Enigma.new
enigma.stubs(:decrypt).with('keder ohulw', '12345', '010121').returns('option1')
enigma.stubs(:decrypt).with('keder ohulw', '12345').returns('option2')
enigma.stubs(:decrypt).with('keder ohulw').returns('option3')
assert_equal 'option1', enigma.parse_data_decrypt('keder ohulw', ['12345', '010121'])
assert_equal 'option2', enigma.parse_data_decrypt('keder ohulw', ['12345'])
assert_equal 'option3', enigma.parse_data_decrypt('keder ohulw', [])
end
def test_it_can_parse_code_break_data
enigma = Enigma.new
enigma.stubs(:crack).with('keder ohulw', '010121').returns('option1')
enigma.stubs(:crack).with('keder ohulw').returns('option2')
assert_equal 'option1', enigma.parse_data_crack('keder ohulw', ['010121'])
assert_equal 'option2', enigma.parse_data_crack('keder ohulw', [])
end
end
| true |
15fb65ab5033f407fbc87448ed346725eb6cb8bf | Ruby | osbornebrook/sanitize_email | /lib/sanitize_email/sanitize_email.rb | UTF-8 | 2,381 | 2.625 | 3 | [
"MIT"
] | permissive | #Copyright (c) 2008 Peter H. Boling of 9thBit LLC
#Released under the MIT license
module OBDev
module SanitizeEmail
def self.included(base)
# Adds the following class attributes to the classes that include OBDev::SanitizeEmail
base.cattr_accessor :force_sanitize
base.force_sanitize = nil
# Specify the BCC addresses for the messages that go out in 'local' environments
base.cattr_accessor :sanitized_bcc
base.sanitized_bcc = nil
# Specify the CC addresses for the messages that go out in 'local' environments
base.cattr_accessor :sanitized_cc
base.sanitized_cc = nil
# The recipient addresses / domains (@example.com) allowed for the messages, either as a string (for a single
# address) or an array (for multiple addresses) that go out in 'local' environments
base.cattr_accessor :allowed_recipients
base.allowed_recipients = nil
base.cattr_accessor :sanitized_recipient
base.sanitized_recipient = nil
base.class_eval do
#We need to alias these methods so that our new methods get used instead
alias :real_bcc :bcc
alias :real_cc :cc
alias :real_recipients :recipients
def localish?
#consider_local is a method in sanitize_email/lib/custom_environments.rb
# it is included in ActionMailer in sanitize_email/init.rb
!self.class.force_sanitize.nil? ? self.class.force_sanitize : self.class.consider_local?
end
def recipients(*addresses)
real_recipients *addresses
puts "sanitize_email error: allowed_recipients is not set" if self.class.allowed_recipients.nil?
use_recipients = [*addresses].map do |a|
user, domain = a.split('@')
[*self.class.allowed_recipients].include?(a) || [*self.class.allowed_recipients].include?("@#{domain}") ? a : self.class.sanitized_recipient
end
localish? ? use_recipients.uniq : real_recipients
end
def bcc(*addresses)
real_bcc *addresses
localish? ? self.class.sanitized_bcc : real_bcc
end
def cc(*addresses)
real_cc *addresses
localish? ? self.class.sanitized_cc : real_cc
end
end
end
end # end Module SanitizeEmail
end # end Module OBDev
| true |
6d253cd5f2bb6f3df6964d7d929f82f97661ae36 | Ruby | mybuddymichael/poke | /test/test.rb | UTF-8 | 2,734 | 2.984375 | 3 | [
"Ruby",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require_relative "test_helper.rb"
class TestWindow < MiniTest::Unit::TestCase
def setup
@window = Window.new
end
def test_that_window_is_created
refute_nil(@window)
end
end
class TestControls < MiniTest::Unit::TestCase
def setup
@window = Window.new
@controls = @window.controls
end
def test_that_pressing_a_button_updates_the_controls
@window.button_down(Gosu::KbLeft)
assert_equal(:left, @controls.last_button_pressed)
end
def test_that_pressing_multiple_buttons_still_returns_last_button
@window.button_down(Gosu::KbLeft)
@window.button_down(Gosu::KbRight)
assert_equal(:right, @controls.last_button_pressed)
end
def test_releasing_a_button_removes_it_from_the_array
@window.button_down(Gosu::KbUp)
@window.button_down(Gosu::KbLeft)
@window.button_down(Gosu::KbDown)
@window.button_down(Gosu::KbRight)
@window.button_up(Gosu::KbDown)
@window.button_up(Gosu::KbRight)
assert_equal(:left, @controls.last_button_pressed)
end
def test_that_pressing_escape_toggles_pause
@window.button_down(Gosu::KbEscape)
assert_equal(true, @window.paused)
@window.button_down(Gosu::KbEscape)
assert_equal(false, @window.paused)
end
def test_pressing_but_not_releasing_escape_toggles_pause
@window.button_down(Gosu::KbEscape)
assert_equal(true, @window.paused)
@window.button_up(Gosu::KbEscape)
assert_equal(true, @window.paused)
end
def test_pressing_Q_should_quit_if_paused
skip("Haven't figured out how to test this yet.")
end
end
class TestUser < MiniTest::Unit::TestCase
def setup
@window = Window.new
@user = @window.instance_variable_get(:@user)
@starting_x = @user.x
@starting_y = @user.y
end
def test_that_user_is_created
refute_nil(@user)
end
def test_that_update_changes_the_direction
@window.button_down(Gosu::KbLeft)
@user.update
assert_equal(:left, @user.direction)
end
def test_that_user_moves
assert_equal(@starting_x, @user.x)
@window.button_down(Gosu::KbRight)
@user.update
assert_equal(:right, @user.direction)
assert_equal(@starting_x+2, @user.x)
end
end
class TestCoordinates < MiniTest::Unit::TestCase
def setup
@window = Window.new
@user = @window.instance_variable_get(:@user)
@coordinates = Coordinates.new(@window, @user)
end
def test_that_coordinates_are_created
refute_nil(@coordinates)
end
def test_that_update_changes_coordinate_text
@coordinates.update
assert_equal(@coordinates.instance_variable_get(:@x), @user.x)
end
def test_that_coordinates_respond_to_draw_method
@coordinates.draw
assert_respond_to(@coordinates, :draw)
end
end
| true |
9019f48097850ea7d70eb2d61752ca958c895a22 | Ruby | timmyshen/Coursera_Programming_Languages | /Section7/subclassing.rb | UTF-8 | 1,001 | 4.09375 | 4 | [
"MIT"
] | permissive | # Programming Languages, Dan Grossman, Jan-Mar 2013
# Section 7: Subclassing
class Point
attr_accessor :x, :y
def initialize(x,y)
@x = x
@y = y
end
def distFromOrigin
Math.sqrt(@x * @x + @y * @y) # why a module method? Less OOP :-(
end
def distFromOrigin2
Math.sqrt(x * x + y * y) # uses getter methods
end
end
class ColorPoint < Point
attr_accessor :color
def initialize(x,y,c="clear") # or could skip this and color starts unset
super(x,y) # keyword super calls same method in superclass
@color = c
end
end
# example uses with reflection
p = Point.new(0,0)
cp = ColorPoint.new(0,0,"red")
p.class # Point
p.class.superclass # Object
cp.class # ColorPoint
cp.class.superclass # Point
cp.class.superclass.superclass # Object
cp.is_a? Point # true
cp.instance_of? Point # false
cp.is_a? ColorPoint # true
cp.instance_of? ColorPoint # true
| true |
9229e86e4187322d5cb27c17cf96edea6c8cbfd4 | Ruby | iamvery/advent-of-code-2019 | /ruby/day9.rb | UTF-8 | 224 | 2.5625 | 3 | [] | no_license | $LOAD_PATH.unshift(File.expand_path("./lib/"))
require "computer"
input_program = File.read("../input/day9.txt")
puts "Enter mode ('1' for test mode [part 1], '2' for sensor boost mode [part 2]):"
Computer.(input_program)
| true |
20df2f6667c2d2e21cad8c10e2a145b22346ed21 | Ruby | jhunschejones/Ruby-Scripts | /episode_namer/lib/models/episode.rb | UTF-8 | 768 | 2.875 | 3 | [] | no_license | class Episode
DARLING_IN_THE_FRANXX_MATCHER = /^.*\](.*)\s-\s(\d{2}).*(\d{4}p).*$/
def self.from_file(file)
show_name, episode_number, episode_resolution = File.basename(file, ".*").match(DARLING_IN_THE_FRANXX_MATCHER).captures
new(
file: file,
number: episode_number,
show_name: show_name.strip,
name: nil,
resolution: episode_resolution
)
end
attr_accessor :file, :number, :show_name, :name, :resolution
def initialize(file:, number:, show_name:, name: nil, resolution: nil)
@file = file
@number = number
@show_name = show_name
@name = name
@resolution = resolution
end
def formatted_file_name
"#{show_name} - S01E#{number} - #{name} [#{resolution}]#{File.extname(file)}"
end
end
| true |
f4343271d99be3b1fa0fe1c16b874ad63457964e | Ruby | Th33x1l3/CRTU | /lib/crtu/utils/logger.rb | UTF-8 | 4,501 | 2.90625 | 3 | [
"MIT"
] | permissive | require 'rubygems'
require 'singleton'
require 'fileutils'
require 'log4r'
require 'tmpdir'
include Log4r
GLOBAL_LOGGER_FOLDER = File.join(Dir.pwd, 'logs')
GLOBAL_LOGGER_LOG_FILE = File.join(GLOBAL_LOGGER_FOLDER, 'logfile.log')
SECONDS_IN_DAY ||= 86400
class GlobalLogger
include Singleton
attr_reader :global_console_logger
attr_reader :global_file_logger
attr_reader :global_mix_logger
def initialize
# Chech if folder exists
# that way it creates the logs folder beforehand
dirname = File.dirname(GLOBAL_LOGGER_FOLDER)
unless File.directory?(dirname)
FileUtils.mkdir_p(GLOBAL_LOGGER_FOLDER)
end
@global_console_logger= Log4r::Logger.new('GlobalLoggerConsole')
@global_file_logger = Log4r::Logger.new('GlobalLoggerFile')
@global_mix_logger = Log4r::Logger.new('GlobalLoggerConsoleAndFile')
pf = PatternFormatter.new(:pattern => "[%l] @ %d : %M")
so = StdoutOutputter.new('console', :formatter => pf)
@global_console_logger.outputters << so
@global_console_logger.level = DEBUG
fo = RollingFileOutputter .new('f1',
filename: GLOBAL_LOGGER_LOG_FILE,
trunc: false,
:formatter => pf,
maxtime: SECONDS_IN_DAY )
@global_file_logger.outputters << fo
@global_file_logger.level = DEBUG
@global_mix_logger.outputters << so
@global_mix_logger.outputters << fo
@global_mix_logger.level = DEBUG
end
end
#add instance to kernel so we have global acess to them
module Kernel
# Console only log
def console_logger
GlobalLogger.instance.global_console_logger
end
# File only log
def file_logger
GlobalLogger.instance.global_file_logger
end
# Console and File log
def all_logger
GlobalLogger.instance.global_mix_logger
end
end
## Local, class wide logger. Should have include LocalLogger added to the class, logger is used
## In cucumber remenber to add teh Utils module to the world
## Usage sample:
## class A
## include LocalLogger
## def method
## mix_logger.debug "Logging to console and File: myHash: #{myHash}"
## end
## end
##
## It is currently implements three functions:
## console_logger() - logging to STDOUT
## file_logger() - logging to FILE
## mix_logger() - logging to both STDOUT and FILE
##
## if LOCAL_LOGGER_LOG_FILE not specified, "/tmp/" + self.class.to_s + "./log" will be used
##
LOCAL_LOGGER_LOG_FILE = File.join(Dir.pwd, 'logs', 'local_logfile.log')
module Utils
module LocalLogger
# Class console logger. The messages only go to the stdout
# No message is saved to file
def console_logger
@logger = Log4r::Logger.new('LocalLoggerConsole')
pf = PatternFormatter.new(:pattern => "[%l] : #{self.class} @ %d : %M")
so = StdoutOutputter.new('console', :formatter => pf)
@logger.outputters << so
@logger.level = DEBUG
@logger
end
# Class simple file logger. Message is stored in file, but
# it does not appear on stdout
def file_logger
log_file = (LOCAL_LOGGER_LOG_FILE.nil?) ? File.join(Dir.tmpdir , "#{self.class}.log") : LOCAL_LOGGER_LOG_FILE
@logger = Log4r::Logger.new('LocalLoggerFile')
pf = PatternFormatter.new(:pattern => "[%l] : #{self.class} @ %d : %M")
fo = RollingFileOutputter.new('f1',
filename: log_file,
trunc: false,
formatter: pf,
maxtime: SECONDS_IN_DAY)
@logger.outputters << fo
@logger.level = DEBUG
@logger
end
# Class wide console and file logger. Message appears on console output and it's stored on file
def all_logger
log_file = (LOCAL_LOGGER_LOG_FILE.nil?) ? File.join(Dir.tmpdir , "#{self.class}.log") : LOCAL_LOGGER_LOG_FILE
@logger = Log4r::Logger.new('LocalLoggerConsoleAndFile')
pf = PatternFormatter.new(:pattern => "[%l] : #{self.class} @ %d : %M")
so = StdoutOutputter.new('console', :formatter => pf)
fo = RollingFileOutputter.new('f1',
filename: log_file,
trunc: false,
formatter: pf,
maxtime: SECONDS_IN_DAY)
@logger.outputters << so
@logger.outputters << fo
@logger.level = DEBUG
@logger
end
end
end
| true |
14e727d6acbb64e6fd5c90785142eba767ddcca7 | Ruby | plkujaw/fizzbuzz | /lib/fizzbuzzapp.rb | UTF-8 | 142 | 3.09375 | 3 | [] | no_license | require_relative "fizzbuzz"
def fizzbuzzapp(count)
result = []
for i in 1..count
result << fizzbuzz(i)
end
return result
end | true |
4d85873dfb36678ddd554c150c3d0e33467c0d37 | Ruby | marcus-a-davis/phase-0 | /week-4/longest-string/my_solution.rb | UTF-8 | 647 | 4.21875 | 4 | [
"MIT"
] | permissive | # Longest String
# I worked on this challenge [by myself, with: ].
# longest_string is a method that takes an array of strings as its input
# and returns the longest string
#
# +list_of_words+ is an array of strings
# longest_string(list_of_words) should return the longest string in +list_of_words+
#
# If +list_of_words+ is empty the method should return nil
# Your Solution Below
def longest_string(list_of_words)
if list_of_words.empty?
nil
elsif list_of_words == ['']
return ''
elsif list_of_words.length == 1
return list_of_words.first
else
sorted = list_of_words.sort_by {|i| i.length}
return sorted[-1]
end
end | true |
6cd0eba13c2b7d790d313f3ca74ddbd8b3c72477 | Ruby | spacetimeltd/sasfeed_automatic | /importize.rake | UTF-8 | 9,054 | 2.578125 | 3 | [] | no_license | require 'csv'
require 'pry'
require 'action_view'
require 'fileutils'
# gen_sas goes first, then sasmap needs to be generated from the header
# after that asproducts, wsproduct, maproducts, can be created
# with amendments to the string types
#lib/tasks/import.rake
task :csv_model_import, [ :filename, :model ] => [ :environment ] do |task,args|
asdata = CSV.read(args[:filename], encoding:"cp1252")
keys = asdata.shift
if args[:model] == 'Asproduct'
keys[keys.index "id"] = "sku"
puts "\nheading name 'id' changed to 'sku'\n"
else
if keys.index "id"
# TODO rename primary_key_field so that id can be used
# for the time being I'm changing 'id' to 'sku' in the 3dcart table
puts "you have a field named id, but sql needs that"
break
end
end
if args[:model] == 'Sasproduct'
keys = Sasmap.attribute_names[1..-3]
end
asdata.each do |values|
params = {}
keys.each_with_index do |key,i|
params[key] = values[i] == nil ? "" : values[i]
end
Module.const_get(args[:model]).create(params)
end
end
task :show_off => :environment do
Sasproduct.where(:storeid => "1").each { |p| puts p.name }
Sasproduct.where(:storeid => "2").each { |p| puts p.name }
puts "How many with :StoreID 1?"
Sasproduct.where(:storeid => "1").count
puts "How many with :StoreID 2?"
Sasproduct.where(:storeid => [1]).count
puts "How many with either?"
Sasproduct.where(:storeid => [1..2]).count
end
task :delete_all_storeid_2 => :environment do
Sasproduct.delete(Sasproduct.where(:storeid => "2").map { |p| p.id })
# or you can do it this way
Sasproduct.where(:storeid => "2").delete_all
end
task :sasmap_3dcart, [ :prefix ] => [ :environment ] do |task,args|
# ok, didn't have as much fun with the database as I would have liked so instead...
# we're gonna grab the sas header (post modification) from the backup file
# then parse the JSON to use as keys for the sasmap object
sash = JSON.parse File.new("./data/sashead.json").readline
mappings = Sasmap.first
pre = args[:prefix]
premap = {
:WS => ["1","http://www.wrightstuff.biz"],
:AS => ["2", "http://www.arthritissupplies.com"],
:CG => ["3", "http://www.caregiverproducts.com"],
:MA => ["4", "http://www.mobility-aids.com"]
}
puts "Using URL: #{premap[pre.to_sym].last} as root"
if File.exists? "./data/#{pre}-exceptions.log"
FileUtils.rm "./data/#{pre}-exceptions.log"
end
outp = "columns:\nnotforsale | stock | sku | name | categories\n"
puts outp.encode!("cp1252")
File.open("./data/#{pre}-exceptions.log", "a+:cp1252") { |f| f << "#{outp}\n" }
include ActionView::Helpers::SanitizeHelper
# start with the mappings
products = Module.const_get("#{pre.capitalize}product").all
products.each do |pdata|
# first weed out the products with no stock - or not for sale
skipit = false
if pdata.notforsale == "1" || pdata.stock == "0"
a = [:notforsale, :stock, :sku, :name, :categories].map { |x| pdata[x] }
outp = a.join " | "
if pdata.stock == "0"
if outp =~ /discontinued/i
skipit = true
else
outp += " <==== ### Not excluded from feed. ###"
end
end
if pdata.notforsale == "1"
skipit = true
end
puts outp.encode!("cp1252")
File.open("./data/#{pre}-exceptions.log", "a+:cp1252") { |f| f << "#{outp}\n" }
if skipit
next
end
end
# Ok, lets break it down
begin
cats = pdata[:categories].split("@").pop.split("/")
rescue
cats = []
end
# and build it up again
params = {}
mappings.attribute_names[1..-3].each_with_index do |key,i|
if pdata[mappings[key]] == nil
pdata[mappings[key]] = mappings[key] # mappings[key] contains default if no mapping
end
data = pdata[mappings[key]]
root = premap[pre.to_sym].last
case key
when /storeid/i
data = premap[pre.to_sym].first
when /status/i
data = "instock"
when /description/i
data = strip_tags(data)
when /url_to_product/i, /url_to_image/i
if data.index("/") == 0
data = root + data
else
data = "#{root}/#{data}"
end
when /url_to_thumbnail/i
if data.index("/") == 0
data = root + "/thumbnail.asp?file=" + data + "&maxx=50&maxy=0"
else
data = "#{root}/thumbnail.asp?file=/#{data}&maxx=50&maxy=0"
end
when /merchantcategory/i
data = cats[0]
when /merchantsubcategory/i
data = cats[1]
when /merchantgroup/i
data = cats[2]
when /merchantsubgroup/i
data = cats[3]
when /QuantityDiscount/i
data = nil
end
if data =~ /<\w+?>/
puts data + " is invalid, possibly\n"
end
#puts "#{i}\t|\t#{key}\t|\t#{data}"
params[key] = data
end
Sasproduct.create(params);
end
# visually inspect the thumbnails
Sasproduct.select("URL_to_thumbnail_image").where("StoreID = 2").map { |sp| sp.URL_to_thumbnail_image }
end
task :export_sasfeed, [:prefix] => [:environment] do |task,args|
header = JSON.parse File.read("./data/sasspec.json")
prefs = {WS:'1', AS:'2', CG:'3', MA:'4'}
pdata = Sasproduct.where(:StoreID => prefs[args[:prefix].to_sym])
file = "./data/#{args[:prefix]}-SAS-products-export.csv"
fields = pdata.attribute_names[1..-3]
puts "selected attributes: #{fields}"
CSV.open(file, "wb:cp1252") do |csv|
csv << header
pdata.select(fields).each do |record|
csv << record.attributes.values
end
end
end
task :outputerrors => :environment do
header = JSON.parse File.read("./data/sasspec.json")
pdata = Sasproduct.where('StoreID NOT IN ( "1", "2", "4" )')
csv = CSV.open("oopsSet.csv", "wb:cp1252")
pdata.select(Sasproduct.attribute_names[1..-3]).each { |r| csv << r.attributes.values }
csv.close
end
task :totals => :environment do
puts "WS SAS-feed product data records: #{Sasproduct.where(StoreID:'1').count}"
puts "AS SAS-feed product data records: #{Sasproduct.where(StoreID:'2').count}"
puts "CG SAS-feed product data records: #{Sasproduct.where(StoreID:'3').count}"
puts "MA SAS-feed product data records: #{Sasproduct.where(StoreID:'4').count}"
puts "total: #{Sasproduct.count}"
end
task :del, [ :target ] => [ :environment ] do |task,args|
puts Sasproduct.where(StoreID:args[:target]).delete_all
end
task :gen_scaffold_args, [ :filename, :model ] => [ :environment ] do |task,args|
asdata = CSV.read(args[:filename], encoding:"cp1252")
header = asdata.first
output = ""
header.each { |x| output += x+":string " };
output = "rails generate scaffold #{args[:model]} #{output}"
outname = "./data/" + args[:model] + "_genscaff.sh"
File.new(outname, "w").write output
# if you have a table heading named ID, that will not do.
# also if you have things with duplicate names, no good at all
if output =~ /id:string/
puts "Whoooooa! Id is not ok for a field name!\n"
end
end
task :gen_sas => :environment do
sashead = CSV.parse(File.new("./data/shareasale.csv").readline, encoding:"cp1252").shift
# save a copy of original column names
sasspec = []
sashead.each { |val| sasspec.push val }
sasspec = sasspec.to_json
Stuff.create(name:"sasspec", data:sasspec)
File.new("./data/sasspec.json", "w").write sasspec
# then modify whitespace
sashead.each_with_index { |val,i| sashead[i] = val.gsub(/ /,"_") }
# save the header keys
count = 0
sashead.map! do |shd|
if shd == "ReservedForFutureUse"
shd = "#{shd}#{count+=1}"
else
shd
end
end
Stuff.create(name:"sashead", data:sashead.to_json)
File.new("./data/sashead.json","w").write sashead.to_json
first, *rest = *sashead
outStr = "#{first}:string"
rest.each { |shd| outStr += " #{shd}:string" }
outStr = "rails generate scaffold Sasmap #{outStr}"
File.new("./data/Sasmap_genscaf.sh", "w").write outStr
# adjust the field types for larger strings
outStr = "#{first}:string"
rest.each do |shd|
case shd
when "Description", "SearchTerms"
type = ":text"
else
type = ":string"
end
outStr += " #{shd}#{type}"
end
outStr = "rails generate scaffold Sasproduct #{outStr}"
File.new("./data/Sasproduct_genscaf.sh", "w").write outStr
puts "\nDon't forget to double check your string limits.\n"
puts "However, Sasmap_genscaf.sh should be all string types\n"
puts "and Sasproduct_genscaf.sh should have 2 fields altered for text.\n"
end
| true |
bd7021dd2779b90f5c7ecf21add3bedccd9fd5ef | Ruby | kateskips/square_array-dumbo-web-career-012819 | /square_array.rb | UTF-8 | 56 | 2.78125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def square_array(array)
array.each
Math.sqrt(array)
end | true |
6a0ea4faffd1dc89e72e11fe34012e363f2765da | Ruby | nuringa/communication_test | /main.rb | UTF-8 | 562 | 2.921875 | 3 | [] | no_license | require_relative 'lib/test_passage'
require_relative 'lib/result'
require_relative 'lib/file_reader'
puts 'ВАШ УРОВЕНЬ ОБЩИТЕЛЬНОСТИ'
puts 'Тест поможет определить ваш уровень коммуникабельности.'
puts
puts 'Правдиво ответьте на вопросы:'
test_data = FileReader.new
test = TestPassage.new
test.proceed_test(test_data.questions)
result = Result.choose_result(test.total, test_data.results)
puts "Результат: #{test.total} баллов."
puts
puts result
| true |
f88fe111a311097fdfeb40e4ca7bc7a7921de576 | Ruby | huangzhichong/shooter.cn_downloader | /downloader.rb | UTF-8 | 2,491 | 2.703125 | 3 | [] | no_license | require "digest/md5"
require "rest-client"
require "json"
require 'open-uri'
require 'open-uri'
class Downloader
def initialize(movie_path)
@shooter_url = "http://www.shooter.cn/api/subapi.php"
@movie_path = movie_path
@movie_utf8_path = URI::encode(@movie_path.force_encoding("utf-8"))
@block_size = 4096
@@file = File.open(@movie_path)
@@file_length = @@file.size
end
def get_movie_fingerprint
# get hash(encode with md5) of movie file
# https://docs.google.com/document/d/1w5MCBO61rKQ6hI5m9laJLWse__yTYdRugpVyz4RzrmM/preview?pli=1
# get file block from 4 parts of file, each block is 4096 byte
# 4k from begining of the file
# 1/3 of total file length
# 2/3 of total file length
# 8k from end of the file
fingerprints = []
unless @@file_length < 8192
[4096,@@file_length/3*2,@@file_length/3, @@file_length-8192].each do |offset|
@@file.seek offset
fingerprints << Digest::MD5.hexdigest(@@file.read(@block_size))
end
else
puts "get wrong file, a vedio should be larger than 8192"
end
fingerprint = URI::encode(fingerprints.join(';').force_encoding("utf-8"))
end
# search subtitle with shooter.cn API
# https://docs.google.com/document/d/1ufdzy6jbornkXxsD-OGl3kgWa4P9WO5NZb6_QYZiGI0/preview?pli=1
def search_subtitles(language="Chn", subtitle_format="srt")
search_result = []
data = {"filehash"=>get_movie_fingerprint,
"pathinfo" => @movie_utf8_path,
"format" => "json",
"lang"=>language}
index=1
begin
results = JSON.parse (RestClient.post @shooter_url,data).body
results.each do |r|
r['Files'].each do |f|
if f['Ext'] == subtitle_format
sub_name = (@movie_path.split(".")[0..-2]<<index<<'srt').join(".")
search_result << {"file" => sub_name, "url" => f['Link'].gsub('https:/','http:/')}
index += 1
end
end
end
rescue Exception => e
puts "Failed to search subtitle from shooter.cn"
puts "get erros ------> #{e}"
end
search_result
end
# download file with wget
def download_subtitles
search_subtitles.each do |result|
command = %Q(wget -O "#{result['file']}" "#{result['url']}")
system command
end
end
end
path = "/Users/huangsmart/Downloads/Non-Stop.2014.1080p.BluRay.X264-AMIABLE[rarbg]/Non-Stop.2014.1080p.BluRay.X264-AMIABLE.mkv"
Downloader.new(path).download_subtitles
| true |
846c5969e80e87692de36ee426ac449be2d1f156 | Ruby | traciechang/algorithm-problems | /longest_palindromic_substring.rb | UTF-8 | 1,282 | 3.828125 | 4 | [] | no_license | require 'pry'
def longest_palindrome(s)
return "" if s == ""
seen = {}
palindromes = {}
s.each_char.with_index do |char, idx|
if seen[char]
# binding.pry
if idx - palindromes[idx-1] - 1 == seen[char] || is_palindrome?(s[seen[char]..idx])
palindromes[idx] = s[seen[char]..idx].length
# palindromes[idx] = palindromes[idx-1] + 1
seen[char] = idx
else
seen[char] = idx
palindromes[idx] = 1
end
else
seen[char] = idx
palindromes[idx] = 1
end
end
# binding.pry
pal_length = palindromes.values.max
idx_end = palindromes.key(pal_length)
s[idx_end-pal_length+1..idx_end]
end
def is_palindrome?(str)
start_idx = 0
end_idx = str.length - 1
until start_idx >= end_idx
return false if str[start_idx] != str[end_idx]
start_idx +=1
end_idx -=1
end
true
end
# puts longest_palindrome("babad")
# puts longest_palindrome("cbbd")
# puts longest_palindrome("racecar")
# puts longest_palindrome("")
# puts longest_palindrome("dog")
puts longest_palindrome("zatabbamafa")
# puts longest_palindrome("ccc")
# puts longest_palindrome("zaabbaaf") | true |
a8423091a438c7b34480c9d62a27b50d9d7f88f7 | Ruby | dendiflet/THPS03J2 | /lib/app/store_into_csv.rb | UTF-8 | 272 | 2.71875 | 3 | [] | no_license | #store_into_csv
require 'csv'
class StoreIntoCSV
def create_file_and_write_in(imput)
#crée un fichier et écris dedans
CSV.open("database/csv_emails_list.csv", "w") do |csv|
imput.each do |k , v|
csv << [k, v]
end
end
end
end
| true |
93b5ba33fd66ddb702be9d628921b4ef4e5f80e9 | Ruby | lsamano/ruby-objects-belong-to-lab-dumbo-web-121018 | /lib/post.rb | UTF-8 | 221 | 2.90625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Post
attr_accessor :title, :author
@@all = []
def self.all
@@all
end
def self.new_post(title, author)
post = Post.new
@title = title
@author = author
self.class.all << post
end
end
| true |
3266e4016c81737cd1fe3a3db8819dd69459552f | Ruby | square/connect-api-examples | /connect-examples/v1/ruby/payments-report.rb | UTF-8 | 6,732 | 3.125 | 3 | [] | no_license | # Demonstrates generating the last year's payments report with the Square Connect API.
# Replace the value of the `ACCESS_TOKEN` variable below before running this script.
#
# This sample assumes all monetary amounts are in US dollars. You can alter the
# formatMoney function to display amounts in other currency formats.
#
# This sample requires the Unirest Ruby gem. Download instructions are here:
# http://unirest.io/ruby.html
require 'set'
require 'unirest'
require 'uri'
require 'date'
# Replace this value with your application's personal access token,
# available from your application dashboard (https://connect.squareup.com/apps)
ACCESS_TOKEN = 'REPLACE_ME'
# The base URL for every Connect API request
CONNECT_HOST = 'https://connect.squareup.com'
# Standard HTTP headers for every Connect API request
REQUEST_HEADERS = {
'Authorization' => 'Bearer ' + ACCESS_TOKEN,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
# Helper function to convert cent-based money amounts to dollars and cents
def format_money(money)
money_string = format("$%.2f", (money.abs/100.to_f))
if money < 0
money_string = '-' + money_string
end
return money_string
end
# Obtains all of the business's location IDs. Each location has its own collection of payments.
def get_location_ids()
request_path = '/v1/me/locations'
response = Unirest.get CONNECT_HOST + request_path,
headers: REQUEST_HEADERS
location_ids = []
if response.code == 200
locations = response.body
for location in locations
location_ids.push(location['id'])
end
else
raise response.body.to_s
end
return location_ids
end
# Retrieves all of a merchant's payments from last year
def get_payments(location_ids)
# Restrict the request to the last calendar year, eight hours behind UTC
# Make sure to URL-encode all parameters
parameters = URI.encode_www_form(
'begin_time' => Date.new(Time.now.year - 1, 1, 1).iso8601.to_s,
'end_time' => Date.new(Time.now.year, 1, 1).iso8601.to_s
)
payments = []
for location_id in location_ids
puts 'Downloading payments for location with ID ' + location_id + '...'
request_path = CONNECT_HOST + '/v1/' + location_id + '/payments?' + parameters
more_results = true
while more_results do
# Send a GET request to the List Payments endpoint
response = Unirest.get request_path,
headers: REQUEST_HEADERS,
parameters: parameters
if response.code == 200
# Read the converted JSON body into the cumulative array of results
payments += response.body
# Check whether pagination information is included in a response header, indicating more results
if response.headers.has_key?(:link)
pagination_header = response.headers[:link]
if pagination_header.include? "rel='next'"
# Extract the next batch URL from the header.
#
# Pagination headers have the following format:
# <https://connect.squareup.com/v1/MERCHANT_ID/payments?batch_token=BATCH_TOKEN>;rel='next'
# This line extracts the URL from the angle brackets surrounding it.
request_path = pagination_header.split('<')[1].split('>')[0]
else
more_results = false
end
else
more_results = false
end
else
raise response.body.to_s
end
end
end
# Remove potential duplicate values from the list of payments
seen_payment_ids = Set.new
unique_payments = []
for payment in payments
if seen_payment_ids.include? payment['id']
next
end
seen_payment_ids.add(payment['id'])
unique_payments.push(payment)
end
return unique_payments
end
# Prints a sales report based on an array of payments
def print_sales_report(payments)
# Variables for holding cumulative values of various monetary amounts
collected_money = taxes = tips = discounts = processing_fees = 0
returned_processing_fees = net_money = refunds = 0
# Add appropriate values to each cumulative variable
for payment in payments
collected_money = collected_money + payment['total_collected_money']['amount']
taxes = taxes + payment['tax_money']['amount']
tips = tips + payment['tip_money']['amount']
discounts = discounts + payment['discount_money']['amount']
processing_fees = processing_fees + payment['processing_fee_money']['amount']
net_money = net_money + payment['net_total_money']['amount']
refunds = refunds + payment['refunded_money']['amount']
# When a refund is applied to a credit card payment, Square returns to the merchant a percentage
# of the processing fee corresponding to the refunded portion of the payment. This amount
# is not currently returned by the Connect API, but we can calculate it as shown:
# If a processing fee was applied to the payment AND some portion of the payment was refunded...
if payment['processing_fee_money']['amount'] < 0 && payment['refunded_money']['amount'] < 0
# ...calculate the percentage of the payment that was refunded...
percentage_refunded = payment['refunded_money']['amount'] /
payment['total_collected_money']['amount'].to_f
# ...and multiply that percentage by the original processing fee
returned_processing_fees = returned_processing_fees +
(payment['processing_fee_money']['amount'] * percentage_refunded)
end
end
# Calculate the amount of pre-tax, pre-tip money collected
base_purchases = collected_money - taxes - tips
# Print a sales report similar to the Sales Summary in the merchant dashboard.
puts ''
puts '==SALES REPORT FOR ' + (Time.now.year - 1).to_s + '=='
puts 'Gross Sales: ' + format_money(base_purchases - discounts)
puts 'Discounts: ' + format_money(discounts)
puts 'Net Sales: ' + format_money(base_purchases)
puts 'Tax collected: ' + format_money(taxes)
puts 'Tips collected: ' + format_money(tips)
puts 'Total collected: ' + format_money(base_purchases + taxes + tips)
puts 'Fees: ' + format_money(processing_fees)
puts 'Refunds: ' + format_money(refunds)
puts 'Fees returned: ' + format_money(returned_processing_fees)
puts 'Net total: ' + format_money(net_money + refunds + returned_processing_fees)
end
# Call the functions defined above
begin
payments = get_payments(get_location_ids())
print_sales_report(payments)
rescue StandardError => e
puts e.message
end
| true |
5f739dc9a0880e82792c98df0c4ccfc5b837b8df | Ruby | ntnga/hoc-ruby | /Ruby/Chuong 10/ex10_2.rb | UTF-8 | 605 | 2.578125 | 3 | [] | no_license | require "./Chuong 10/lib_json"
include Lib_json
url = "http://dev-er.com/service_api_ban_sach/api_service_sach.php?task=sach_noi_bat"
content = doc_json_httparty(url)
puts "===========================THỐNG KÊ SÁCH NỔI BẬT==========================="
tong_sach = content.size
puts "Tổng số sách nổi bật : #{tong_sach} đầu sách"
i = 1
content.each do |sach|
puts "#{i} / #{sach["ten_sach"]} - Tác giả: #{sach["ten_tac_gia"]}"
puts "\t Ngày xuất bản: #{sach["ngay_xuat_ban"]} - Giá bìa: #{sach["gia_bia"]}"
puts "\t Nội dung: #{sach["gioi_thieu"][0,100]}"
i += 1
end | true |
279fb0714e0a06c034fab750906b29da7a78918b | Ruby | estebanz01/ruby-statistics | /spec/statistics/math_spec.rb | UTF-8 | 4,997 | 3.53125 | 4 | [
"MIT"
] | permissive | require 'spec_helper'
describe Math do
describe '.factorial' do
it 'is not defined for numbers less than zero' do
expect(described_class.factorial(rand(-100...0))).to be_nil
end
it 'returns one for zero or one' do
expect(described_class.factorial(0)).to eq 1
expect(described_class.factorial(1)).to eq 1
end
it 'calculates the correct factorial for the specified number' do
expect(described_class.factorial(2)).to eq 2
expect(described_class.factorial(3)).to eq 6
expect(described_class.factorial(4)).to eq 24
expect(described_class.factorial(5)).to eq 120
end
it 'truncates the decimal numbers and calculates the factorial for the real part' do
expect(described_class.factorial(5.4535459823483432434)).to eq 120
end
end
describe '.permutation' do
it 'calculates the possible permutations of k objects from a set of n elements' do
expect(described_class.permutation(15,4)).to eq 32760
expect(described_class.permutation(16, 3)).to eq 3360 # 16 balls, choose 3.
expect(described_class.permutation(10, 2)).to eq 90 # 10 people to select 1th and 2nd place.
end
end
describe '.combination' do
it 'calculates the possible combinations of k object from a set of n elements' do
expect(described_class.combination(16, 3)).to eq 560 # Order 16 balls in 3 ways.
expect(described_class.combination(5, 3)).to eq 10 # How to choose 3 people out of 5.
expect(described_class.combination(12, 5)).to eq 792 # How to choose 5 games out of 12.
end
end
describe '.simpson_rule' do
it 'approximates a solution in the [a,b] interval for the integral of the specified function' do
lower = rand(10)
upper = rand(11..20)
function_a = described_class.simpson_rule(lower, upper, 10_000) do |x|
x ** 2
end
function_b = described_class.simpson_rule(lower, upper, 10_000) do |x|
Math.sin(x)
end
res_a = ((upper ** 3)/3.0) - ((lower ** 3)/3.0) # Integral of x^2
res_b = -Math.cos(upper) + Math.cos(lower) # Integral of sin(x)
expect(function_a.floor).to eq res_a.floor
expect(function_b.floor).to eq res_b.floor
end
it 'is not defined when the iterations are not even numbers' do
expect(
described_class.simpson_rule(1, 2, 3) { |x| x }
).to be_nil
end
end
describe '.lower_incomplete_gamma_function' do
it "solves the function using the simpson's rule" do
lower = 0
upper = rand(1..5)
iteration = 10_000 * upper
expect(described_class).to receive(:simpson_rule).with(lower, upper, iteration)
described_class.lower_incomplete_gamma_function(lower, upper)
end
it 'returns the expected calculation' do
results = [0.6322, 0.594, 1.1536, 3.3992, 13.4283]
(1..5).each_with_index do |number, index|
expect(
described_class.lower_incomplete_gamma_function(number, number).round(4)
).to eq results[index]
end
end
# The following context is based on the numbers reported in https://github.com/estebanz01/ruby-statistics/issues/78
# which give us a minimum test case scenario where the integral being solved with simpson's rule
# uses zero iterations, raising errors.
context 'When X for the lower incomplete gamma function is rounded to zero' do
let(:s_parameter) { 4.5 }
let(:x) { (52/53).to_r }
it 'does not try to perform a division by zero' do
expect do
described_class.lower_incomplete_gamma_function(s_parameter, x)
end.not_to raise_error
end
it "tries to solve the function using simpson's rule with at least 100_000 iterations" do
expect(described_class).to receive(:simpson_rule).with(0, x, 100_000)
described_class.lower_incomplete_gamma_function(s_parameter, x)
end
end
end
describe '.beta_function' do
it 'returns 1 for the special case x = y = 1' do
expect(described_class.beta_function(1, 1)).to eq 1
end
it 'Calculates the expected values for the beta function' do
# TODO: Find a way to better test this instead of fixing some values.
result = [1, 0.1667, 0.0333, 0.0071, 0.0016]
(1..5).each_with_index do |number, index|
expectation = described_class.beta_function(number, number).round(4)
expect(expectation).to eq result[index]
end
end
end
describe '.incomplete_beta_function' do
it 'calculates the expected values for the incomplete beta function' do
# The last 2 values:
# For 9 is 0.9999979537560903519733 which is rounding to 1.0
# For 10 is 1.0
results = [0.19, 0.1808, 0.2557, 0.4059, 0.6230, 0.8418, 0.9685, 0.9985, 1.0, 1.0]
(1..10).each_with_index do |number, index|
expect(described_class.incomplete_beta_function(number/10.0, number, number + 1).round(4))
.to eq results[index]
end
end
end
end
| true |
819ba2c85c046c68dc801e817e55c3b9d9089036 | Ruby | ColtAdkins/calculator-cucumber | /features/step_definitions/addition_steps.rb | UTF-8 | 665 | 3.328125 | 3 | [
"MIT"
] | permissive | require 'calculator'
When /^I add two numbers$/ do
@value = Calculator.new.sum 6, 23
end
Then /^I get their value$/ do
expect(@value).to eq 29
end
When /^I add zero to a number$/ do
@value = Calculator.new.sum 6, 0
end
Then /^the value is that number$/ do
expect(@value).to eq 6
end
When /^I add the same numbers in different orders$/ do
@value1 = Calculator.new.sum 6
@value2 = Calculator.new.sum @value1
end
Then /^the values are the same$/ do
expect(@value1).to eq @value2
end
When /^I add more than two numbers$/ do
@value = Calculator.new.sum 15, 6, 9, 0
end
Then /^I get the value of multiple numbers$/ do
expect(@value).to eq 30
end | true |
19f615cd1aee408bafd9fabd5be090e24d8ef6d9 | Ruby | govindarajanv/ruby | /sololearn/namespacing.rb | UTF-8 | 724 | 4.34375 | 4 | [] | no_license | #namespacing means organizing similar classes in a module. In other words, we'll use modules to group related classes.
module Pet
class Dog
def speak
puts "Woof!"
end
end
class Cat
def speak
puts "Meow"
end
end
end
#We can have the same class names across different modules.
blacky = Pet::Dog.new
tinu = Pet::Cat.new
module MyMath
PI = 3.14
def self.square(x)
x*x
end
def self.negate(x)
-x
end
def self.factorial(x)
(1..x).inject(:*) || 1
end
end
# note the self keyword), and we call them using the dot syntax
# You can call the methods using two colon syntax (::) as well (MyMath::factorial(8)), but the dot syntax is preferred
puts MyMath.factorial(8)
| true |
22faf12d2e00bd32a2152426e92dd917a259244e | Ruby | alvarodltp/project-euler-multiples-3-5-dc-web-062518 | /lib/oo_multiples.rb | UTF-8 | 330 | 3.765625 | 4 | [] | no_license | # Enter your object-oriented solution here!
class Multiples
attr_accessor :num
def initialize(num)
@num = num
end
def collect_multiples
(1...self.num).to_a.select do |n|
n % 3 == 0 || n % 5 == 0
end
end
def sum_multiples
arr = collect_multiples
arr.inject(0){|sum, n| sum + n}
end
end
| true |
ce6fcbddba1ea3f34630cfc1c0a85c17f3fcb108 | Ruby | dhinojosa/language-matrix | /ruby/arrays/arrays.rb | UTF-8 | 370 | 3.53125 | 4 | [
"MIT"
] | permissive | a = [1, 2, 3, 4, 5]
b = a.collect do |i|
i + 2
end
c = a.collect {|i| i + 10}
puts "a: #{a}"
puts "b: #{b}"
puts "c: #{c}"
d = a[1]
puts "d: #{d}"
e = a.select{|i| i % 2 == 0}
puts "e:#{e}"
a.each{|i| puts i}
a.each_index{|i| puts i}
a.each_with_index{|o,i| puts "Object: #{o}; Index: #{i}"}
f = a.delete_if do |i|
i > 3
end
puts "a:#{a}"
puts "f:#{f}"
| true |
00f688bb36c732693072a8a20f2c1938a594068d | Ruby | nacltsutomu/ruby-exercise | /c11_compile.rb | UTF-8 | 3,653 | 4.28125 | 4 | [] | no_license | #
#puts "金額を入力してください"
#bill = gets.to_i
#puts "割り勘する人数を入力してください"
#number = gets.to_i
#warikan = bill / number
#puts "1人あたり#{warikan}円です"
# <hint>
# getsはキーボードからの入力を取り込むメソッド
# numberを0で入力した場合、ZeroDivisionError
#1
#例外処理
puts "金額を入力してください"
bill = gets.to_i
puts "割り勘する人数を入力してください"
number = gets.to_i
begin
warikan = bill / number
puts "1人あたり#{warikan}円です"
rescue ZeroDivisionError
#ZeroDivisionError例外が発生したらメッセージを表示
puts "おっと、0人では割り勘できません"
end
#2
#例外処理:メソッド内で例外処理を書く場合はbeginとendを省略できる。
def keisan(bill,number)
warikan = bill /number
puts "1人あたり#{warikan}円です"
rescue ZeroDivisionError
#ZeroDivisionError例外が発生したらメッセージを表示
puts "おっと、0人では割り勘できません"
end
keisan(100,0)
keisan(100,1)
keisan(100,2)
#3
#例外処理:ブロック内でもbeginとendを省略できる。
bill = 100
numbers = [0,1,2]
numbers.each do |number|
warikan = bill /number
puts "1人あたり#{warikan}円です"
rescue ZeroDivisionError
#ZeroDivisionError例外が発生したらメッセージを表示
puts "おっと、0人では割り勘できません"
end
#4
#例外処理を使わない:事前に値をチェックする。
def keisan(bill,number)
if number.zero?
puts "おっと、0人では割り勘できません"
return
end
warikan = bill /number
puts "1人あたり#{warikan}円です"
end
keisan(100,0)
keisan(100,1)
keisan(100,2)
#5
#例外の詳細情報を得る。
def cat(filename)
File.open(filename) do |file| #=> ファイルを開く
file.each_line {|line| puts line} #=> ファイルの内容を表示
end #=> ファイルを閉じる
rescue SystemCallError => e
puts "--- 例外が発生しました ---"
puts "例外クラス: #{e.class}"
puts "例外メッセージ: #{e.message}"
end
filename = ARGV.first #=> コマンドプロンプトの引数を読み込み
cat(filename)
# <hint>
# c11_test_menu.txtを作成する
# ruby c11_test.rb c11_test_menu.txtを実行
# これはエラーとはならないが、
# ruby c11_test.rb c11_test_menu2.txtを実行
# するとエラーになる。
# ※ARGVはRubyが用意した特別な定数で、
# コマンドプロンプトで指定した引数を要素
# として持つ配列
#
#6
#例外を発生させる。
def type(age)
if age < 0
raise "年齢がマイナスです (#{age}才)"
elsif age < 20
"未成年"
else
"成年"
end
end
age = ARGV.first.to_i
type = type(age)
puts "#{age}才は#{type}です"
# <hint>
# ruby c11_test2.rb -5を実行
# するとエラーになる。
#7
#例外を発生させる。
#例外の有無に関わらず必ず処理を実行する。
def type(age)
if age < 0
raise "年齢がマイナスです (#{age}才)"
elsif age < 20
"未成年"
else
"成年"
end
end
begin
age = ARGV.first.to_i
type = type(age)
puts "#{age}才は#{type}です"
rescue => e
puts "例外が発生しました: #{e.message}"
ensure
puts "ご利用ありがとうございました"
end
# <hint>
# ruby c11_test3.rb -5を実行
# するとエラーになるが、
# "ご利用ありがとうございました"は実行される。
| true |
4f3deba18e21e5a3737313a9bbb3306e97040a58 | Ruby | YulyKo/ruby-tasks | /task55.rb | UTF-8 | 236 | 3.21875 | 3 | [] | no_license | a = 35
b = 55
c = 35
d = 22
def check_big_figure(a, b, c, d)
if a > 0 and b > 0
if a >= c and b >= d
puts "one rectangle inside another rectangle"
else
puts 'no way'
end
end
end
check_big_figure(a, b, c, d) | true |
ef23c10ea38198d19d4cda7521f7def618424b86 | Ruby | loisyang/bread_express | /app/helpers/orders_helper.rb | UTF-8 | 563 | 2.546875 | 3 | [] | no_license | module OrdersHelper
# create a helper to get the options for the address select menu
# will return an array with key being recipient : address so
# that customers can choose the right address for this order
def get_address_options
Address.active.by_recipient.map{|add| ["#{add.recipient} : #{add.street_1}", add.id] }
end
def get_address_options_for_customer(customer)
options = Address.active.by_recipient.select{|address| address.customer_id == customer.id}
options.map{|add| ["#{add.recipient} : #{add.street_1}", add.id] }
end
end
| true |
c5f46da6fba9b246ea068ec9a95af70b8011eb97 | Ruby | edwardkerry/battle | /spec/features/attack_spec.rb | UTF-8 | 1,941 | 2.90625 | 3 | [] | no_license | feature 'Attack' do
before do
allow(Kernel).to receive(:rand).and_return(20)
end
# As Player 1,
# So I can win a game of Battle,
# I want to attack Player 2, and I want to get a confirmation
scenario 'attacking player 2' do
sign_in_and_play
click_button('Attack')
expect(page).to have_content "Ed attacked Michael"
end
# As Player 1,
# So I can start to win a game of Battle,
# I want my attack to reduce Player 2's HP
scenario 'attacking reduces HP' do
sign_in_and_play
attack_and_ok_twice
expect(page).to have_content('Michael HP: 80')
end
# As Player 1,
# So I can lose a game of Battle,
# I want Player 2 to attack me, and I want to get a confirmation
scenario 'player 2 attacking' do
sign_in_and_play
click_button('Attack')
click_button('OK')
click_button('Attack')
expect(page).to have_content('Michael attacked Ed')
end
# As Player 1,
# So I can start to lose a game of Battle,
# I want Player 2's attack to reduce my HP
scenario 'player 2 attacking reduces player 1 hp' do
sign_in_and_play
attack_and_ok_twice
click_button('Attack')
click_button('OK')
expect(page).to have_content('Ed HP: 80')
end
# As a Player,
# So I can play a suspenseful game of Battle,
# I want all Attacks to deal a random amount of damage
scenario 'player receives random damage' do
allow(Kernel).to receive(:rand).and_return(17)
sign_in_and_play
click_button('Attack')
click_button('OK')
expect(page).to have_content ('Michael HP: 83')
end
# As a Player,
# So I can enjoy a game of Battle with more variety,
# I want to choose from a range of attacks I could make
scenario 'player can use another attack' do
allow(Kernel).to receive(:rand).and_return(45)
sign_in_and_play
click_button('Big Attack!')
click_button('OK')
expect(page).to have_content ('Michael HP: 55')
end
end
| true |
dd7118a9df5852dc51bbdf6d4560c05b900d3219 | Ruby | wazsmwazsm/Ruby_prc | /data_type.rb | UTF-8 | 672 | 3.578125 | 4 | [] | no_license | #!/usr/bin/ruby
# -*- coding:UTF-8 -*-
# 次幂计算
puts '计算';
puts 2**(1/4);
puts 16**(1/4.0);
# 字符串
puts '字符串';
puts 'escape using "\\"';
puts 'That\'s right';
puts "相乘 : #{24*60*60}";
name = "Ruby";
puts "#{name+",ok"}";
# 数组
puts '数组';
arr = ['aa', 10, 3.22, "hello you", 'heheheheh'];
arr.each do |i|
puts i
end
# Hash
puts 'Hash';
hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f };
hsh.each do |key, value|
# 逗号隔开的每个都会打印换行
puts key, " is ", value, "\n";
end
# range 范围
puts 'range';
# 每行都能加分号,也可以什么都不加
(0..15).each do |n|;
puts n;
end;
| true |
9630e1b555620fd4ace3a24c349f74271281b3c3 | Ruby | KaraAJC/know-yourself | /lib/result.rb | UTF-8 | 682 | 3.265625 | 3 | [] | no_license | class Result
attr_reader :counts, :summary
def initialize
@counts = { true: 0, false: 0, skipped: 0 }
@summary = { answered_yes: [], answered_no: [] }
end
def confirm(statement)
@counts[:true] += 1
@summary[:answered_yes] << statement
end
def deny(statement)
@counts[:false] += 1
@summary[:answered_no] << statement
end
def skip(_statement)
@counts[:skipped] += 1
end
def privileges
@summary[:answered_yes].group_by(&:privilege_type).map do |privilege, statements|
{
name: privilege&.name || "Unknown",
explainer: privilege&.explainer || "",
count: statements.count,
}
end
end
end
| true |
b51e7249204d7e1d6d02ab549c3722211bf69ecc | Ruby | dcdc100/launch_school_repository | /intro_to_ruby/hashes/exercise2.rb | UTF-8 | 278 | 3.296875 | 3 | [] | no_license | hash1 = { a: 100, b: 200 }
hash2 = { c: 300, d: 400 }
hash1.merge(hash2)
puts hash1 # => {:a=>100, :b=>200}
puts hash2 # => {:c=>300, :d=>400}
hash1.merge!(hash2)
puts hash1 # => {:a=>100, :b=>200, :c=>300, :d=>400}
puts hash2 # => {:c=>300, :d=>400} | true |
348673336153f55686fb1fe940a5f260e3f96ed4 | Ruby | deebot10/enigma | /lib/enigma.rb | UTF-8 | 1,188 | 3.0625 | 3 | [] | no_license | require './lib/encryptable'
require 'date'
class Enigma
include Encryptable
attr_reader :key,
:date
def initialize
@alphabet = ("a".."z").to_a << " "
@key_range = ("A".."D").each_with_object({}) { |chr, hash| hash[chr] = 0 }
@offset_range = ("A".."D").each_with_object({}) { |chr, hash| hash[chr] = 0 }
@final_range = {}
end
def encrypt(message, key = "0" + rand(1000...9999).to_s, date = Date.today.strftime('%d%m%y'))
key_range_method(key)
offset_range_method(date)
final_range_method
encrypted_phrase = ""
encrypt_magic(message).each_with_index {|idx, index| encrypted_phrase << "#{@alphabet[encrypt_magic(message)[index].remainder(27)]}"}
{encryption: encrypted_phrase,
key: key,
date: date
}
end
def decrypt(message, key, date = Date.today.strftime('%d%m%y'))
key_range_method(key)
offset_range_method(date)
final_range_method
encrypted_phrase = ""
decrypt_magic(message).each_with_index {|idx, index| encrypted_phrase << "#{@alphabet[decrypt_magic(message)[index].remainder(27)]}"}
{decryption: encrypted_phrase,
key: key,
date: date
}
end
end
| true |
5b1ecfdab14bf8bea73ea87efbdd93bcdb331df8 | Ruby | okaryo/Hello-World | /RubyPractice/practice1.rb | UTF-8 | 170 | 3.671875 | 4 | [] | no_license | puts 27.to_s(16)
puts 12.to_s(2)
puts 15.to_s(2)
def add(a, b, c)
a + b + c
end
puts add(2, 4, 8)
n = 5
puts n
puts "hello\nworld"
name = "ruby"
puts "hello #{name}" | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.