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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bf0bf09bfe14f069e8ce9ab53d5c0e22b2016292 | Ruby | shivapbhusal/vulnerability_analysis | /map/prettify/process_codes.rb | UTF-8 | 480 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env ruby
# country codes:
# http://en.wikipedia.org/wiki/ISO_3166-1
require 'rubygems'
require 'nokogiri'
require 'csv'
filename = ARGV[0]
header = ["name","2code","3code","numeric","iso"]
rows = []
f = File.open(filename)
doc = Nokogiri::HTML(f)
f.close
doc.css('tr').each do |tr|
row = []
tr.css('td').each do |cell|
row << cell.text
end
rows << row
end
CSV.open("country-codes.csv", "wb") do |csv|
csv << header
rows.each do |row|
csv << row
end
end | true |
fbf17a8c9233da6a28818cbc25f696054e0e553f | Ruby | travisariggs/RubyExercises | /Lesson2/super.rb | UTF-8 | 346 | 3.71875 | 4 | [] | no_license | class Parent
def something(a='Hello')
puts a
end
end
class Child < Parent
# alias_method :parent_method, :method
def something
super 'Goodbye'
end
# def other_method
# parent_method
# #OR
# Parent.instance_method(:method).bind(self).call
# end
end
p = Parent.new
p.something
puts
c = Child.new
c.something
| true |
0a588b922649265ed697f7eca0bd3100cf4bfaad | Ruby | inasacu/thepista | /httparty/ruby/1.9.1/gems/geokit-1.8.4/lib/geokit/bounds.rb | UTF-8 | 3,342 | 3.484375 | 3 | [
"MIT"
] | permissive | module Geokit
# Bounds represents a rectangular bounds, defined by the SW and NE corners
class Bounds
# sw and ne are LatLng objects
attr_accessor :sw, :ne
# provide sw and ne to instantiate a new Bounds instance
def initialize(sw,ne)
raise ArgumentError if !(sw.is_a?(Geokit::LatLng) && ne.is_a?(Geokit::LatLng))
@sw,@ne=sw,ne
end
#returns the a single point which is the center of the rectangular bounds
def center
@sw.midpoint_to(@ne)
end
# a simple string representation:sw,ne
def to_s
"#{@sw.to_s},#{@ne.to_s}"
end
# a two-element array of two-element arrays: sw,ne
def to_a
[@sw.to_a, @ne.to_a]
end
# Returns true if the bounds contain the passed point.
# allows for bounds which cross the meridian
def contains?(point)
point=Geokit::LatLng.normalize(point)
res = point.lat > @sw.lat && point.lat < @ne.lat
if crosses_meridian?
res &= point.lng < @ne.lng || point.lng > @sw.lng
else
res &= point.lng < @ne.lng && point.lng > @sw.lng
end
res
end
# returns true if the bounds crosses the international dateline
def crosses_meridian?
@sw.lng > @ne.lng
end
# Returns true if the candidate object is logically equal. Logical equivalence
# is true if the lat and lng attributes are the same for both objects.
def ==(other)
return false unless other.is_a?(Bounds)
sw == other.sw && ne == other.ne
end
# Equivalent to Google Maps API's .toSpan() method on GLatLng's.
#
# Returns a LatLng object, whose coordinates represent the size of a rectangle
# defined by these bounds.
def to_span
lat_span = (@ne.lat - @sw.lat).abs
lng_span = (crosses_meridian? ? 360 + @ne.lng - @sw.lng : @ne.lng - @sw.lng).abs
Geokit::LatLng.new(lat_span, lng_span)
end
class <<self
# returns an instance of bounds which completely encompases the given circle
def from_point_and_radius(point,radius,options={})
point=LatLng.normalize(point)
p0=point.endpoint(0,radius,options)
p90=point.endpoint(90,radius,options)
p180=point.endpoint(180,radius,options)
p270=point.endpoint(270,radius,options)
sw=Geokit::LatLng.new(p180.lat,p270.lng)
ne=Geokit::LatLng.new(p0.lat,p90.lng)
Geokit::Bounds.new(sw,ne)
end
# Takes two main combinations of arguments to create a bounds:
# point,point (this is the only one which takes two arguments
# [point,point]
# . . . where a point is anything LatLng#normalize can handle (which is quite a lot)
#
# NOTE: everything combination is assumed to pass points in the order sw, ne
def normalize (thing,other=nil)
# maybe this will be simple -- an actual bounds object is passed, and we can all go home
return thing if thing.is_a? Bounds
# no? OK, if there's no "other," the thing better be a two-element array
thing,other=thing if !other && thing.is_a?(Array) && thing.size==2
# Now that we're set with a thing and another thing, let LatLng do the heavy lifting.
# Exceptions may be thrown
Bounds.new(Geokit::LatLng.normalize(thing),Geokit::LatLng.normalize(other))
end
end
end
end
| true |
7827baf84cd5001bec3e7ac6be78afe18c4dbb36 | Ruby | jdelmazo9/tadp_ruby_metaprogramming | /ruby/lib/pruebilla.rb | UTF-8 | 338 | 3.140625 | 3 | [] | no_license |
class Sarasa
def metodoCualquiera instancia
a = 0
eval( lambda {"a = 11"}.call )
puts a
bloque = proc { puts a + b }
instancia.instance_exec &bloque
end
end
class ClaseCualquieraQueNoConoceAA
attr_accessor :b
def initialize
@b = 1
end
end
Sarasa.new.metodoCualquiera ClaseCualquieraQueNoConoceAA.new | true |
39c9b5483f1d9acbb719bf135cb06cff54ce2115 | Ruby | 19WH1A0578/BVRITHYDERABAD | /CSE/Scripting Languages Lab/18WH1A0580/program4.rb | UTF-8 | 375 | 2.921875 | 3 | [] | no_license | #comment
#file = "/Desktop/sl/prog3.rb"
puts "Enter file name"
file = gets.chomp
#file name
fbname = File.basename file
puts "file name: " +fbname
#base name
bname = File.basename file,".rb"
puts "Base name: " + bname
#file extention
fextn = File.extname file
puts "Extension:" +fextn
#path name
pathname = File.dirname file
puts "path name: "+pathname | true |
09cfaa864d173a091ac1b3341dce0753c9810224 | Ruby | techtrailhead/metanorma-standoc | /lib/liquid/custom_blocks/key_iterator.rb | UTF-8 | 550 | 2.53125 | 3 | [
"BSD-2-Clause"
] | permissive | module Liquid
module CustomBlocks
class KeyIterator < Block
def initialize(tag_name, markup, tokens)
super
@context_name, @var_name = markup.split(',').map(&:strip)
end
def render(context)
res = ''
iterator = context[@context_name].is_a?(Hash) ? context[@context_name].keys : context[@context_name]
iterator.each.with_index do |key, index|
context['index'] = index
context[@var_name] = key
res += super
end
res
end
end
end
end
| true |
c0b6df567e9aa274248bd0255b918a4634ca4724 | Ruby | aequitas/puppet-profile-parser | /catalog-analyzer.rb | UTF-8 | 2,773 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'json'
require 'terminal-table'
require 'colored'
require 'set'
class Catalog
attr_reader :name, :environment, :version
def initialize(hash)
@data = hash['data']
@metadata = hash['metadata']
@name = @data['name']
@version = @data['version']
@environment = @data['environment']
end
def resources
@data['resources']
end
def edges
@data['edges']
end
def classes
@data['classes']
end
def resource_type_count
type_map = Hash.new { |h, k| h[k] = 0 }
@data['resources'].each do |resource|
resource_type = resource['type']
type_map[resource_type] += 1
end
type_map
end
def source_edge_count
source_map = Hash.new { |h, k| h[k] = 0 }
@data['edges'].each do |edge|
source_map[edge['source']] += 1
end
source_map
end
def target_edge_count
target_map = Hash.new { |h, k| h[k] = 0 }
@data['edges'].each do |edge|
target_map[edge['target']] += 1
end
target_map
end
end
def tableflip(headings, hash, take = nil)
rows = hash.to_a.sort { |a, b| b[1] <=> a[1] }
if take
rows = rows.take(take)
end
table = Terminal::Table.new(:headings => headings, :rows => rows)
puts table
end
hash = JSON.parse(File.read(ARGV[0]))
catalog = Catalog.new(hash)
puts "--- Catalog ---"
name = catalog.name
environment = catalog.environment
version = catalog.version
puts "Name: #{name.inspect}"
puts "Environment: #{environment.inspect}"
puts "Catalog version: #{version.inspect}"
puts "--- Statistics ---"
puts "Edges: #{catalog.edges.count}"
puts "Resources: #{catalog.resources.count}"
puts "Classes: #{catalog.classes.count}"
puts "--- Resource types: ---"
tableflip(['Resource Type', 'Count'], catalog.resource_type_count)
puts "--- Edges ---"
source_map = catalog.source_edge_count
target_map = catalog.target_edge_count
deleter = lambda { |k, v| v <= 1 }
source_map.delete_if(&deleter)
target_map.delete_if(&deleter)
tableflip(['Heavily depended resources', 'Count'], source_map, 20)
tableflip(['Heavily dependent resources', 'Count'], target_map, 20)
file_map = Hash.new { |h, k| h[k] = [] }
catalog.resources.each do |resource|
file_map[resource['file']] << "#{resource['type']}[#{resource['title']}]" if resource['file']
end
puts "--- Files with the most defined resources ---"
file_rows = file_map.to_a.sort { |a, b| b[1].count <=> a[1].count }
tableflip(['File', 'Resource count'], file_rows.map { |(file, resources)| [file, resources.count] }, 20)
puts "--- Resources per file ---"
file_rows.take(20).map do |(file, resources)|
puts "#{file} " + "(#{resources.count} resources)".yellow
resources.sort.each do |resource|
puts " -- #{resource}"
end
puts "-" * 20
end
| true |
ae520b630fb4cfdd476100fa5a0836d3cab9688d | Ruby | RobPando/connect_four | /lib/connect_four.rb | UTF-8 | 2,425 | 3.890625 | 4 | [] | no_license | class ConnectFour
attr_accessor :playe1, :player2, :board
def initialize(player1, player2)
@players = [player1, player2]
@turn = 0
@board = [Array.new(7), Array.new(7), Array.new(7), Array.new(7), Array.new(7), Array.new(7)]
end
def show_board
@board.reverse.each { |row| print "#{row}" + "\n" }#Array is reversed to display @board[0] at the bottom in console.
if winner_yet? == true
@turn == 0 ? @turn = 1 : @turn = 0
puts "#{@players[@turn].name} WINS!"
else
interface
end
end
def interface
begin
print "It's #{@players[@turn].name}'s turn, choose a column (0 to 6): "
disc_in_column = Integer(gets)
end until (0..6).include?(disc_in_column)
add_disc(@players[@turn].disc, disc_in_column)
show_board
end
def add_disc(disc, column)
if check_full(column) == true
puts "Can't place there, column is filled!"
else
@board.each { |row|
if row[column].nil?
row[column] = disc
break
end
}
@turn == 0 ? @turn = 1 : @turn = 0
end
end
def check_full(place)
if @board[5].all? == true
return "We have a DRAW!"
elsif @board[5][place].nil?
return false
else
return true
end
end
def winner_yet?
@board.reverse.each_with_index { |row, i|
row.each_with_index { |slot, column|
unless slot.nil?
return true if row[column..column+3].all? { |x| x == slot } && column < 5 #Checks if 4 of the same discs are in the same row or Array sequentially.
count = 0
@board.each_with_index { |x, dex| #Iterates through each nested array of @board and keeps track if 4 of the same discs are sequentially in the same index(column).
if x[column] == slot
count += 1
return true if count == 4 || diagonal_win?(x[column], dex, column)
else
count = 0
end }
end }
}
return false
end
def diagonal_win?(disc, row, column)
count = 1 #starts in one from winner_yet? function.
if row < 3 #if the row is less than 3 it can only be diagonal win if it goes upwards[adding].
while @board[row + 1][column + 1] == disc
count += 1
row += 1
column += 1
return true if count == 4
end
else
while @board[row - 1][column + 1] == disc
count += 1
row -= 1
column += 1
return true if count == 4
end
end
return false
end
end
class Player
attr_reader :name, :disc
def initialize(name, disc)
@name = name
@disc = disc
end
end
| true |
2c61b27ca33fb8af520627c60294aa48c87321e0 | Ruby | github2play/Acadgild | /Module4/ques2.rb | UTF-8 | 659 | 4.21875 | 4 | [] | no_license | # Write a program that takes a number from the user between 0 and 100 and reports back whether the number is between 0 and 50, 50 and 100, or above 100.
def check(num)
if(num<0)then
puts"You have entered an Invalid Number...\nPlease any positive Number between 0 to 100"
check(gets.to_i)
else
case
when (0 <= num)&& (num <= 50)
puts "The entered Number is in between 0 and 50"
when ( num >50 ) && (num<=100)
puts "The entered Number is in between 50 and 100"
else (num > 100)
puts "The entered Number is greater than 100"
end
end
end
puts "Enter any Number between 0 - 100 :"
check(gets.to_i)
| true |
1be5632abc0717e41b318d854d9a77264ab25113 | Ruby | Katy600/student-directory | /directory.rb | UTF-8 | 5,949 | 3.953125 | 4 | [] | no_license |
#We are de-facto using CSV format to store data.
#However, Ruby includes a library to work with the CSV files that we could use instead of working directly with the files.
#Refactor the code to use this library.
require 'csv'
@students = []
def print_menu
puts "1. Input the students"
puts "2. Show the students"
puts "3. Save the list to students.csv"
puts "4. Load the list to students.csv"
puts "5. Select by cohort"
puts "6. Select student by letter"
puts "9. Exit"
end
def interactive_menu
loop do
print_menu
process(STDIN.gets.chomp)
end
end
def process(selection)
case selection
when "1"
input_students
puts
puts "To view your students go back to the main menu and press 1"
when "2"
show_students
when "3"
save_students
when "4"
load_students
puts
puts "Your file has been loaded"
puts
when "5"
select_cohort
when "6"
student_finder
when "9"
exit #this will cause the program to terminate
else
puts "I don't know what you meant, try again"
end
end
def input_students
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
puts "Please enter the name of the student: "
puts "To finish, just hit return twice"
loop do
puts "Add another student"
name = STDIN.gets[0...-1]
break if name.empty?
puts "What cohort are they on?".center(100)
cohort = STDIN.gets.chomp
if cohort == ""
cohort = "(none listed)"
else
until months.any?{|valid_month| cohort == valid_month}
puts "Incorrect spell. Please try again".center(50)
cohort = STDIN.gets.chomp
end
end
puts "What are #{name}'s hobbies?: "
hobbies = STDIN.gets.chomp
if hobbies == ""
hobbies = "(none listed)"
end
puts "What is #{name}'s country of birth? "
country = STDIN.gets.chomp
if country == ""
country = "(none listed)"
end
add_students(name, cohort, hobbies, country)
if @students.count == 1
puts "Now we have #{@students.count} student".center(100)
puts ""
else
puts "Now we have #{@students.count} students".center(100)
puts ""
end
end
end
def show_students
print_header
print_output
print_footer
end
def print_header
if @students.count == 0
puts "There are no students yet".center(100)
else
puts "The students of Makers Academy".center(100)
puts "-------------".center(100)
end
end
def print_output
@students.each_with_index {|student, index|
if student[:name].length < 12
puts
puts "#{index + 1}. #{student[:name]} is from #{student[:country]} and registered in the #{student[:cohort]} cohort.#{student[:name]} likes to #{student[:hobbies]}".center(100)
puts ""
end
}
end
def print_footer
if @students.count == 0
puts "There are no students registered"
elsif @students.count == 1
puts "Overall, we have #{@students.count} great student!".center(100)
else
puts "Overall, we have #{@students.count} great students!".center(100)
end
end
def select_cohort
print "what cohort would you like to select? "
month = STDIN.gets.chomp.to_sym
@students.select {|student|
if student[:cohort] == month
puts
puts "#{student[:name]} is from #{student[:country]} and registered in the #{student[:cohort]} cohort. #{student[:name]} likes to #{student[:hobbies]}"
puts
end
}
end
def student_finder
print "What is the first letter of the student's name?: "
letter = STDIN.gets.chomp.upcase
selected_students = @students.select { |student|
if student[:name][0] == letter
puts ""
puts "#{student[:name]} is from #{student[:country]} and registered in the #{student[:cohort]} cohort.#{student[:name]} likes to #{student[:hobbies]}"
end
}
end
def store_students(name, cohort)
@students << { name: name,
cohort: cohort.to_sym
}
end
def save_students
puts 'What would you like to name your file?'
filename = STDIN.gets.chomp
if filename.empty?
filename = "students.csv"
end
# open the file for writing.
file = CSV.open(filename, "w") do |csv|
@students.each do |student|
student_data = [student[:name], student[:cohort], student[:hobbies], student[:country]]
csv << student_data
end
end
puts "Your file has been saved as #{filename}"
end
def load_students(filename = "students.csv")
#file = CSV.open(filename, "r") do |file|
CSV.foreach(filename) do |line|
name, cohort = line
store_students(name, cohort)
end
end
#file.readlines.each {|line|
#name, cohort, hobbies, country = line.chomp.split(",")
#add_students(name, cohort, hobbies, country)
=begin
def load_students(filename = "students.csv")
file = CSV.open(filename, "r") do |file|
CSV.read(file) do |row|
puts row
end
#file.readlines.each do |line|
#name, cohort, hobbies, country = line.chomp.split(',')
add_students(name, cohort, hobbies, country)
end
end
=end
def try_load_students
filename = ARGV.first # first argument from the command line
if filename.nil?
filename = "students.csv" # get out of the method if it isn't given
end
if File.exists?(filename) # if it exists
load_students(filename)
puts "Loaded #{@students.count} from #{filename}"
else # if it doesn't exist
puts "Sorry, #{filename} doesn't exist."
exit
end
end
def add_students(name, cohort, hobbies, country)
@students << {name: name, cohort: cohort.to_sym, hobbies: hobbies, country: country}
end
#try_load_students
interactive_menu
| true |
3e1ba105a20b5799a7dbae24df17b04c601ca0ab | Ruby | hspitzer2/badges-and-schedules-online-web-prework | /conference_badges.rb | UTF-8 | 532 | 3.515625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def badge_maker(name)
"Hello, my name is #{name}."
end
def batch_badge_creator(array)
badges = []
array.each do |name|
badges.push( "Hello, my name is #{name}." )
end
badges
end
def assign_rooms(array)
room_assignments = []
array.each_with_index do |name, index|
room_assignments.push("Hello, #{name}! You'll be assigned to room #{index+1}!")
end
room_assignments
end
def printer
batch_badge_creator(array).each do |x|
puts x
badges_and_room_assignments(array).each do |y|
puts y
end
printer
end
| true |
690c39e31385e0de70c2a51eb6d7cd936534887a | Ruby | kjdchapman/advent-of-code-2019 | /lib/day-2/run_intcode.rb | UTF-8 | 818 | 3.375 | 3 | [] | no_license | class RunIntcode
def initialize(convert_intcode_string:, interpret_instruction:)
@convert_intcode_string = convert_intcode_string
@interpret_instruction = interpret_instruction
end
def execute(input)
instructions = @convert_intcode_string.execute(input)
instructions.each_slice(4) do |slice|
instruction = @interpret_instruction.execute(slice)
first_number = instruction[:positions][0]
second_number = instruction[:positions][1]
new_number = case instruction[:operation]
when :add
first_number + second_number
when :multiply
first_number * second_number
when :quit
break
else
raise
end
target = instruction[:target]
instructions[target] = new_number
end
instructions.first
end
end
| true |
41a3f43d345acc9a4cf3e8de43f91b7f5c911bb8 | Ruby | Sokre95/simple_server_log_analyzer | /server_log_analyzer/evaluator.rb | UTF-8 | 252 | 2.546875 | 3 | [] | no_license | module ServerLogAnalyzer
class Evaluator
def initialize(storage:)
@storage = storage
end
def evaluate(proc = nil, &block)
return proc.call(@storage) if proc
return block.call(@storage) if block
end
end
end
| true |
a83ed3d0e013d3abff66b13af1233abbfc400b2b | Ruby | buchheimt/marvel_101 | /lib/marvel_101/character.rb | UTF-8 | 942 | 2.734375 | 3 | [
"MIT"
] | permissive | require_relative 'topic'
class Marvel101::Character < Marvel101::Topic
attr_accessor :list, :team, :details
DETAIL_ORDER = [:real_name, :height, :weight, :abilities, :powers,
:group_affiliations, :first_appearance, :origin]
def display
display_description
display_details
display_links
display_empty_message if no_info?
end
def display_details
DETAIL_ORDER.each do |type|
if details.include?(type)
title = type.to_s.split("_").join(" ").upcase
format_output("#{title}: #{details[type]}")
puts "" if "#{title}: #{details[type]}".size > 60
end
end
end
def display_empty_message
puts "Sorry, Marvel doesn't seem to care about #{name}"
puts "Type 'source' to open source in browser, but don't get your hopes up"
end
def no_info?
!description && details.empty? && urls.size <= 1
end
def valid_input?(input)
false
end
end
| true |
4bcda33d2efe5889e18118a40f891e295a772e60 | Ruby | edelhaye/Ruby_Training | /Session1/classes.rb | UTF-8 | 378 | 3.390625 | 3 | [] | no_license | class Car
def initialize
puts "creating a new car"
end
def set_make(make)
@make = make
end
def set_model(model)
@model = model
end
def description
@make + " " + @model
end
end
audi = Car.new
audi.set_make("Audi")
audi.set_model("A1")
puts audi.description
vw = Car.new
vw.set_make("Volkswagen")
vw.set_model("Polo")
puts vw.description
| true |
25f40cdef40b9401b34f98cf82fb498925e2d5c8 | Ruby | nealdeters/pre-coursework | /todo.rb | UTF-8 | 850 | 4.625 | 5 | [] | no_license | #Create a program that asks a user to enter
#four different words, one at a time. Then,
#the computer will ask the user to choose a
#number between 1 and 4. The computer will
#then display the word corresponding to the
#correct number. For example, assume the user
#typed in the words: ghost, umbrella, candy,
#and pepperoni - in that order. The user is
#then prompted to choose a number. If the user
#chooses the number 2, the computer displays
#the second word, which in this example is umbrella.
puts "Welcome, please enter 4 of your favorite words: "
words = []
4.times do
words << gets.chomp
end
puts "Now choose a number between 1 and 4:"
number = gets.chomp.to_i
while number > 4 || number < 0
puts "Please enter a number between 1 and 4:"
number = gets.chomp.to_i
end
number -= 1
puts "You chose the word #{words[number]}"
| true |
12b455347975ebc02fba768056acb897c152f905 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/cs169/800/feature_try/whelper_source/23165.rb | UTF-8 | 378 | 3.328125 | 3 | [] | no_license | def combine_anagrams(words)
temp = words
p = Array.new
h = Hash.new
temp.each { |word| h = makeHash(h, word) }
h.values.each { |ary| p.push(ary) }
return p
end
def makeHash(h, word)
seq = word.downcase.scan(/\w/).sort.join
if h.has_key?(seq) then
h[seq] = h[seq].push(word)
else
h[seq] = Array.new
h[seq] = h[seq].push(word)
end
return h
end
| true |
93f75099ed461dd1dd645cfb23d7213321fd0bc9 | Ruby | DanielEFrampton/backend_module_0_capstone | /day_7/alt_caesar_cipher.rb | UTF-8 | 3,650 | 4.25 | 4 | [] | no_license | # An alternate version of CaesarCipher with an interactive console interface.
# Class to contain encoding method
class CaesarCipher
# Declare instance variables to contain non-encoded user input and shift value
attr_accessor :non_encoded_input, :shift_value
# Define intialization method, declare instance variables
def initialize
@non_encoded_input = ""
@shift_value = ""
end
# Method definition for optional process: console prompts for user input and data validation
def input
# Loop to manage user input and validation of that input
while non_encoded_input == "" do
# Prompt user for phrase to encode
print "Enter the word or phrase you want to encode (only letters and spaces): "
string_input = gets.chomp.upcase
# Validate user's string input
if /[^A-Z\s]/.match?(string_input) == false
self.non_encoded_input = string_input
else
puts "You entered an invalid character. Use only letters and spaces."
end
end
# Loop manage user input and validation of that input
while shift_value == "" do
# Prompt user for shift value integer
print "Enter the desired shift value (an integer): "
shift_value_input = gets.chomp
# Validate user's shift value input
if /[^0-9\-]/.match?(shift_value_input) == false
# If numeric, assign corrected (moduland of division by 26) value to instance variable
self.shift_value = shift_value_input.to_i % 26
else
puts "You entered an invalid character. Use only integers."
end
end
puts "Non-encoded text is \"#{non_encoded_input}\" and corrected shift value is #{shift_value}."
end
# Method definition for encoding; default value of arguments pulls from instance variables filled by .input method
def encode(string = non_encoded_input, shift = shift_value)
# Validate arguments
if /[^A-Z\s]/.match?(string.upcase) == false
self.non_encoded_input = string.upcase
else
puts "You entered an invalid character. Use only letters and spaces."
return nil
end
if /[^0-9\-]/.match?(shift.to_s) == false
# If numeric, assign corrected (moduland of division by 26) value to instance variable
self.shift_value = shift.to_i % 26
else
puts "You entered an invalid character. Use only integers."
return nil
end
# Convert non-encoded string to array
non_encoded_array = non_encoded_input.chars
# Declare alphabet array
alphabet = ("A".."Z").to_a
# Encoding iteration block
encoded_array = non_encoded_array.map do |letter|
# Checking for spaces
if letter != " "
# Checking for negative indexes
if (alphabet.index(letter) - shift_value) < 0
shifted_letter = alphabet[(alphabet.index(letter) - shift_value) + 26]
shifted_letter
else
shifted_letter = alphabet[alphabet.index(letter) - shift_value]
shifted_letter
end
else
letter
end
end
# Join encoded array into a string
encoded_string = encoded_array.join
# Print encoded string to console
puts "Done encoding. Encoded string:"
puts encoded_string
# Finally, return encoded string.
encoded_string
end
end
# Testing functionality, with and without dependence on .input loop
cipher = CaesarCipher.new
cipher.input
cipher.encode
cipher.encode("Hello World", 5)
# Testing error message in passing-argument usage
cipher.encode("1234", 5)
cipher.encode("Hello World", "wrong")
# Testing manipulation of return value
puts cipher.encode("Hello World", 7).capitalize
| true |
76bf767c05fa751929ba4c760f720835a1e3d9b9 | Ruby | IFTTT/polo | /lib/polo/translator.rb | UTF-8 | 2,298 | 2.6875 | 3 | [
"MIT"
] | permissive | require "polo/sql_translator"
require "polo/configuration"
module Polo
class Translator
# Public: Creates a new Polo::Collector
#
# selects - An array of SELECT queries
#
def initialize(selects, configuration=Configuration.new)
@selects = selects
@configuration = configuration
end
# Public: Translates SELECT queries into INSERTS.
#
def translate
SqlTranslator.new(instances, @configuration).to_sql.uniq
end
def instances
active_record_selects, raw_selects = @selects.partition{|s| s[:klass]}
active_record_instances = active_record_selects.flat_map do |select|
select[:klass].find_by_sql(select[:sql]).to_a
end
if fields = @configuration.blacklist
obfuscate!(active_record_instances, fields)
end
raw_instance_values = raw_selects.flat_map do |select|
table_name = select[:sql][/^SELECT .* FROM (?:"|`)([^"`]+)(?:"|`)/, 1]
select[:connection].select_all(select[:sql]).map { |values| {table_name: table_name, values: values} }
end
active_record_instances + raw_instance_values
end
private
def obfuscate!(instances, fields)
instances.each do |instance|
next if intersection(instance.attributes.keys, fields).empty?
fields.each do |field, strategy|
field = field.to_s
if table = table_name(field)
field = field_name(field)
end
correct_table = table.nil? || instance.class.table_name == table
if correct_table && instance.attributes[field]
instance.send("#{field}=", new_field_value(field, strategy, instance))
end
end
end
end
def field_name(field)
field.to_s.include?('.') ? field.split('.').last : field.to_s
end
def table_name(field)
field.to_s.include?('.') ? field.split('.').first : nil
end
def intersection(attrs, fields)
attrs & fields.map { |pair| field_name(pair.first) }
end
def new_field_value(field, strategy, instance)
value = instance.attributes[field]
if strategy.nil?
value.split("").shuffle.join
else
strategy.arity == 1 ? strategy.call(value) : strategy.call(value, instance)
end
end
end
end
| true |
beca59a288451f08237534a2935e8ba3a2327745 | Ruby | sbackus/calculating-pi | /leibniz.rb | UTF-8 | 386 | 3.34375 | 3 | [] | no_license | # Take the infinite series of all the odd fractions
# alternate adding and subtracting them
# the sum is equal to pi over 4
# 1/1 - 1/3 + 1/5 - 1/7 + 1/9... = pi/4
sum = 0
start = 1
finish = 1000000
by = 2
plus_or_minus = 1
for n in start.step(finish,by)
sum += 1.0/n * plus_or_minus
plus_or_minus *= -1
end
puts sum * 4
# https://www.youtube.com/watch?v=HrRMnzANHHs&t=243s
| true |
168c6c07467189ad52c0ef0abbc3068e4692d27d | Ruby | jaymccoy300/blocipedia | /db/seeds.rb | UTF-8 | 758 | 2.53125 | 3 | [] | no_license | require 'random_data'
5.times do
User.create!(
email: RandomData.random_email,
password: 'standardpassword',
standard: true,
premium: false,
admin: false
)
end
4.times do
User.create!(
email: RandomData.random_email,
password: 'premiumpassword',
standard: false,
premium: true,
admin: false
)
end
3.times do
User.create!(
email: RandomData.random_email,
password: 'adminpassword',
standard: false,
premium: false,
admin: true
)
end
users = User.all
100.times do
Wiki.create!(
title: RandomData.random_sentence,
body: RandomData.random_paragraph,
private: false
)
end
wikis = Wiki.all
puts 'Seed finished'
puts "#{users.count} users created"
puts "#{wikis.count} wikis created"
| true |
5e72339d5bd3c390d971f97719c4cf92ebfb6759 | Ruby | vcraescu/eyecare | /lib/eyecare/audio.rb | UTF-8 | 731 | 2.671875 | 3 | [
"MIT"
] | permissive | module Eyecare
# Audio
class Audio
attr_accessor :filename
attr_accessor :player
DEFAULT_PLAYER = 'aplay :file'
def initialize(filename, player = nil)
@filename = filename
@player = player ? player : DEFAULT_PLAYER
end
def play
return unless player
pid = spawn(player_cmd + ' > /dev/null 2>&1')
Process.detach(pid)
end
private
def player_cmd
return @player_cmd if @player_cmd
@player_cmd = @player ? @player : DEFAULT_PLAYER
@player_cmd = @player_cmd.gsub(/:filename/, ':file')
.gsub(/:filepath/, ':file')
.gsub(/:file_path/, ':file')
.gsub(/:file/, filename)
end
end
end
| true |
814a641ffabcfb3d279b5cecb8eb325f2890ff71 | Ruby | pkayokay/ruby-notes | /challenges/random_color.rb | UTF-8 | 148 | 3.34375 | 3 | [] | no_license | class Ghost
attr_accessor :color
def initialize
@color = ["Yellow","Red","Blue","Green"].sample
end
end
ghost = Ghost.new
puts ghost.color | true |
ff7ac2cc9bc8896d479be866c29ab582aea1e21e | Ruby | lwoodson/ispeech | /lib/ispeech.rb | UTF-8 | 1,151 | 2.8125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'uri'
require 'net/http'
require 'ostruct'
module ISpeech
URL_ENCODED_ENDPOINT = 'http://api.ispeech.org/api/rest'
def self.parameterize(hash)
hash.inject(""){|str,tuple| str << "&#{tuple[0].to_s}=#{tuple[1].to_s.gsub(/\s/, '+')}"}[1..-1]
end
def self.decode_param_string(pstring)
map = {}
pstring.split("&").each do |pair|
key, value = pair.split "="
map[key] = value
end
OpenStruct.new map
end
class Client
def initialize(config)
@endpoint = config[:endpoint] ||= ISpeech::URL_ENCODED_ENDPOINT
@api_key = config[:api_key]
end
def information
url = "#{@endpoint}?apikey=#{@api_key}&action=information"
result = Net::HTTP.get(URI.parse(url))
ISpeech.decode_param_string result
end
def convert(opts)
params = ISpeech.parameterize opts
url = "#{@endpoint}?apikey=#{@api_key}&action=convert&#{params}"
puts url
result = Net::HTTP.get(URI.parse(url))
if !opts[:filename].nil?
File.open(opts[:filename], 'w') do |file|
file.write result
end
end
result
end
end
end
| true |
ea8ce407b1e7481133157d98d23d6e034df9ffbc | Ruby | lifepillar/RubyBackupBouncer | /copiers/dd_rescue.rb | UTF-8 | 1,260 | 2.53125 | 3 | [
"MIT"
] | permissive | =begin
Clones a volume using dd_rescue.
dd_rescue (http://www.garloff.de/kurt/linux/ddrescue/) is modeled
after dd but optimized for copying data from possible damaged disks to
your system.
This task unmounts the source and target volumes, then runs
sudo dd_rescue <source device> <target device>
then remounts the volumes. For convenience, this task renames the
target volume after cloning.
dd_rescue can be installed via MacPorts (sudo port install dd_rescue).
=end
task :clone do
begin
copier = `which dd_rescue 2>/dev/null`.chomp!
if copier =~ /dd_rescue/
target = make_volume 'dd_rescue', :ram => true
puts '===> [clone] dd_rescue'
$source.unmount
target.unmount
begin
run_baby_run copier, [$source.dev_node, target.dev_node], :sudo => true, :verbose => false
rescue => ex
puts "dd_rescue clone task has failed: #{ex}"
end
$source.mount
target.mount
target.rename('dd_rescue')
else
puts '-' * 70
puts 'NOTE: dd_rescue is not installed. You may install dd_rescue using'
puts 'MacPorts (sudo port install dd_rescue)'
puts '-' * 70
end
rescue Rbb::DiskImageExists
puts 'Skipping dd_rescue clone task (volume exists).'
end
end
| true |
835840d91de96b4f4fa2536edebd8839931e2b88 | Ruby | readyready15728/codewars-ruby-solutions | /7-kyu/square-every-digit.rb | UTF-8 | 97 | 3.125 | 3 | [] | no_license | def square_digits(num)
num.to_s.chars.map { |c| c.to_i ** 2 }.map { |n| n.to_s }.join.to_i
end
| true |
f5e388c0effcb8649afc6aeabce868e988af1e16 | Ruby | SPrio/competitive-coding-practice | /code4.rb | UTF-8 | 1,094 | 4.0625 | 4 | [] | no_license | # Task
#
# Your task is to print an array of the first N palindromic prime numbers.
# For example, the first 10 palindromic prime numbers are .
#
# Input Format
#
# A single line of input containing the integer N.
#
# Constraints
#
# You are not given how big N is.
#
# Output Format
#
# Print an array of the first N palindromic primes.
#
# Sample Input
#
# 5
# Sample Output
#
# [2, 3, 5, 7, 11]
pal_prime_array = lambda do |array_size|
2.upto(Float::INFINITY).lazy.filter do |x|
prime?(x) && palindrome?(x)
end.first(array_size)
end
def prime?(number)
if number > 2
return (2..(Math.sqrt(number).floor + 1)).none? do |x|
(number % x).zero?
end
end
return false if number < 2
return true if number == 2
end
def palindrome?(number)
reversed_numnber = 0
original_number = number
while number != 0
remainder = number % 10
reversed_numnber = reversed_numnber * 10 + remainder
number /= 10
end
original_number == reversed_numnber && true
end
inp = gets
print pal_prime_array.call(inp.to_i)
| true |
9030c4061cd1dca23b809907a611c0d0f0f5a3dc | Ruby | class-snct-rikitakelab/Understanding-Computation | /program/statement_script.rb | UTF-8 | 8,888 | 3.890625 | 4 | [] | no_license | #
# 前回の続き
#
require "./expression_script.rb"
#
# 文(statement)という違う種類のプログラムの構成を作る。
#
# 式は、ある式から新しい式を生成する。
# 一方、文は仮想計算機の状態を変える。
# この仮想計算機の持つ状態は環境だけだから、式で新しい環境を作って置き換える事ができるようにする。
#
# もっとも簡単な文は、なにもしないもので、簡約不能、そして環境にあらゆる影響を与えられないものである。
# これは簡単に作れる。
#
# 他のすべての構文クラスはstructクラスを継承しているが、DoNothingクラスは何も継承していない。
# これは、DoNothingは属性を持たず、struct.newには空の属性名のリストを渡すことができないためである。
class DoNothing
def to_s
'do-nothing'
end
def inspect
"<<#{self}>>"
end
# 他の構文クラスはStructクラスから同じか比較する演算を継承しているが、DoNothingクラスは何も継承していないため、これを自身で定義する。
def ==(other_statement)
other_statement.instance_of?(DoNothing)
end
def reducible?
false
end
end
#
# 何もしない文は、無意味に思えるかもしれないが、プログラムの実行が正常に完了していることを表す特別な文として使うことができる。
# DoNothingクラスをそういった使い方をするには、作業を終えたあと最終的に<<do-nothing>>に簡約される文を生成すればよい。
#
#
# 代入( x = x + 1 みたいなもの)を行える文を作る。
# これは次のような簡約ルールにしたがって実現する。
# 代入文は、変数名(x)と、変数に代入する式(x+1)からなる。
# 式が簡約可能ならば、式の簡約ルールによって簡約する。
# (例えば、 変数x=2のとき、 x = x + 1 → x = 2 + 1 → x = 3 )
# 式の簡約ができなくなったならば、実際に代入を行う。
# つまり導出した値を変数名に関連付けて環境を更新する。
#
# 代入クラス定義
class Assign < Struct.new(:name, :expression)
def to_s
"#{name} = #{expression}"
end
def inspect
"«#{self}»"
end
def reducible?
true
end
# 式が簡約可能なら簡約する。
# 簡約できないなら、式と代入した変数を関係付けて環境を更新し、do-nothing文と新しい環境を返す。
# 代入クラスのreduceメソッドは文と環境の両方を返す必要があるが、Rubyのメソッドは1つのオブジェクトしか返すことができないため、文と環境を2要素配列に入れて返すことで2つのオブジェクトを返すように見せかける。
def reduce(environment)
if expression.reducible?
[Assign.new(name, expression.reduce(environment)), environment]
else
[DoNothing.new, environment.merge({ name => expression })]
end
end
end
#
# 式と同じように、代入文を手動で簡約することにより評価できる。
#
#>> statement = Assign.new(:x, Add.new(Variable.new(:x), Number.new(1)))
#=> «x = x + 1»
#>> environment = { x: Number.new(2) }
#=> {:x=>«2»}
#>> statement.reducible?
#=> true
#>> statement, environment = statement.reduce(environment)
#=> [«x = 2 + 1», {:x=>«2»}]
#>> statement, environment = statement.reduce(environment)
#=> [«x = 3», {:x=>«2»}]
#>> statement, environment = statement.reduce(environment)
#=> [«do-nothing», {:x=>«3»}]
#>> statement.reducible?
#=> false
#
# 仮想計算機が文も扱えるようにする。
#
Object.send(:remove_const, :Machine)
class Machine < Struct.new(:statement, :environment)
def step
self.statement, self.environment = statement.reduce(environment)
end
# 文と環境の途中経過を表示しながら、簡約できなくなるまで簡約する。
def run
while statement.reducible?
puts "#{statement}, #{environment}"
step
end
puts "#{statement}, #{environment}"
end
end
# これで文にも対応した。
#>> Machine.new(
#Assign.new(:x, Add.new(Variable.new(:x), Number.new(1))),
#{ x: Number.new(2) }
#).run
#x = x + 1, {:x=>«2»}
#x = 2 + 1, {:x=>«2»}
#x = 3, {:x=>«2»}
#do-nothing, {:x=>«3»}
#=> nil
#
# 仮想計算機の簡約は、構文木のトップレベルではなく文の内部で行われる。
#
#Ifクラス
class If < Struct.new(:condition, :consequence, :alternative)
def to_s
"if (#{condition}) { #{consequence} } else { #{alternative} }"
end
def inspect
"«#{self}»"
end
def reducible?
true
end
def reduce(environment)
if condition.reducible?
[If.new(condition.reduce(environment), consequence, alternative), environment]
else
case condition
when Boolean.new(true)
[consequence, environment]
when Boolean.new(false)
[alternative, environment]
end
end
end
end
#Ifクラスを使った文
#>> Machine.new(
# If.new(
# Variable.new(:x),
# Assign.new(:y, Number.new(1)),
# Assign.new(:y, Number.new(2))
# ),
# { x: Boolean.new(true) }
# ).run
#if (x) { y = 1 } else { y = 2 }, {:x=>«true»}
#if (true) { y = 1 } else { y = 2 }, {:x=>«true»}
#y = 1, {:x=>«true»}
#do-nothing, {:x=>«true», :y=>«1»}
#=> nil
#>> Machine.new(
# If.new(Variable.new(:x), Assign.new(:y, Number.new(1)), DoNothing.new),
# { x: Boolean.new(false) }
# ).run
#if (x) { y = 1 } else { do-nothing }, {:x=>«false»}
#if (false) { y = 1 } else { do-nothing }, {:x=>«false»}
#do-nothing, {:x=>«false»}
#=> nil
#Sequenceクラス
class Sequence < Struct.new(:first, :second)
def to_s
"#{first}; #{second}"
end
def inspect
"«#{self}»"
end
def reducible?
true
end
def reduce(environment)
case first
when DoNothing.new
[second, environment]
else
reduced_first, reduced_environment = first.reduce(environment)
[Sequence.new(reduced_first, second), reduced_environment]
end
end
end
#Sequenceクラスを利用した文?
#>> Machine.new(
# Sequence.new(
# Assign.new(:x, Add.new(Number.new(1), Number.new(1))),
# Assign.new(:y, Add.new(Variable.new(:x), Number.new(3)))
# ),
# {}
# ).run
#x = 1 + 1; y = x + 3, {}
#x = 2; y = x + 3, {}
#do-nothing; y = x + 3, {:x=>«2»}
#y = x + 3, {:x=>«2»}
#y = 2 + 3, {:x=>«2»}
#y = 5, {:x=>«2»}
#do-nothing, {:x=>«2», :y=>«5»}
#=> nil
#whileクラス
class While < Struct.new(:condition, :body)
def to_s
"while (#{condition}) { #{body} }"
end
def inspect
"«#{self}»"
end
def reducible?
true
end
def reduce(environment)
[If.new(condition, Sequence.new(body, self), DoNothing.new), environment]
end
end
#whileクラスを利用した文
#>> Machine.new(
# While.new(
# LessThan.new(Variable.new(:x), Number.new(5)),
# Assign.new(:x, Multiply.new(Variable.new(:x), Number.new(3)))
# ),
# { x: Number.new(1) }
# ).run
#while (x < 5) { x = x * 3 }, {:x=>«1»}
#if (x < 5) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«1»}
#if (1 < 5) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«1»}
#if (true) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«1»}
#x = x * 3; while (x < 5) { x = x * 3 }, {:x=>«1»}
#x = 1 * 3; while (x < 5) { x = x * 3 }, {:x=>«1»}
#x = 3; while (x < 5) { x = x * 3 }, {:x=>«1»}
#do-nothing; while (x < 5) { x = x * 3 }, {:x=>«3»}
#while (x < 5) { x = x * 3 }, {:x=>«3»}
#if (x < 5) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«3»}
#if (3 < 5) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«3»}
#if (true) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«3»}
#x = x * 3; while (x < 5) { x = x * 3 }, {:x=>«3»}
#x = 3 * 3; while (x < 5) { x = x * 3 }, {:x=>«3»}
#x = 9; while (x < 5) { x = x * 3 }, {:x=>«3»}
#do-nothing; while (x < 5) { x = x * 3 }, {:x=>«9»}
#while (x < 5) { x = x * 3 }, {:x=>«9»}
#if (x < 5) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«9»}
# if (9 < 5) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«9»}
#if (false) { x = x * 3; while (x < 5) { x = x * 3 } } else { do-nothing }, {:x=>«9»}
#do-nothing, {:x=>«9»}
#=> nil
#>> Machine.new(
# Sequence.new(
# Assign.new(:x, Boolean.new(true)),
# Assign.new(:x, Add.new(Variable.new(:x), Number.new(1)))
# ),
# {}
# ).run
#x = true; x = x + 1, {}
#do-nothing; x = x + 1, {:x=>«true»}
#x = x + 1, {:x=>«true»}
#x = true + 1, {:x=>«true»}
#NoMethodError: undefined method `+' for true:TrueClass | true |
dea25245097d66294e27a337256baf832ca7db2d | Ruby | Freshly/law | /lib/law/judgement.rb | UTF-8 | 1,544 | 2.671875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# A **Judgement** determines if an **Actor** (represented by their **Roles**) are in violation of the given **Statute**.
module Law
class Judgement < Spicerack::RootObject
class << self
def judge!(petition)
new(petition).judge!
end
def judge(petition)
new(petition).judge
end
end
attr_reader :petition, :violations, :applied_regulations
delegate :statute, :applicable_regulations, :compliant?, to: :petition, allow_nil: true
def initialize(petition)
@petition = petition
@violations = []
@applied_regulations = []
end
def adjudicated?
applied_regulations.present?
end
def authorized?
adjudicated? && violations.blank?
end
def judge
judge!
rescue NotAuthorizedError => exception
error :not_authorized, exception: exception
false
end
def judge!
raise AlreadyJudgedError if adjudicated?
if statute&.unregulated?
@applied_regulations = [ nil ]
return true
end
ensure_jurisdiction
reckon!
true
end
private
def ensure_jurisdiction
raise InjunctionError if applicable_regulations.blank?
raise ComplianceError unless compliant?
end
def reckon!
@applied_regulations = applicable_regulations.map { |regulation| regulation.new(petition: petition) }
@violations = applied_regulations.reject(&:valid?)
raise NotAuthorizedError unless authorized?
end
end
end
| true |
eb49653560827e8a3794e2f03dad4fe4603798b5 | Ruby | wilson-penagos-admios/rubyTest | /reverser.rb | UTF-8 | 666 | 3.59375 | 4 | [] | no_license | class Reverser
def initialize(objectString)
raise unless objectString.is_a?(String)
@x = objectString
end
def original
@x
end
def reverse_odds
baseString = String.new(@x)
stringLength = baseString.length
# Avoiding one odd char strings
if stringLength < 4
return baseString
end
baseCount = 0
result = ""
for char in baseString.split('')
if baseCount % 2 == 0
result << char
else
# Note that this should happen stringLength/4.floor times
result << baseString[stringLength - baseCount - 1]
end
baseCount += 1
end
puts result
result
end
end
| true |
8084c12276e75a48c76e148f831556b893387d30 | Ruby | kentaroi/gmaps-rails | /lib/gmaps/js.rb | UTF-8 | 1,760 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'active_support/core_ext/string/output_safety'
class GMaps
class JS
class << self
def [](*args)
self.new(*args)
end
end
def initialize(str, *args)
@str = if args.empty?
str
elsif args.length == 1 && args.first.is_a?(Hash)
escaped_args = {}
args.first.each { |k, v| escaped_args[k] = v.is_a?(String) ? escape_javascript(v) : v}
str % (escaped_args)
else
args.map!{ |arg| arg.is_a?(String) ? escape_javascript(arg) : arg}
str % args
end
end
def inspect
@str
end
alias to_s inspect
###################################################
# escape_javascript
# Copied from ActionView::Helpers::JavaScriptHelper
JS_ESCAPE_MAP = {
'\\' => '\\\\',
'</' => '<\/',
"\r\n" => '\n',
"\n" => '\n',
"\r" => '\n',
'"' => '\\"',
"'" => "\\'"
}
JS_ESCAPE_MAP["\342\200\250".force_encoding(Encoding::UTF_8).encode!] = '
'
JS_ESCAPE_MAP["\342\200\251".force_encoding(Encoding::UTF_8).encode!] = '
'
# Escapes carriage returns and single and double quotes for JavaScript segments.
#
# Also available through the alias j(). This is particularly helpful in JavaScript
# responses, like:
#
# $('some_element').replaceWith('<%=j render 'some/element_template' %>');
def escape_javascript(javascript)
if javascript
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
javascript.html_safe? ? result.html_safe : result
else
''
end
end
end
end
| true |
82d61825f36674db1a007a14dff51c06b5231c25 | Ruby | catedm/launch-school-130-ruby-foundations-more-topics | /ls_challenges/easy_1/sum_of_multiples.rb | UTF-8 | 675 | 4.3125 | 4 | [] | no_license | # input: number
# output: number
# rules:
# => find sum of all multiples of particular numbers up to but not including the given num
# => write program that can find sum of multiples of a given set of numbers
# => if no set of numbers is given, default to 3 and 5
# => class method
# algorithm:
# => sum = []
# => 0.upto(end_num)
require 'pry'
class SumOfMultiples
attr_reader :multiples
def initialize(*multiples)
@multiples = multiples
end
def self.to(end_num)
new(3, 5).to(end_num)
end
def to(end_num)
(0...end_num).select do |num|
multiples.any? { |mult| num % mult == 0 }
end.reduce(:+)
end
end
SumOfMultiples.to(10) # == 4419
| true |
4bbe080a30e80b09b332d107b94a70bcb531ceb7 | Ruby | prognostikos/cb2 | /spec/strategies/rolling_window_spec.rb | UTF-8 | 2,003 | 2.546875 | 3 | [
"MIT"
] | permissive | require "spec_helper"
describe CB2::RollingWindow do
let(:breaker) do
CB2::Breaker.new(
strategy: :rolling_window,
duration: 60,
threshold: 5,
reenable_after: 600)
end
let(:strategy) { breaker.strategy }
describe "#open?" do
it "starts closed" do
refute strategy.open?
end
it "checks in redis" do
redis.set(strategy.key, Time.now.to_i)
assert strategy.open?
end
it "closes again after the specified window" do
redis.set(strategy.key, Time.now.to_i - 601)
refute strategy.open?
end
end
describe "#half_open?" do
it "indicates the circuit was opened, but is ready to enable calls again" do
redis.set(strategy.key, Time.now.to_i - 601)
assert strategy.half_open?
end
it "is not half_open when the circuit is just open (before time reenable_after time)" do
redis.set(strategy.key, Time.now.to_i - 599)
refute strategy.half_open?
end
end
describe "#trip!" do
it "sets a key in redis with the time the circuit was opened" do
t = Time.now
Timecop.freeze(t) { strategy.trip! }
assert_equal t.to_i, redis.get(strategy.key).to_i
end
end
describe "#success" do
it "resets the counter so half open breakers go back to closed" do
redis.set(strategy.key, Time.now.to_i - 601)
strategy.success
assert_nil redis.get(strategy.key)
end
end
describe "#error" do
before { @t = Time.now }
it "opens the circuit when we hit the threshold" do
5.times { strategy.error }
assert strategy.open?
end
it "opens the circuit right away when half open" do
redis.set(strategy.key, Time.now.to_i - 601) # set as half open
strategy.error
assert strategy.open?
end
it "trims the window" do
Timecop.freeze(@t-60) do
4.times { strategy.error }
end
Timecop.freeze do
strategy.error
refute strategy.open?
end
end
end
end
| true |
94a9ebef4fbde9b7f8606f132eb44347147dd270 | Ruby | jmoglesby/uabootcamp-challenges | /linked_list/linked_list_2.rb | UTF-8 | 1,591 | 3.921875 | 4 | [] | no_license | class LinkedListNode
attr_accessor :value, :next_node
def initialize value, next_node=nil
@value = value
@next_node = next_node
end
end
def print_values list_node
if list_node
print "#{list_node.value} --> "
print_values list_node.next_node
else
print "nil\n"
return
end
end
def reverse_list head, previous=nil
new_head = head.next_node
head.next_node = previous
if new_head
reverse_list new_head, head
else
return head
end
end
def infinite_list? head
tortoise = head
hare = head
return t_and_h_race tortoise, hare
end
def t_and_h_race tortoise, hare
tortoise = tortoise.next_node
if hare.next_node
hare = hare.next_node.next_node
else
hare = nil
end
if tortoise == nil || hare == nil
return false
elsif tortoise == hare
return true
else
t_and_h_race tortoise, hare
end
end
# EXECUTE >>>>>>>>>>>>>>>>>>>>>>>>>>>>
node1 = LinkedListNode.new(2)
node2 = LinkedListNode.new(4, node1)
node3 = LinkedListNode.new(6, node2)
node4 = LinkedListNode.new(8, node3)
puts "\n**\nReverse Recursively:"
print_values(node4)
puts "---------------------------"
new_head = reverse_list(node4)
print_values(new_head)
inf_node1 = LinkedListNode.new(2)
inf_node2 = LinkedListNode.new(4, inf_node1)
inf_node3 = LinkedListNode.new(6, inf_node2)
inf_node4 = LinkedListNode.new(8, inf_node3)
inf_node1.next_node = inf_node3
puts "\n**\nDetect Infinite List:"
puts "inf_node4 is infinte? #{infinite_list?(inf_node4)}"
puts "--------------------------"
puts "node4 is infinite? #{infinite_list?(node4)}\n\n" | true |
e57e983993b09eab9d717be97cdd62a8097bc7e3 | Ruby | sitepress/sitepress | /sitepress-rails/lib/sitepress/models/collection.rb | UTF-8 | 826 | 3.203125 | 3 | [
"MIT"
] | permissive | module Sitepress
module Models
# Everything needed to iterate over a set of resources from a glob and wrap
# them in a model so they are returned as a sensible enumerable.
class Collection
include Enumerable
# Page models will have `PageModel.all` method defined by default.
DEFAULT_NAME = :all
# Iterate over all resources in the site by default.
DEFAULT_GLOB = "**/*.*".freeze
attr_reader :model, :glob, :site
def initialize(model:, site:, glob: DEFAULT_GLOB)
@model = model
@glob = glob
@site = site
end
def resources
site.glob glob
end
# Wraps each resource in a model object.
def each
resources.each do |resource|
yield model.new resource
end
end
end
end
end
| true |
c88f02fb7fb5f31cd2232ae3cefc9f71ba3f52a7 | Ruby | sicXnull/cryptoplace | /scripts/pixelize.rb | UTF-8 | 858 | 3 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'chunky_png'
require 'color'
colors = ['ffffff', 'e4e4e4', '888888', '222222', 'ffa7d1', 'e50000', 'e59500', 'a06a42', 'e5d900', '94e044', '02be01', '00d3dd', '0083c7', '0000ea', 'cf6ee4', '820080']
colors = colors.map { |color| "##{color}".match(/#(..)(..)(..)/) }.map { |a| Color::RGB.new(a[1].hex, a[2].hex, a[3].hex )}
p colors
image = ChunkyPNG::Image.from_file('doge.png')
(0...image.height).each do |y|
(0...image.width).each do |x|
arr = [ChunkyPNG::Color.r(image[x,y]), ChunkyPNG::Color.g(image[x,y]), ChunkyPNG::Color.b(image[x,y]), ChunkyPNG::Color.a(image[x,y])]
tc = Color::RGB.new(arr[0], arr[1], arr[2])
closest = tc.closest_match(colors)
image[x,y] = ChunkyPNG::Color.from_hex(closest.hex)
end
end
# image.save('output_cheat.png')
w = 20
h = 20
image.resize(w, h).save('output_tmp.png')
| true |
103c70f5bef8d6010eb45d2b2ea30fa9a77a10b4 | Ruby | krbrewer/advent-of-code-2020 | /day9/part1.rb | UTF-8 | 373 | 2.953125 | 3 | [] | no_license | file_data = File.read("day9.txt").split("\n")
n = 25
x = nil
for i in 0..file_data.length - n - 1
options = []
for j in i..i + n - 2
for k in i + 1..i + n - 1
options.push(file_data[j].to_i + file_data[k].to_i)
end
end
if !options.include?(file_data[i + n].to_i)
x = file_data[i + n]
break
end
end
puts x | true |
7f4dc0ad485e72beae68a944c2a21aaf3c1d0950 | Ruby | dorton/Samfundet | /app/models/standard_hour.rb | UTF-8 | 857 | 2.65625 | 3 | [
"MIT"
] | permissive | # == Schema Information
#
# Table name: standard_hours
#
# id :integer not null, primary key
# open_time :time
# close_time :time
# area_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# day :string(255)
#
class StandardHour < ActiveRecord::Base
belongs_to :area
WEEKDAYS = %w(monday tuesday wednesday thursday friday
saturday sunday).freeze
validates_inclusion_of :day, in: WEEKDAYS, message: "Invalid weekday"
validates_presence_of :day, :area
validates_presence_of :open_time, :close_time, if: :open?
validates :day, uniqueness: { scope: :area_id }
attr_accessible :close_time, :open_time, :day, :open
scope :open_today, -> { today.where(open: true) }
scope :today, -> do
where(day: Time.current.strftime("%A").downcase)
end
end
| true |
03483659f5cc3d44c895880b435bf83edc77c35c | Ruby | tiffnuugen/sinatra-views-lab-dumbo-web-082718 | /app.rb | UTF-8 | 345 | 2.53125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class App < Sinatra::Base
get '/' do
erb :index
end
get '/hello' do
erb :hello
end
get '/goodbye' do
@name = "Joe"
erb :goodbye
end
get '/date' do
@weekday = Date.today.strftime("%A")
@month = Date.today.strftime("%B")
@day = Time.now.asctime.split(" ")[2]
@year = Time.now.asctime.split(" ")[4]
erb :date
end
end
| true |
439d02f40a34d8887f363e0eba11c2b20ff8cde5 | Ruby | jeik0210/testing | /example.rb | UTF-8 | 447 | 2.953125 | 3 | [] | no_license | require 'minitest/spec'
require 'minitest/autorun'
describe 'MyTestSuit' do
before do
@array = []
end
it "adds 2 + 2 " do
(2 + 2).must_equal 4
end
it "includes a dog" do
%w(dog cat elephant).must_include 'dog'
end
it "is instance of fixnum" do
(2 + 2).must_be_instance_of Fixnum
end
it "must be nill" do
a = nil
a.must_be_nil
end
it "must raise an error " do
proc {@array.watever}.must_raise NoMethodError
end
end
| true |
695d51051d54f513256ecb01b58df2d113c420f2 | Ruby | chweeks/takeaway-challenge | /spec/menu_spec.rb | UTF-8 | 546 | 2.703125 | 3 | [] | no_license | require 'menu'
describe Menu do
let(:dish) {double :dish, show_details: 'Coke: £1'}
it { is_expected.to respond_to :dishes }
describe '#add_dish' do
it { is_expected.to respond_to :add_dish }
it 'should add dish to menu' do
subject.add_dish(dish)
expect(subject.dishes.first).to eql dish
end
end
describe '#show' do
it { is_expected.to respond_to :add_dish }
it 'should show the entire menu' do
subject.add_dish(dish)
expect(subject.show).to eql "Menu:\nCoke: £1"
end
end
end
| true |
ba2ad7d20a64d3d123892c0a355ff1e6e708a27a | Ruby | catherineemond/challenges | /leet-code/dynamic_programming/longest_subsequence.rb | UTF-8 | 841 | 4.0625 | 4 | [] | no_license | # Given an unsorted array of integers, find the length of longest increasing subsequence.
#
# Example:
#
# Input: [10,9,2,5,3,7,101,18]
# Output: 4
# Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
#
# Note:
#
# There may be more than one LIS combination, it is only necessary for you to return the length.
# Your algorithm should run in O(n2) complexity.
#
# Follow up: Could you improve it to O(n log n) time complexity?
def length_of_list(numbers)
list = numbers.shift
numbers.each_with_index do |num, idx|
break if idx == numbers.size - 1
if numbers[idx + 1] < num
current_length += 1
else
longest_length = current_length if current_length > longest_length
current_length = 1
end
end
longest_length
end
p length_of_list([10,9,2,5,3,7,101,18])
| true |
826b7033fee5d63af9c9ce1a0316aa7442359ae1 | Ruby | STRd6/strd6 | /hero_squad/app/models/game.rb | UTF-8 | 2,448 | 2.9375 | 3 | [] | no_license | class Game < ActiveRecord::Base
has_many :entries, :class_name => 'GameEntry'
has_many :players, :through => :entries, :order => 'position'
has_many :cards
has_many :character_instances
belongs_to :active_player, :class_name => 'Player'
belongs_to :active_character, :class_name => 'CharacterInstance'
validates_presence_of :name
module Phase
SETUP = "SETUP"
DEPLOY = "DEPLOY"
MAIN = "MAIN"
end
def self.make(name, players)
game = Game.new
game.configure name, players
game.save
return game
end
def configure(name, players)
self.name = name
self.phase = Phase::SETUP
# Set up player entries
position = 0
players.each do |p|
entries.build :player => p, :position => position, :game => self
position += 1
# Set up Character instances for player
#TODO: Use character list
Character.all.each do |character|
character_instances.build(
:character => character,
:player => p,
:game => self
)
end
end
# Create deck for game
#TODO: Use decklists for this
Item.all.each do |i|
cards.build :data => i, :game => self
end
Ability.all.each do |a|
cards.build :data => a, :game => self
end
end
def finish_setup(player)
"#{player} is done with setup"
end
# Assign all unassigned cards to players evenly
def deal
num_players = players.size
current_index = 0
current_player = players[current_index]
Game.transaction do
cards.unowned.random.each do |card|
#puts "#{card.id} - #{current_player.name}"
card.owner = current_player
card.save!
current_index = (current_index + 1)%num_players
current_player = players[current_index]
end
end
end
def cards_for_player(player)
cards.for_player player
end
def move_character(character, position)
if phase == Phase::DEPLOY
#TODO: Validate position
character.position = position
character.save
else
false
end
end
def assign_ability(character, ability, slot)
if phase == Phase::SETUP
character.assign_ability(ability, slot)
else
false
end
end
def assign_card(character, card, slot)
if phase == Phase::SETUP
character.assign_card(card, slot)
else
false
end
end
end
| true |
c86522846cf1f75852c4bdee97e5251ff9eea9a0 | Ruby | osgood1024/ruby-oo-object-relationships-has-many-lab-nyc-web-012720 | /lib/author.rb | UTF-8 | 406 | 3.171875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry'
class Author
attr_accessor :name
def initialize (name)
@name=name
@posts=[]
end
def posts
Post.all
end
def add_post (post)
@posts << self
post.author=self
end
def add_post_by_title (title)
post=Post.new(title)
add_post(post)
end
def self.post_count
Post.all.count
end
end
| true |
46e8eb5b383a995c605847d5e053453ceb97faf4 | Ruby | softecspa/puppetlabs-mysql | /lib/puppet/parser/functions/mysql_hashruntime.rb | UTF-8 | 950 | 2.859375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | module Puppet::Parser::Functions
newfunction(:mysql_hashruntime, :type => :rvalue, :doc => <<-EOS
TEMPORARY FUNCTION: EXPIRES 2014-03-10
When given a hash this function strips out all blank entries.
EOS
) do |args|
input_hash = args[0]
allowed = args[1]
unless input_hash.is_a?(Hash)
raise(Puppet::ParseError, 'mysql_hashruntime(): Requires hash as first parameter to work with')
end
unless allowed.is_a?(Array)
raise(Puppet::ParseError, 'mysql_hashruntime(): Requires array as second parameter to work with')
end
result = Hash.new
input_hash.each do |section, hash|
if section == 'mysqld'
hash.each do |key, val|
variable_name = key.sub('-','_')
if allowed.include?(variable_name)
keyval = Hash.new
keyval['value']=val
result[variable_name] = keyval
end
end
end
end
return(result)
end
end
| true |
4229609206834e7a27c38d9d71234aaf18e56584 | Ruby | supersquashman/character-generator | /Resources/Lists/ClassList.rb | UTF-8 | 1,505 | 2.640625 | 3 | [] | no_license | # ClassList - Manager of D&D Classes[ClassModel]
# Copyright (C) 2011 Cody Garrett, Josh Murphy, and Matt Ingram
# This file is part of FishTornado D&D Character Generator.
# FishTornado D&D Character Generator is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# FishTornado D&D Character Generator is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with FishTornado D&D Character Generator. If not, see <http://www.gnu.org/licenses/>.
require "#{File.dirname(__FILE__)}/../Models/ClassModel"
#--== ClassList ========================================================================#
#++
class ClassList
@@list=Hash.new
#-- list -------------------------------------------------------------------------------#
#++
def list
return @@list
end
#-- self.push(classes) -----------------------------------------------------------------#
#++
def self.push(classs)
@@list[classs.to_s] = classs
end
#-- self.list --------------------------------------------------------------------------#
#++
def self.list
return @@list
end
end | true |
6687cb4ae05f12569eea764f123bb673720f4f5d | Ruby | capral/home | /home6/station2.rb | UTF-8 | 1,951 | 3.59375 | 4 | [] | no_license | class Station
attr_reader :name, :list
@@all_stations = []
def self.all_stations
@@all_stations
end
def initialize (name)
@name = name
@list = []
validate!
@@all_stations << self
end
def anything_station(&block)
@list.each{ |train| block.call(train) }
end
def add_list (train)
@list << train
end
def delete_list (train)
@list.delete
end
def type_list
type_list = Hash.new(0)
@list.map { |train| type_list[train.type] += 1 }
type_list
end
def valid?
validate!
true
rescue
false
end
# protected
def validate!
raise ArgumentError, "!!! Вы не ввели название станции !!!" if name.empty?
raise ArgumentError, "!!! Название станции не может состоять из одной буквы !!!" if name.size < 2
end
def start
attempt = 1
begin
puts "Введите название станции:"
name = gets.chomp
station1 = Station.new(name)
puts "Вы создали станцию #{station1.name}"
puts "Список всех станций класса Station: #{Station.all_stations}"
rescue ArgumentError
attempt += 1
puts "Попробуйте ещё раз (попытка #{attempt}) :"
puts "Введите два и более символов" if attempt == 3
puts "Не балуйся!" if attempt > 3
retry
end
attempt = 1
begin
puts "Введите название станции:"
name = gets.chomp
station2 = Station.new(name)
puts "Вы создали станцию #{station2.name}"
puts "Список всех станций класса Station: #{Station.all_stations}"
rescue ArgumentError
attempt += 1
puts "Попробуйте ещё раз (попытка #{attempt}) :"
puts "Введите два и более символов" if attempt == 3
puts "Не балуйся!" if attempt > 3
retry
end
end
end
| true |
fff8dfb8329cc43847aff1e717a5ad6f8495fefb | Ruby | CodeHaven9ja/binlist | /lib/binlist.rb | UTF-8 | 322 | 2.6875 | 3 | [
"MIT"
] | permissive | require "binlist/version"
require "httparty"
module Binlist
include HTTParty
base_uri "https://lookup.binlist.net"
# This is called to find a Bin
# @params bin [string]
# @return [Net::HTTPResponse] A subclass of Net::HTTPResponse, e.g. Net::HTTPOK
def self.find(bin)
get("/#{bin}", verify: false)
end
end
| true |
a89c06774c4d80020efd6545f0ae61207aa60d2d | Ruby | manuelbouvierpiz/ILoveBanana | /Defi.rb | UTF-8 | 2,681 | 2.984375 | 3 | [] | no_license | # Valentin CHAILLOU
# Defi.rb
# Implémentation de la classe Defi
# == Classe Defi :
# - connaît son envoyeur, son destinataire, sa Grille
# - sait relever un défi, supprimer un défi, donne le score de l'envoyeur
class Defi
# Variables d'instance
# * Variable d'instance (un <b>String</b>) qui représente le pseudo de l'envoyeur du *Defi*
# * Est initialisée lors de la création de l'objet
# * Accessible en lecture uniquement
attr :envoyeur, false
# * Variable d'instance (un <b>String</b>) qui représente le pseudo du destinataire du *Defi*
# * Est initialisée lors de la création de l'objet
# * Accessible en lecture uniquement
attr :destinataire, false
# * Variable d'instance qui représente la *Grille* du *Defi*
# * Est intialisée lors de la création de l'objet
# * Accessible en lecture uniquement
attr :idGrille, false
attr :scoreEnvoi, false
# Méthodes d'instance
# * Méthode d'instance qui relève un *Defi*
# * crée une nouvelle *Partie* dans le *Jeu*
# * Retourne la *Partie* en cours dans le *Jeu*
def relever
Jeu.JEU.partie = PartieDefi.creer(@idGrille, @envoyeur, score)
return Jeu.JEU.partie
end
# * Méthode d'instance qui supprime le défi courant
# * Supprime le *Defi* dans la BDD
# * Retourne *nil*
def supprimer
BaseDeDonnees.supprimeDefi(@envoyeur, @destinataire, @idGrille)
# ACHTUNG ! L'instance n'est pas supprimée directement : NE PAS RELEVER UN DEFI SUPPRIME !!!
# Par précaution il vaut mieux faire listeDefis[X] = listeDefis.supprimer! afin de supprimer l'instance
return nil
end
# * Méthode d'instance qui retourne le score réalisé par l'envoyeur pour le *Defi*
# * Recherche le score de l'envoyeur dans la BDD
# * Retourne un entier représentant le score de l'envoyeur
def score
return BaseDeDonnees.getDefiScore(@envoyeur, @destinataire, @idGrille)
end
def initialize(unDestinataire, unEnvoyeur, unIdGrille, unScore) # :nodoc:
@envoyeur, @destinataire, @idGrille, @scoreEnvoi = unEnvoyeur, unDestinataire, unIdGrille, unScore
end
# * Méthode d'instance qui envoie le *Defi*
# * Retourne -1 si échoué
def envoyerDefi
return BaseDeDonnees.setDefi(@destinataire, @envoyeur, @idGrille, @scoreEnvoi)
end
# Méthode de classe
# * Méthode de classe permettant de créer un *Defi*
# ===== Attributs :
# - unEnvoyeur : le Compte de l'envoyeur
# - unDestinataire : le Compte du destinataire
# - uneGrille : la Grille du Defi
# - unScore : un entier représentant le score réalisé par l'envoyeur
def Defi.creer(unDestinataire, unEnvoyeur, unIdGrille, unScore)
new(unDestinataire, unEnvoyeur, unIdGrille, unScore)
end
private_class_method :new
end
| true |
1735ed59df55f31dd2f2a05b1d19ff4ab97fd465 | Ruby | danilobarion1986/desafio_vagas | /spec/talk_spec.rb | UTF-8 | 1,177 | 3.171875 | 3 | [] | no_license | require_relative './spec_helper.rb'
describe Talk do
before :all do
@title = "Title of talk lightning"
@long_title = "Long title 45min"
@talk = Talk.new @title
@long_talk = Talk.new @long_title
end
describe "#new" do
it "return a new Talk object" do
#@talk.should be_an_instance_of Talk # => Deprecated format
expect(@talk).to be_an_instance_of Talk
end
it "takes no parameteres and not returns a Talk object" do
#lambda { Talk.new }.should raise_exception ArgumentError # => Deprecated format
expect { Talk.new }.to raise_error(ArgumentError)
end
it "takes more than one parameter and not returns a Talk object" do
expect { Talk.new "Title", "More Title" }.to raise_error(ArgumentError)
end
end
describe "#title" do
it "returns the correct title" do
#@talk.title.should == @title # => Deprecated format
expect(@talk.title).to eql(@title) # => eql: same value and type
end
end
describe "#duration" do
it "returns the corret duration for flash talks" do
expect(@talk.duration).to eql(5)
end
it "returns the corret duration for long talks" do
expect(@long_talk.duration).to eql(45)
end
end
end | true |
26f550c6ddd0f5b43d81ebd164fbb055b53000a8 | Ruby | kitwalker12/ruby-interview | /min_stack.rb | UTF-8 | 530 | 4.15625 | 4 | [] | no_license | # Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
class MinStack
attr_accessor :vals, :min
def initialize
@vals = []
@min = []
end
def push(x)
if min.empty? || x <= self.get_min()
min.push(x)
end
vals.push(x)
end
def pop
if vals.last == self.get_min()
min.pop
end
vals.pop
end
def get_min
min.last
end
end
min_stack = MinStack.new
90.upto(100) do |i|
min_stack.push(i)
end
min_stack.pop
min_stack.get_min
| true |
e0824fb79392783983f004816cd21b00a9ba19fb | Ruby | Agsiegert/Meeting_rooms | /spec/meeting_rooms_spec.rb | UTF-8 | 3,579 | 3.515625 | 4 | [] | no_license | require 'meeting_room'
RSpec.describe 'Meeting Rooms' do
context 'initialized with known constraints'do
room1 = MeetingRoom.new('Room 1')
room2 = MeetingRoom.new('Room 2')
it 'a room1 has a name Room 1:' do
expect(room1.name).to eq('Room 1')
end
it 'a room2 has a name Room 2:' do
expect(room2.name).to eq('Room 2')
end
it 'have working hours' do
expect(room1.work_hours).to eq('09:00 - 17:00')
end
it 'has a lunch break' do
expect(room2.lunch).to eq('12:00 - 13:00')
end
end
context 'have available meeting_times' do
room = MeetingRoom.new('Room 1')
it 'takes the work_hours and splits up based on lunch' do
expect(room.meeting_times[:am][:available_time]).to eq(180)
expect(room.meeting_times[:pm][:available_time]).to eq(240)
end
end
# build meeting room object, knows its buckets of time,
# build a meeting object? knows its name and time, input from file?
# build a scheduler, greedy loads rooms (room time.sort.reverse) fill large meetings first. Keeps track of meetings to report out the schedule for each room
end
# You are in charge of assigning meeting rooms at your company. Especially many meetings have been planned for next Thursday. so you decided to write a program to help you fit the meetings within your time constraints.
# There are 2 meeting rooms
# The meetings have to be scheduled during core work hours (09:00 - 17:00)
# No meetings can be scheduled during lunchtime (12:00 - 13:00)
# Meetings at your company never overrun and can be scheduled back-to-back. with no gaps in between them.
# Apart from these constraints, meetings can be placed anywhere. and the duration of gaps between them doesn't matter.
# The input contains one meeting per line; the meeting title can contain any characters and is followed by a space and the meeting duration. which is always given in minutes. Since multiple meeting configurations are possible, the test output given here is only one of the possible solutions. and your output doesn‘t have to match it as long as it meets all constraints.
# Please submit your answer as a link to a github repository {or the program you wrote.
test_input =
"All Hands meeting 60min,
Marketing presentation 30min,
Product team sync 30min,
Ruby vs Go presentation 45min,
New app design presentation 45min,
Customer support sync 30min,
Frontvend coding interview 60min,
Skype Interview A 30min,
Skype Interview 30min,
Project Bananaphone Kickoff 45min,
Developer talk 60min,
API Architecture planning 45min,
Android app presentation 45min,
Back-end coding interview A 60min,
Back-end coding interview B 60min,
Back-end coding interview C 60min,
Sprint planning 45min,
New marketing campaign presentation 30min"
# Test output:
# Room 1:
# 09:00AM All Hands meeting 60min
# 10:00AM API Architecture planning 45min
# 10:45AM Product team sync 30min
# 11:15AM Ruby vs Go presentation 45min
# 12:00PM Lunch
# 01:00PM Back-end coding interview A 60min
# 02:00PM Android app presentation 45min
# 02:45PM New app design presentation 45min
# 03:30PM New marketing campaign presentation 30min
# 04:00PM Customer support sync 30min
# 04:30PM Skype Interview A 30min
# Room 2:
# 09:00AM Back-end coding interview B 60min
# 10:00AM Front-end coding interview 60min
# 11:00AM Skype Interview 30min
# 12:00PM Lunch
# 01:00PM Project Bananaphone Kickoff 45min
# 01:45PM Sprint planning 45min
# 02:30PM Marketing presentation 30min
# 03:00PM Developer talk 60min
# 04:00PM Back-end coding interview C 60min
| true |
114b83bab2d553f8f5698c06b50f0c144b14fde4 | Ruby | developer88/Blitz-rake-task | /lib/tasks/blitz.rake | UTF-8 | 1,725 | 2.546875 | 3 | [] | no_license | require 'rubygems'
require 'blitz'
require 'pp'
URL_PRODUCTION = "http://production_somesite.com" # Default production URL
URL = "https://stage_or_development_url.com" # Default url
DLM0 = "====================================================="
DLM1 = "\n-----------------------------------------------------\n "
namespace :blitz do
desc "Run performance tests by using Blitz gem.
Params:
PRODUCTION=1 - user production url
URL - url to sprint"
task sprint: 'environment' do
url = ENV['PRODUCTION'].to_i == 1 ? URL_PRODUCTION : URL
url = (!ENV['URL'].nil? && ENV['URL'].size > 0) ? ENV['URL'] : url
puts DLM0
puts "Start Blitz sprint"
# Run a sprint
require 'blitz'
sprint = Blitz::Curl.parse("-r ireland #{url}")
result = sprint.execute
pp :duration => result.duration
puts DLM1
end
desc "Run performance tests by using Blitz gem.
Params:
PRODUCTION=1 - user production url
URL - url to rush"
task rush: 'environment' do
url = ENV['PRODUCTION'].to_i == 1 ? URL_PRODUCTION : URL
url = (!ENV['URL'].nil? && ENV['URL'].size > 0) ? ENV['URL'] : url
puts DLM0
puts "Start Blitz rush"
# Or a Rush
rush = Blitz::Curl.parse("-r ireland -p 1-250:60 #{url}")
rush.execute do |partial|
pp [ partial.region, partial.timeline.last.hits ]
end
puts DLM1
end
desc "Run performance tests by using Blitz gem.
Params:
PRODUCTION=1 - user production url
URL - url to rush"
task all: 'environment' do
args = {'URL' => ENV['URL'], 'PRODUCTION' => ENV['PRODUCTION']}
Rake::Task['blitz:sprint'].invoke(args)
Rake::Task['blitz:rush'].invoke(args)
end
end | true |
324f146c0c72999125a9b98b5ca38e50be53cc5d | Ruby | Rubeasts/gitget | /lib/gitget/github_repository.rb | UTF-8 | 1,698 | 2.859375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Github
# Main class to set up a Github User
class Repository
attr_reader :id, :name, :full_name, :is_private, :is_fork, :created_at,
:updated_at, :pushed_at, :size, :stargazers_count,
:watchers_count, :has_issues, :has_downloads, :forks_count,
:open_issues_count, :forks, :open_issues, :watchers, :language,
:git_url
def initialize(data: nil)
load_data(data)
end
def stats(stat_names: ['code_frequency'])
return @stats if @stats
@stats = {}
stats_promises = {}
stat_names.each do |stat|
stats_promises[stat.to_sym] = Concurrent::Promise.execute {
Github::API.repo_stat(@full_name, stat)
}
end
stats_promises.each do |stat_name, stat_value|
@stats[stat_name] = stat_value.value
end
@stats
end
def load_data(repo_data)
@id = repo_data['id']
@full_name = repo_data['full_name']
@is_private = repo_data['is_private']
@is_fork = repo_data['is_fork']
@created_at = repo_data['created_at']
@pushed_at = repo_data['pushed_at']
@size = repo_data['size']
@stargazers_count = repo_data['stargazers_count']
@watchers_count = repo_data['watchers_count']
@forks_count = repo_data['forks_count']
@open_issues_count = repo_data['open_issues_count']
@language = repo_data['language']
@git_url = repo_data['git_url']
end
def self.find(owner:, repo:)
repo_data = Github::API.repo_info(owner, repo)
return nil if repo_data['message'] == 'Not Found'
new(data: repo_data)\
end
end
end
| true |
22a6a0079b5edd7a61e2e22ba5bea25081d4bbf4 | Ruby | RomanADavis/challenges | /advent/2017/day8/solutions/part2.rb | UTF-8 | 510 | 3.4375 | 3 | [] | no_license | # --- Part Two ---
#
# To be safe, the CPU also needs to know the highest value held in any register
# during this process so that it can decide how much memory to allocate to these
# operations
require_relative "part1.rb"
class Computer
attr_accessor :max
def solve
self.max = 0
self.lines.each do |line|
parse(line)
highest = self.registers.values.max
self.max = highest if highest > self.max
end
self.max
end
end
p Computer.new("../input/instructions.txt").solve
| true |
ee3b83686a8fadf0c3c3dd4cc6a24cbefbc514ef | Ruby | sumkincpp/CodeTest | /ruby/basics.rb | UTF-8 | 1,242 | 3.609375 | 4 | [] | no_license |
################################################
#
# Check if array includes Range
#
################################################
['w', '-', 12].grep('a'..'z') # => ["w"]
[ 4 , :a, '^'].grep('a'..'z') # => []
['w', '-', 'e'].grep('a'..'z') # => ["w", "e"]
# Here is a modified code of your using #grep :
ary = ['w', '-', 12]
if ary.grep('a'..'z').empty?
puts "Doesnt have Permutation"
else
puts "Have permutation"
end
"hello James!".downcase
"hello James!".upcase
"hello James!".capitalize
### Dates ###
Date.today.month # => current month(int)
Date::MONTHNAMES[1] # => January
Date::ABBR_MONTHNAMES[1] # => JAN
### Arrays / Enumerators ###
(1..6).group_by { |i| i%3 } # => {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
(1..10).each_slice(3).to_a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
### Files ###
# File size in MBs
compressed_file_size = '%.2f' % (File.size("file.txt").to_f / 2**20)
# in bytes
File.stat("testfile").size
# Touch File
require 'fileutils'
FileUtils.touch('file.txt') #1
File.open("foo.txt", "w") {} #2
File.write("foo.txt", "") #3
# Glob files
Dir["config.?"] #=> ["config.h"]
Dir.glob("config.?") #=> ["config.h"]
12.method("+").call(3) # => 15
| true |
bd2cfc8b3220abe7164cc12609db0969ef38689f | Ruby | rshiva/MyDocuments | /10-book-case/ruby1.9/samples/refcio_4.rb | UTF-8 | 647 | 2.53125 | 3 | [] | no_license | #---
# Excerpted from "Programming Ruby",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/ruby3 for more book information.
#---
IO.foreach("testfile", nil, mode: "rb", encoding: "ascii-8bit") do |content|
puts content.encoding
end
IO.foreach("testfile", nil, open_args: ["r:iso-8859-1"]) do |content|
puts content.encoding
end
| true |
7a3506426d471a4f16163cde36c0a6544887fd91 | Ruby | ybasabe/rspec-fizzbuzz-ruby-intro-000 | /fizzbuzz.rb | UTF-8 | 171 | 2.5625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | Don't forget! This file needs to be 'required' in its spec file
# See README.md for instructions on how to do this
def fizzbuzz(int)
if int % 3 == log10
"Fizz"
end
end | true |
d98e85242c6ea3f3260c0f4e5bc538eca575dfcc | Ruby | PureMVC/puremvc-ruby-standard-framework | /src/org/puremvc/ruby/patterns/mediator/mediator.rb | UTF-8 | 1,001 | 2.59375 | 3 | [] | no_license | class Mediator < Notifier
# The name of the Mediator
# Typically, a Mediator will be written to serve one specific control or group
# controls and so,will not have a need to be dynamically named.
attr_reader :name
attr_accessor :view
def initialize(name="Mediator", view=nil )
@name = name
@view = view
end
# List the Notification names this Mediator is interested in being notified of.
def list_notification_interests
[]
end
# Handle Notifications.
#
# Typically this will be handled in a switch statement, with one 'case' entry
# per Notification the Mediator is interested in.
def handle_notification(note)
#override if you want to do something on this event
end
# Called by the View when the Mediator is registered
def on_register
#override if you want to do something on this event
end
# Called by the View when the Mediator is removed
def on_remove
#override if you want to do something on this event
end
end | true |
926d6e5c83de82568a01b6d6c12b38461fc58a3a | Ruby | spookyorange/top_projects | /binary_search_tree/bst.rb | UTF-8 | 4,752 | 3.34375 | 3 | [] | no_license | class Node
include Comparable
attr_accessor :right, :left, :root
def initialize(root = nil, left = nil, right = nil)
@root = root
@left = left
@right = right
end
def put
puts @root
end
end
class Tree
attr_reader :array
def initialize(array)
@array = array.uniq.sort
end
def root(a = @a)
@root = a
@root
end
def build_tree(array, start = 0, done)
return if start > done
mid = (done + start) / 2
root = Node.new
root.root = array[mid]
root.right = build_tree(array[mid + 1..-1], 0, array.length / 2 - 1)
root.left = build_tree(array[0..mid - 1], 0, mid - 1)
@a = root
end
def insert(value, pointer = @a)
return if pointer.root == value
if value > pointer.root
if pointer.right.nil? && pointer.left.nil?
pointer.right = Node.new(value, nil, nil)
else
insert(value, pointer.right)
end
elsif value < pointer.root
if pointer.left.nil?
pointer.left = Node.new(value, nil, nil)
else
insert(value, pointer.left)
end
end
end
def delete(value, pointer = @a, bef = @a)
if value == pointer.root
if pointer.right.nil? && pointer.left.nil?
if bef.root < pointer.root
bef.right = nil
else
bef.left = nil
end
elsif pointer.right.nil? && !pointer.left.nil?
if bef.root > pointer.root
bef.left = pointer.left
else
bef.right = pointer.left
end
elsif !pointer.right.nil? && pointer.left.nil?
if bef.root > pointer.root
bef.left = pointer.right
else
bef.right = pointer.right
end
elsif !pointer.right.left.nil?
pointer.root = pointer.right.left.root
pointer.right.left = nil
else
pointer.root = pointer.left.right.root
pointer.left.right = nil
end
return
end
if value < pointer.root
delete(value, pointer.left, pointer)
elsif value > pointer.root
delete(value, pointer.right, pointer)
end
end
def find(value, pointer = @a)
return false if pointer.nil?
return pointer if pointer.root == value
if pointer.root > value
find(value, pointer.left)
else
pointer.root < value
find(value, pointer.right)
end
end
def level_order(pointer = @a)
@all = Array.new
queue = Array.new
@all << pointer
queue << pointer
while !queue.empty?
pointer = queue[0]
queue << pointer.left if !pointer.left.nil?
queue << pointer.right if !pointer.right.nil?
@all << queue[0].root
queue.shift
end
@all.shift
@all
end
def inorder(pointer = @a, all = Array.new)
return if pointer.nil?
all << inorder(pointer.left)
all << pointer.root
all << inorder(pointer.right)
all.compact
end
def preorder(pointer = @a, all = Array.new)
return if pointer.nil?
all << pointer.root
all << preorder(pointer.left)
all << preorder(pointer.right)
all.compact
end
def postorder(pointer = @a, all = Array.new)
return if pointer.nil?
all << postorder(pointer.left)
all << postorder(pointer.right)
all << pointer.root
all.compact
end
def height(node, count = 0)
return -1 if node.nil?
count += 1
if height(node.left) > height(node.right)
count += height(node.left)
elsif height(node.right) > height(node.left)
count += height(node.right)
else
count += height(node.left)
end
count
end
def depth(node, pointer = @a)
count = 0
return -1 if node == nil
return count if pointer.root == node.root
while pointer.root != node.root
if pointer.root > node.root
pointer = pointer.left
count += 1
end
if node.root > pointer.root
pointer = pointer.right
count += 1
end
if node.root == pointer.root
return count
end
end
end
def balanced?(pointer = @a)
return if pointer.left.nil? && pointer.right.nil?
if height(pointer.right) - height(pointer.left) > 1
return false
elsif height(pointer.left) - height(pointer.right) > 1
return false
else
balanced?(pointer.left) if !pointer.left.nil?
balanced?(pointer.right) if !pointer.right.nil?
end
return true
end
def rebalance(pointer = @a)
build_tree(level_order, 0, level_order.length - 1)
end
end
my_array = [1, 7, 4, 23, 8, 9, 4, 3, 5, 7, 9, 67, 6345, 324]
tree = Tree.new(my_array)
tree.build_tree(tree.array, 0, tree.array.length - 1)
tree.insert(-34)
tree.insert(-2)
tree.insert(-65)
tree.insert(-845)
puts tree.root.right.root
tree.rebalance
puts tree.balanced? | true |
72c5dfea2699ba99f7b565e056fe05eb6b28c72c | Ruby | knthompson2/backend_mod_1_prework | /section2/exercises/ex2.rb | UTF-8 | 1,471 | 4.3125 | 4 | [] | no_license | people = 30
cars = 40
trucks = 15
#analyzing if cars is greater than 30; follwoign that, commands for the computer to return.
#In this case, cars is greater than 30, so it will return : "we should take the cars."
if cars > 30
puts "We should take the cars."
elsif cars < people
puts "We should not take the cars."
else
puts "We can't decide."
end
#analyzing if there are more trucks than cars; because there are fewer trucks than cars, computer will return elsif command puts "Maybe we could take the trucks."
if trucks > cars
puts "That's too many trucks."
elsif trucks < cars
puts "Maybe we could take the trucks."
else
puts "We still can't decide."
end
#analyzing if more people than trucks. if more people, puts "Alright, let's just take the trucks." If not, will analyze elsif and else commands to return appropraite response.
if people > trucks
puts "Alright, let's just take the trucks."
else
puts "Fine, let's stay home then."
end
# || represents "or"
# analyzes if more cars than people OR fewer trucks than cars, the put "Alright, let's just take the trucks." More cars than people so this is true. If neither is true, will put else return command
if cars > people || trucks < cars
puts "Alright, let's just take the trucks."
else
puts "Fine, let's stay home then."
end
#1. elsif specifies another if clause that ruby will use after the initial if Statements
# else puts something for any other option if `if` and `elsif` aren't true
| true |
854353b6ca8716e1bef14dbc2224b1a9d3d62fa2 | Ruby | emrancub/Basic-Ruby-Programming-Practice | /chapter_3.1/comparitions_expressions.rb | UTF-8 | 555 | 4.0625 | 4 | [] | no_license | # age = 10
# puts "You are teenager" if age >=12 && age <=20
# puts "You're Not teenager" unless age >= 12 && age <= 20
# age = 23
# puts "You're 24!" if age == 24
# age = 2
# puts "You're either very young or very old" if age >= 80 || age <= 10
gender = "male"
age = 87
puts "A very young or old man" if gender == "male" && (age <=18 || age >= 85)
# age = 18
# puts "You're too young to use this system" if age <= 18
# age = 15
# puts "You're a teenager" if age > 12 && age < 20
# age = 15
# puts "You're NOT a teenager" unless age > 12 && age < 20 | true |
2a723ff730528cbd80b3b66193d4780ad40fa454 | Ruby | srycyk/mine | /lib/mine/fetch/http/build_uri.rb | UTF-8 | 1,903 | 2.625 | 3 | [
"MIT"
] | permissive |
require "mine/fetch/http/url_to_uri"
module Mine
module Fetch
module Http
class BuildUri < Struct.new(:url)
include UrlToUri
TYPES = %i(params)
attr_accessor :address
def initialize(*)
super
self.address = uri
end
def call
address
end
def to_s
address.to_s
end
def params
EscapeUri.new(address.query || {}).(:params)
end
def params=(other)
self.address.query = EscapeUri.new(other).(:query)
end
def merge(other)
self.params = params.merge(other)
self
end
def delete(*names)
self.params = params.delete_if {|key, _| names.include? key }
self
end
def path
address.path[1..-1]
end
def path=(other)
address.path = absolute_path(other)
end
def replace(from, to='')
self.path = path.sub(/#{from}/, to)
self
end
def set(elements)
elements.each {|name, value| address.send "#{name}=", value }
self
end
def absolute(relative)
relative_path, relative_query = relative.to_s.split '?'
self.class.new(address.dup).set path: absolute_path(relative_path),
query: relative_query
end
alias abs absolute
class << self
def absolute(url, original_url)
if absolute? url
url
else
new(original_url).absolute(url).to_s
end
end
def absolute?(url)
url =~ /^http/
end
end
private
def absolute_path(path)
path.start_with?('/') ? path : '/' + path
end
end
end
end
end
| true |
8095b2c4f3cd9bc8499b6823dab91e8576357199 | Ruby | jenko/query_engine | /test_datasetfunction.rb | UTF-8 | 2,989 | 2.53125 | 3 | [] | no_license | require 'test/unit'
require './dataset.rb'
require './datasetfunction.rb'
class TestDataset < Test::Unit::TestCase
def test_pct_move_2_insts
ds_sig = Datasetfunction.make_signature("PCT_MOVE", "F.SP.CLOSE", "F.SP.CLOSE", "-3", "1")
assert_equal([["F.SP.CLOSE","F.SP.CLOSE"], "{|d,v,i|100*(@ds1[i+1]-@ds0[i+-3])/@ds0[i+-3]}"], ds_sig)
ds = Dataset.new(ds_sig)
assert_equal(3.62, ds[44].round(2))
end
def test_pct_move_of_true_high
ds_sig = Datasetfunction.make_signature("PCT_MOVE", "TRUE_HIGH(F.SP)", "-3", "1")
assert_equal([[[["F.SP.CLOSE","F.SP.HIGH"],"{|d,v,i| if @ds0[i-1]>@ds1[i] then @ds0[i-1] else @ds1[i] end}"]] ,"{|d,v,i|100*(@ds0[i+1]-@ds0[i+-3])/@ds0[i+-3]}"], ds_sig)
ds = Dataset.new(ds_sig)
assert_equal(3.17, ds[44].round(2))
end
def test_pct_move_1_insts
ds_sig = Datasetfunction.make_signature("PCT_MOVE", "F.SP.CLOSE", "-3", "1")
assert_equal([["F.SP.CLOSE"], "{|d,v,i|100*(@ds0[i+1]-@ds0[i+-3])/@ds0[i+-3]}"], ds_sig)
end
def test_average_default_attr
ds_sig = Datasetfunction.make_signature("AVERAGE", "F.SP", "-3", "1")
assert_equal([["F.SP.CLOSE"], "{|d,v,i| @ds0[i+-3..i+1].inject(0.0) { |sum, v| sum + v.to_f } /5}"], ds_sig)
ds = Dataset.new(ds_sig)
assert_equal(109.66, ds[44].round(2))
end
def test_average_specified_attr
ds_sig = Datasetfunction.make_signature("AVERAGE", "F.SP.HIGH", "-3", "1")
assert_equal([["F.SP.HIGH"], "{|d,v,i| @ds0[i+-3..i+1].inject(0.0) { |sum, v| sum + v.to_f } /5}"], ds_sig)
end
def test_true_high
ds_sig = Datasetfunction.make_signature("TRUE_HIGH","F.SP")
assert_equal([["F.SP.CLOSE","F.SP.HIGH"],"{|d,v,i| if @ds0[i-1]>@ds1[i] then @ds0[i-1] else @ds1[i] end}"], ds_sig)
end
def test_true_low
ds_sig = Datasetfunction.make_signature("TRUE_LOW","F.SP")
assert_equal([["F.SP.CLOSE","F.SP.LOW"],"{|d,v,i| if @ds0[i-1]<@ds1[i] then @ds0[i-1] else @ds1[i] end}"], ds_sig)
end
def test_true_range
ds_sig = Datasetfunction.make_signature("TRUE_RANGE","F.SP")
th_sig = Datasetfunction.make_signature("TRUE_HIGH","F.SP")
tl_sig = Datasetfunction.make_signature("TRUE_LOW","F.SP")
assert_equal([[th_sig,tl_sig],"{|d,v,i|@ds0[i]-@ds1[i]}"], ds_sig)
end
def test_true_ATR_as_Average_of_TR
# user call: ATR("F.SP")
# DOES call make_average
ds_sig = Datasetfunction.make_signature("AVERAGE","TRUE_RANGE(F.SP)","-13","0")
ds = Dataset.new(ds_sig)
assert_equal(2.65, ds[44].round(2))
end
def test_true_ATR_as_ATR_func
# does NOT call make_average, constructs the average itself
ds_sig = Datasetfunction.make_signature("AVERAGE_TRUE_RANGE","F.SP","14")
ds = Dataset.new(ds_sig)
assert_equal(2.65, ds[44].round(2))
end
#ATR
#assert_equal([[th_sig,tl_sig],"{|d,v,i|@ds0[i-(14-1)..i].inject(0.0) { |sum, v| sum + v.to_f } /14}"], ds_sig)
=begin
=end
# make_signature(:dsfunction=>"TRUE_HIGH",:insts=>["F.SP"],:from=>-13,:to=>0)
# => [["F.SP.CLOSE","F.SP.HIGH"],"{|d,v,i| if @ds0[i-1]>@ds1[i] then @ds0[i-1] else @ds1[i] end}"]
end
| true |
20f29321d538189aa3a904525774988ff93ade25 | Ruby | MondoGao/oo-student-scraper-cb-gh-000 | /lib/scraper.rb | UTF-8 | 987 | 2.859375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'open-uri'
require 'pry'
require 'nokogiri'
class Scraper
def self.scrape_index_page(index_url)
students = []
index_folder = index_url.split(/index\.html/)[0]
doc = Nokogiri::HTML(open(index_url))
doc.css(".student-card").each do |card|
students << {
name: card.css(".student-name").text,
location: card.css(".student-location").text,
profile_url: index_folder + card.css("a").attribute("href").value
}
end
students
end
def self.scrape_profile_page(profile_url)
doc = Nokogiri::HTML(open(profile_url))
student = {
profile_quote: doc.css(".profile-quote").text,
bio: doc.css(".bio-content .description-holder").text.strip
}
doc.css(".social-icon-container a").each do |social|
key = social.css("img").attribute("src").value.match(/img\/\w+/)[0][4..-1]
key = "blog" if key == "rss"
student[key.to_sym] = social.attribute("href").value
end
student
end
end
| true |
85aabc936d8ead8104cd70db10ea01e4467dc056 | Ruby | ferocia/snek | /client/random_snake.rb | UTF-8 | 1,724 | 3.609375 | 4 | [] | no_license | class RandomSnake
def initialize(our_snake, game_state, map)
# Game state is an hash with the following structure
# {
# alive_snakes: [{snake}],
# leaderboard: []
# }
# Each snake is made up of the following:
# {
# id: id,
# name: name,
# head: {x: <int>, y: <int>,
# color: <string>,
# length: <int>,
# body: [{x: <int>, y: <int>}, etc.]
# }
@game_state = game_state
# Map is a 2D array of chars. # represents a wall and '.' is a blank tile.
# The map is fetched once - it does not include snake positions - that's in game state.
# The map uses [y][x] for coords so @map[0][0] would represent the top left most tile
@map = map
@our_snake = our_snake
@current_position = @our_snake.fetch("head")
end
def get_intent
# Let's evaluate a random move
possible_moves = ["N", "S", "E", "W"].shuffle
# Note we should probably avoid walls, or other snakes hey...
# An exercise for the reader!
possible_moves.reject!{|possible_intent|
@our_snake.fetch(:body).include?(next_position(possible_intent).with_indifferent_access)
}
if possible_moves.empty?
# Doh - we're dead anyway
"N"
else
possible_moves.first
end
end
private
def next_position(possible_intent)
case possible_intent
when 'N' then {y: @current_position.fetch(:y) - 1, x: @current_position.fetch(:x)}
when 'S' then {y: @current_position.fetch(:y) + 1, x: @current_position.fetch(:x)}
when 'E' then {y: @current_position.fetch(:y), x: @current_position.fetch(:x) + 1}
when 'W' then {y: @current_position.fetch(:y), x: @current_position.fetch(:x) - 1}
end
end
end | true |
71b1a2b29ae230e31de38aed9dd4c3071794086d | Ruby | zhangruochi/Codewars | /Switch_it_Up.rb | UTF-8 | 841 | 4.21875 | 4 | [] | no_license | #!/usr/bin/env ruby
#info
#-name : zhangruochi
#-email : zrc720@gmail.com
=begin
When provided with a number between 0-9, return it in words.
Input :: 1
Output :: "One".
Try using "Switch" statements.
This kata is meant for beginners. Rank and upvote to bring it out of beta
=end
def switch_it_up(number)
case number
when 0
return "Zero"
when 1
return "One"
when 2
return "Two"
when 3
return "Three"
when 4
return "Four"
when 5
return "Five"
when 6
return "Six"
when 7
return "Seven"
when 8
return "Eight"
when 9
return "Nine"
end
end
def switch_it_up(number)
numbers = %w(zero one two three four five six seven eight nine ten)
return "#{numbers[number]}".capitalize
end
puts switch_it_up(9)
| true |
4d84dab90fc7704452575dba81cf26fcc68516ab | Ruby | vishalsanfran/ruby-algo | /graph/prim_maze_gen.rb | UTF-8 | 2,001 | 3.515625 | 4 | [] | no_license | class Maze
def initialize(rows, cols, wall="|", path="-")
@brd = Array.new(rows){Array.new(cols){wall}}
@path = path
end
def get_moves(row, col)
r_offs = [-1, 1, 0, 0]
c_offs = [0, 0, 1, -1]
moves = r_offs.each_with_index.map{|off, idx| [off + row, c_offs[idx] + col]}
moves.select{|move| is_valid(move[0], move[1])}
end
def get_valid_moves(row, col)
moves = get_moves(row, col)
moves.select{|move| @brd[move[0]][move[1]] != @path}
end
def is_valid(row, col)
row >= 0 && row < @brd.length && col >= 0 && col < @brd[0].length
end
def get_starting_pos
prng = Random.new
is_row = prng.rand(2) == 1? true : false
st_row = is_row ? prng.rand(@brd.length) : 0
st_col = is_row ? 0: prng.rand(@brd[0].length)
[st_row, st_col]
end
def no_self_loop(row, col)
all_moves = get_moves(row, col)
tmp = all_moves.select{|move| @brd[move[0]][move[1]] == @path}
all_moves.select{|move| @brd[move[0]][move[1]] == @path}.length <= 1
end
def set_prim_maze(rand_start=false)
move = rand_start ? get_starting_pos() : [0, 0]
@brd[move[0]][move[1]] = @path
#puts "pos #{move}"
moves = get_valid_moves(move[0], move[1])
while moves.length > 0
move = pop_random(moves)
if no_self_loop(move[0], move[1])
@brd[move[0]][move[1]] = @path
moves += get_valid_moves(move[0], move[1])
end
end
show
end
def show
@brd.each do |row|
puts row.join
end
print "\n"
end
def pop_random(list)
prng = Random.new
list.delete_at(prng.rand(list.length))
end
end
def get_maze_rows_cols(deflt_rows=15, deflt_cols=20)
begin
rows = ARGV.length >= 1 ? ARGV[0].to_i : deflt_rows
cols = ARGV.length >= 2 ? ARGV[1].to_i : deflt_cols
rescue
rows = deflt_rows
cols = deflt_cols
end
puts "Presenting a #{rows} x #{cols} maze:"
[rows, cols]
end
row_col = get_maze_rows_cols
maze = Maze.new(row_col[0], row_col[1])
maze.set_prim_maze
| true |
044dafb2484f543c628765bff157c74862731133 | Ruby | SergioETrillo/code_wars | /Ruby/5kyu/firstnprimes.rb | UTF-8 | 198 | 3.640625 | 4 | [] | no_license | # TODO implement a Primes class with a class method first(n)
# that returns an array of the first n prime numbers.
require 'prime'
class Primes
def first(n)
Prime.first n
end
end | true |
4d43720972a564cf704df984a1126ab3d87deca9 | Ruby | Andreas-AS/W2D2 | /pieces/king.rb | UTF-8 | 192 | 2.578125 | 3 | [] | no_license | class King < Piece
include Steppable
KING_DIFS = [[0,1], [0,-1], [1, 1], [1,-1], [1,0], [-1, 0], [-1, 1], [-1,-1]]
def moves
unblocked_moves(pos, KING_DIFS)
end
end | true |
28b0f024d94a7c63808413ae2a861e1935365c98 | Ruby | arifikhsan/hello-ruby | /loop/range.rb | UTF-8 | 397 | 3.34375 | 3 | [] | no_license | (1..3).each do
puts 'range each 1 to 3'
end
(1..3).each do |i|
puts "range each, index: #{i}"
end
(1..3).map do
puts 'range map 1 to 3'
end
(1..3).map do |i|
puts "range map, index: #{i}"
end
(1..3).each { puts 'range each oneline' }
(1..3).each { |i| puts "range each oneline, i: #{i}" }
(1..3).map { puts 'range map oneline' }
(1..3).map { |i| puts "range map oneline, i: #{i}" }
| true |
d6e200c46149d25347ae242e2f396416775450cc | Ruby | jessicajyeh/sp18-hw2 | /app/controllers/concerns/person.rb | UTF-8 | 353 | 3.734375 | 4 | [] | no_license | class Person
attr_accessor :name, :age, :nickname
def initialize(name, age)
@name = name
@age = age
@nickname = name[0,4]
end
def nickname
@nickname
end
def birth_year
year = (Time.now.year).to_i
@age = (age).to_i
year - @age - 1
end
def introduction
"I'm #{name} and I'm #{age} years old"
end
end
| true |
b8656681ba25fecb3a6b5317597243ebfee13240 | Ruby | educabilia/ohm-identity_map | /test/identity_map_test.rb | UTF-8 | 2,048 | 2.75 | 3 | [
"Unlicense"
] | permissive | require_relative "prelude"
class Post < Ohm::Model
attribute :title
end
class Comment < Ohm::Model
attribute :body
reference :post, :Post
end
scope do
setup do
post = Post.create(title: "How to create an Identity Map in Ruby")
Comment.create(post_id: post.id, body: "Great article!")
Comment.create(post_id: post.id, body: "Not so great...")
end
test "Model#[] - identity map disabled" do
assert Comment[1].object_id != Comment[1].object_id
end
test "Model#[] - identity map enabled" do
comments = Ohm::Model.identity_map do
[Comment[1], Comment[1]]
end
assert_equal 1, comments.map(&:object_id).uniq.size
assert Comment[1].object_id != Comment[1].object_id
end
test "Model#fetch - identity map disabled" do
comments = Comment.fetch([1, 2])
assert_equal 2, comments.map(&:object_id).uniq.size
end
test "Model#fetch - identity map enabled" do
comments = Ohm::Model.identity_map { Comment.fetch([1]) + Comment.fetch([1]) }
assert_equal 1, comments.map(&:object_id).uniq.size
comments = Ohm::Model.identity_map { Comment.fetch([1]) + Comment.fetch([2]) }
assert_equal 2, comments.map(&:object_id).uniq.size
comments = Ohm::Model.identity_map { Comment.fetch([1]) + Comment.fetch([1, 2]) }
assert_equal 2, comments.map(&:object_id).uniq.size
end
test "Model#reference - identity map disabled" do
assert Comment[1].post.object_id != Comment[2].post.object_id
end
test "Model#reference - identity map enabled" do
posts = Ohm::Model.identity_map { [Comment[1].post, Comment[2].post] }
assert_equal 1, posts.map(&:object_id).uniq.size
orphan = Comment.create(body: "No post.")
assert_equal nil, orphan.post
end
test "does not confuse models" do
models = Ohm::Model.identity_map { [Comment[1], Post[1]] }
assert_equal 2, models.map(&:object_id).uniq.size
models = Ohm::Model.identity_map { Comment.fetch([1]) + Post.fetch([1]) }
assert_equal 2, models.map(&:object_id).uniq.size
end
end
| true |
334ddb20966e353e99536cab4b5ceebca2a27477 | Ruby | dylankb/sprinter | /main.rb | UTF-8 | 5,081 | 2.625 | 3 | [] | no_license | require 'rubygems'
require 'sinatra'
require 'sinatra/reloader' if development?
require "tilt/erubis"
require 'date'
require 'csv'
use Rack::Session::Cookie, :key => 'rack.session',
:path => '/',
:secret => 'barmaged0n'
SPRINT_DAYS = 14.0
MINUTES_IN_HOUR = 60
helpers do
def format_time_in_hours(time)
time.to_f % 1 == 0 ? time.to_i / 60 : time.to_f / 60
end
def round_all_fractions_up(days)
days.to_f % 1 == 0 ? days.to_i : days.to_i + 1
end
def calculate_total_time(projects)
total_time = 0
projects.each do |key,value|
total_time += value['time']
end
total_time
end
end
configure do
set :erb, :escape_html => true
end
get '/' do
if session[:username]
redirect '/project_entry'
else
redirect '/new_user'
end
end
get '/new_user' do
erb :get_name
end
post '/new_user' do
session[:projects] = nil
session[:time_available] = nil
session[:show_results_button] = false
if params[:username].empty?
@error = "Please enter your name."
halt erb(:get_name)
else
session[:username] = params[:username]
redirect '/project_entry'
end
end
get '/project_entry' do
erb :project_entry
end
post '/add_project' do
if params[:project_name].empty?
@error= 'Please add a name for your project.'
halt erb(:project_entry)
end
if !(/^[0-9]*\.?[0-9]+/ =~ params[:project_minutes])
@error= 'Please enter a valid number for your estimated project time.'
halt erb(:project_entry)
end
project = {
params[:project_name] => {
'time'=>params[:project_minutes].to_f,
'days'=> 0 }
}
project[params[:project_name]]['time'] *= MINUTES_IN_HOUR
if session[:projects]
session[:projects].merge!(project)
else
session[:projects] = project
end
session[:show_availability_button] = true
redirect '/project_list'
end
get '/project_list' do
erb :project_list
end
get '/availability' do
erb :get_availability
end
post '/availability' do
time_in_minutes = params[:time_available].to_f * MINUTES_IN_HOUR * SPRINT_DAYS
if time_in_minutes < calculate_total_time(session[:projects])
@error = "Hmm, if you only spend #{params[:time_available]} hours a day it doesn't look like you'll be able to finish all your tasks by the end of the two weeks. Try entering a higher number."
halt erb(:get_availability)
end
session[:hours_available] = params[:time_available]
session[:time_available] = time_in_minutes
session[:show_results_button] = true
session[:show_availability_button] = false
redirect '/project_list'
end
post '/calculate_sprint' do
daily_projects_times = []
days_to_complete_projects = 0
projects_updated = session[:projects].dup
projects_iterator = session[:projects].dup
session[:projects].each do |_, info|
daily_projects_times << info['time']
end
uniq_project_times = daily_projects_times.uniq.size
uniq_project_times.times do
num_of_projects = projects_iterator.size
current_daily_project_time = (session[:time_available] / SPRINT_DAYS) / num_of_projects
smallest_project = projects_iterator.group_by { |_, info| info['time'] }.min.last.to_h
days_to_complete_smallest_project = smallest_project.first[1]['time'] / current_daily_project_time
days_to_complete_projects += days_to_complete_smallest_project
projects_iterator.each do |name, info|
projects_updated[name] = projects_updated[name].dup
projects_updated[name]['days'] += days_to_complete_smallest_project
end
smallest_project.size.times do |i|
projects_iterator.delete(smallest_project.keys[i])
end
projects_iterator.each do |name, info|
info['time'] = info['time'] - current_daily_project_time * days_to_complete_smallest_project
end
end
session[:days_to_complete_projects] = round_all_fractions_up(days_to_complete_projects)
session[:projects_updated] = projects_updated
session[:today] = Time.new.to_date
redirect '/project_list_results'
end
get '/project_list_results' do
erb :project_list_results
end
post '/export_tasks' do
projects_exporter = session[:projects_updated].dup
projects_exporter.each do |key, value|
projects_exporter[key] = projects_exporter[key].dup
projects_exporter[key]['today'] = session[:today]
projects_exporter[key]['time'] = "Time: #{value['time']} minutes"
projects_exporter[key]['days'] = (session[:today] + value['days']).to_s
end
convert = []
count = 0
projects_exporter.each do |key,value|
convert << [key]
int_count = 0
value.each do |k, v|
convert[count] << v
int_count += 1
if int_count == value.size
count += 1
end
end
end
session[:csv_export] = convert
redirect '/download'
end
get '/download' do
content_type 'application/csv'
attachment "#{session[:username]}'s tasks.csv"
result = CSV.generate do |csv|
csv << ['Subject','Description','End Date','Start Date']
session[:csv_export].each do |p|
csv << p
end
end
end | true |
4292ecb94e50c4c92684249a9fdd7c179eac1e8f | Ruby | everypolitician-scrapers/mongolia-khurai-wp-multiple-terms | /lib/term_page.rb | UTF-8 | 737 | 2.625 | 3 | [] | no_license | require_relative 'constituency_member_table'
require_relative 'party_list_member_table'
require 'scraped'
class TermPage < Scraped::HTML
field :members do
constituency_members + party_list_members
end
field :constituency_members do
ConstituencyMemberTable.new(noko: constituency_member_table, response: response).members
end
field :party_list_members do
PartyListMemberTable.new(noko: party_list_member_table, response: response).members
end
private
def constituency_member_table
noko.xpath('.//h2/span[text()[contains(.,"Constituency")]]/following::table[1]')
end
def party_list_member_table
noko.xpath('//h2[span[@id="Party_list"]]/following-sibling::table[@class="wikitable"]')
end
end
| true |
ba361e071c5125fc94cdcdb95f0c559f3c3196a9 | Ruby | susiirwin/acquire_a_hire | /app/models/conversation.rb | UTF-8 | 370 | 2.71875 | 3 | [] | no_license | class Conversation
def initialize(raw_conversation, user_id)
@job_id = raw_conversation[0]
@sender_id = raw_conversation[1]
@recipient_id = raw_conversation[2]
@user_id = user_id
end
def job
Job.find(@job_id)
end
def with
if @user_id == @sender_id
User.find(@recipient_id)
else
User.find(@sender_id)
end
end
end
| true |
1fb55d80b6f7cf0930b1578be1646817fc33dd82 | Ruby | elyrly/pickpocket | /config/config.rb | UTF-8 | 364 | 2.96875 | 3 | [] | no_license | class Config
def initialize(file_path)
@file_path = file_path
@config = JSON.parse(File.read(file_path))
end
def [](key)
@config[key.downcase]
end
def []=(key, value)
@config[key.downcase] = value
save
value
end
protected
def save
File.open(@file_path, 'w') do |f|
f.write(@config.to_json)
end
end
end
| true |
f93678da28d67509dfb1494e53582c2071b618ff | Ruby | zeitschlag/adventofcode | /2019/01/first_day.rb | UTF-8 | 526 | 3.734375 | 4 | [] | no_license | def calculate_fuel(module_mass)
module_fuel = (module_mass.to_f/3).floor - 2
return module_fuel
end
def calculate_total_fuel(mass)
fuel = calculate_fuel(mass)
additional_fuel = calculate_fuel(fuel)
while additional_fuel >= 0 do
fuel += additional_fuel
additional_fuel = calculate_fuel(additional_fuel)
end
return fuel
end
required_fuel = 0
File.open("input.txt", "r") do |file|
file.each_line do |module_mass|
required_fuel += calculate_total_fuel(module_mass)
end
end
puts required_fuel
| true |
2659c1787bd5c8a5b836d6124e92850fd1dd9a29 | Ruby | jnn-natsumi/Ruby | /problem/d11-30.rb | UTF-8 | 120 | 3.390625 | 3 | [] | no_license | # D013:割り算
x, y = gets.split(" ").map!{|i| i.to_i}
ans1 = x / y
ans2 = x % y
print ans1
print " "
print ans2
| true |
557e1e20a1349156d6113b3300db07e92ed652a7 | Ruby | sotayamashita/cal_exporter | /lib/cal_exporter/exporter.rb | UTF-8 | 1,104 | 2.640625 | 3 | [
"MIT"
] | permissive | require "yaml"
module CalExporter
class Exporter
def initialize(format, save_location)
@format = format
@save_location = save_location
end
def to_jekyll(event)
output_list = {
"title" => event.summary.gsub(/[|]|:/, '[' => '(', ']' => ')', ':' => ':'),
"location" => event.location.chomp,
"date" => event.dtstart.strftime('%Y-%m-%d'),
"friendly_date" => event.dtstart.strftime('%A %d %b %Y'),
"link" => url_list(event.description)[0],
"layout" => "post",
"categories" => "meetups"
}
output_list.to_yaml + "---\n#{event.description}"
end
def save_as_jekyll(event)
file_name = "#{@save_location}/#{event.dtstart.strftime('%Y-%m-%d')}-#{event.uid[0, 7]}.md"
Dir.mkdir(@save_location) unless Dir.exist?(@save_location)
f = File.open("#{file_name}", "w")
f.write(to_jekyll(event))
f.close
file_name
end
def url_list(description)
URI.extract(description, %w[http https])
end
end
end | true |
c1eee0367fa175b9e1d75c1d5b3d6d4b10e578c0 | Ruby | ro31337/math-apps | /app-addition.rb | UTF-8 | 3,103 | 3.75 | 4 | [] | no_license | class Addition
INFINITY = 1.to_f / 0
attr_reader :a, :b
def initialize
@a = @b = INFINITY
end
def regenerate
loop do
@a = rand(0..10)
@b = rand(0..10)
break if @a + @b <= 10
end
end
end
class Subtraction
attr_reader :a, :b
def regenerate
loop do
@a = rand(0..10)
@b = rand(0..10)
next if @a - @b > 10 || @a - @b < 0
break
end
end
end
class AsString
def initialize(origin:)
@origin = origin
end
def print
10.times do
@origin.regenerate
a = @origin.a
b = @origin.b
puts "#{a} + #{b} = "
puts
puts "#{spaced('.' * a)} + #{spaced('.' * b)} ="
puts
puts
end
end
private
def spaced(s)
s.scan(/.{1,5}/).join(' ')
end
end
class AsHtml
def initialize(origin:)
@origin = origin
end
def head
puts <<~HTML
<html>
<head>
<style>
body { font-family: Arial }
.exercise { border-bottom: 1px dotted #000; padding: 9px 0 }
.exercise:last-child { border-bottom: none }
.example { font-size: 30px }
.hint { font-size: 40px; display: flex; flex-direction: row; line-height: 14px; margin-top: 8px }
.hint > div { margin-right: 10px }
.hint .plus { color: #888; font-size: 20px }
.hint .x { font-size: 17px; }
</style>
</head>
<body>
<div class="exercise" style="border-bottom: 3px solid #000">
<div class="example">1 2 3 4 5 6 7 8 9 10</div>
<div class="hint">
<div>
#{spaced('•' * 1)}
</div>
<div>
#{spaced('•' * 2)}
</div>
<div>
#{spaced('•' * 3)}
</div>
<div>
#{spaced('•' * 4)}
</div>
<div>
#{spaced('•' * 5)}
</div>
<div>
#{spaced('•' * 6)}
</div>
<div>
#{spaced('•' * 7)}
</div>
<div>
#{spaced('•' * 8)}
</div>
<div>
#{spaced('•' * 9)}
</div>
<div>
#{spaced('•' * 10)}
</div>
</div>
</div>
HTML
end
def print_with_head(...)
head
print(...)
end
def print
10.times do
@origin.regenerate
a = @origin.a
b = @origin.b
yield(a, b)
end
end
end
def spaced(s)
s.scan(/.{1,5}/).join('<br />')
end
AsHtml.new(origin: Addition.new).print_with_head do |a, b|
puts <<~HTML
<div class="exercise">
<div class="example">#{a} + #{b} =</div>
<div class="hint">
<div>
#{spaced('•' * a)}
</div>
<div class="plus">+</div>
<div>
#{spaced('•' * b)}
</div>
</div>
</div>
HTML
end
| true |
9adb5a6a6aa2b7b03e78ec30a4c9d7e9dc5b9afd | Ruby | gisikw/wemote | /lib/wemote/switch.rb | UTF-8 | 4,376 | 3.234375 | 3 | [
"MIT"
] | permissive | require 'socket'
require 'ipaddr'
require 'timeout'
require 'ssdp'
module Wemote
# This class encapsulates an individual Wemo Switch. It provides methods for
# getting and setting the switch's state, as well as a {#toggle!} method for
# convenience. Finally, it provides the {#poll} method, which accepts a block
# to be executed any time the switch changes state.
class Switch
GET_HEADERS = {
"SOAPACTION" => '"urn:Belkin:service:basicevent:1#GetBinaryState"',
"Content-type" => 'text/xml; charset="utf-8"'
}
SET_HEADERS = {
"SOAPACTION" => '"urn:Belkin:service:basicevent:1#SetBinaryState"',
"Content-type" => 'text/xml; charset="utf-8"'
}
class << self
def device_type
'urn:Belkin:device:controllee:1'
end
# Returns all Switches detected on the local network
#
# @param [Boolean] refresh Refresh and redetect Switches
# @return [Array] all Switches on the network
def all(refresh=false)
@switches = nil if refresh
@switches ||= Wemote::Collection::Switch.new(discover)
end
# Returns a Switch of a given name
#
# @param name [String] the friendly name of the Switch
# @return [Wemote::Switch] a Switch object
def find(name)
all.detect{|s|s.name == name}
end
protected
def discover
finder = SSDP::Consumer.new timeout: 3, first_only: false
finder.search(service: self.device_type).map do |device|
self.new(device[:address], device[:params]['LOCATION'].match(/:([0-9]{1,5})\//)[1])
end
end
end
attr_accessor :name
def initialize(host,port=nil)
@host, @port = host, port
set_meta
end
def device_type
'urn:Belkin:device:controllee:1'
end
# Turn the Switch on or off, based on its current state
def toggle!
on? ? off! : on!
end
# Turn the Switch off
def off!
set_state(0)
end
# Turn the Switch on
def on!
set_state(1)
end
# Return whether the Switch is off
#
# @return [Boolean]
def off?
get_state == :off
end
# Return whether the Switch is on
#
# @return [Boolean]
def on?
get_state == :on
end
# Monitors the state of the Switch via polling, and yields to the block
# given with the updated state.
#
# @example Output when a Switch changes state
# light.poll do |state|
# if state == :on
# puts "The switch turned on"
# else
# puts "The switch turned off"
# end
# end
#
# @param rate [Float] The rate in seconds at which to poll the switch
# @param async [Boolean] Whether or not to poll the switch in a separate thread
#
# @return [Thread] if the method call was asynchronous
def poll(rate=0.25,async=true,&block)
old_state = get_state
poller = Thread.start do
loop do
begin
state = get_state
if state != old_state
old_state = state
yield state
end
rescue Exception
end
sleep rate
end
end
puts "Monitoring #{@name} for changes"
async ? poller : poller.join
end
protected
def get_state
self.get_binary_state() == '1' ? :on : :off
end
def get_binary_state
response = begin
client.post("http://#{@host}:#{@port}/upnp/control/basicevent1",Wemote::XML.get_binary_state,GET_HEADERS)
rescue Exception
client.post("http://#{@host}:#{@port}/upnp/control/basicevent1",Wemote::XML.get_binary_state,GET_HEADERS)
end
response.body.match(/<BinaryState>(\d)<\/BinaryState>/)[1]
end
def set_state(state)
begin
client.post("http://#{@host}:#{@port}/upnp/control/basicevent1",Wemote::XML.set_binary_state(state),SET_HEADERS)
rescue Exception
client.post("http://#{@host}:#{@port}/upnp/control/basicevent1",Wemote::XML.set_binary_state(state),SET_HEADERS)
end
end
def client
@client ||= Wemote::Client.new
end
def set_meta
response = client.get("http://#{@host}:#{@port}/setup.xml")
@name = response.body.match(/<friendlyName>([^<]+)<\/friendlyName>/)[1]
end
end
end
| true |
8007342a4b8a9ad5a36e6b0c48dc955ff5fc5884 | Ruby | jplao/module_3_diagnostic | /app/models/station.rb | UTF-8 | 479 | 3 | 3 | [] | no_license | class Station
attr_reader :name,
:address,
:access_times,
:distance
def initialize(data)
@name = data['station_name']
@address = data['street_address']
@distance = data['distance']
@fuel_types = data['fuel_type_code']
@access_times = data['access_days_time']
end
def fuel_types
@fuel_types.map do |fuel|
if 'ELEC'
'Electric'
elsif 'E85'
'Propane'
end
end
end
end
| true |
699e3a42f39dc000afc2d44ce6f81944e75a6bdb | Ruby | CristianCvc/arraysg49 | /filtro_procesos.rb | UTF-8 | 445 | 3.109375 | 3 | [] | no_license | num_mayor = ARGV[0].to_i
def read_file(filename)
original_data = open(filename).readlines
lines = original_data.count
array =[]
lines.times do |i|
array<<original_data[i].to_i
end
return array
end
datos = read_file("procesos.data")
filtrado = datos.select { |data| data > num_mayor}
output_file = File.open("procesos_filtrados.data", "w")
filtrado.each { |line| output_file.puts("#{line}\n") }
output_file.close
| true |
5b3d0f34927f4b0a37037b49703bdc319d7f8a91 | Ruby | JasonGL123/my-dcoder-solutions | /Easy/tracys_love.rb | UTF-8 | 97 | 3.03125 | 3 | [] | no_license | puts (n = gets.chomp.split().map(&:to_i)).inject(:+) == 6 || n.max - n.min == 6 ? "Love" : "Hate" | true |
908dbd7422dbb9df1fa20a9c10384cad6f780e0f | Ruby | krismacfarlane/godot | /w09/d05/instructor/pig_latin/lib/word.rb | UTF-8 | 88 | 2.6875 | 3 | [] | no_license | class Word
def initialize(original_word)
@original_word = original_word
end
end
| true |
55d5021c37ad95a75b7938f24e844fcb275cc446 | Ruby | Yates101/design_strategies_1 | /spec/remembering_names_spec.rb | UTF-8 | 172 | 2.734375 | 3 | [] | no_license | require "remembering_names.rb"
describe "the add_name method" do
it "appeases our terrible memory" do
expect(add_name("Alice")).to eq "Person remembered!"
end
end
| true |
6da7055504bb46bdb4c895a363f623301d575037 | Ruby | Josh-Gotro/ruby-enumerables-generalized-map-and-reduce-lab-austin-web-030920 | /lib/my_code.rb | UTF-8 | 1,367 | 3.359375 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry' #binding.pry
def map(source_array)
i = 0
new = []
while i < source_array.length
new << yield(source_array[i])
i += 1
end
new
end
def reduce(array, sv=nil)
if sv
sum = sv
i = 0
else
sum = array[0]
i = 1
end
while i < array.length
sum = yield(sum, array[i])
i += 1
end
sum
end
# def map(array)
# i = 0
# new = []
# while i < array.length
# new << yield(array[i])
# i += 1
# end
# new
# end
# def reduce(array, sv=nil)
# i = 0
# if sv
# ttl = sv
# i = 0
# else
# ttl = array[0]
# i = 1
# end
# while i < array.length
# ttl = yield(ttl, array[i])
# <<<<<<< HEAD
# i += 1
# =======
# i += 0
# >>>>>>> bf26ba5ca00392b1e42f94597ac2c4e264dd8483
# end
# ttl
# end
# <<<<<<< HEAD
# # reduce([1,2,3]1) do |x, y|
# # x + y
# # end
# =======
# >>>>>>> bf26ba5ca00392b1e42f94597ac2c4e264dd8483
# def map(array)
# result = []
# i = 0
# while i < array.length
# result << yield(array[i])
# i += 1
# end
# result
# end
# def reduce(array, sv=nil)
# if sv
# sum = sv
# i = 0
# else
# sum = array[0]
# i = 1
# end
# while i < array.length
# sum = yield(sum, array[i])
# i += 1
# end
# sum
# end
| true |
b4790bc5388357c0a765ff67f549ee22ce471c79 | Ruby | markmcspadden/ruby-in-a-can | /compare.rb | UTF-8 | 3,455 | 3.140625 | 3 | [] | no_license | # We can now track the ruby as it gets fed into the compiler
SCRIPT_LINES__ = {}
# Setup file_path variable
file_path = nil
# Default to only one benchmark
n = 1
# Requried: a file path at the end of the ARGVs
# Optional: -n : number of benchmarks to us
ARGV.each_with_index do |a, idx|
if a.to_s == "-n"
n = ARGV[idx+1].to_i
end
if idx == ARGV.size-1
file_path = a
end
end
throw "A file path pointing to a .rb file is required" if file_path.nil?
# Bring in our solutions
require file_path
# And our benchmark tool
require 'benchmark'
# Some math methods
# TODO: I know there's a library for these...
def mean(ary)
ary.inject(0) { |sum, i| sum += i }/ary.length.to_f
end
def std_dev(ary, mean)
Math.sqrt( (ary.inject(0) { |dev, i|
dev += (i - mean) ** 2}/ary.length.to_f) )
end
# Get our solutions
available_solutions = Solutions.singleton_methods.sort!
# Initialize a hash to hold the results
# { :john => [], :mark => [] }
all_times = available_solutions.inject({}){ |h,k| h.merge({k.to_sym => {:all => []}})}
# Do x number of benchmarks
# We randomize the order as we go
n.times do
solutions = available_solutions.sort_by{ rand }
bench = Benchmark.bmbm(10) do |x|
solutions.each do |solution|
x.report("#{solution}") { Solutions.send("#{solution}") }
end
end
# Add the times into all_times
bench.each_with_index do |b, idx|
all_times[solutions[idx].to_sym][:all] << b.format("%r").gsub(/(\(|\))/, "").to_f
end
end
all_times.each_pair do |k,v|
avg = mean(v[:all])
sd = std_dev(v[:all], avg)
all_times[k][:avg] = avg
all_times[k][:std_dev] = sd
end
# Start putting together results
# Includes:
# * Output from each solution
# * Best Average
# * All Averages
# * Performance difference between Best and Worst method
# * Most Stable (based on Std Dev)
# * All Std Devs
results = ""
results << "Results \r\n"
available_solutions.each do |solution|
results << "#{solution}: #{Solutions.send(solution)}\r\n"
end
results << "-------\r\n"
results << "Benchmarks: #{n}"
results << "\r\n-------\r\n"
best_avg = all_times.to_a.sort_by{ |a| a.last[:avg] }
best_sd = all_times.to_a.sort_by{ |a| a.last[:std_dev] }
results << "Best Average: #{best_avg.first.first} (#{best_avg.first.last[:avg]})"
results << "\r\n-------\r\n"
results << "All Averages\r\n"
best_avg.each { |a| results << "#{a.first}: #{a.last[:avg]}\r\n" }
diff = best_avg.last.last[:avg]/best_avg.first.last[:avg]
results << "-------\r\n"
results << "Difference Between Best Method and Worst Method (based on average time): A factor of #{format("%f", diff)}. (Meaning the best method is about #{diff.round}x better than the worst)"
results << "\r\n-------\r\n"
results << "Most Consistent (based on Std Dev): #{best_sd.first.first} (#{format("%f", best_avg.first.last[:std_dev])})"
results << "\r\n"
results << "All Standard Deviations\r\n"
best_sd.each { |a| results << "#{a.first}: #{format("%f", a.last[:std_dev])}\r\n" }
# Output results to file
file_name = file_path.to_s.split("/").last
file_dirs = file_path.to_s.split("/") - [file_name]
File.open(file_dirs.join("/") + "/results.txt", "w+") do |file|
file.puts results
end
# Outputs results to console
# Also output the whole solutions.rb file to console
puts "=" * 100
puts "\r\n"
SCRIPT_LINES__["./" + file_path].each do |line|
puts "#{line}"
end
puts "\r\n"
results.split("\r\n").each { |r| puts r }
| true |
253fb22fdd00bdf0563e37aab72a332f17b9d539 | Ruby | Lorjuo/tgt | /lib/tasks/importer/messages_importer.rb | UTF-8 | 1,769 | 2.859375 | 3 | [] | no_license | # rails c
# Message.all.each{|message| message.destroy}
# TODO: import creation date
module MessagesImporter
# see for caching: http://stackoverflow.com/questions/6934415/prevent-rails-from-caching-results-of-activerecord-query
# import messages
def import_messages
puts "Importing messages..."
use_old_database
messages = ActiveRecord::Base.connection.execute('
SELECT message.id, message.title, message.content, message.date, department.name AS department FROM message LEFT JOIN department ON message.department = department.id
')
use_new_database
import_counter = 0
for i in 0...messages.count do
row = messages.get_row i
# puts "-import \"#{row.get("title")}\""
# Check if message exists already
message = Message.where(name: row.get("title"), content: row.get("content"))
# Reload message / Avoid caching problems
message.reload
if message.empty?
department = Department.where(name: row.get("department")).first
department_id = department.present? ? department.id : Department.where(:name => "generic").first.id
message = Message.new(name: row.get("title"),
content: row.get("content"),
department_id: department_id,
custom_date: row.get("date"),
created_at: row.get("date"),
updated_at: row.get("date"),
published: true)
begin
message.save!
rescue Exception => e
puts "Failed to save \"#{row.get("title")}\": #{e.message}"
else
import_counter+=1
end
end
end
puts "... imported #{import_counter} messages"
end
end | true |
30eed9000d209ea26e48097f576722953b764f82 | Ruby | JaniceYR/002_aA | /W2D3/poker/spec/hand_spec.rb | UTF-8 | 1,125 | 3.46875 | 3 | [] | no_license | require 'rspec'
require 'hand'
require 'deck'
describe Hand do
let(:four_of_a_kind) { [Card.new(1, "S"), Card.new(1, "C"), Card.new(1, "H"),
Card.new(1, "D"), Card.new(5, "S")]}
subject(:hand) { Hand.new(four_of_a_kind) }
describe "#initialize" do
it 'creates a card instance variable of length 5' do
expect(hand.cards.length).to eq(5)
end
it 'gets five Card object' do
expect(hand.cards.all? {|card| card.is_a? Card }).to be true
end
end
describe "#score" do
it 'returns an array of rank and value of rank' do
expect(hand.score.is_a?(Array)).to be true
end
it 'returns an array of Integers' do
expect(hand.score.all? {|ele| ele.is_a?(Fixnum)}).to be true
end
describe "#find_rank" do
it 'returns 0 when hand gets five of a kind'
it 'returns 3 when hand is a full house'
it 'returns 8 when hand is one pair'
end
describe "#find_value_of_rank" do
it 'returns 13 when rank is from the king'
it 'returns the card from the combination even if there is a larger value'
end
end
end
| true |
a0725340dc3551410dbe07c1596844345dcdd2c8 | Ruby | adelapie/cryptopals | /05/36.rb | UTF-8 | 3,486 | 2.640625 | 3 | [
"Unlicense"
] | permissive | require_relative '../util'
ROLE = ENV['ROLE'] || 'C'
C = '/tmp/cryptopals-36-C'.freeze
S = '/tmp/cryptopals-36-S'.freeze
NIST_PRIME = 0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff
assert(%w(C S).include?(ROLE))
ensure_pipe(C)
ensure_pipe(S)
# the protocol description looks incomplete/wrong, the great benefit
# of SRP is that you don't send a password or hashed equivalent at any
# time, however the first step is about agreeing on N, g, k, I and P
# and the second one requires the server knowing that password
# judging from wikipedia it should instead look like this (with |
# denoting concatenation):
# prelude:
#
# C & S
# Agree on N=[NIST Prime], g=2, k=3
# signup:
#
# C
# Choose I (email) and P (password)
# C
# Generate salt as random integer
# Generate string xH=SHA256(salt|password)
# Convert xH to integer x somehow (put 0x on hexdigest)
# Generate v=g**x % N
# C->S
# Send I, salt, v
# S
# Save salt and v indexed by I
# login (unchanged):
#
# C->S
# Send I, A=g**a % N (a la Diffie Hellman)
# S->C
# Send salt, B=kv + g**b % N
# S, C
# Compute string uH = SHA256(A|B), u = integer of uH
# C
# Generate string xH=SHA256(salt|password)
# Convert xH to integer x somehow (put 0x on hexdigest)
# Generate S = (B - k * g**x)**(a + u * x) % N
# Generate K = SHA256(S)
# S
# Generate S = (A * v**u) ** b % N
# Generate K = SHA256(S)
# C->S
# Send HMAC-SHA256(K, salt)
# S->C
# Send "OK" if HMAC-SHA256(K, salt) validates
assert(sha256_hmac([], []) ==
'b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad')
N = NIST_PRIME
def signup_client(email, password)
g = 2
salt = rand(1..1024)
x = sha256_hexdigest("#{salt}#{password}".bytes).to_i(16)
v = modexp(g, x, N)
snd(S, "#{email} #{salt} #{v}")
info("signed up with #{email}")
end
def signup_server
_I, salt, v = rcv(S).split(' ')
salt = salt.to_i
v = v.to_i
info("signup from #{_I}")
[_I, salt, v]
end
def login_client(email, password)
g = 2
k = 3
a = rand(1..1024)
_A = modexp(g, a, N)
snd(S, "#{email} #{_A}")
salt, _B = rcv(C).split(' ')
_B = _B.to_i
u = sha256_hexdigest("#{_A}#{_B}".bytes).to_i(16)
x = sha256_hexdigest("#{salt}#{password}".bytes).to_i(16)
_S = modexp(_B - k * modexp(g, x, N), a + u * x, N)
_K = sha256_hexdigest(_S.to_s.bytes)
snd(S, sha256_hmac(_K.bytes, salt.to_s.bytes))
assert(rcv(C) == 'OK')
end
def login_server(credentials)
g = 2
k = 3
_I, _A = rcv(S).split(' ')
_A = _A.to_i
salt, v = credentials[_I]
b = rand(1..1024)
_B = (k * v + modexp(g, b, N)) % N
snd(C, "#{salt} #{_B}")
u = sha256_hexdigest("#{_A}#{_B}".bytes).to_i(16)
_S = modexp(_A * modexp(v, u, N), b, N)
_K = sha256_hexdigest(_S.to_s.bytes)
hmac = rcv(S)
ok = sha256_hmac(_K.bytes, salt.to_s.bytes) == hmac
snd(C, ok ? 'OK' : 'FAIL')
end
if ROLE == 'C'
email = "#{random_word}@example.com"
password = random_word
signup_client(email, password)
login_client(email, password)
else
credentials = {}
_I, salt, v = signup_server
credentials[_I] = [salt, v]
login_server(credentials)
end
info('login successful!')
| true |
59bfdcad38434365442b741f4c29353c8b1fac96 | Ruby | liftiuminc/dashboard | /test/unit/event_recorder_test.rb | UTF-8 | 6,336 | 2.625 | 3 | [] | no_license | require 'test_helper'
class EventRecorderTest < ActiveSupport::TestCase
context "class methods" do
setup do
@event_array = ['Ad Delivered', 'AdBrite', 'US']
now = Time.parse("2009/12/01 20:30")
Time.stubs(:now).returns(now)
end
context "#serialize_key" do
should "build the key based off of the elements provided and html escape the name" do
assert_match "Ad%20Delivered:AdBrite:US", EventRecorder.serialize_key(@event_array)
end
should "append YYYYMMDD_HH by default or if 'hour' is specified in the rotation" do
assert_equal "Ad%20Delivered:AdBrite:US:20091201_20", EventRecorder.serialize_key(@event_array)
assert_equal "Ad%20Delivered:AdBrite:US:20091201_20", EventRecorder.serialize_key(@event_array, "hour")
end
should "append YYYYMMDD_HHMM if 'minute' is specified in the rotation" do
assert_equal "Ad%20Delivered:AdBrite:US:20091201_203000", EventRecorder.serialize_key(@event_array, "minute")
end
should "append YYYYMMDD if 'day' is specified in the rotation" do
assert_equal "Ad%20Delivered:AdBrite:US:20091201", EventRecorder.serialize_key(@event_array, "day")
end
should "not append a time if 'none' is specified in the rotation" do
assert_equal "Ad%20Delivered:AdBrite:US", EventRecorder.serialize_key(@event_array, "none")
end
end
context "#unserialize_key" do
should "break the key into it's interesting parts" do
results = { :events => @event_array, :time => "20091201_203000", :rotation => "minute" }
assert_equal results, EventRecorder.unserialize_key("Ad%20Delivered:AdBrite:US:20091201_203000")
end
context "get_rotation" do
should "return 'minute' when the strlen of time is 15 characters" do
results = { :events => @event_array, :time => "20091201_203000", :rotation => "minute" }
assert_equal results, EventRecorder.unserialize_key("Ad%20Delivered:AdBrite:US:20091201_203000")
end
should "return 'hour' when the strlen of time is 11 characters" do
results = { :events => @event_array, :time => "20091201_20", :rotation => "hour" }
assert_equal results, EventRecorder.unserialize_key("Ad%20Delivered:AdBrite:US:20091201_20")
end
should "return 'day' when the strlen of time is 8 characters" do
results = { :events => @event_array, :time => "20091201", :rotation => "day" }
assert_equal results, EventRecorder.unserialize_key("Ad%20Delivered:AdBrite:US:20091201")
end
end
end
context "#read" do
should "read an array of data from memcache" do
key = EventRecorder.serialize_key(@event_array)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:read).with(key, EventRecorder::MEMCACHE_READ_OPTIONS).returns(@event_array)
assert @event_array, EventRecorder.read(key)
end
end
context "#record" do
setup do
@key = EventRecorder.serialize_key(@event_array)
end
should "create the memcache key based off the given data, rotation (default 'hour') and timeout (default 86400) and increment the count" do
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:write).with(@key, 0, :expires_in => 86400).returns(true)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:increment).with(@key, 1).returns(true)
assert EventRecorder.record(@event_array)
end
should "not write the key if it already exists in memcache, just increment it" do
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:exist?).with(@key, EventRecorder::MEMCACHE_READ_OPTIONS).returns(true)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:write).never
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:increment).with(@key, 1).returns(true)
assert EventRecorder.record(@event_array)
end
should "return true on successful write, false if not" do
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:write).with(@key, 0, :expires_in => 86400).returns(false)
assert !EventRecorder.record(@event_array)
end
context "timeout" do
should "set the key lifetime to 360 when rotation = 'minute'" do
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:exist?).with(@key, EventRecorder::MEMCACHE_READ_OPTIONS).returns(false)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:write).with(@key, 0, :expires_in => 360).returns(true)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:increment).with(@key, 1).returns(true)
assert EventRecorder.record(@event_array, "minute")
end
should "set the key lifetime to 86400 when rotation = 'hour'" do
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:exist?).with(@key, EventRecorder::MEMCACHE_READ_OPTIONS).returns(false)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:write).with(@key, 0, :expires_in => 86400).returns(true)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:increment).with(@key, 1).returns(true)
assert EventRecorder.record(@event_array, "hour")
end
should "set the key lifetime to 604800 when rotation = 'day'" do
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:exist?).with(@key, EventRecorder::MEMCACHE_READ_OPTIONS).returns(false)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:write).with(@key, 0, :expires_in => 604800).returns(true)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:increment).with(@key, 1).returns(true)
assert EventRecorder.record(@event_array, "day")
end
should "set the key lifetime to 300 when rotation is nil" do
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:exist?).with(@key, EventRecorder::MEMCACHE_READ_OPTIONS).returns(false)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:write).with(@key, 0, :expires_in => 300).returns(true)
ActiveSupport::Cache::MemCacheStore.any_instance.expects(:increment).with(@key, 1).returns(true)
assert EventRecorder.record(@event_array, nil)
end
end
end
end
end
| true |
6c72d2877e98509e235fc9d2ca84e7098d6a0aa4 | Ruby | kalebpomeroy/godtear | /dice.rb | UTF-8 | 157 | 3.265625 | 3 | [] | no_license | # This is the die roll thingy
DIE = [0, 0, 1, 1, 1, 2]
def roll dice
results = []
dice.times { results << DIE.sample }
results.inject(0, :+)
end
| true |
04d4d02b10ae81968165ebd0e961c4849ba47136 | Ruby | Overby/mastermind_redux | /guess.rb | UTF-8 | 1,205 | 3.53125 | 4 | [] | no_license | require './gameplay' #was './game'
#require './messages'
def start_guessing
puts Messages.call[:play]
loop do
input = gets.chomp.downcase
if input == 'q' || input =='quit'
puts "Thanks for playing!"
return
elsif input.chars.count < 4
puts "That is too short. Try again."
elsif input.chars.count > 4
puts "That is too long. Try again."
elsif input == "rrgb"
puts "Correct! Thanks for playing!"
puts Time.new
return
else
puts "You've taken one guess."
#How many letters are correct?
#How many letters in the right position?
position_count = 0
answer = 'rrgb'
if input.chars[0] == answer.chars[0]
position_count += 1
elsif input.chars[1] == answer.chars[1]
position_count += 1
elsif input.chars[2] == answer.chars[2]
position_count += 1
elsif input.chars[3] == answer.chars[3]
position_count += 1
end
# correct_count = 0
# input.chars.each do |letter|
# index = answer.chars.find_index(letter)
# if index
# answer.chars.delete_at(index)
# correct_count += 1
# end
end
end
| true |
46fdbc18c995a9c5f515a9496a32f4554498cc60 | Ruby | kcierzan/phase-0 | /week-6/bingo_solution.rb | UTF-8 | 6,077 | 4.40625 | 4 | [
"MIT"
] | permissive | # A Nested Array to Model a Bingo Board SOLO CHALLENGE
# I spent [2.5] hours on this challenge.
# Release 0: Pseudocode
# Outline: Create an instance of BingoBoard that
# Create a method to generate a letter ( b, i, n, g, o) and a number (1-100)
#Create a list with b, i, n, g, and o.
#Create a random number between 0 and 4 and store it.
#Create a random number between 1 and 100.
#Output a list in the format: ["bing_list[random_1]", random_2] and store it as called_number.
# Check the called column for the number called.
#Define a method where
#FOR EVERY element in the board with an index equal to random_1
#CHECK to see if that number is equal to random_2
# If the number is in the column, replace with an 'x'
#IF the number is equal to random_2, set that number equal to 'x'
# Display a column to the console
# Create a new list with the letter called in it
# For every a list within the bingo board, put the item in the list with the index equal to random_2 into the new list
# Display the board to the console (prettily)
# Add a list of the letters in BINGO to the bingo board
# Display that list to the console
# FOR every list int the bingo board, display the list on a new line
# Initial Solution
# class BingoBoard
# def initialize(board)
# @bingo_board = board
# end
# def call
# @random_column = Random.new.rand(0..4)
# random_number = Random.new.rand(1..100)
# @bingo_arry = ["B", "I", "N", "G", "O"]
# @called_number = [@bingo_arry[@random_column], random_number]
# end
# def check
# @bingo_board.each do |row|
# row.collect! { |number| (number == @called_number[1]) ? 'X' : number }
# end
# end
# def print_column
# column = [@called_number[0]]
# @bingo_board.each do |row|
# column << row[@random_column]
# end
# column.each { |number| puts number}
# end
# def display_board
# @bingo_board.insert(0, @bingo_arry)
# #p @bingo_board
# @bingo_board.each do |row|
# row << "\n"
# print row.join(" ")
# end
# end
# end
# Refactored Solution
class BingoBoard
def initialize(board)
@bingo_board = board
end
def call
@random_column = Random.new.rand(0..4)
random_number = Random.new.rand(1..100)
@bingo_arry = ["B", "I", "N", "G", "O"]
@called_number = [@bingo_arry[@random_column], random_number]
end
def check
@bingo_board.each do |row|
row.map! { |number| (number == @called_number[1]) ? 'X' : number }
end
end
def print_column
column = [@called_number[0]]
@bingo_board.each { |row| column << row[@random_column] }
end
column.each { |number| puts number}
end
def display_board
@bingo_board.insert(0, @bingo_arry)
#p @bingo_board
@bingo_board.each do |row|
row << "\n"
print row.join(" ")
end
end
end
#DRIVER CODE (I.E. METHOD CALLS) GO BELOW THIS LINE
board = [[47, 44, 71, 8, 88],
[22, 69, 75, 65, 73],
[83, 85, 97, 89, 57],
[25, 31, 96, 68, 51],
[75, 70, 54, 80, 83]]
my_game = BingoBoard.new(board)
my_game.call
my_game.check
my_game.call
my_game.check
my_game.call
my_game.check
my_game.call
my_game.check
my_game.print_column
my_game.display_board
# new_game = BingoBoard.new(board)
#Reflection
=begin
How difficult was pseudocoding this challenge? What do you think of your pseudocoding style?
Pseudocoding for this challenge was difficult as describing the nested data structures and their associated indexes was difficult without using Ruby-specific terminology. The methods-to-be were easier to describe as they were largely of the "check" or "update" variety. I think my pseudocode attempt to conceptually lay the groundwork without using too much Ruby specific words however I need to work on standardizing it and making it more readable.
What are the benefits of using a class for this challenge?
The use of a class in this challenge allows one to store a number of data structures and methods without having to constantly re-define them. For example, in the "call" method, I was able to generate two random numbers that I used to 1) randomly select a column in the board, and 2) randomly select a number between 1 and 100 that would be called. With the class, I was able to store these values and instance variables and make them available to other methods within the class.
How can you access coordinates in a nested array?
Accessing coordinates in a nested array is accomplished by referring to the index of the "row" followed by the "column". For example, assuming we are displaying these nested arrays in a grid-like format, array[0][1] refers to the first row, second column.
Give an example of a new method you learned while reviewing the Ruby docs. Based on what you see in the docs, what purpose does it serve, and how is it called?
I learned the .insert method while working on this challenge. According to the ruby docs, insert is used to insert an element into an array at a given index. In this challenge, I am using it to insert the BINGO "header" into the beingo board for display purposes. I call it on the @bingo_board instance variable and I supplied it with arguments for index and array.
How did you determine what should be an instance variable versus a local variable?
If multiple methods needed to access a variable, I would use an instance variable. For example, I set the random column variable and the bingo array to instance variables as I had to access information about the random column variable in my print column method. I also used the bingo array instance variable for both calling the numbers and for display purposes.
What do you feel is most improved in your refactored solution?
I do not believe my refactored solution differes greatly from my initial solution. I was able to shorten some iteration to one-line however I felt I struck a good balance between efficiency and readability with my initial solution that I could not improve upon it dramatically without compromising one of those aspects.
=end | true |
146e1a0e9fd6682ce32bcf3972f7a93ceb9722e0 | Ruby | tapena/w02 | /diamond_refactoring/diamond_refactoring_exercise.rb | UTF-8 | 6,585 | 4.15625 | 4 | [
"MIT"
] | permissive | # Diamond Refactoring
# Initial Solution
def diamond_printer(word)
message = word.split("")
array = []
characters_list = {
"A" => 1,
"B" => 2,
"C" => 3,
"D" => 4,
"E" => 5,
"F" => 6,
"G" => 7,
"H" => 8,
"I" => 9,
"J" => 10,
"K" => 11,
"L" => 12,
"M" => 13,
"N" => 14,
"O" => 15,
"P" => 16,
"Q" => 17,
"R" => 18,
"S" => 19,
"T" => 20,
"U" => 21,
"V" => 22,
"W" => 23,
"X" => 24,
"Y" => 25,
"Z" => 26
}
characters_list_reversed = {
"Z" => 26,
"Y" => 25,
"X" => 24,
"W" => 23,
"V" => 22,
"U" => 21,
"T" => 20,
"S" => 19,
"R" => 18,
"Q" => 17,
"P" => 16,
"O" => 15,
"N" => 14,
"M" => 13,
"L" => 12,
"K" => 11,
"J" => 10,
"I" => 9,
"H" => 8,
"G" => 7,
"F" => 6,
"E" => 5,
"D" => 4,
"C" => 3,
"B" => 2,
"A" => 1
}
message.each do |l|
upcased_l = l.upcase # Why is it important to run #upcase?
if upcased_l == " " || upcased_l == "?" || upcased_l == "." || upcased_l == "!" || upcased_l == "-" # When will this prove true? What happens if it proves true?
array << [upcased_l]
else
word_array = [] # What does this represent in the code? Is this a good name for the variable?
characters_list.each_key do |c| # What is c?
upcased_c = c.upcase
if characters_list[upcased_c] == 1
if characters_list[upcased_l].even? # What is it checking for being even? what does that do?
line = " " * (characters_list[upcased_l] * 2 - 1)
middle = line.length / 2
line[middle] = "A"
word_array << line
end
if characters_list[upcased_l].odd?
line = " " * (characters_list[upcased_l] * 2 - 1)
middle = line.length / 2
line[middle] = "A"
word_array << line
end
if characters_list[upcased_l] == 1
break # Is this necessary?
end
elsif characters_list[upcased_c] == characters_list[upcased_l]
if characters_list[upcased_l].even?
word_array << upcased_c + " " * (characters_list[upcased_c] * 2 - 3) + upcased_c
end
if characters_list[upcased_l].odd?
word_array << upcased_c + " " * (characters_list[upcased_c] * 2 - 3) + upcased_c
end
break # Is this necessary? Is it different from the other break?
else
if characters_list[upcased_l].even?
line = " " * (characters_list[upcased_l] * 2 - 1) # What is created on this line?
middle = line.length / 2
placement_1 = middle - (characters_list[upcased_c] - 1) # What are the placements?
placement_2 = middle + (characters_list[upcased_c] - 1)
line[placement_1] = upcased_c
line[placement_2] = upcased_c
word_array << line
end
if characters_list[upcased_l].odd?
line = " " * (characters_list[upcased_l] * 2 - 1)
middle = line.length / 2
placement_1 = middle - (characters_list[upcased_c] - 1)
placement_2 = middle + (characters_list[upcased_c] - 1)
line[placement_1] = upcased_c
line[placement_2] = upcased_c
word_array << line
end
end
end
if upcased_l != "A" # Is this if statement necessary
characters_list_reversed.each_key do |c|
upcased_c = c.upcase
if characters_list[upcased_c] == 1
if characters_list[upcased_l].even?
line = " " * (characters_list[upcased_l] * 2 - 1)
middle = line.length / 2
line[middle] = "A"
word_array << line
end
if characters_list[upcased_l].odd?
line = " " * (characters_list[upcased_l] * 2 - 1)
middle = line.length / 2
line[middle] = "A"
word_array << line
end
elsif characters_list[upcased_c] < characters_list[upcased_l]
if characters_list[upcased_l].even?
line = " " * (characters_list[upcased_l] * 2 - 1)
middle = line.length / 2
placement_1 = middle - (characters_list[upcased_c] - 1)
placement_2 = middle + (characters_list[upcased_c] - 1)
line[placement_1] = upcased_c
line[placement_2] = upcased_c
word_array << line
end
if characters_list[upcased_l].odd?
line = " " * (characters_list[upcased_l] * 2 - 1)
middle = line.length / 2
placement_1 = middle - (characters_list[upcased_c] - 1)
placement_2 = middle + (characters_list[upcased_c] - 1)
line[placement_1] = upcased_c
line[placement_2] = upcased_c
word_array << line
end
end
end
end
array << word_array
end
end
array.flatten!.join("\n") + "\n"
end
#Commit 3 - Refactor Solution
#Commit 2 - Write Runner Code / Tests
puts diamond_printer("ace")
puts "========================="
puts diamond_printer("ghost")
puts "========================="
puts diamond_printer("De Beers")
| true |
e33c0ecaebda223e3629d28d0ae99c32040f80fe | Ruby | jmuldvp/ltc-ruby | /9/concat.rb | UTF-8 | 229 | 3.671875 | 4 | [] | no_license | p [1, 2, 3] + [4, 5]
p [1, 2, 3].concat([4, 5])
puts
nums = [1, 2, 3]
nums.concat([4, 5, 6])
p nums
puts
a = [1, 2, 3]
b = [4, 5, 6]
def custom_concat(arr1, arr2)
arr2.each { |e| arr1 << e }
arr1
end
p custom_concat(a, b)
| true |
b372fd58cbef4d4696c20f3680985464b66d5f5e | Ruby | habeshawit/ruby-collaborating-objects-lab-onl01-seng-pt-072720 | /lib/mp3_importer.rb | UTF-8 | 513 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class MP3Importer
attr_accessor :artist, :song, :path
@@all = []
def initialize(path)
@path = path
end
def files
path_ = @path + "/**/*.mp3"
Dir[path_].map{ |f| File.basename(f)} #gets the file name without the file path
#Dir[path_].map{ |f| File.basename(f,".mp3") #gets the file name and removes the ".mp3" from each file
end
#binding.pry
def import
files.each do |filename|
Song.new_by_filename(filename)
end
end
end
| true |
c2fb8f746930a3fc6a2c911d9e3fcf02c082fd00 | Ruby | A-Legg/class-inheritance-warmup | /spec/rectangle_spec.rb | UTF-8 | 291 | 2.578125 | 3 | [] | no_license | require 'spec_helper'
describe Rectangle do
before do
@rectangle = Rectangle.new(50, 25)
end
it "should return it's area" do
@rectangle.area.should eq(1250)
end
it "should return it's perimeter" do
@rectangle.perimeter.should eq(150)
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.