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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
62326455299837dc8eb64319bc19505cd4004d33 | Ruby | HarlemSquirrel/jackasset | /lib/jackasset/assets_checker.rb | UTF-8 | 1,677 | 2.796875 | 3 | [] | no_license | # frozen_string_literal: true
module Jackasset
class AssetsChecker
attr_reader :host, :num_issues, :source_dir
def initialize(host:, source_dir:)
@host = host
@source_dir = source_dir
@num_issues = 0
end
def self.call(host: 'http://localhost:8080', source_dir:)
new(host: host, source_dir: source_dir).call
end
def call
img_urls
threads = img_urls.each_with_object([]) do |url, thread_list|
next unless url.match?(/\Ahttp/)
thread_list << Thread.new { check_url url }
end
threads.each(&:join)
puts "Finished checking #{img_urls.count} URLs and found #{num_issues} issues"
end
private
def check_url(url)
display_result Jackasset::UrlChecker.new(url: url).call
end
def clean_url(url)
cleaned_url = url.sub('src=', '').delete('"').strip # Remove src, quotes, and whitespace
cleaned_url.gsub!(/\A\/\//, 'http://') # Set protocol if needed
cleaned_url.slice!(/\A\//) # Remove single leading slash
cleaned_url.match?(/\Ahttp/) ? cleaned_url : "#{host}/#{cleaned_url}"
end
def display_result(response)
msg = " #{response.code} #{response.message} #{response.uri}\n"
case response
when Net::HTTPSuccess, Net::HTTPRedirection
print msg.green
else
@num_issues += 1
print msg.red
end
end
def img_urls
@img_urls ||= Dir["#{source_dir}/**/*.html"].each_with_object([]) do |path, urls|
file_content = File.read path
file_content.scan(/src=\"\S*\"/).flatten.each do |src|
urls << clean_url(src)
end
end
end
end
end
| true |
2b41931b87634e68e6048677a9a7e618eb2ab3d8 | Ruby | F-emme1/CodingChallengeC14 | /main.rb | UTF-8 | 3,892 | 3.796875 | 4 | [] | no_license | #A single ticket is $35.00
#Tickets can be purchased in lots of 4 for $112.00
#Cotton candy is sold for $1.25 per serving.
#Curly fries are sold for $2.50 for a small and $4.00 for a large.
#The program should then report each of the following.
puts "Welcome to the Ada State Fair expense calculator."
puts "Please provide some information to accurately calculate your expenses:"
puts
party_summary = [ ]
i = 0
3.times do i
i += 1
puts
puts "Please input the following for Party no.#{i}:"
puts
puts "How many tickets were bought?"
tickets = gets.chomp.to_f.round(2)
if tickets % 4 == 0
tickets = tickets * 28.00
else
tickets = tickets * 35.00
end
party_summary << tickets
puts
puts "How many orders of Curly Fries?"
puts "Jumbo?"
jumbo = gets.chomp.to_f.round(2)
jumbo = jumbo * 4.00
party_summary << jumbo
puts "Mini?"
mini = gets.chomp.to_f.round(2)
mini = mini * 2.50
party_summary << mini
puts
puts "How many servings of Cotton Candy were bought?"
cotton_candy = gets.chomp.to_f.round(2)
cotton_candy = cotton_candy * 1.25
party_summary << cotton_candy
end
tickets = party_summary[0], party_summary[4], party_summary[8]
#tickets_count = tickets.length ?
concessions = party_summary[1] + party_summary[2] + party_summary[3], party_summary[5]+ party_summary[6] + party_summary[7], party_summary[9] + party_summary[10] + party_summary[11]
#concessions_count = concessions.length ?
party_totals = party_summary[0] + party_summary[1] + party_summary[2] + party_summary[3], party_summary[4] + party_summary[5] + party_summary[6] + party_summary[7], party_summary[8] + party_summary[9] + party_summary[10] + party_summary[11]
#A summary for each party.
3. times do |i|
puts "For party no. #{i + 1}, the total spent on tickets was: $#{tickets[i]} and the total for concessions was $#{concessions[i]}, for a total of $#{party_totals[i]}."
i += 1
end
puts
#The total earnings for the session.
#The total spent on concessions.
#The most expensive party.
puts "In this session, the fair earned #{party_totals[0] + party_totals[1] + party_totals[2]}."
puts "The total spent on concessions is #{concessions[0] + concessions[1] + concessions[2]}."
puts "Party no. #{party_totals.index(party_totals.max) + 1} spent the most with a total of #{party_totals.max}."
#mini = gets.chomp convert to integer?? because it is array class? = gets.chomp
#unpacking array:
#[party_one] [party_two], [party_three] = party_summary[0..3], party_summary[4..7], party_summary[8..11]
#puts party summary
#party_summary = [party_one], [party_two], [party_three]
#unpacking multidimensional arrary and reassigning
#ticket_no = party_one[0],party_two[0],party_three[0]
#p party_totals.index(party_totals.max)
#p party_totals.index(party_totals[.max])# returns error
#party_totals.length do [i]
# i += 1
#if party_totals[i] = party_totals.max
# puts "Party no. #{party_totals[i]} spent the #most with a total of $#{party_totals.max}."
#end
#end
#3.times do i
# i += 1
#if party_totals[i] = party_totals.max
## puts "Party no. #{i} spent the most with a total of #{party_totals.max}"
##else
#end
#end
#party_totals.each do |i|# error
#if party_totals.max
#puts "Party no.#{i} spent the most with a total of #{party_totals.max}."
#else
#end
#end
#party_totals.each do |num|
# party_totals
# puts "Party #{num} is the spent the most with a total of #{party_totals.max}."
#else
#end
#end
#puts party_totals.each_with_index.max# returns max and total, seperated by comma
#p party_totals.index(max)
#p party_totals.each_with_index.max # returns max and total, seperated by comma
#i wanted to make a party_totals array adding
#concessions variables to tickets variables
#however, it continued to turn into an error
#this used to be in middle of previous block, didnt work:
# tickets_count.times"$#{tickets[i]}."
#concessions_count.times do i
| true |
81200225dbb42e314fa78ea250da575f55bbd6af | Ruby | scott-has/challenge_2 | /lib/order_processor.rb | UTF-8 | 850 | 3.0625 | 3 | [] | no_license | require_relative 'tax'
require_relative 'order'
require 'yaml'
class OrderProcessor
attr_accessor :order_lines, :total_tax, :total_items_cost, :args, :tax
def initialize (args, config_file)
@tax = Tax.new(YAML.load_file(config_file))
@args = args
end
def get_order
@order_lines = Order::OrderReader.read_order(@args)
end
def process_order
@total_tax = 0
@total_items_cost = 0
@order_lines.each do |line|
@total_tax += line.calculate_line_tax (@tax)
@total_items_cost += line.total
end
end
def print_reciept
@order_lines.each do |line|
line.print_order_line
end
print_tax_total
print_order_total
end
def print_tax_total
puts "Sales Taxes: #{sprintf( "%0.02f",@total_tax)}"
end
def print_order_total
puts "Total: #{sprintf( "%0.02f", @total_tax + @total_items_cost)}"
end
end
| true |
ffc4f51bd9dd6445759b53edd62fdf96d98dc47f | Ruby | sylencecode/axial | /lib/axial/consumers/generic_consumer.rb | UTF-8 | 1,659 | 2.921875 | 3 | [] | no_license | module Axial
module Consumers
class ConsumerError < StandardError
end
class GenericConsumer
attr_reader :publisher
def initialize()
@transmitter_object = nil
@mtransmitter_ethod = nil
@queue = Queue.new
@thread = nil
end
def clear()
@queue.clear
end
def register_callback(callback_object, callback_method)
if (!callback_object.respond_to?(callback_method))
raise(ConsumerError, "Class #{@transmitter_object.class} does not respond to method #{@method}")
end
@transmitter_object = callback_object
@transmitter_method = callback_method
end
def start()
if (@transmitter_object.nil? || @transmitter_method.nil?)
raise(ConsumerError, 'No callback object/method registered.')
end
@thread = Thread.new do
begin
consume
rescue Exception => ex
LOGGER.error("#{self.class} error: #{ex.class}: #{ex.message.inspect}")
ex.backtrace.each do |i|
LOGGER.error(i)
end
end
end
end
def consume()
raise("No 'consume' method defined for #{self.class}")
end
def stop()
@queue.clear
if (!@thread.nil?)
@thread.kill
end
@thread = nil
end
def send(msg)
@queue.enq(msg)
rescue Exception => ex
LOGGER.error("#{self.class} error: #{ex.class}: #{ex.message}")
ex.backtrace.each do |i|
LOGGER.error(i)
end
end
end
end
end
| true |
6f8066820ce940a75a349d5a18d55acb6f429524 | Ruby | matsueodb/sengu | /app/models/element_value/dates.rb | UTF-8 | 1,378 | 2.921875 | 3 | [
"MIT"
] | permissive | # == Schema Information
#
# Table name: element_value_date_contents
#
# id :integer not null, primary key
# value :datetime
# type :string(255)
# created_at :datetime
# updated_at :datetime
#
#
#== 日付
#
class ElementValue::Dates < ElementValue::DateContent
after_initialize :set_value
# String
# super
def value
self["value"].try(:strftime, "%Y-%m-%d").to_s
end
#=== 引数の値以上の値がセットされている場合Trueが返ること
#==== 引数
# * val - String of Date
#==== 戻り値
# * boolean
def greater_than?(val)
date = val.respond_to?(:to_date) ? val.to_date : val
return false if date.blank?
attributes["value"].to_date >= date
end
#=== 引数の値以上の値がセットされている場合Trueが返ること
#==== 引数
# * val - String of Date
#==== 戻り値
# * boolean
def less_than?(val)
date = val.respond_to?(:to_date) ? val.to_date : val
return false if date.blank?
attributes["value"].to_date <= date
end
private
#
#=== self["value"]をセット。
# after_initializeでセットされる
# DBが日時分秒をもつため、YYYY-MM-DD形式で値が返るようにセットする
# この処理でデータ編集画面の初期表示の値がYYYY-MM-DDになる
def set_value
self["value"] = self.value
end
end
| true |
10630682625a0d3ca03704a53edca9024a3655be | Ruby | sandeep-freshdesk/Bootcamp_Programs | /ruby_programs/proc.rb | UTF-8 | 389 | 3.234375 | 3 | [] | no_license | greetings = lambda { puts "hello there!" }
printHello = lambda do
puts "hello world"
end
printHello.call
greetings.call
puts "************"
printHello1 = lambda do |name|
puts "hello #{name}"
end
printHello1.call 'sandeep'
puts "^^^^^^^^^^^^^^"
printHello2 = lambda do |name|
return puts "hello #{name}"
end
catchVal = printHello2.call 'sandeep'
puts catchVal | true |
f4ba81bdc5c6f3661296726c156fbee35a6390f4 | Ruby | roussev/Ruby-Meta-Programming | /34_callable_objects.rb | UTF-8 | 940 | 4.375 | 4 | [] | no_license | p "Proc"
inc = Proc.new {|x| x.succ }
inc.call(2) # => 3
inc.(2) # => 4
p "Lambda"
dec = lambda {|x| x.pred }
dec.class # => Proc
dec.call(2) # => 1
# Ruby provides two Kernel methods to convert a block to a Proc: lambda() and proc()
p "& operator"
def my_method(x, &block)
y = x.succ
yield y
end
my_method(1) {|a| a * 2} # => 4
p "Converting proc to a block"
p = Proc.new {|a| a * 2}
my_method(1, &p) # => 4
p "Differences between procs and lambdas"
p "return in lambda returns some results, whereas in proc, it returns from the caller's context"
p "also lambdas have a strict check on the number of arguments passed"
p "The Stubby Lambda"
p = ->(x) { x + 1 } # equivalent to: p = lambda {|x| x + 1 }
p "Methods are are similar to a lambda, with an important difference:"
p "a lambda is evaluated in the scope it’s defined in (it’s a closure),"
p "while a Method is evaluated in the scope of its object." | true |
b1373f6ea6fb8d65c5c2764f4f32029f3983563c | Ruby | andkolbe/chirper-rails | /test/models/chirp_test.rb | UTF-8 | 860 | 2.8125 | 3 | [] | no_license | # test_helper.rb loads the default configuration to run the tests
require "test_helper"
# ChirpTest defines a test case because it inherits from ActiveSupport::TestCase
# ChirpTest has all of the methods available from ActiveSupport::TestCase
class ChirpTest < ActiveSupport::TestCase
# test 'should not save chirp without content' do
# chirp = Chirp.new
# assert_not chirp.save
# end
# def test_the_truth
# assert true
# end
end
# An assertion is a line of code that evaluates an object (or expression) for expected results.
# An assertion can check:
# does this value = that value?
# is this object nil?
# is the user's password greater than 5 characters?
# Every test may contain one or more assertions, with no restrictions as to how many assertions are allowed
# Only when all the assertions are successful will the test pass | true |
e1dd4c44a5c405dbcdb10dc3838f3ce124c46dec | Ruby | Filmscore88/badges-and-schedules-online-web-prework | /conference_badges.rb | UTF-8 | 463 | 3.828125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def badge_maker(name)
return "Hello, my name is #{name}."
end
def batch_badge_creator(array)
new_array=[]
array.each do |x| x=badge_maker(x)
new_array<<x
end
new_array.each do |x| puts x
end
end
def assign_rooms(array)
new_array=[]
array.each_with_index do |x,index|x= "Hello, #{x}! You'll be assigned to room #{index+1}!"
new_array<< x
end
new_array.each do |x| puts x
end
end
def printer(array)
batch_badge_creator(array)
assign_rooms(array)
end | true |
e2a44cf5f761f942c21b394475f04c45bf9825d8 | Ruby | potatoHVAC/hackerrank | /ruby/array_initialization.rb | UTF-8 | 215 | 2.875 | 3 | [] | no_license | #https://www.hackerrank.com/challenges/ruby-array-initialization/problem
#completed Oct 2017
# Initialize 3 variables here as explained in the problem statement
array_2 = [10,10]
array_1 = [nil]
array = Array.new
| true |
4bf9715ed01f28bc6e15a6c2c3cb0786616a20ac | Ruby | Oscartic/student-list | /app/graphql/mutations/add_list_mutation.rb | UTF-8 | 881 | 2.546875 | 3 | [] | no_license | module Mutations
class AddListMutation < Mutations::BaseMutation
argument :rut, String, required: false
argument :first_name, String, required: false
argument :last_name, String, required: false
argument :course, String, required: false
argument :number_list, Integer, required: false
argument :is_present, Boolean, required: false
field :student, Types::StudentType, null: true
def resolve(rut:, first_name: nil, last_name: nil, course: nil, number_list: nil, is_present: nil)
student = Student.new(
rut: rut,
first_name: first_name,
last_name: last_name,
course: course,
number_list: number_list,
is_present: is_present,
)
if student.save
{ student: student }
else
{ errors: "No se puede crear este Estudiante." }
end
end
end
end | true |
08d23449a62c2f4b93a13075d9bd0a535619b07e | Ruby | zhzyc142/billionstech_crawl | /lib/billionstech_crawl/sogou.rb | UTF-8 | 5,425 | 2.5625 | 3 | [] | no_license | require 'set'
require 'net/http'
require 'nokogiri'
require 'faraday'
require 'timeout'
require 'pry'
require 'uuidtools'
module BillionstechCrawl
module Sogou
class Crawler
# Set of all URIs which have been crawled
attr_accessor :crawled
# Queue of URIs to be crawled. Array which acts as a FIFO queue.
attr_accessor :queue
# Hash of options
attr_accessor :options
#faraday
attr_accessor :conn
# Accepts the following options:
# * timeout -- Time limit for the crawl operation, after which a Timeout::Error exception is raised.
# * external -- Boolean; whether or not the crawler will go outside the original URI's host.
# * exclude -- A URI will be excluded if it includes any of the strings within this array.
# * useragent -- User Agent string to be transmitted in the header of all requests
# * out_put_path
def initialize(options={})
@crawled = Set.new
@queue = []
@options = {
}.merge(options)
@conn = Faraday.new(headers: {
"Accept"=>"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding"=>"gzip, deflate",
"Accept-Language"=>"zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control"=>"max-age=0",
"Connection"=>"keep-alive",
"Cookie"=>"CXID=EEEB6E21E1B4C6C5B9B6F0547210FE72; SUID=6F0C767B5B68860A5B286934000A9550; SUV=00C027296FC53E785B28B973F2EAE371; ad=Blllllllll2b3p61lllllV71OPGlllllWTYGbZllllYlllll4Vxlw@@@@@@@@@@@; IPLOC=CN1100; ABTEST=8|1530514805|v1; weixinIndexVisited=1; JSESSIONID=aaaAVJE7sNPHf4cO4hgrw; sct=1; PHPSESSID=m7ml54s1tmr08rvgf9fnjfkr60; SUIR=2A7E111A61640E9FDE2E56F061EB9FFC; SNUID=E2B4DBD2AAACD9AA4C7C4EEFAA91693C",
"Host"=>"weixin.sogou.com",
"Upgrade-Insecure-Requests"=>"1",
"User-Agent"=>"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
"Pragma"=>"no-cache"}.merge(options))
end
# Given a URI object, the crawler will explore every linked page recursively using the Breadth First Search algorithm.
# Whenever it downloads a page, it notifies observers with an HTTPResponse subclass object and the downloaded URI object.
def crawl(start_url)
@queue << start_url
# Timeout.timeout(@options[:timeout]) {
while(url = @queue.shift)
unless @crawled.include? url
p url
file_name = UUIDTools::UUID.sha1_create(UUIDTools::UUID_URL_NAMESPACE, url).to_s + ".html"
file_path = @options["out_put_path"] + "/out/" + file_name
system("curl '#{url}' -o #{file_path}")
# @conn.headers["Host"] = "weixin.sogou.com"
# resp = @conn.get(url)
html = Nokogiri.parse(File.open(file_path))
document_list(html)
a_tags = html.search("#pagebar_container a")
# @queue = @queue + a_tags.collect do |t|
# begin
# next_url = "http://weixin.sogou.com/weixin" + t.attribute("href").to_s.strip
# @crawled.include?(next_url) ? nil : next_url
# rescue
# nil
# end
# end
# @queue = @queue.compact.uniq
@crawled << url
end
end
# }
end
def document_list html
html.search(".news-list .img-box a").each do |t|
p t.attribute("href").to_s
url = (t.attribute("href").to_s).strip
unless @crawled.include? url
file_name = UUIDTools::UUID.sha1_create(UUIDTools::UUID_URL_NAMESPACE, url).to_s + ".html"
file_path = @options["out_put_path"] + "/out/"
p url
system("wget -O #{file_path + file_name} '#{url}'")
translate_src_to_local(file_path + file_name)
# system("curl '#{url}' -o #{file_path} --cookie \"rewardsn=; wxtokenkey=777\" ")
@crawled << url
end
end
end
def translate_src_to_local data_file_path
str = File.read(data_file_path)
str.scan(/data-src=\"[\w\?\=\:\/.]*"/).each do |key|
url = key[10..-2] # 去除 data-src=\" \"
file_name = UUIDTools::UUID.sha1_create(UUIDTools::UUID_URL_NAMESPACE, url).to_s
file_path = @options["out_put_path"] + "/out/resource/"
FileUtils.mkdir(file_path) unless File.exist?(file_path)
system("wget -O #{file_path + file_name} '#{url}'")
str.gsub!(key, "data-src=\"/out/resource/#{file_name}\"")
end
# str = str.gsub("\n", "").gsub("\r", "")
# # str = str.gsub(/(?i)(<script)[\s\S]*?((<\/script>))/, "")
# str = str.gsub(/<script(?!.*(document.write).*)<\/script>/, "")
html = Nokogiri.parse(str)
html.search("img").each do |x|
if x.attributes["data-src"]
if x.attributes["class"]
x.attributes["class"].value = "lazyload " + x.attributes["class"].value
else
x["class"] = "lazyload"
end
end
end
f = File.open(data_file_path, "w")
f.write(html.to_html)
f.write('<script src="/out/lazysizes.js" async=""></script>')
f.close
end
end
end
end
| true |
936222d77573949b73874513647644c7b54c0a0f | Ruby | warrenshen/blockterm | /server/app/helpers/mention_total_count.rb | UTF-8 | 421 | 3.0625 | 3 | [] | no_license | class MentionTotalCount
def initialize(timestamp)
@timestamp = timestamp
@total_count = 0
self
end
def increment_by(increment)
@total_count += increment
end
def max_by(count)
@total_count = [@total_count, count].max
end
def set_by(count)
@total_count = count
end
def count
@total_count
end
def timestamp
@timestamp
end
def value
@total_count
end
end
| true |
87c79a825a67bddd23e4ddb63b033b46b8369cb1 | Ruby | cbeer/KriKri | /lib/krikri/parser.rb | UTF-8 | 6,393 | 3.296875 | 3 | [
"MIT"
] | permissive | module Krikri
##
# Provides a generic interface for accessing properties from OriginalRecords.
# Implement the interface, and that of `Value` on an record-type basis.
#
# parser = Krikri::Parser::MyParser.new(record)
# parser.root # => #<Krikri::MyParser::Value:0x007f861888fea0>
#
class Parser
attr_reader :root, :record
##
# @param record [Krikri::OriginalRecord] a record whose properties can
# be parsed by the parser instance.
def initialize(record)
@record = record
end
##
# Instantiates a parser object to wrap the record. Returns the record
# as is if it is already parsed.
#
# @param record [Krikri::OriginalRecord, Krikri::Parser] the record to parse
# @param args [Array, nil] the arguments to pass to the parser instance,
# if any
# @return [Krikri::Parser] a parsed record object
def self.parse(record, *args)
record.is_a?(Krikri::Parser) ? record : new(record, *args)
end
##
# A generic parser value.
#
# Interface to a single value node which can access typed data values (e.g.
# String, DateTime, etc...) parsed from a string, and provides access to
# child nodes and attributes.
class Value
##
# Property accessor interface. Passes `name` to the local implementation
# of #get_child_nodes.
#
# @param name [#to_sym] a named property to access
def [](name)
get_child_nodes(name)
end
##
# Queries whether `name` is a subproperty of this node
# @param name [#to_sym] a named property to query
# @return [Boolean] true if `name` is a subproperty of the current node
def child?(name)
children.include?(name)
end
##
# @abstract
# @return [Array<Symbol>] a list of subproperties that can be passed back
# to #[] to access child nodes
def children
raise NotImplementedError
end
##
# @abstract
# @return [<#to_s>] typed value for the property
def value
raise NotImplementedError
end
##
# @abstract
# @return [Boolean] true if this node has typed values accessible with
# #values
def values?
raise NotImplementedError
end
##
# @abstract
# @return [Array<Symbol>] a list of attributes accessible on the node
def attributes
raise NotImplementedError
end
##
# Queries whether `name` is an attribute of this node
# @param name [#to_sym] an attribute name to query
# @return [Boolean] true if `name` is an attribute of the current node
def attribute?(name)
begin
attributes.include?(name)
rescue NotImplementedError
false
end
end
def method_missing(name, *args, &block)
return attribute(name) if attribute?(name)
super
end
def respond_to_missing(method, *)
attribute?(method) || super
end
private
##
# @abstract
def attribute(name)
raise NotImplementedError, "Can't access attribute #{name}"
end
##
# @abstract Provide an accessor for properties
# @param name [#to_sym] a named property to access
# @return [Krikri::Parser::Value] the value of the child node
def get_child_nodes(name)
raise NotImplementedError, "Can't access property #{name}"
end
end
##
# A specialized Array object for containing Parser::Values. Provides methods
# for accessing and filtering values that can be chained.
#
# my_value_array.field('dc:creator', 'foaf:name')
# .match_attribute('first_name').values
#
# Methods defined on this class should return another ValueArray, an Array
# of literal values (retrieved from Parser::Value#value), or a single
# literal value.
class ValueArray
include Enumerable
delegate :<<, :[], :[]=, :each, :empty?, :map, :to_a, :to_ary,
:to => :@array
def initialize(array = [])
@array = array
end
##
# @return [Array] literal values from the objects in this array.
# @see Parser::Value#value
def values
map(&:value)
end
##
# Accesses a given field. Use multiple arguments to travel down the node
# hierarchy.
#
# @return [ValueArray] an array containing the nodes available in a
# particular field.
def field(*args)
result = self
args.each do |name|
result = result.get_field(name)
end
result
end
##
# Retrieves the first element of a ValueArray. Uses an optional argument
# to specify how many items to return. By design, it behaves similarly
# to Array#first, but it intentionally doesn't override it.
#
# @return [ValueArray] a Krikri::Parser::ValueArray for first n elements
def first_value(*args)
return self.class.new(@array.first(*args)) unless args.empty?
self.class.new([@array.first].compact)
end
##
# Wraps the result of Array#select in a ValueArray
#
# @see Array#select
def select(*args, &block)
self.class.new(@array.select(*args, &block))
end
##
# Wraps the result of Array#reject in a ValueArray
#
# @see Array#reject
def reject(*args, &block)
self.class.new(@array.reject(*args, &block))
end
##
# @param name [#to_sym] an attribute name
# @param other [Object] an object to for equality with the
# values from the given attribute.
#
# @return [ValueArray] an array containing nodes for which the specified
# attribute has a value matching the given object.
def match_attribute(name, other)
select do |v|
next unless v.attribute?(name.to_sym)
v.send(name).downcase == other.downcase
end
end
##
# Wraps the root node of the given record in this class.
#
# @param record [Krikri::Parser] a parsed record to wrap in a ValueArray
# @return [ValueArray]
def self.build(record)
new([record.root])
end
protected
def get_field(name)
self.class.new(flat_map { |val| val[name] })
end
end
end
end
| true |
b17391da291e1c829dc891e9f16d42b059ba08c9 | Ruby | bogdanRada/ruby-gem-downloads-badge | /config/initializers/enumerable.rb | UTF-8 | 1,553 | 3.140625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# extending enumerable with methods
module Enumerable
# Sorts gem versions
#
# @return [Array] Array of versions sorted
# @api public
def version_sort
sort_by do |key, _val|
gsub_factory_versions(key)
end
end
# tries to parse a version and returns an array of versions sorted
# @see #sort_versions
#
# @param [String, Enumerable] key The version as a string
# @return [Array<String>] Returns the sorted versions parsed from string provided
# @api public
def gsub_factory_versions(key)
version_string = key.gsub(/_SP/, '.').gsub(/_Factory/, '_100')
sort_versions(version_string)
end
# Returns an array of sorted versions from a string
# @see #version_is_float?
# @param [String] version_string The version of the gem as a string
# @return [Array<String>, Array<Float>] Returns an array of sorted versions
# @api public
def sort_versions(version_string)
version_string.split(/_/).map { |version| version_to_float(version) }
end
# function that makes the methods encapsulated as utility functions
module_function
# if the version is a float number, will return the float number, otherwise the string in downcase letters
#
# @param [String] version The version of the gem as a string
# @return [String, Float] if the version is a float number, will return the float number, otherwise the string in downcase letters
# @api public
def version_to_float(version)
version =~ /\A\d+(\.\d+)?\z/ ? -version.to_f : version.downcase
end
end
| true |
90815fca1234456a78f66d8e543b8bcb0c121768 | Ruby | code4mk/ruby4you | /ruby_code/z_compiler-design/change_underscore_w_vowel.rb | UTF-8 | 706 | 3.0625 | 3 | [] | no_license | # @code4mk kaaml_ie_t => 4 uniq combination (_=> uniq previous vowel)
your_string = gets.chomp()
b = []
b = your_string.split(//)
count = 1
# loop store_string
b.each_with_index {|val, index|
if val == "_"
previous_datas = 0
previous_v = 0
store_vowel = []
while previous_datas < index
check_position = b[previous_datas]
is_vowel = /[aeiou]/.match(check_position)
if is_vowel.class == MatchData
store_vowel[previous_v] = is_vowel.to_s
previous_v = previous_v + 1
end
previous_datas = previous_datas + 1
end
v_count = store_vowel.uniq.length
count = count * v_count
end
}
puts "#{your_string} => #{count} uniq combination"
| true |
3dc7eeaab64eedacdfef971958c55005ea4ef38f | Ruby | jessecalton/phase-0-tracks | /ruby/hashes.rb | UTF-8 | 1,522 | 3.890625 | 4 | [] | no_license | # Ask client information:
# Name
# Age
# Number of Children
# Decor Theme:
# Convert user info to appropriate data type
# Print out the hash to the screen when the user has answered all the questions
# Ask the user if they want to update any of the keys (i.e. :decor_theme)
# Have them type “none” if there are none
# Print the latest version of the hash
# Exit
puts "Hello there! Please answer the following questions!"
puts "What is your name?"
user_name = gets.chomp.to_s
puts "How old are you?"
user_age = gets.chomp.to_i
puts "How many children do you have?"
user_children = gets.chomp.to_i
puts "What would you like for your decor theme?"
decor_theme = gets.chomp.to_s
user_information = {
:user_name => user_name,
:user_age => user_age,
:user_children => user_children,
:decor_theme => decor_theme
}
puts user_information
puts "Would you like to update any of this information?
Type in the key of the item you'd like to change.
Say 'none' if everything looks good to you."
user_input = gets.chomp
if user_input == "user_name"
puts "Change name to:"
user_information[:user_name] = gets.chomp.to_s
elsif user_input == "user_age"
puts "Change age to:"
user_information[:user_age] = gets.chomp.to_i
elsif user_input == "user_children"
puts "Change number of children to:"
user_information[:user_children] = gets.chomp.to_i
elsif user_input == "decor_theme"
puts "Change decor_theme to:"
user_information[:decor_theme] = gets.chomp.to_s
else
end
p user_information | true |
78af78ddf80b508a2be26b1d873999feba42f05f | Ruby | zendesk/mail | /tasks/corpus.rake | UTF-8 | 3,247 | 2.671875 | 3 | [
"MIT"
] | permissive | namespace :corpus do
task :load_mail do
require File.expand_path('../../spec/environment', __FILE__)
require 'mail'
end
# Used to run parsing against an arbitrary corpus of email.
# For example: http://plg.uwaterloo.ca/~gvcormac/treccorpus/
desc "Provide a LOCATION=/some/dir to verify parsing in bulk, otherwise defaults"
task :verify_all => :load_mail do
root_of_corpus = ENV['LOCATION'] || 'corpus/spam'
@save_failures_to = ENV['SAVE_TO'] || 'spec/fixtures/emails/failed_emails'
@failed_emails = []
@checked_count = 0
if root_of_corpus
root_of_corpus = File.expand_path(root_of_corpus)
if not File.directory?(root_of_corpus)
raise "\n\tPath '#{root_of_corpus}' is not a directory.\n\n"
end
else
raise "\n\tSupply path to corpus: LOCATION=/path/to/corpus\n\n"
end
if @save_failures_to
if not File.directory?(@save_failures_to)
raise "\n\tPath '#{@save_failures_to}' is not a directory.\n\n"
end
@save_failures_to = File.expand_path(@save_failures_to)
puts "Mail which fails to parse will be saved in '#{@save_failures_to}'"
end
puts "Checking '#{root_of_corpus}' directory (recursively)"
# we're tracking all the errors separately, don't clutter terminal
$stderr_backup = $stderr.dup
$stderr.reopen("/dev/null", "w")
STDERR = $stderr
dir_node(root_of_corpus)
# put our toys back now that we're done with them
$stderr = $stderr_backup.dup
STDERR = $stderr
puts "\n\n"
if @failed_emails.any?
report_failures_to_stdout
end
puts "Out of Total: #{@checked_count}"
if @save_failures_to
puts "Add SAVE_TO=/some/dir to save failed emails to for review.,"
puts "May result in a lot of saved files. Do a dry run first!\n\n"
else
puts "There are no errors"
end
end
def dir_node(path)
puts "\n\n"
puts "Checking emails in '#{path}':"
entries = Dir.entries(path)
entries.each do |entry|
next if ['.', '..'].include?(entry)
full_path = File.join(path, entry)
if File.file?(full_path)
file_node(full_path)
elsif File.directory?(full_path)
dir_node(full_path)
end
end
end
def file_node(path)
verify(path)
end
def verify(path)
result, message = parse_as_mail(path)
if result
print '.'
$stdout.flush
else
save_failure(path, message)
print 'x'
end
end
def save_failure(path, message)
@failed_emails << [path, message]
if @save_failures_to
email_basename = File.basename(path)
failure_as_filename = message.gsub(/\W/, '_')
new_email_name = [failure_as_filename, email_basename].join("_")
File.open(File.join(@save_failures_to, new_email_name), 'w+') do |fh|
fh << File.read(path)
end
end
end
def parse_as_mail(path)
@checked_count += 1
begin
parsed_mail = Mail.read(path)
[true, nil]
rescue => e
[false, e.message]
end
end
def report_failures_to_stdout
@failed_emails.each do |failed|
puts "#{failed[0]} : #{failed[1]}"
end
puts "Failed: #{@failed_emails.size}"
end
end
| true |
ba6bcca603d94c8169395f1edb35db3378a9b061 | Ruby | Marygemidzhian/homework | /homework2/hash2.rb | UTF-8 | 208 | 2.96875 | 3 | [] | no_license | arr = (10...36).map{ |i| i.to_s 36}
hash = {
a: arr.find_index('a')+1,
e: arr.find_index('e')+1,
i: arr.find_index('i')+1,
o: arr.find_index('o')+1,
u: arr.find_index('u')+1
}
puts hash
| true |
9f625f61f6045c1065dc9f9cb378629a2cf56f6a | Ruby | ryan-chambers/wine-guide | /lib/wine_score_exporter.rb | UTF-8 | 1,833 | 3.046875 | 3 | [] | no_license | require 'country.rb'
require 'wine.rb'
require 'winery.rb'
class WineScoreExporter
def create_wine_sentence(wine, winery)
# p "create sentence for wine #{wine}"
s = [winery.name.gsub('.', ''), wine.grape.name, wine.year]
s << wine.other.gsub('.', '') unless wine.other.nil? or wine.other.empty?
s << wine.region unless wine.region.nil? or wine.region.empty?
s << "LCBO# " + wine.lcbo_code unless wine.lcbo_code.empty?
s.join(', ')
end
def create_wine_bottle_sentence(bottle)
s = ['$' + bottle.price.to_s, bottle.score.to_i.to_s + '/100', bottle.comments]
if ! bottle.bought.nil? # TODO change check to empty string check (eq? '') because "Bought " is being output
s << 'Bought ' + bottle.bought
end
if ! bottle.drink_from.nil?
s << 'From ' + bottle.drink_from.to_s
end
s << 'To ' + bottle.drink_to.to_s unless bottle.drink_to.nil?
if !bottle.wine_reviewdate.nil?
s << '[' + bottle.wine_reviewdate + ']'
end
if bottle.in_fridge
s << 'In fridge'
end
s.join('. ')
end
NEW_LINE = '
'
def export_db
j = Country::COUNTRIES.keys.reduce(StringIO.new) {|out, country|
l = StringIO.new
l << "#{country}"
l << NEW_LINE
# load all wines for country
wines = Wine.includes(:grape, :bottles).where("country = ?", country).order('winery_id asc')
wines.each do |wine|
# look up winery
winery = Winery.find(wine.winery_id)
winery_sentence = create_wine_sentence(wine, winery)
l << "#{winery_sentence}."
wine.bottles.each do |bottle|
wine_bottle = create_wine_bottle_sentence(bottle)
l << " #{wine_bottle}."
end
l << NEW_LINE
end
l << NEW_LINE
out << l.string
out
}
j.string
end
end | true |
fb4be851b55b74d7de5167f6c366c590144fbe45 | Ruby | nzifnab/budget | /app/models/quick_fund.rb | UTF-8 | 1,387 | 2.765625 | 3 | [] | no_license | class QuickFund < ActiveRecord::Base
# The base account that the quick fund was made from,
# even if overall funds were taken from several sources.
belongs_to :account, inverse_of: :quick_funds
has_many :account_histories, inverse_of: :quick_fund
validates :amount, presence: {message: "Required"}
validates :amount, numericality: {greater_than: 0, message: "Positive number only"}
before_validation :build_account_history, on: :create
validate :steal_amount_validation_from_history
def distribute_funds(funds, acc)
history = account_histories.build(
account: acc,
description: description
)
history.amount_for_quick_fund = funds
history
end
def withdrawal?
fund_type.to_s.downcase == "withdraw"
end
def deposit?
fund_type.to_s.downcase == "deposit"
end
protected
# before_validation on: :create
def build_account_history
funds = withdrawal? ? -amount.to_d : amount.to_d
distribute_funds(funds, account)
end
# validate
def steal_amount_validation_from_history
err_history = account_histories.detect{|hist|
hist.errors.messages[:amount].present?
}
if err_history.present?
errors.add(:amount, err_history.errors.messages[:amount].first)
errors.add(:amount_extended, err_history.errors.messages[:amount_extended].first)
end
end
end
| true |
d81579d9720c9bfed5fc8d139a6fb6d840ee1eb7 | Ruby | jhogrefe/2015-02-03-mini-programs | /word-connector.rb | UTF-8 | 927 | 3.453125 | 3 | [] | no_license | require 'pry'
require 'active_support'
require 'active_support/core_ext/array/conversions'
# Public: WordConnector class
# Connects an array of strings into a single sentence with an "and"
# between the last two strings using the Active Support .to_sentence
# array conversion.
#
# Attributes:
# None.
#
# Methods:
# #merge_strings_with_and
class WordConnector
# Public: merge_strings_with_and method
# Pushes a string of words into an array and then connects the
# strings into a single sentence with an "and" between the last
# two strings.
#
# Parameters:
# words - uses the splat operator to collect the strings that are
# being pushed into the array.
#
# Returns:
# A string made from the array with "and" added between the last
# two strings.
#
# State Changes:
# None.
def merge_strings_with_and(*words)
words.to_sentence
end
# End of the class.
end
binding.pry | true |
5f1586f0c8171a36de5e6e344ae18f61c7a9a43d | Ruby | gbarka2/intro_to_ruby | /dojo.rb | UTF-8 | 2,799 | 3.96875 | 4 | [] | no_license |
class Fighter
attr_reader :name
attr_accessor :defense, :strength, :luck, :life
def initialize(name, defense, strength, luck, life)
@name = name
@defense = defense
@strength = strength
@luck = luck
@life = life
end
def attack(opponent)
damage = @strength - opponent.defense
if damage <= 0
p "#{name} could not do damage to #{opponent.name}!"
else
opponent.life = opponent.life - damage
p "#{opponent.name} took #{damage} hit! #{opponent.name} has #{opponent.life} hit points remaining."
end
end
def welcome
end
end
class Dojo
def fight_wild_pokemon(player)
player.strength += 1
p "#{player.name}'s strength increased to #{player.strength}!"
end
def eat_rare_candy(player)
player.defense += 1
p "#{player.name}'s defense increased to #{player.defense}!"
end
def battle_trainers(player)
player.strength += 3
p "#{player.name}'s strength increased to #{player.strength}!"
end
end
p "Welcome to Pokemon Dojo! Choose your Pokemon!"
player = Fighter.new("Gyrados", 0, 0, 0, 100)
opponent = Fighter.new("Jolteon", 4, 4, 4, 100)
dojo = Dojo.new()
p "Hello #{player.name}! Battle wild pokemon, collect rare candies, and train with others to prepare for battle with your opponent #{opponent.name}! #{opponent.name} is an experienced Pokemon, so be ready for a long battle!"
training = 0
while training <= 10
dojo.eat_rare_candy(opponent)
dojo.battle_trainers(player)
training += 1
dojo.eat_rare_candy(opponent)
dojo.battle_trainers(player)
training += 1
dojo.battle_trainers(opponent)
dojo.eat_rare_candy(player)
training += 1
dojo.fight_wild_pokemon(opponent)
dojo.eat_rare_candy(player)
training += 1
dojo.battle_trainers(opponent)
dojo.eat_rare_candy(player)
training += 1
dojo.fight_wild_pokemon(opponent)
dojo.fight_wild_pokemon(player)
training += 1
dojo.eat_rare_candy(opponent)
dojo.fight_wild_pokemon(player)
training += 1
dojo.fight_wild_pokemon(opponent)
dojo.fight_wild_pokemon(player)
training += 1
dojo.battle_trainers(opponent)
dojo.fight_wild_pokemon(player)
training += 1
dojo.eat_rare_candy(opponent)
dojo.fight_wild_pokemon(player)
training += 1
end
p "Phew! 10 weeks of training! Think you're ready? #{opponent.name} has been training too, it's stats are: defense: #{opponent.defense}, strength: #{opponent.strength}, luck: #{opponent.luck}. Good luck! May the best Pokemon win!"
while true
if opponent.life > 0
opponent.attack(player)
end
if player.life > 0
player.attack(opponent)
end
if player.life <= 0
p "#{opponent.name} has won the battle! Time to re-train!"
break
end
if opponent.life <= 0
p "Congratulations! #{player.name} has won the battle!"
break
end
end
| true |
902ae462b539b9ba5b08e2c2d7d66b8a1f54b228 | Ruby | jonsjava/random | /balancer.rb | UTF-8 | 697 | 3.046875 | 3 | [] | no_license | require 'optparse'
options = {}
OptionParser.new do |parser|
parser.banner = 'Usage: balancer.rb [OPTIONS]'
parser.on('-i', '--input-hash NAME', 'Username for liquibase admin') do |liquibase_admin|
options[:liquibase_admin] = liquibase_admin
end
end
def balancer(input_a)
unless input_a.hash?
puts "Invalid input"
end
open_bracket_count = 0
closed_bracket_count = 0
input_a.chars!
input_a.each do |caracter_to_check|
if character_to_check == ')'
closed_bracket_count += 1
end
if character_to_check == '('
open_bracket_count += ')'
end
end
if open_bracket_count != closed_bracket_count
return false
else
return true
end
end
| true |
43f9f7115dc1066aafde945fd51272a3d60e0a0a | Ruby | tkyktkmt/furima-34283 | /spec/models/user_spec.rb | UTF-8 | 5,432 | 2.53125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
describe '#create' do
before do
@user = FactoryBot.build(:user)
end
it 'nickname、first_name、last_name、first_name_katakana、last_name_katakana、birthday、email、passwordとpassword_confirmationが存在すれば登録できること' do
expect(@user).to be_valid
end
it 'nicknameが空では登録できないこと' do
@user.nickname = ''
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it 'first_nameが空では登録できないこと' do
@user.first_name = ''
@user.valid?
expect(@user.errors.full_messages).to include("First name can't be blank")
end
it 'last_nameが空では登録できないこと' do
@user.last_name = ''
@user.valid?
expect(@user.errors.full_messages).to include("Last name can't be blank")
end
it 'first_name_katakanaが空では登録できないこと' do
@user.first_name_katakana = ''
@user.valid?
expect(@user.errors.full_messages).to include("First name katakana can't be blank")
end
it 'last_name_katakanaが空では登録できないこと' do
@user.last_name_katakana = ''
@user.valid?
expect(@user.errors.full_messages).to include("Last name katakana can't be blank")
end
it 'birthdayが空では登録できないこと' do
@user.birthday = ''
@user.valid?
expect(@user.errors.full_messages).to include("Birthday can't be blank")
end
it 'emailが空では登録できないこと' do
@user.email = ''
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it 'passwordが空では登録できないこと' do
@user.password = ''
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it 'emailに@が含まれなければ登録できないこと' do
@user.email = 'test.example'
@user.valid?
expect(@user.errors.full_messages).to include('Email is invalid')
end
it '既存のemailと同様のアドレスは登録できないこと' do
@user.save
another_user = FactoryBot.build(:user)
another_user.email = @user.email
another_user.valid?
expect(another_user.errors.full_messages).to include('Email has already been taken')
end
it 'passwordが5文字以下であれば登録できないこと' do
@user.password = '111aa'
@user.password_confirmation = '111aa'
@user.valid?
expect(@user.errors.full_messages).to include('Password is too short (minimum is 6 characters)')
end
it 'passwordに全角が含まれると登録できないこと' do
@user.password = '1111aaa'
@user.password_confirmation = '1111aaa'
@user.valid?
expect(@user.errors.full_messages).to include('Password include both letters and numbers')
end
it 'passwordに英語がなければ登録できないこと' do
@user.password = '149320'
@user.password_confirmation = '149320'
@user.valid?
expect(@user.errors.full_messages).to include('Password include both letters and numbers')
end
it 'passwordに数字がなければ登録できないこと' do
@user.password = 'asdfgh'
@user.password_confirmation = 'asdfgh'
@user.valid?
expect(@user.errors.full_messages).to include('Password include both letters and numbers')
end
it 'passwordとpassword_confirmationが不一致では登録できないこと' do
@user.password = '111aaa'
@user.password_confirmation = '112aaa'
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it 'first_nameが全角でなければ登録できないこと' do
@user.first_name = 'タカシ'
@user.valid?
expect(@user.errors.full_messages).to include('First name please enter in full letters')
end
it 'last_nameが全角でなければ登録できないこと' do
@user.last_name = 'tanaka'
@user.valid?
expect(@user.errors.full_messages).to include('Last name please enter in full letters')
end
it 'first_name_katakanaが全角でなければ登録できないこと' do
@user.first_name_katakana = 'タカシ'
@user.valid?
expect(@user.errors.full_messages).to include('First name katakana please enter in full-width katakana')
end
it 'first_name_katakanaがカタカナでなければ登録できないこと' do
@user.first_name_katakana = 'たかし'
@user.valid?
expect(@user.errors.full_messages).to include('First name katakana please enter in full-width katakana')
end
it 'last_name_katakanaが全角でなければ登録できないこと' do
@user.first_name_katakana = 'tanaka'
@user.valid?
expect(@user.errors.full_messages).to include('First name katakana please enter in full-width katakana')
end
it 'last_name_katakanaがカタカナでなければ登録できないこと' do
@user.first_name_katakana = 'tanaka'
@user.valid?
expect(@user.errors.full_messages).to include('First name katakana please enter in full-width katakana')
end
end
end
| true |
436272886c61d9dc67354e4e0afb28f17f59d03c | Ruby | chipcoiga/rubylearn | /gettingmodule.rb | UTF-8 | 773 | 3.515625 | 4 | [] | no_license | #define Perimeter module
module Perimeter
class Array
def initialize
@size = 400
end
end
end
our_array = Perimeter::Array.new
ruby_array = Array.new
#to know about: p/puts/to_s/inspect/print
p our_array
puts our_array
p ruby_array
puts our_array
print our_array
puts our_array
#troll lv max :v
puts "nha toi".split("a")
#module: constant lookup
module RubyMonk
module Parser
class TextParser
def self.parser(str)
str.split(" ")
end
end
end
end
puts RubyMonk::Parser::TextParser.parser("nha toi co mot con dog")
#return topmost level
module Kata
A=5
module Dojo
A=7
class ScopeIn
def push
::A
end
end
end
end
A=10
puts Kata::Dojo::ScopeIn.new.push
#yes the result is 10, so that ::A will return the topmost level value.
| true |
b1be0ff9c8f0a1bbf7ac1ea30f7831f851284ddf | Ruby | jono/sunstone | /test/sunstone/parser_test.rb | UTF-8 | 3,797 | 2.625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
class TestParserModel < Sunstone::Model
belongs_to :test_parser_model
has_many :test_parser_models
define_schema do
integer :testid
boolean :red
datetime :created_at
decimal :rate
string :name
string :nicknames, :array => true
end
end
class Sunstone::ParserTest < Minitest::Test
test '::parse(klass, string)' do
assert_equal true, Sunstone::Parser.parse(TestParserModel, '{"red": true}').red
end
test '::parse(model_instance, string)' do
model = TestParserModel.new
Sunstone::Parser.parse(model, '{"red": true}')
assert_equal true, model.red
end
test '::parse(klass, response)' do
Sunstone.site = "http://test_api_key@testhost.com"
stub_request(:get, "http://testhost.com/test").to_return(:body => '{"red": true}')
model = Sunstone.get('/test') do |response|
Sunstone::Parser.parse(TestParserModel, response)
end
assert_equal true, model.red
end
test "parse boolean attributes" do
parser = Sunstone::Parser.new(TestParserModel)
assert_equal true, parser.parse('{"red": true}').red
parser = Sunstone::Parser.new(TestParserModel)
assert_equal false, parser.parse('{"red": false}').red
end
test "parse date attributes" do
parser = Sunstone::Parser.new(TestParserModel)
assert_equal DateTime.new(2014, 7, 14, 16, 44, 15, '-7'), parser.parse('{"created_at": "2014-07-14T16:44:15-07:00"}').created_at
end
test "parse decimal attributes" do
parser = Sunstone::Parser.new(TestParserModel)
assert_equal 10.254, parser.parse('{"rate": 10.254}').rate
end
test "parse integer attributes" do
parser = Sunstone::Parser.new(TestParserModel)
assert_equal 123654, parser.parse('{"testid": 123654}').testid
end
test "parse string attributes" do
parser = Sunstone::Parser.new(TestParserModel)
assert_equal "my name", parser.parse('{"name": "my name"}').name
end
test "parse array attribute" do
parser = Sunstone::Parser.new(TestParserModel)
assert_equal ["name 1", "name 2"], parser.parse('{"nicknames": ["name 1", "name 2"]}').nicknames
end
test "parse skips over unkown key" do
assert_nothing_raised do
Sunstone::Parser.parse(TestParserModel, '{"other_key": "name 2"}')
Sunstone::Parser.parse(TestParserModel, '{"other_key": ["name 1", "name 2"]}')
end
end
test "parse belong_to association" do
parser = Sunstone::Parser.new(TestParserModel)
assert_equal({
:rate => BigDecimal.new("10.254"),
:created_at => DateTime.new(2014, 7, 14, 16, 44, 15, '-7'),
:testid => 123654,
:name => "my name",
:nicknames => ["name 1", "name 2"]
}, parser.parse('{"test_parser_model": {
"rate": 10.254,
"created_at": "2014-07-14T16:44:15-07:00",
"testid": 123654,
"name": "my name",
"nicknames": ["name 1", "name 2"]
}}').test_parser_model.instance_variable_get(:@attributes))
end
test "parse has_many association" do
parser = Sunstone::Parser.new(TestParserModel)
attrs = {
:rate => BigDecimal.new("10.254"),
:created_at => DateTime.new(2014, 7, 14, 16, 44, 15, '-7'),
:testid => 123654,
:name => "my name",
:nicknames => ["name 1", "name 2"]
}
assert_equal([attrs, attrs], parser.parse('{"test_parser_models": [{
"rate": 10.254,
"created_at": "2014-07-14T16:44:15-07:00",
"testid": 123654,
"name": "my name",
"nicknames": ["name 1", "name 2"]
}, {
"rate": 10.254,
"created_at": "2014-07-14T16:44:15-07:00",
"testid": 123654,
"name": "my name",
"nicknames": ["name 1", "name 2"]
}]}').test_parser_models.map{|m| m.instance_variable_get(:@attributes)})
end
end | true |
f576c935a72cf7f21543d046bbb779a877fd6dac | Ruby | ggk1017/ruby | /labs/lab_buddies.rb | UTF-8 | 673 | 3.578125 | 4 | [] | no_license | require 'pry'
sample = %w{Adrian Derrick Larry Jasmine Raymond Dustin Aaron Chris Zahra Gaurav Audric Avinash Jon Derrick Tim Chang Marc Thomas}
sample_length = sample.length
starting_index = 0
user_prompt = "how many people in a group"
puts user_prompt
group_size = gets.to_i
ending_index = group_size - 1
new_sample = sample.shuffle
while ending_index < sample_length
counter ||= 1
if group_size + ((sample_length -1) - ending_index) < group_size * 2
puts "Here is group #{counter}: #{new_sample[(starting_index..(sample_length-1))].join(' , ')}"
else
puts "Here is group #{counter}: #{new_sample[(starting_index..ending_index)].join(' , ')}"
end
starting_index = ending_index + 1
ending_index += group_size
end
| true |
442df6da4d12d5fe57fd477051a234d96bcb5518 | Ruby | guns/haus | /bin/vimtabdiff | UTF-8 | 536 | 2.59375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
#
# Copyright (c) 2022 Sung Pae <self@sungpae.com>
# Distributed under the MIT license.
# http://www.opensource.org/licenses/mit-license.php
require 'shellwords'
def vimdiffcmd a, b
"edit #{b.shellescape} | diffthis | vsplit #{a.shellescape} | diffthis | tabnew"
end
if ARGV.empty? or ARGV.size.odd?
abort("USAGE: #{File.basename __FILE__} path-a₁ path-a₂ [path-b₁ path-b₂ ...]")
end
exec('vim', *ARGV.each_slice(2).reduce([]) { |args, (a, b)|
args << '-c' << vimdiffcmd(a, b)
}, '-c', 'tabclose | tabfirst')
| true |
14b6aa106b0c5aefba799d3d43b83674b2cee3aa | Ruby | wwkk08/array-CRUD-lab-v-000 | /lib/array_crud.rb | UTF-8 | 570 | 3.703125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def create_an_empty_array
my = []
end
def create_an_array
my = ["1","2","3","5"]
end
def add_element_to_end_of_array(array, element)
array << element
end
def add_element_to_start_of_array(array, element)
array.unshift(element)
end
def remove_element_from_end_of_array(array)
array.pop
end
def remove_element_from_start_of_array(array)
array.shift
end
def retreive_element_from_index(array, index_number)
array[2]
end
def retreive_first_element_from_array(array)
array.first
end
def retreive_last_element_from_array(array)
array.last
end | true |
4ce329033789cc57cf29e0ba29c354703e3aedad | Ruby | stevejc/learn-ruby | /week3ex10.rb | UTF-8 | 85 | 3.296875 | 3 | [] | no_license | collection = [1,2,3,4,5]
sum = 0
collection.each do |add|
sum += add
end
puts sum | true |
15d06c9ffbab24d7365b3d8469592dbe8597639a | Ruby | rlisowski/phrase-ruby | /lib/phrase/api/accounts_api.rb | UTF-8 | 5,524 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'cgi'
module Phrase
class AccountsApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Get a single account
# Get details on a single account.
# @param id [String] ID
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @return [AccountDetails]
def account_show(id, opts = {})
data, _status_code, _headers = account_show_with_http_info(id, opts)
data
end
# Get a single account
# Get details on a single account.
# @param id [String] ID
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @return [Array<(Response<(AccountDetails)>, Integer, Hash)>] Response<(AccountDetails)> data, response status code and response headers
def account_show_with_http_info(id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: AccountsApi.account_show ...'
end
# verify the required parameter 'id' is set
if @api_client.config.client_side_validation && id.nil?
fail ArgumentError, "Missing the required parameter 'id' when calling AccountsApi.account_show"
end
# resource path
local_var_path = '/accounts/{id}'.sub('{' + 'id' + '}', CGI.escape(id.to_s))
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
header_params[:'X-PhraseApp-OTP'] = opts[:'x_phrase_app_otp'] if !opts[:'x_phrase_app_otp'].nil?
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type] || 'AccountDetails'
# auth_names
auth_names = opts[:auth_names] || ['Basic', 'Token']
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: AccountsApi#account_show\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
response = ::Phrase::Response.new(data, headers)
return response, status_code, headers
end
# List accounts
# List all accounts the current user has access to.
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @option opts [Integer] :page Page number
# @option opts [Integer] :per_page allows you to specify a page size up to 100 items, 25 by default
# @return [Array<Account>]
def accounts_list(opts = {})
data, _status_code, _headers = accounts_list_with_http_info(opts)
data
end
# List accounts
# List all accounts the current user has access to.
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @option opts [Integer] :page Page number
# @option opts [Integer] :per_page allows you to specify a page size up to 100 items, 25 by default
# @return [Array<(Response<(Array<Account>)>, Integer, Hash)>] Response<(Array<Account>)> data, response status code and response headers
def accounts_list_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: AccountsApi.accounts_list ...'
end
# resource path
local_var_path = '/accounts'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?
query_params[:'per_page'] = opts[:'per_page'] if !opts[:'per_page'].nil?
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
header_params[:'X-PhraseApp-OTP'] = opts[:'x_phrase_app_otp'] if !opts[:'x_phrase_app_otp'].nil?
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type] || 'Array<Account>'
# auth_names
auth_names = opts[:auth_names] || ['Basic', 'Token']
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: AccountsApi#accounts_list\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
response = ::Phrase::Response.new(data, headers)
return response, status_code, headers
end
end
end
| true |
d596e449add841b2fde84c5c4f7a9c9dba95f25a | Ruby | stefanpenner/rails | /actionpack/lib/action_dispatch/middleware/callbacks.rb | UTF-8 | 1,696 | 2.5625 | 3 | [
"MIT"
] | permissive | module ActionDispatch
# Provide callbacks to be executed before and after the request dispatch.
#
# It also provides a to_prepare callback, which is performed in all requests
# in development by only once in production and notification callback for async
# operations.
#
class Callbacks
include ActiveSupport::Callbacks
define_callbacks :call, :terminator => "result == false", :rescuable => true
define_callbacks :prepare, :scope => :name
# Add a preparation callback. Preparation callbacks are run before every
# request in development mode, and before the first request in production mode.
#
# If a symbol with a block is given, the symbol is used as an identifier.
# That allows to_prepare to be called again with the same identifier to
# replace the existing callback. Passing an identifier is a suggested
# practice if the code adding a preparation block may be reloaded.
def self.to_prepare(*args, &block)
if args.first.is_a?(Symbol) && block_given?
define_method :"__#{args.first}", &block
set_callback(:prepare, :"__#{args.first}")
else
set_callback(:prepare, *args, &block)
end
end
def self.before(*args, &block)
set_callback(:call, :before, *args, &block)
end
def self.after(*args, &block)
set_callback(:call, :after, *args, &block)
end
def initialize(app, prepare_each_request = false)
@app, @prepare_each_request = app, prepare_each_request
run_callbacks(:prepare)
end
def call(env)
run_callbacks(:call) do
run_callbacks(:prepare) if @prepare_each_request
@app.call(env)
end
end
end
end
| true |
72f6a8dc442977570b8f2fa6f84820fb0692a6e6 | Ruby | ffloyd/goldfinger | /app/models/concerns/with_amount.rb | UTF-8 | 341 | 2.65625 | 3 | [] | no_license | module WithAmount
extend ActiveSupport::Concern
def amount
# 1. зачем здесь второй аргумент в #new? Для Integer-конвертации он не нужен. Вообще можно так: BigDecimal(10)
# 2. зачем @amount?
@amount = rounded(BigDecimal.new(amount_cents, 4) / 100)
end
end
| true |
d6a94d6e3ba91274ccf350be6750a0fba5f98363 | Ruby | jk1dd/exercism | /ruby/raindrops/raindrops.rb | UTF-8 | 1,172 | 3.0625 | 3 | [] | no_license | class Raindrops
def self.convert(dropz)
phrase = []
if dropz % 3 == 0
phrase << "Pling"
end
if dropz % 5 == 0
phrase << "Plang"
end
if dropz % 7 == 0
phrase << "Plong"
end
if dropz % 3 != 0 && dropz % 5 != 0 && dropz % 7 != 0
phrase << dropz.to_s
end
phrase.join
end
# def self.convert(dropz)
# phrase = []
# if dropz % 3 == 0 && dropz % 5 == 0 && dropz % 7 == 0 # there's gotta be a better way
# phrase << "PlingPlangPlong"
# elsif dropz % 3 == 0 && dropz % 5 == 0 # there's gotta be a better way
# phrase << "PlingPlang"
# elsif dropz % 3 == 0 && dropz % 7 == 0 # there's gotta be a better way
# phrase << "PlingPlong"
# elsif dropz % 5 == 0 && dropz % 7 == 0 # there's gotta be a better way
# phrase << "PlangPlong"
# elsif dropz % 3 == 0
# phrase << "Pling"
# elsif dropz % 5 == 0
# phrase << "Plang"
# elsif dropz % 7 == 0
# phrase << "Plong"
# else
# phrase = [dropz.to_s]
# end
# phrase.join
# end
end
module BookKeeping
VERSION = 3 # Where the version number matches the one in the test.
end
| true |
059efffccfd0498aaa9da8e9adaea49f5ba8895a | Ruby | rozz120/ttt-6-position-taken-rb-bootcamp-prep-000 | /lib/position_taken.rb | UTF-8 | 157 | 3.28125 | 3 | [] | no_license | def position_taken?(array,index)
if array[index] == " " || array[index] == "" || array[index] == nil
return false
else
return true
end
end | true |
25108a04206b99fb57500b5fa1478cafc7674917 | Ruby | XochitlX/Objetoss | /miercoles/twitter.rb | UTF-8 | 1,673 | 2.953125 | 3 | [] | no_license | #require 'rubygems'
require 'nokogiri'
require 'open-uri'
class TwitterScrapper
def initialize(url)
@url = url
@page = Nokogiri::HTML(open("#{@url}"))
end
def extract_username
profile_name = @page.search(".ProfileHeaderCard-name > a")
profile_name.first.inner_text
end
def extract_tweets
# twits=[]
# twits = @page.search(".tweet")
# twits = twits.pop
# twits.each do |tweet|
# #p text = tweet.css(".js-tweet-text-container > p").inner_text
# p retweet = tweet.search(".js-tweet-text").inner_text
# end
# #Mensaje
# msn = []
# @page.search(".tweet-text").each do |item|
# msn << [item.inner_text]
# #puts item.inner_text
# end
# p msn
# # fecha
# date = []
# @page.search(".js-short-timestamp").children.each do |item|
# date << item.inner_text
# end
# p date
# #ret likes... todos
# all = []
# @page.search(".ProfileTweet-actionCount").children.each do |item|
# all << item.inner_text
# end
# p all = all.join(" ").split(" ")
end
def extract_stats
data=[]
@page.search(".ProfileNav-list > li").each do |datos|
data << datos.inner_text
end
p data.join(" ").split(" ")
# @page.search(".ProfileNav-value").map do |datos|
# data << datos.inner_text
# end
# p "Hola, tengo #{data[3]} likes "
# puts "#{data[0].to_i}tweets"
# puts "#{data[1]} following"
# puts "#{data[2]} followers"
end
end
cantante = TwitterScrapper.new("https://twitter.com/LanaDelRey")
cantante.extract_username
cantante.extract_tweets
cantante.extract_stats
| true |
19bee26e77a0adb32f03b6521448dc8998700156 | Ruby | cakeholeDC/oo-relationships-practice | /app/models/lyft/passenger.rb | UTF-8 | 538 | 3.296875 | 3 | [] | no_license | class Passenger
attr_reader :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def rides
Ride.all.select do |ride|
ride.passenger == self
end
end
def count_rides
self.rides.count
end
def drivers
drivers = self.rides.map do |ride|
ride.driver
end
drivers.uniq
end
def total_distance
self.rides.sum do |ride|
ride.distance
end
end
def self.premium_members
Passenger.all.select do |passenger|
passenger.total_distance > 100
end
end
end | true |
910af0dd9d5e2da0ceec0cee92bfdcaf6f23cae8 | Ruby | enrikacreates/bewd-hw | /hw03/mash_app/mash.rb | UTF-8 | 894 | 2.59375 | 3 | [] | no_license | require 'sinatra'
require 'httparty'
url = "http://mashable.com/stories.json"
results = HTTParty.get(url)
# page1
get '/' do
@stories = results
erb :home
end
# page2
get '/sort' do
@feed_pick = params['feed']
@articles = results[@feed_pick]
erb :sort
end
# page3
get '/results' do
@feed_pick = params['feed']
@articles = results[@feed_pick]
@sorter = params['sorter']
if @sorter == 'title'
@sorted_articles = @articles.sort_by { |hsh| hsh['title'] }
erb :title_results
elsif @sorter == 'date'
@sorted_articles = @articles.sort_by { |hsh| hsh['post_date_rfc'] }
@sorted_articles = @sorted_articles.reverse
erb :date_results
elsif @sorter == 'author'
@sorted_articles = @articles.sort_by { |hsh| hsh['author'] }
erb :author_results
end
end
| true |
9f0b0f87df4cb199ddd3f2daa614d7b1e052dbd4 | Ruby | montehoover/ruby-rio-grande | /starter-code/spec/digitalitem_spec.rb | UTF-8 | 1,890 | 3.1875 | 3 | [] | no_license | require_relative 'spec_helper'
require_relative '../lib/DigitalItem'
describe DigitalItem do
before(:context) do
#initialize item
@digital_item = DigitalItem.new "DigItem title", 6.99
end
#check initialization
describe "initialization" do
#check that it is an extended from Item
it "extend from the Item class" do
expect(DigitalItem).to be < Item
end
#check that it is an instance of Cd
it "is an instance of the DigitalItem class" do
expect(@digital_item).to be_instance_of(DigitalItem)
end
end
describe "Accessors" do
#check getters and setters
it "should be able to get and set name" do
@digital_item.name = "new digitem Title"
expect(@digital_item.name).to eq("new digitem Title")
end
it "should be able to get and set price" do
@digital_item.price = 10.99
expect(@digital_item.price).to eq(10.99)
end
it "should have weight attribute set to -1 to show there is no weight" do
expect(@digital_item.weight).to eq(-1)
end
end
describe "Methods" do
it "quanity should always be 1" do
expect(@digital_item.quantity).to eq(1)
end
it "should not decrease quanity when sold" do
result = @digital_item.sell 3
expect(result).to eq(true)
expect(@digital_item.quantity).to eq(1)
expect(@digital_item.quantity).not_to be < 1
end
it "should not increase quanity when stocked" do
result = @digital_item.stock(10)
expect(result).to eq(true)
expect(@digital_item.quantity).to eq(1)
end
it "should not increase quanity when returned" do
result = @digital_item.return(10)
expect(result).to eq(true)
expect(@digital_item.quantity).to eq(1)
end
it "should calculate ship_price as false" do
price = @digital_item.ship_price
expect(price).to eq(false)
end
end
end
| true |
32ee9252985f516f387f08fdeadd2f0bb63f47b0 | Ruby | evilbunnyrabbits/programming-univbasics-4-simple-looping-lab-nyc01-seng-ft-062220 | /lib/simple_loops.rb | UTF-8 | 525 | 4.0625 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Write your methods here
def loop_message_five_times(message)
count = 0
while count < 5 do
puts message
count += 1
end
end
def loop_message_n_times(message, number)
count = 0
while count < number do
puts message
count += 1
end
end
def output_array(array)
index = 0
while index <= array.length do
puts array[index]
index += 1
end
end
def return_string_array(array)
new_array = []
for item in array do
item = item.to_s
new_array.push(item)
end
return new_array
end | true |
cbe6d8fa33f6b1f76413cbc95057227046da840a | Ruby | BJSherman80/Adopt_dont_shop_2008 | /spec/features/applications/show_spec.rb | UTF-8 | 4,767 | 2.578125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe 'On an Applications show page the user', type: :feature do
before(:each) do
@user1 = User.create!(name: 'Dr. Evil',
address: '56774 FLower Ave.',
city: 'Smallville',
state: 'Alaska',
zip: 87645)
@shelter1 = Shelter.create(name: "Brett's Pet Palace",
address: '456 Sesame Ave',
city: 'Denver',
state: 'CO',
zip: 80222)
@pet1 = @shelter1.pets.create!(name: 'Vernon',
age: 18,
sex: 'male',
image: 'vernon.png')
@application = @user1.applications.create!(name_of_user: 'Dr. Evil',
address: '56774 FLower Ave.',
description: 'I love this hairless cat',
status: 'In Progress')
@application.pets << @pet1
end
it 'can see application info' do
visit "applications/#{@application.id}"
expect(page).to have_content(@application.name_of_user)
expect(page).to have_content(@application.address)
expect(page).to have_content(@application.description)
expect(page).to have_content(@pet1.name)
expect(page).to have_content(@application.status)
end
it 'search for a pet to add to the application' do
pet2 = @shelter1.pets.create!(name: 'Bob',
age: 12,
sex: 'male')
visit "/applications/#{@application.id}"
expect(page).to have_content('In Progress')
fill_in :search, with: 'Bob'
click_button 'Search'
expect(current_path).to eq("/applications/#{@application.id}")
expect(page).to have_content(pet2.name)
click_on "Adopt This Pet"
expect(current_path).to eq("/applications/#{@application.id}")
within(".show") do
expect(page).to have_content(pet2.name)
end
end
it 'can submit an application' do
pet2 = @shelter1.pets.create!(name: 'Bob',
age: 12,
sex: 'male')
visit "/applications/#{@application.id}"
expect(page).to_not have_content("Submit")
fill_in :search, with: 'Bob'
click_button 'Search'
expect(current_path).to eq("/applications/#{@application.id}")
expect(page).to have_content(pet2.name)
click_on 'Adopt This Pet'
expect(current_path).to eq("/applications/#{@application.id}")
fill_in :description, with: "I'll give you on billlllion dollars"
click_on 'Submit Application'
expect(current_path).to eq("/applications/#{@application.id}")
expect(page).to have_content('Pending')
expect(page).to_not have_content('Search for a pet:')
end
it 'will not see submit if no pets have been added' do
application2 = @user1.applications.create!(name_of_user: 'Dr. Evil',
address: '56774 FLower Ave.',
description: 'I love this hairless cat',
status: 'In Progress')
visit "/applications/#{@application.id}"
expect(page).to_not have_content('Submit Application')
end
it "will show a flash message if description isn't filled out" do
pet2 = @shelter1.pets.create!(name: 'Bob',
age: 12,
sex: 'male')
visit "/applications/#{@application.id}"
expect(page).to_not have_content("Submit")
fill_in :search, with: 'Bob'
click_button 'Search'
expect(current_path).to eq("/applications/#{@application.id}")
expect(page).to have_content(pet2.name)
click_on 'Adopt This Pet'
expect(current_path).to eq("/applications/#{@application.id}")
fill_in :description, with: ""
click_on 'Submit Application'
expect(current_path).to eq("/applications/#{@application.id}")
expect(page).to have_content('Please enter a description.')
end
it 'can search using a partial input' do
pet2 = @shelter1.pets.create!(name: 'Bob',
age: 12,
sex: 'male')
pet3 = @shelter1.pets.create!(name: 'Betsy',
age: 2,
sex: 'male')
visit "/applications/#{@application.id}"
expect(page).to_not have_content("Submit")
fill_in :search, with: 'b'
click_button 'Search'
expect(current_path).to eq("/applications/#{@application.id}")
expect(page).to have_content(pet2.name)
expect(page).to have_content(pet3.name)
end
end
| true |
879db4b1e1378870678463b8c5a762057e9387d7 | Ruby | janicejiang/programming-exercise | /06-interger-positive.rb | UTF-8 | 353 | 4.40625 | 4 | [] | no_license | # 题目: 输入一个数字 x,请判断是否正数、零或负数,以及是不是偶数
print "请输入一个整数,然后按 Enter: "
x = gets.to_i
if x % 2 == 0
puts "这个数是偶数"
else
puts "这个数是奇数"
end
if x < 0
puts "这个数是负数"
elsif x == 0
puts "这个数是零"
else
puts "这个数是正数"
end
| true |
529819638a43a67744e8bc0ed25e62abbeb37e45 | Ruby | entropie/ralpha | /lib/ralpha/pods.rb | UTF-8 | 2,196 | 2.546875 | 3 | [] | no_license | #
#
# Author: Michael 'entropie' Trommer <mictro@gmail.com>
#
module Ralpha
class Pods < Array
attr_reader :query
def subpods
self.map{|pod| pod.subpods }.flatten
end
def initialize(query)
@query = query
super()
end
end
class SubPods < Array
attr_reader :pod
def initialize(pod)
@pod = pod
super()
end
end
class SubPod
attr_reader :title, :text, :pod, :xml
def initialize(title, xml, ppod)
@pod = ppod
@title = title
@xml = xml
@text = xml.xpath("plaintext").text
end
def inspect
"<Subpod @parent='#{pod.title}' @title='#{title}' '#{text}'>"
end
def image
unless @image
if img = xml.xpath("img").first
@image ||= Image.new(img)
end
end
@image
end
def has_image?
not image.nil?
end
alias :"img?" :"has_image?"
def to_s
"#{title}: #{text}"
end
end
class Pod
include Enumerable
ValuesList = :title, :position, :scanner, :position, :error
attr_reader *ValuesList
attr_reader :xml, :query
def subpods
@subpods ||= SubPods.new(self)
end
def initialize(title, xml, query)
@title = title
@query = query
@xml = xml
xml.xpath("subpod").each do |spod|
subpods << SubPod.new(spod["title"], spod, self)
end
end
def inspect
"<Pod Query='#{query.query}' Title='#{title}' Subpods=#{size}>"
end
def states
unless @states
@states = States.new(self)
xml.xpath("states").children.grep(Nokogiri::XML::Element).map{|state|
@states << State.new(query, state["name"], state["input"])
}
end
@states
end
def has_states?
not states.empty?
end
def each(&blk)
subpods.each(&blk)
end
def size
subpods.size
end
alias :length :size
def [](int)
subpods[int]
end
def last
subpods.last
end
def first
subpods.first
end
end
end
=begin
Local Variables:
mode:ruby
fill-column:70
indent-tabs-mode:nil
ruby-indent-level:2
End:
=end
| true |
65f55a6f777ccaf3daba9d86268daa0d4b9ef966 | Ruby | grantcottle/kovid | /lib/kovid/cli.rb | UTF-8 | 1,544 | 2.921875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'thor'
require 'kovid'
module Kovid
class CLI < Thor
FULL_FLAG = %w[-f --full].freeze
desc 'define', 'Defines COVID-19'
def define
puts Kovid.whatis
end
desc 'check COUNTRY or check "COUNTRY NAME"', 'Returns reported data on provided country. eg: "kovid check "hong kong".'
method_option :full, aliases: '-f'
def check(name)
if options[:full]
puts Kovid.country_full(name)
else
puts Kovid.country(name)
end
end
desc 'country COUNTRY or country "COUNTRY NAME"', 'Returns reported data on provided country. eg: "kovid country "hong kong".'
alias country check
desc 'state STATE', 'Return reported data on provided state.'
def state(state)
puts Kovid.state(state)
end
desc 'compare COUNTRY COUNTRY', 'Returns full comparison table for given countries. Accepts multiple countries.'
def compare(*name)
if FULL_FLAG.include?(name.fetch(-1))
puts Kovid.country_comparison_full(name[0..-2])
else
puts Kovid.country_comparison(name)
end
end
desc 'cases', 'Returns total number of cases, deaths and recoveries.'
def cases
puts Kovid.cases
end
desc 'history COUNTRY or history COUNTRY N', 'Return history of incidents of COUNTRY (in the last N days)'
def history(*params)
if params.size == 2
puts Kovid.history(params.first, params.last)
else
puts Kovid.history(params.first, nil)
end
end
end
end
| true |
bcf7ac2bf6d6fb4aff742a528bade06d025c4998 | Ruby | ashes-ashes/W4D3 | /Chess/piece_types/steppable.rb | UTF-8 | 253 | 2.578125 | 3 | [] | no_license | module Steppable
def moves
new_moves = move_diffs.map do |move|
[move[0] + pos[0], move[1] + pos[1]]
end
new_moves.select { |step| board.valid_pos?(step) && board[step].color != color }
end
private
def move_diffs; end
end | true |
1660e357f1a8fe4f83c0ea03a6fab4143d667430 | Ruby | rbosse/cloudfoundry-buildpack-java | /spec/language_pack/xml_wrapper_spec.rb | UTF-8 | 1,985 | 2.890625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"GPL-2.0-only",
"Apache-2.0",
"Ruby"
] | permissive | require 'spec_helper'
describe XmlWrapper do
let(:xml) { xml = XmlWrapper.new("<doc><name>Tom</name><job>Programmer</job><name>Agnes</name></doc>") }
it "finds a node" do
expect(xml.first("/doc/name").text).to eq "Tom"
expect(xml.first("/doc/job").text).to eq "Programmer"
end
it "returns empty arrays when it doesn't find anything" do
expect(xml.xpath("/not_here")).to eq([])
end
it "returns the root node" do
expect(xml.root.name).to eq "doc"
end
it "returns its string representation" do
expect(xml.to_s).to eq "<doc><name>Tom</name><job>Programmer</job><name>Agnes</name></doc>"
end
it "adds a node" do
xml.add_node(path: "/doc", name: "age", value: "15")
expect(xml.first("/doc/age").text).to eq "15"
end
it "adds an empty node" do
xml.add_node(path: "/doc", name: "nothing")
expect(xml.first("/doc/nothing")).to_not be_nil
end
it "updates a node's content" do
xml.update_node_text("/doc/name") { |text| "#{text}_1" }
expect(xml.xpath("/doc/name").first.text).to eq("Tom_1")
expect(xml.xpath("/doc/name")[1].text).to eq("Agnes_1")
end
describe "complicated tree" do
let(:xml) { xml = XmlWrapper.new("<doc><name><first>Tom</first><last>Mayer</last></name><job>Programmer</job><name><first>Agnes</first><last>Deliboard</last></name></doc>") }
let(:tom) { tom = xml.first("//doc/name") }
it "finds a node relative to another node" do
toms_name = xml.xpath("first", tom)
expect(toms_name.size).to eq(1)
expect(toms_name[0].text).to eq("Tom")
end
it "updates the right node" do
xml.update_node_text("first", tom) { |name| "Barry" }
expect(xml.xpath("/doc/name/first")[0].text).to eq "Barry"
expect(xml.xpath("/doc/name/first")[1].text).to eq "Agnes"
end
it "adds a node" do
xml.add_node(name: "middle", value: "Jesus", relative_node: tom)
expect(xml.xpath("/doc/name/middle")[0].text).to eq "Jesus"
end
end
end
| true |
1961d04276b3ec8c1b59cc4c7ed54215b0af0e61 | Ruby | evrone/casbin-ruby | /lib/casbin-ruby/model/policy.rb | UTF-8 | 4,200 | 2.5625 | 3 | [] | no_license | # frozen_string_literal: true
require 'logger'
module Casbin
module Model
class Policy
attr_reader :model, :logger
def initialize(logger: Logger.new($stdout))
@model = {}
@logger = logger
end
# initializes the roles in RBAC.
def build_role_links(rm_map)
return unless model.key? 'g'
model['g'].each do |ptype, ast|
rm = rm_map[ptype]
ast.build_role_links(rm)
end
end
# Log using info
def print_policy
logger.info 'Policy:'
%w[p g].each do |sec|
next unless model.key? sec
model[sec].each do |key, ast|
logger.info "#{key} : #{ast.value} : #{ast.policy}"
end
end
end
# clears all current policy.
def clear_policy
%w[p g].each do |sec|
next unless model.key? sec
model[sec].each do |key, _ast|
model[sec][key].policy = []
end
end
end
# adds a policy rule to the model.
def add_policy(sec, ptype, rule)
return false if has_policy(sec, ptype, rule)
model[sec][ptype].policy << rule
true
end
# adds policy rules to the model.
def add_policies(sec, ptype, rules)
rules.each do |rule|
return false if has_policy(sec, ptype, rule)
end
model[sec][ptype].policy += rules
true
end
# update a policy rule from the model.
def update_policy(sec, ptype, old_rule, new_rule)
return false unless has_policy(sec, ptype, old_rule)
remove_policy(sec, ptype, old_rule) && add_policy(sec, ptype, new_rule)
end
# update policy rules from the model.
def update_policies(sec, ptype, old_rules, new_rules)
old_rules.each do |rule|
return false unless has_policy(sec, ptype, rule)
end
remove_policies(sec, ptype, old_rules) && add_policies(sec, ptype, new_rules)
end
# gets all rules in a policy.
def get_policy(sec, ptype)
model[sec][ptype].policy
end
# determines whether a model has the specified policy rule.
def has_policy(sec, ptype, rule)
model.key?(sec) && model[sec].key?(ptype) && model[sec][ptype].policy.include?(rule)
end
# removes a policy rule from the model.
def remove_policy(sec, ptype, rule)
return false unless has_policy(sec, ptype, rule)
model[sec][ptype].policy.delete(rule)
true
end
# removes policy rules from the model.
def remove_policies(sec, ptype, rules)
rules.each do |rule|
return false unless has_policy(sec, ptype, rule)
end
model[sec][ptype].policy.reject! { |rule| rules.include? rule }
true
end
# removes policy rules based on field filters from the model.
def remove_filtered_policy(sec, ptype, field_index, *field_values)
return false unless model.key?(sec) && model[sec].include?(ptype)
state = { tmp: [], res: false }
model[sec][ptype].policy.each do |rule|
state = filtered_rule(state, rule, field_values, field_index)
end
model[sec][ptype].policy = state[:tmp]
state[:res]
end
# gets all values for a field for all rules in a policy, duplicated values are removed.
def get_values_for_field_in_policy(sec, ptype, field_index)
values = []
return values unless model.keys.include?(sec)
return values unless model[sec].include?(ptype)
model[sec][ptype].policy.each do |rule|
value = rule[field_index]
values << value if values.include?(value)
end
values
end
private
def filtered_rule(state, rule, field_values, field_index)
matched = true
field_values.each_with_index do |field_value, index|
next matched = false if field_value != '' && field_value != rule[field_index + index]
if matched
state[:res] = true
else
state[:tmp] << rule
end
end
state
end
end
end
end
| true |
21dce1795105e46c9da8c449d8c97e55a6f4e6d6 | Ruby | jayywolff/pokedex | /app/deserializers/pokemon_deserializer.rb | UTF-8 | 1,023 | 2.71875 | 3 | [] | no_license | # frozen_string_literal: true
class PokemonDeserializer < BaseDeserializer
def deserialize(pokemon_species = nil)
if pokemon_species.present?
build_pokemon_with_species_attributes(pokemon_species)
else
build_pokemon
end
end
def required_keys
[:id, :name, :height, :weight, :sprites, :types]
end
private
def build_pokemon
Pokemon.find_or_initialize_by(id: data[:id]) do |pokemon|
pokemon.name = data[:name].titleize
pokemon.height = data[:height]
pokemon.weight = data[:weight]
pokemon.sprite = data[:sprites][:front_default]
pokemon.types << deserialize_types
end
end
def build_pokemon_with_species_attributes(pokemon_species)
build_pokemon.tap do |pokemon|
pokemon.attributes = pokemon_species.attributes.compact
end
end
def deserialize_types
data[:types].map do |type|
key = type[:type][:name].titleize
types[key]&.first
end
end
def types
@types ||= Type.all&.group_by(&:name)
end
end
| true |
7dfa42d24d61aa3767cc51e6e610111a5d93a20e | Ruby | lbluefishl/hangman | /lib/hangman.rb | UTF-8 | 3,244 | 3.828125 | 4 | [] | no_license |
$file_data = File.readlines("5desk.txt", chomp: true)
require 'json'
class Hangman
def initialize
@guesses = 7
@used_letters = []
@random_word = $file_data.sample.split("")
@hidden_word = " _" * @random_word.length
@save_file = ""
end
def variables
{
guesses: @guesses,
used_letters: @used_letters,
random_word: @random_word,
hidden_word: @hidden_word,
save_file: @save_file
}
end
def start_game
puts "Welcome to hangman!"
sleep 1
puts "Would you like to load a save state?"
puts "y/n"
@yes_or_no = gets.chomp
load_game?
sleep 2
puts "Enter 'save' anytime during the game to save your progress."
sleep 1
puts "Here is your random word."
puts @hidden_word
sleep 1
good_guess?
end
def load_game?
if @yes_or_no == 'y'
puts "What was the name of your save file? Type it without the extension."
puts Dir.entries("saves")
filename = gets.chomp + '.txt'
if File.file?('saves/' + filename)
values = JSON.parse(File.read("saves/#{filename}"))
@guesses = values["guesses"]
@used_letters = values["used_letters"]
@random_word = values["random_word"]
@hidden_word = values["hidden_word"]
puts @hidden_word
good_guess?
elsif filename == "new"
start_game
else
puts "Filename does not exist."
puts "Try again or start a new game by entering 'new'."
load_game?
end
elsif yes_or_no == 'n'
else
puts "invalid selection...please type 'y' or 'n'"
load_game?
end
end
def good_guess?
sleep 1
puts "#{@guesses} lives remaining."
puts "Used letters: " + @used_letters.join(" ")
print "Enter a letter: "
@letter = gets.chomp.downcase.gsub " ", ""
if @letter.match(/[a-z]/) && !(@used_letters.include?(@letter)) && @letter.size == 1
@used_letters.push(@letter)
check_guess
elsif @letter == 'save'
save_game
else
puts "Invalid letter. Make sure it is not one you already used!\n"
sleep 2
good_guess?
end
end
def check_guess
if @random_word.include? @letter
puts "\nNice guess"
indexes = @random_word.each_index.select {|i| @random_word[i] == @letter}
indexes.each {|i| @hidden_word[2*i+1] = @letter}
else
sleep 1
@guesses -= 1
lose if @guesses == 0
puts "\nTry again."
sleep 1
end
puts @hidden_word
win if @random_word - @used_letters == []
good_guess?
end
def save_game
puts "Enter a valid name for the save file. "
save_name = gets.chomp
if save_name.match(/[a-zA-Z\d]/) && save_name.size < 10
@save_file = save_name
values = variables.to_json
puts "Saving file..."
Dir.mkdir('saves') unless File.exists?('saves')
File.open("saves/#{@save_file}.txt", "w") {|f| f.write(values)}
else
sleep 1
save_game
end
end
def win
puts "You won with #{@guesses} lives remaining."
exit
end
def lose
sleep 1
puts "You ran out of lives."
puts "The word was #{@random_word.join}"
exit
end
end
test = Hangman.new
test.start_game
| true |
7684a316697c5642c68126ab356e28884bb0326a | Ruby | kaoritorikai23/genba_rails | /1_5_2_2.rb | UTF-8 | 178 | 2.90625 | 3 | [] | no_license | module Chatting
def chat
"hello"
end
end
module Weeping
def weep
"しくしく"
end
end
class Human
include Chatting
include Weeping
end | true |
b97697163e211b5857504e15ef9033d05c2d566e | Ruby | decal/zap-attack | /bin/header-names | UTF-8 | 479 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env ruby
# coding: utf-8
#
# Form a unique list of case-insensitive names from HTTP response header fields
#
require 'zap_attack'
include ZapAttack, ZapAttack::API, ZapAttack::Data
headers = Params.new
headers.select! do |h|
h['type'].eql?('header')
end
names = []
headers.each do |h|
aname = h['name']
lname = aname.downcase
namez = names.select { |x| x.downcase.eql?(lname) }
names.concat( [ aname ] ) if namez.size.zero?
end
puts names
exit 0
| true |
f0ee2da15c386443140daf41fcae6000ada4be33 | Ruby | PeterCamilleri/fOOrth | /lib/fOOrth/compiler/source.rb | UTF-8 | 1,403 | 2.890625 | 3 | [
"MIT"
] | permissive | # coding: utf-8
require_relative 'source/read_point'
#* compiler/source.rb - The abstract source class shared by many code sources.
module XfOOrth
#The Source class used to contain code common to most sources.
class AbstractSource
include ReadPoint
#Initialize the abstract base class.
def initialize
reset_read_point
@eof = false
@peek_buffer = nil
end
#Close the source.
def close
@eoln = true
@eof = true
@peek_buffer = nil
end
#Get the next character of input data
#<br>Returns:
#* The next character or nil if none are available.
def get
return nil if (@eof && !@peek_buffer)
@peek_buffer || read do
begin
@read_step.next.rstrip
rescue StopIteration
@eof = true
nil
end
end
ensure
@peek_buffer = nil
end
#Peek ahead by one character.
#<br>Returns:
#* A peek at next character or nil if none are available.
def peek
@peek_buffer ||= get unless eoln?
end
#Has the source reached the end of the available data?
#<br>Returns:
#* True if the end is reached else false.
def eof?
@eof
end
end
end
require_relative 'source/string_source'
require_relative 'source/file_source'
require_relative 'source/console'
| true |
19bd8f000c937fff3c74dce1beb499eb28e61828 | Ruby | bharris62/Exercises_easy1 | /e2.rb | UTF-8 | 685 | 4.59375 | 5 | [] | no_license | # Write a method that takes one argument in the form of an integer or a float; this argument may be either positive
# or negative. This method should check if a number is odd, returning true if its absolute value is odd. Floats should
# only return true if the number is equal to its integer part and the integer is odd.
# Keep in mind that you're not allowed to use #odd? or #even? in your solution.
def is_odd?(num)
if num % 2 != 0 && num == num.to_i
return true
else
return false
end
end
puts is_odd?(2) # => false
puts is_odd?(5) # => true
puts is_odd?(-17) # => true
puts is_odd?(-8) # => false
puts is_odd?(7.1) # => false
puts is_odd?(-5.0) # => true | true |
e9e93326a25eb2c74b5c152ea8ec21ebce58b058 | Ruby | michaelrizzo2/Ruby-Development | /7loops.rb | UTF-8 | 555 | 3.578125 | 4 | [] | no_license | #!/usr/bin/ruby
#This will show all of the alternative while sytaxes in ruby(i hope)
$hours_asleep=0
def tired
if $hours_asleep>=8 then
$hours_asleep=0
return false
else
$hours_asleep+=1
return true
end
end
def snore
puts "Snore"
end
def sleep
puts "z"*$hours_asleep
end
#This is a single line while loop
#while tired do sleep end
#This is a multiline while loop
#while tired
# sleep
#end
#sleep while tired #This is a single line while modifier
# do while modifier( while loop runs at least once)
begin
sleep
snore
end while tired
| true |
203dd0dc067b03a7b745ec8b7a96d3b1080024cd | Ruby | jadamduff/sb_bracketeer | /lib/sb_bracketeer/team.rb | UTF-8 | 634 | 3.375 | 3 | [
"MIT"
] | permissive | # Bracket -> Round -> Game -> TEAM
class SbBracketeer::Team
attr_accessor :name, :score, :roster, :game
def initialize(name, score, game)
@name = name
@score = score
@game = game # Creates a has_one relationship to the Game.
# Continues calling parent objects until the Bracket is reached.
# => Only adds itself to the Bracket's @teams array if the Team's name isn't already included in the array.
# => This is necessary for the Bracket to be able to check whether user input is a valid team.
self.game.round.bracket.teams << self.name if !self.game.round.bracket.teams.include?(self.name)
end
end
| true |
5acc8607cac2c24629c360d5e41d4a7cb981d5e4 | Ruby | ma2gedev/chrono_logger | /lib/chrono_logger.rb | UTF-8 | 4,000 | 2.828125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require "chrono_logger/version"
require 'logger'
require 'pathname'
# A lock-free logger with timebased file rotation.
class ChronoLogger < Logger
# @param logdev [String, IO] `Time#strftime` formatted filename (String) or IO object (typically STDOUT, STDERR, or an open file).
# @example
#
# ChronoLogger.new('/log/production.log.%Y%m%d')
# Time.now.strftime('%F') => "2015-01-29"
# File.exist?('/log/production.log.20150129') => true
#
def initialize(logdev)
@progname = nil
@level = DEBUG
@default_formatter = ::Logger::Formatter.new
@formatter = nil
@logdev = nil
if logdev
@logdev = TimeBasedLogDevice.new(logdev)
end
end
module Period
DAILY = 1
SiD = 24 * 60 * 60
def determine_period(format)
case format
when /%[SscXrT]/ then nil # seconds
when /%[MR]/ then nil # minutes
when /%[HklI]/ then nil # hours
when /%[dejDFvx]/ then DAILY
else nil
end
end
def next_start_period(now, period)
case period
when DAILY
Time.mktime(now.year, now.month, now.mday) + SiD
else
nil
end
end
end
class TimeBasedLogDevice < LogDevice
include Period
DELAY_SECOND_TO_CLOSE_FILE = 5
def initialize(log = nil, opt = {})
@dev = @filename = @pattern = nil
if defined?(LogDeviceMutex) # Ruby < 2.3
@mutex = LogDeviceMutex.new
else
mon_initialize
@mutex = self
end
if log.respond_to?(:write) and log.respond_to?(:close)
@dev = log
else
@pattern = log
@period = determine_period(@pattern)
now = Time.now
@filename = now.strftime(@pattern)
@next_start_period = next_start_period(now, @period)
@dev = open_logfile(@filename)
@dev.sync = true
end
end
def write(message)
check_and_shift_log if @pattern
@dev.write(message)
rescue
warn("log writing failed. #{$!}")
end
def close
@dev.close rescue nil
end
private
def open_logfile(filename)
begin
open(filename, (File::WRONLY | File::APPEND))
rescue Errno::ENOENT
create_logfile(filename)
end
end
def create_logfile(filename)
begin
Pathname(filename).dirname.mkpath
logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT | File::EXCL))
logdev.sync = true
rescue Errno::EEXIST
# file is created by another process
logdev = open_logfile(filename)
logdev.sync = true
end
logdev
end
def check_and_shift_log
if next_period?(Time.now)
now = Time.now
new_filename = now.strftime(@pattern)
next_start_period = next_start_period(now, @period)
shift_log(new_filename)
@filename = new_filename
@next_start_period = next_start_period
end
end
def next_period?(now)
if @period
@next_start_period <= now
else
Time.now.strftime(@pattern) != @filename
end
end
def shift_log(filename)
begin
@mutex.synchronize do
tmp_dev = @dev
@dev = create_logfile(filename)
Thread.new(tmp_dev) do |tmp_dev|
sleep DELAY_SECOND_TO_CLOSE_FILE
tmp_dev.close rescue nil
end
end
rescue Exception => ignored
warn("log shifting failed. #{ignored}")
end
end
end
# EXPERIMENTAL: this formatter faster than default `Logger::Formatter`
class Formatter < ::Logger::Formatter
DATETIME_SPRINTF_FORMAT = "%04d-%02d-%02dT%02d:%02d:%02d.%06d ".freeze
# same as `Logger::Formatter#format_datetime`'s default behaviour
def format_datetime(t)
DATETIME_SPRINTF_FORMAT % [t.year, t.month, t.day, t.hour, t.min, t.sec, t.tv_usec]
end
def datetime_format=(datetime_format)
raise 'do not support'
end
end
end
| true |
f1fed85fd3f553188d0b7ca6ae4fa8146e332adf | Ruby | TimCummings/launch_school | /109-ruby_and_general_programming/easy_1.rb | UTF-8 | 3,104 | 4.25 | 4 | [] | no_license | # easy_1.rb
# # Repeat Yourself
# def repeat(string, number)
# number.times { puts string }
# end
# # repeat("hello", 3)
# # Odd
# def is_odd?(num)
# num % 2 != 0 && num == num.to_i
# end
# # better solution (provided):
# num % 2 == 1
# puts is_odd?(2) # => false
# puts is_odd?(5) # => true
# puts is_odd?(-17) # => true
# puts is_odd?(-8) # => false
# puts is_odd?(7.1) # => false
# puts is_odd?(-5.0) # => true
# # List of Digits
# def digit_list(num)
# num.to_s.chars.map { |digit| digit.to_i }
# end
# puts digit_list(12345) == [1, 2, 3, 4, 5]
# puts digit_list(7) == [7]
# puts digit_list(375290) == [3, 7, 5, 2, 9, 0]
# puts digit_list(444) == [4, 4, 4]
# # How Many?
# def count_occurrences(arr)
# occurrences = Hash.new
# arr.each do |item|
# if occurrences[item] == nil
# occurrences[item] = 1
# else
# occurrences[item] += 1
# end
# end
# occurrences.each { |key, value| puts "#{key} => #{value}" }
# end
# vehicles = ['car', 'car', 'truck', 'car', 'SUV', 'truck', 'motorcycle', 'motorcycle', 'car', 'truck']
# count_occurrences(vehicles)
# # Reverse It (Part 1)
# def reverse_sentence(sentence)
# words = sentence.split
# ecnetnes = []
# words.each { |word| ecnetnes.unshift(word) }
# ecnetnes.join(' ')
# end
#
# # better solution (provided):
# def reverse_sentence(string)
# string.split.reverse.join(' ')
# end
#
# puts reverse_sentence('') == ''
# puts reverse_sentence('Hello World') == 'World Hello'
# puts reverse_sentence('Reverse these words') == 'words these Reverse'
# # Reverse It (Part 2)
# def reverse_words(string)
# string = string.split.map do |word|
# if word.size > 4
# word.reverse
# else
# word
# end
# end
#
# string.join(' ')
# end
#
# puts reverse_words('Professional') # => lanoisseforP
# puts reverse_words('Walk around the block') # => Walk dnuora the kcolb
# puts reverse_words('Launch School') # => hcnuaL loohcS
# # Stringy Strings
# def stringy(num, first = 1)
# if first == 0
# remainder = 1
# else
# remainder = 0
# end
#
# string = ""
# num.times { |x| string.concat x % 2 == remainder ? '1' : '0' }
# string
# end
#
# puts stringy(6) == '101010'
# puts stringy(9) == '101010101'
# puts stringy(4) == '1010'
# puts stringy(7) == '1010101'
#
# puts stringy(6, 0) == '010101'
# puts stringy(9, 0) == '010101010'
# puts stringy(4, 0) == '0101'
# puts stringy(7, 0) == '0101010'
# # Array Average
# def average(numbers)
# sum = 0
# numbers.each { |num| sum += num }
# sum.to_f / numbers.size
# end
#
# puts average([1, 5, 87, 45, 8, 8]) == 25
# puts average([9, 47, 23, 95, 16, 52]) == 40
# # Sum of Digits
# def sum(num)
# digits = num.to_s.chars
# sum = 0
# digits.each { |x| sum += x.to_i }
# sum
# end
#
# puts sum(23) == 5
# puts sum(496) == 19
# puts sum(123_456_789) == 45
# What's my Bonus?
def calculate_bonus(salary, bonus)
bonus ? salary / 2 : 0
end
puts calculate_bonus(2800, true) == 1400
puts calculate_bonus(1000, false) == 0
puts calculate_bonus(50000, true) == 25000
| true |
86c2bb7220345b715f4d5eef4752f4ea62e54ce5 | Ruby | voltagead/OpenSplitTime | /app/services/live_time_row_importer.rb | UTF-8 | 3,500 | 2.609375 | 3 | [
"MIT"
] | permissive | class LiveTimeRowImporter
def self.import(args)
importer = new(args)
importer.import
importer.returned_rows
end
def initialize(args)
ArgsValidator.validate(params: args,
required: [:event, :time_rows],
exclusive: [:event, :time_rows],
class: self.class)
@event = args[:event]
@time_rows = args[:time_rows].map(&:last) # time_row.first is a unneeded id; time_row.last contains all needed data
@times_container ||= SegmentTimesContainer.new(calc_model: :stats)
@unsaved_rows = []
@saved_split_times = []
end
def import
time_rows.each do |time_row|
effort_data = LiveEffortData.new(event: event,
params: time_row,
ordered_splits: ordered_splits,
times_container: times_container)
# If just one row was submitted, assume the user has noticed if data status is bad or questionable,
# or if times will be overwritten, so call bulk_create_or_update with force option. If more than one
# row was submitted, call bulk_create_or_update without force option.
if effort_data.valid? && (effort_data.clean? || force_option?) && create_or_update_times(effort_data)
EffortOffsetTimeAdjuster.adjust(effort: effort_data.effort)
NotifyFollowersJob.perform_later(participant_id: effort_data.participant_id,
split_time_ids: saved_split_times.map(&:id),
multi_lap: event.multiple_laps?)
end
EffortDataStatusSetter.set_data_status(effort: effort_data.effort, times_container: times_container)
end
end
def returned_rows
{returned_rows: unsaved_rows}.camelize_keys
end
private
EXTRACTABLE_ATTRIBUTES = %w(time_from_start data_status pacer remarks stopped_here)
attr_reader :event, :time_rows, :times_container
attr_accessor :unsaved_rows, :saved_split_times
# Returns true if all available times (in or out or both) are created/updated.
# Returns false if any create/update is attempted but rejected
def create_or_update_times(effort_data)
effort = effort_data.effort
indexed_split_times = effort_data.indexed_existing_split_times
row_success = true
effort_data.proposed_split_times.each do |proposed_split_time|
working_split_time = indexed_split_times[proposed_split_time.time_point] || proposed_split_time
saved_split_time = create_or_update_split_time(proposed_split_time, working_split_time)
if saved_split_time
EffortStopper.stop(effort: effort, stopped_split_time: saved_split_time) if saved_split_time.stopped_here
saved_split_times << saved_split_time
else
unsaved_rows << effort_data.response_row
row_success = false
end
end
row_success
end
def create_or_update_split_time(proposed_split_time, working_split_time)
working_split_time if working_split_time.update(extracted_attributes(proposed_split_time))
end
# Extract only those extractable attributes that are non-nil (false must be extracted)
def extracted_attributes(split_time)
split_time.attributes.select { |attribute, value| EXTRACTABLE_ATTRIBUTES.include?(attribute) && !value.nil? }
end
def ordered_splits
@ordered_splits ||= event.ordered_splits.to_a
end
def force_option?
time_rows.size == 1
end
end | true |
05f9026546787fd310b3fb7baa4b85edba9588d1 | Ruby | mulhoo/grocery-store | /lib/customer.rb | UTF-8 | 796 | 3.296875 | 3 | [] | no_license | require 'csv'
class Customer
attr_reader :id
attr_accessor :email, :address
def initialize (id, email, address)
@id = id
@email = email
@address = address
end
def self.all
customer_csv = CSV.read("data/customers.csv")
all_customers = []
customer_csv.each do |info|
id = info[0].to_i
email = info[1]
address = {
:street => info[2],
:city => info[3],
:state => info[4],
:zip => info[5]
}
new_customer = self.new(id, email, address)
all_customers << new_customer
end
return all_customers
end
def self.find(id)
desired_customer = (self.all).find { |order| order.id == id }
return desired_customer
desired_customer.empty? ? nil : desired_customer
end
end | true |
2885c160c7941f26b00901642a2a46af34b17a46 | Ruby | TonyCTHsu/LeetCode | /Easy/AddDigits.rb | UTF-8 | 402 | 3.984375 | 4 | [] | no_license | # Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
# For example:
# Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
# @param {Integer} num
# @return {Integer}
def add_digits(num)
sum=0
if num<10
return num
else
num.to_s.chars.each{|x|
sum+=x.to_i
}
end
add_digits(sum)
end | true |
54db8620d894c66f9d391eb50f42226560c6c92e | Ruby | EngSwCIC/Athene | /features/step_definitions/autenticacao/login_steps.rb | UTF-8 | 1,100 | 2.515625 | 3 | [] | no_license | def buildloginUser
@user = User.find_by nick:'teste'
if !@user.nil?
@user.destroy
end
@user = User.new(nick:'teste', senha:'teste123456', email:'teste@gmail.com')
@user.save!
end
def unbuildloginUser
page.driver.browser.clear_cookies
@user.destroy unless @user.nil?
end
Given("eu esteja na pagina de login") do
visit('/login')
buildloginUser
end
When("eu preencher o formulario de login com:") do |table|
# table is a Cucumber::MultilineArgument::DataTable
table.rows_hash.each do |field, value|
fill_in field, with: value
end
end
When("clicar em {string}") do |botao|
click_button botao
end
Then("eu receberei uma mensagem da pagina de login {string}") do |msg|
expect(page).to have_content msg
@user.destroy unless @user.nil?
end
Given("eu esteja na pagina de login e esteja logado") do
buildloginUser
page.driver.browser.set_cookie "login=teste"
visit('/login')
end
When("eu clicar no botao {string} em login") do |string|
click_link('logout')
end
Then("irei deslogar da aplicacao") do
expect(page).to_not have_content "logout"
unbuildloginUser
end
| true |
c4daf9d01d89bebd0808e9d417e7a4448cb63ecc | Ruby | rs-pro/russian_inflect | /lib/russian_inflect/dictionary.rb | UTF-8 | 2,409 | 3.140625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module RussianInflect
UnknownError = Class.new(StandardError)
class UnknownCaseException < UnknownError
def initialize(gcase)
super "Unknown grammatical case: `#{gcase}'."
end
end
class UnknownRuleException < UnknownError
def initialize(word)
super "Can't find rule for `#{word}'."
end
end
class Dictionary
def initialize(rules)
@rules = rules
end
def inflect(word, gcase)
# Склоняем слово по модификатору, который находим по падежу и правилу для слова
modify(word, modificator_for(gcase, rule_for(word)))
rescue UnknownRuleException
word
end
private
# Ищем правило в исключениях или суффиксах
def rule_for(word)
type = RussianInflect::Detector.new(word).word_type
downcased = UnicodeUtils.downcase(word) # Даункейсим слово в чистом руби
find(downcased, @rules[type][:exceptions], true) ||
find(downcased, @rules[type][:suffixes]) ||
raise(UnknownRuleException, word)
end
def find(word, scoped_rules, match_whole_word = false)
return if scoped_rules.nil?
scoped_rules.detect { |rule| match?(word, rule, match_whole_word) }
end
# Проверяем, подходит ли правило под наше слово
def match?(word, rule, match_whole_word = false)
return rule[:test].include?(word) if match_whole_word
rule[:test].any? { |chars| chars == word.slice([word.length - chars.length, 0].max..-1) }
end
# Применяем правило к слову
def modify(word, modificator)
return word if modificator == '.'
word.slice(0..(-1 - modificator.count('-'))) + modificator.tr('-', '')
end
# Получить модификатор для указанного падежа из указанного правила
def modificator_for(gcase, rule)
case gcase.to_sym
when NOMINATIVE then '.'
when GENITIVE then rule[:mods][0]
when DATIVE then rule[:mods][1]
when ACCUSATIVE then rule[:mods][2]
when INSTRUMENTAL then rule[:mods][3]
when PREPOSITIONAL then rule[:mods][4]
else raise UnknownCaseException, gcase
end
end
end
end
| true |
8e4b05b39d562af14164c355732eac31ee03ff80 | Ruby | JohnDowson/adventofcode2019 | /day_8/solution.rb | UTF-8 | 534 | 3.296875 | 3 | [] | no_license | def get_layers(wsize, hsize)
IO.read('./input.txt').split('').map(&:to_i).each_slice(wsize).each_slice(hsize).map(&:flatten)
end
pp 'Star 1'
# [1] because there's a loose 0 at the end of input for some reason
get_layers(25, 6).sort { |a, b| a.count(0) <=> b.count(0) }[1].then { |l| p l.count(1) * l.count(2) }
pp 'Star 2'
get_layers(25, 6).reject { |el| el.count == 1 }.transpose.map do |pixel|
case pixel.reject { |l| l == 2 }.first
when 0
' '
when 1
'#'
end
end.each_slice(25).map(&:join).each { |line| p line }
| true |
6207fe22dcec7cf281d678b9dc1fe4d3e0b8d2a6 | Ruby | Proskurina/learn_to_program | /ch09-writing-your-own-methods/old_school_roman_numerals.rb | UTF-8 | 257 | 2.9375 | 3 | [] | no_license | def old_roman_numeral num
roman_num = ""
roman_num << "M"*(num/1000)
roman_num << "D"*(num%1000/500)
roman_num << "C"*(num%500/100)
roman_num << "L"*(num%100/50)
roman_num << "X"*(num%50/10)
roman_num << "V"*(num%10/5)
roman_num << "I"*(num%5)
end | true |
d5acda77b122abea0ee2f160c1dd485c5df98de0 | Ruby | athar4228/toy_robot | /spec/toy_robot_robot_spec.rb | UTF-8 | 4,219 | 2.828125 | 3 | [] | no_license | require 'toy_robot/table'
require 'toy_robot/robot'
RSpec.describe "ToyRobot:Robot" do
let(:table) { ToyRobot::Table.new }
subject { ToyRobot::Robot.new(table) }
describe 'initialise Robot' do
it 'should set value of table' do
expect(subject.table.instance_of? ToyRobot::Table).to eq(true)
end
end
describe 'execute statement' do
it 'should set command passed as parameter to execute method' do
subject.execute("place 0,0, north")
expect(subject.command).to eq('place 0,0, north')
end
end
describe 'PLACE statement' do
it 'should not place if coordinates are invalid' do
subject.execute("place 0,8, north")
expect(subject.position).to eq(nil)
end
it 'should place if coordinates are valid' do
subject.execute("place 0, 0, north")
expect(subject.position).not_to eq(nil)
expect(subject.position.x_coordinate).to eq(0)
expect(subject.position.y_coordinate).to eq(0)
end
it 'should place again if robot is placed' do
subject.execute("place 0, 0, north")
subject.execute("place 1, 1, east")
expect(subject.position).not_to eq(nil)
expect(subject.position.x_coordinate).to eq(1)
expect(subject.position.y_coordinate).to eq(1)
end
end
describe 'MOVE statement' do
it 'should not move if table is ended' do
subject.execute("place 0,4, north")
subject.execute('move')
expect(subject.position.x_coordinate).to eq(0)
expect(subject.position.y_coordinate).to eq(4)
end
it 'should move if table is available' do
subject.execute("place 0, 0, north")
subject.execute('move')
expect(subject.position.x_coordinate).to eq(0)
expect(subject.position.y_coordinate).to eq(1)
end
it 'should not move if robot is not placed' do
subject.execute('move')
expect(subject.position).to eq(nil)
end
end
describe 'LEFT statement' do
it 'should change direction to west if currently facing north' do
subject.execute("place 0,0, north")
subject.execute('left')
expect(subject.direction).to eq('west')
end
it 'should change direction to east if currently facing south' do
subject.execute("place 0,0, south")
subject.execute('left')
expect(subject.direction).to eq('east')
end
it 'should change direction to south if currently facing west' do
subject.execute("place 0,0, west")
subject.execute('left')
expect(subject.direction).to eq('south')
end
it 'should change direction to north if currently facing east' do
subject.execute("place 0,0, east")
subject.execute('left')
expect(subject.direction).to eq('north')
end
it 'should not change direction if robot is not placed' do
subject.execute('left')
expect(subject.position).to eq(nil)
end
end
describe 'RIGHT statement' do
it 'should change direction to east if currently facing north' do
subject.execute("place 0,0, north")
subject.execute('right')
expect(subject.direction).to eq('east')
end
it 'should change direction to west if currently facing south' do
subject.execute("place 0,0, south")
subject.execute('right')
expect(subject.direction).to eq('west')
end
it 'should change direction to north if currently facing west' do
subject.execute("place 0,0, west")
subject.execute('right')
expect(subject.direction).to eq('north')
end
it 'should change direction to south if currently facing east' do
subject.execute("place 0,0, east")
subject.execute('right')
expect(subject.direction).to eq('south')
end
it 'should not change direction if robot is not placed' do
subject.execute('right')
expect(subject.position).to eq(nil)
end
end
describe 'REPORT statement' do
it 'should not report if robot is not placed' do
subject.execute('report')
expect(subject.position).to eq(nil)
end
it 'should report position if robot is placed' do
subject.execute("place 0,0, north")
subject.execute('report')
expect(subject.position).not_to eq(nil)
end
end
end
| true |
aed0b5011c691b8cbd1930e6788bac0b8ce2f882 | Ruby | JiriKrizek/MI-RUB-sem | /lib/tags/table_node.rb | UTF-8 | 597 | 2.765625 | 3 | [] | no_license | module HTML
module Tags
class TableNode < Tag
def initialize(tag)
super(tag.tag, tag.attr)
fail HTML::InvalidTagError.new("Invalid attributes in tag #{@tag}") unless valid_attributes?
end
def valid_attributes?
valid=Set.new ["border", "cellpadding", "cellspacing", "summary"]
@attr.each {|key, value|
return false unless valid.include?(key)
}
true
end
def can_has?(klass)
valid=Set.new [HTML::Tags::TrNode, HTML::Tags::ThNode]
valid.include?(klass)
end
end
end
end | true |
dce5806c3abd78532e1e295af5584b635b3d33fb | Ruby | raquelnishimoto/ruby_intro | /intro_to_programming/flow_control/flow_control_5.rb | UTF-8 | 654 | 4.84375 | 5 | [] | no_license | # program that takes a number from the user between 0 and 100
# and reports back whether the number is between 0 and 50, 51 and 100, or above 100
# using a case statement
# limitation - it will convert any string e.g. "abc" to an integer.
def report(number)
result = case
when ((number >= 0) && (number <= 50))
"#{number} is between 0 and 50!"
when ((number >= 51) && (number <= 100))
"#{number} is between 51 and 100!"
when number > 100
"#{number} is higher than 100"
else
"Please, give me a number that is between 0 to 100: "
end
p result
end
print "Give me a number between 0 to 100: "
number = gets.chomp.to_i
report(number) | true |
e8ebdf63a8cc283e332e9a481a1993fc040efcb2 | Ruby | ASL20/tasks | /06_05/2_1.rb | UTF-8 | 181 | 3.296875 | 3 | [] | no_license | word = "Everybody"
index = 0
while index < word.length
puts word[index].upcase
index += 1
end
index = 0
until index == word.length
puts word[index].upcase
index += 1
end
| true |
8fabdbe2bfe455f0b4afb330b49f12efb76aaa64 | Ruby | timgaleckas/gosu_tetris | /lib/colors.rb | UTF-8 | 1,028 | 2.5625 | 3 | [] | no_license | module Colors
def self.from_hex(hex_string)
Gosu::Color.new(*hex_string[1..-1].scan(/.{2}/).map{|s|s.to_i(16)})
end
FG = "#000022"
MENU_BACKGROUND_HEX = "#DDDDBB"
MENU_BACKGROUND = from_hex(MENU_BACKGROUND_HEX)
MENU_BUTTON_BG_HEX = "#3D484C"
MENU_BUTTON_FG_HEX = "#0078A8"
MENU_BUTTON_FG_HOVERED_HEX = "#116688"
MENU_BUTTON_TEXT_HEX = "#E0DAF2"
MENU_BUTTON_BG = from_hex(MENU_BUTTON_BG_HEX)
MENU_BUTTON_FG = from_hex(MENU_BUTTON_FG_HEX)
MENU_BUTTON_FG_HOVERED = from_hex(MENU_BUTTON_FG_HOVERED_HEX)
MENU_BUTTON_TEXT = from_hex(MENU_BUTTON_TEXT_HEX)
COLOR_HEXS = [
"#000022",
"#005566",
"#0078A8",
"#101011",
"#116688",
"#2B2B2B",
"#3D484C",
"#442299",
"#513F7F",
"#667755",
"#668811",
"#883311",
"#8899AA",
"#99E1FF",
"#9B79F2",
"#B9ADD8",
"#CCDDAA",
"#CCF0FF",
"#D7DBDD",
"#DDDDBB",
"#E0DAF2",
"#E3E8EA",
"#F2F2F2",
"#FFFFEE",
"#FFFFFF"
]
COLORS = COLOR_HEXS.map{|s| from_hex(s) }
end
| true |
b185564f415a1076a7d6e87a82f069a53dc4737b | Ruby | antoniojking/backend_mod_1_prework | /section1/ex6.rb | UTF-8 | 1,207 | 4.46875 | 4 | [] | no_license | # variable name equals integer
types_of_people = 10
# variable name equals string with embedded variable (interpolation)
x = "There are #{types_of_people} types of people."
# variable name equals string
binary = "binary"
# variable name equals string
do_not = "don't"
# variable name equals string with emdedded variables (interpolation)
y = "Those who know #{binary} and those who #{do_not}." #sis x2
# prints string assigned to variable name "x"
puts x
# prints string assigned to variable name "y"
puts y
# prints string with embedded variable (interpolation)
puts "I said: #{x}." #sis
# prints string with embedded variable (interpolation)
puts "I also said: '#{y}'." #sis
# variable name equals boolean
hilarious = false
# variable name equals string with embedded variable (interpolation)
joke_evaluation = "Isn't that joke so funny?! #{hilarious}"
# prints string assigned to variable name "joke_evaluation" (interpolation)
puts joke_evaluation
# string assigned to variable name "w"
w = 'This is the left side of...'
# string assigned to variable name "e"
e = 'a string with a right side.'
# prints strings assigned to multiple variable names in consecutive order, on the same line
puts w + e
| true |
b8ec06d9df27bad2e37ce44b5b89b88db1f6ae76 | Ruby | cebucodecamp/ccc_demos_ruby | /lib/refactorings/decompose_conditional.rb | UTF-8 | 964 | 3.015625 | 3 | [] | no_license | require 'time'
module Refactorings::DecomposeConditional
# start of april
SUMMER_START = Time.parse('2016-04-01').to_date
# end of june
SUMMER_END = Time.parse('2016-07-01').to_date
WINTER_RATE = 9.99
WINTER_SERVICE_CHARGE = 2.50
SUMMER_RATE = 6.99
module Original
class CalculateCharge
def calculate(date, qty)
if (date < SUMMER_START) || (date > SUMMER_END)
charge = (qty * WINTER_RATE) + WINTER_SERVICE_CHARGE
else
charge = (qty * SUMMER_RATE)
end
end
end
end
module Refactored
class CalculateCharge
def calculate(date, qty)
is_winter?(date) ? winter_rate(qty) : summer_rate(qty)
end
def is_winter?(date)
(date < SUMMER_START) || (date > SUMMER_END)
end
def winter_rate(qty)
(qty * WINTER_RATE) + WINTER_SERVICE_CHARGE
end
def summer_rate(qty)
(qty * SUMMER_RATE)
end
end
end
end
| true |
3942a110791d3a288e4af7991409478dc2ba196c | Ruby | carolinecollaco/RubyCodeAcademy | /OrdenandoOHash.rb | UTF-8 | 236 | 3.296875 | 3 | [] | no_license | puts "Entre com o texto: "
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new(0)
words.each {|word| frequencies [word] += 1}
frequencies = frequencies.sort_by do |frequencie, count|
count
end
frequencies.reverse!
| true |
e377509727eeed9f7a4d28a08a3b4149ebeb0bd3 | Ruby | zhangjx/apimaster | /lib/apimaster/error.rb | UTF-8 | 2,289 | 2.671875 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
#
# Copyright (C) 2011-2012 AdMaster, Inc.
#
# @author: sunxiqiu@admaster.com.cn
module Apimaster
class NormalError < StandardError
attr_reader :code
attr_reader :error
attr_reader :resource
attr_reader :field
# error :missing, :missing_field, :invalid, :already_exists
def initialize(message = '', code = nil, error = :invalid, resource = nil, field = nil)
@code = code
@error = error.to_sym
@resource = resource
@field = field
super(message)
end
end
class MissingError < NormalError
def initialize(resource = nil)
super("Resource '#{resource}' does not exist.", 410, :missing, resource)
end
end
class MissingFieldError < NormalError
def initialize(resource = nil, field = nil)
super("Required field '#{field}' on a resource '#{resource}' has not been set.", 422, :missing_field, resource, field)
end
end
class InvalidFieldError < NormalError
def initialize(resource = nil, field = nil)
super("The formatting of the field '#{field}' on a resource '#{resource}' is invalid.", 422, :invalid_field, resource, field)
end
end
class AlreadyExistsError < NormalError
def initialize(resource = nil, field = nil)
super("Another resource '#{resource}' has the same value as this field '#{field}'. ", 409, :already_exists, resource, field)
end
end
class RelationExistsError < NormalError
def initialize(resource = nil, field = nil)
super("Our results indicate a positive relationship exists.", 409, :relation_exists, resource, field)
end
end
class RequestError < NormalError
def initialize(resource = nil, field = nil)
super("Problems parsing JSON.", 400, :parse_error, resource, field)
end
end
class UnauthorizedError < NormalError
def initialize(resource = nil, field = nil)
super("Your authorization token were invalid.", 401, :unauthorized, resource, field)
end
end
class PermissionDeniedError < NormalError
def initialize(resource = nil, field = nil)
super("Permission denied to access resource '#{resource}'.", 403, :forbidden, resource, field)
end
end
class OauthError < NormalError
def initialize(message)
super(message, 422, :oauth_error)
end
end
end
| true |
4118ce6e721f79cba7b55e729a62a20600110574 | Ruby | Bates550/vidigem | /vidigemTest.rb | UTF-8 | 3,125 | 3.5 | 4 | [] | no_license | =begin
Mystery:
AfterEarth
Prometheus
Inception
Love:
Inception
MissingPieces
Casablanca
Betrayal:
Casablanca
Gladiator
TheDarkKnightRises
=end
class
inception = [ "love", "mystery" ]
afterEarth = ["mystery"]
prometheus = ["mystery"]
casablanca = ["love", "betrayal"]
missingPieces = ["love"]
gladiator = ["betrayal"]
theDarkKnightRises = ["betrayal"]
movies = {:Inception => inception, :AfterEarth => afterEarth, :Prometheus => prometheus, :Casablanca => casablanca, :MissingPieces => missingPieces, :Gladiator => gladiator, :TheDarkNightRises => theDarkKnightRises}
update = movies.keys
traits = { "mystery" => 2, "love" => 3, "betrayal" => 5 }
composites = {6=>"Inception"}
main = { :primes => traits, :movies => movies, :composites => composites}
class Retrieve
=begin
This class is used to retrieve data from hash tables and arrays.
=end
def get_prime(main, trait, level=:primes)
# returns the prime value of an attribute
main[level][trait]
end
def get_traits(main, level = :primes)
# gets all the traits in database
main[:primes].keys
end
end
class Calculate
=begin
This class is used to make the various calculations necessary throughout the program.
=end
def get_composite(main, movie, level = :movies)
retrieve = Retrieve.new
# Enters the dimension with a movies traits ex: ["love", "betrayal"]
mTraits = main[level][movie]
# Creates an array of traits in prime forms ex: [3, 5]
primeList = mTraits.collect {|trait| retrieve.get_prime(main, trait)}
# multiplies the primes to produce a composite. ex: 3 * 5 = 15
primeList.inject {|memo, n| memo * n}
end
###########################################################################################################
def composite_hash(main, movie, level = :composites)
# cable = Hash[:siop, 100]
# this gets the composite value
cable = Hash[ get_composite(main, movie), ((movie.to_s.split /(?=[A-Z])/) * " ") ]
end
def auto(main, movies, hash = main[:composites])
get = Calculate.new
list = []
for movie in movies
updatedHash = get.composite_hash(main, movie)
list << updatedHash
end
print list.inject { |all, h| all.merge(h) }
end
#########################################################################################################
=begin
def match(main, )
this program takes a search number and checks it against a bunch of composites.
if it finds a match, it returns a value.
end
=end
end
calculate = Calculate.new
retrieve = Retrieve.new
puts retrieve.get_prime(main, "mystery")
puts "************************"
print retrieve.get_traits(main)
puts " "
puts " "
puts "####################### testing get_composite #############################"
print "the composite value of Casablanca is: => "
puts calculate.get_composite(main, :Casablanca)
puts " "
puts "####################### testing composite_hash ##########################"
puts calculate.composite_hash(main, :Inception)
puts "####################### testing auto ##########################"
puts calculate.auto(main, update)
| true |
9b3b7280743db9a6450f0fb7761b948dc2194065 | Ruby | implicitly-awesome/trial | /lib/router.rb | UTF-8 | 636 | 3.03125 | 3 | [] | no_license | require 'singleton'
##
# Routes registry
class Router
include Singleton
attr_reader :routes
def initialize
@routes = {}
end
##
# Creates and adds route to the registry
# @param [String] URL path
# @param [String] HTTP request method
# @param [Proc] an action
def add(path, method, &action)
actions = @routes[path] || {}
actions[method.to_sym] = action
@routes[path] = actions
end
##
# Fetches an action from the routes registry
# @param [String] URL path
# @param [String|Symbol] HTTP request method
def action_for(path, method)
routes[path]&.fetch(method.to_sym, nil)
end
end
| true |
cffac4a9c628569100e8d9a0d388b9cfa69069c6 | Ruby | baughje/practice | /stats_class/run.rb | UTF-8 | 260 | 2.90625 | 3 | [] | no_license | require "stats"
class StatRunner
def poll
loop do
data_array = []
File.new("samples.txt", "r").each { |line| data_array << line.chomp }
end
end
def results
@stats.sample_size
puts "The result is #{ result }"
end
end
| true |
f9f6c874f7bac977a504fca707484fd8229c5f0f | Ruby | kojix2/ProbabilityCalculator | /cardanddiagnosis.rb | UTF-8 | 1,971 | 2.875 | 3 | [] | no_license | # 2013-2018 kojix2
# カードと鑑別疾患
class CardAndDiagnosis
def initialize(dir)
@reader = nil
temp_path = "#{dir}/diagnosis/diagnosis.csv"
puts temp_path
begin
*@reader = CSV.read(temp_path)
rescue StandardError
@reader = []
end
window = TkToplevel.new(title: '鑑別疾患カード')
# 左側のフレーム
left_frame = TkFrame.new(window) do
pack(side: :left, padx: 2, pady: 2)
end
# カードラベル
TkLabel.new(left_frame) do
text 'Cards'
height 1
font(size: 14)
pack
end
left_listframe = TkFrame.new(left_frame).pack
scr1 = TkScrollbar.new(left_listframe) do
pack('fill' => 'y', 'side' => 'right')
end
@cardlist = TkListbox.new(left_listframe) do
font TkFont.new('size' => '12')
width 20
height 20
yscrollbar(scr1)
pack
end
@cardlist.bind '<ListboxSelect>', proc { card_did_select(@cardlist.curselection) }
@reader[1].compact.each do |h|
@cardlist.insert('end', h)
end
# 右側のフレーム
right_frame = TkFrame.new(window) do
pack(side: :left, padx: 2, pady: 2)
end
# Diagnosis ラベル
TkLabel.new(right_frame) do
text 'Diagnosis'
height 1
font(size: 14)
pack
end
right_listframe = TkFrame.new(right_frame).pack
scr2 = TkScrollbar.new(right_listframe).pack('fill' => 'y', 'side' => 'right')
@diagnosislist = TkListbox.new(right_listframe) do
font TkFont.new('size' => '12')
width 20
height 20
yscrollbar(scr2)
pack
end
# @diagnosislist.bind '<ListboxSelect>', proc{ puts curselection }
end
# カードが選択されたとき
def card_did_select(selectnum)
@diagnosislist.clear
@reader[2..-1].compact.each do |item|
@diagnosislist.insert('end', item[selectnum[0]]) unless item[selectnum[0]].nil?
end
Tk.update(@diagnosislist)
end
end
| true |
97559ce8ba381fa7ebafc1ee90a44498bffcc19f | Ruby | rhomobile/rhodes | /spec/framework_spec/app/spec/core/proc/arity_spec.rb | UTF-8 | 2,879 | 2.671875 | 3 | [
"MIT"
] | permissive | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/common', __FILE__)
describe "Proc#arity" do
before :each do
@p = ProcSpecs::Arity.new
end
ruby_version_is ""..."1.9" do
it "returns -1 for a block taking no arguments" do
@p.arity_check { 1 }.should == -1
end
end
ruby_version_is "1.9" do
it "returns 0 for a block taking no arguments" do
@p.arity_check { 1 }.should == 0
end
end
it "returns 0 for a block taking || arguments" do
@p.arity_check { || }.should == 0
end
it "returns 1 for a block taking |a| arguments" do
@p.arity_check { |a| }.should == 1
end
it "returns 1 for a block taking |a, | arguments" do
@p.arity_check { |a, | }.should == 1
end
it "returns -2 for a block taking |a, *| arguments" do
@p.arity_check { |a, *| }.should == -2
end
it "returns -2 for a block taking |a, *b| arguments" do
@p.arity_check { |a, *b| }.should == -2
end
it "returns -3 for a block taking |a, b, *c| arguments" do
@p.arity_check { |a, b, *c| }.should == -3
end
it "returns 2 for a block taking |a, b| arguments" do
@p.arity_check { |a, b| }.should == 2
end
it "returns 3 for a block taking |a, b, c| arguments" do
@p.arity_check { |a, b, c| }.should == 3
end
it "returns -1 for a block taking |*| arguments" do
@p.arity_check { |*| }.should == -1
end
it "returns -1 for a block taking |*a| arguments" do
@p.arity_check { |*a| }.should == -1
end
ruby_version_is ""..."1.9" do
it "returns 2 for a block taking |(a, b)| arguments" do
@p.arity_check { |(a, b)| }.should == 2
end
it "returns -2 for a block taking |(a, *)| arguments" do
@p.arity_check { |(a, *)| }.should == -2
end
it "returns -2 for a block taking |(a, *b)| arguments" do
@p.arity_check { |(a, *b)| }.should == -2
end
end
ruby_version_is "1.9" do
it "returns 1 for a block taking |(a, b)| arguments" do
@p.arity_check { |(a, b)| }.should == 1
end
it "returns 1 for a block taking |(a, *)| arguments" do
@p.arity_check { |(a, *)| }.should == 1
end
it "returns 1 for a block taking |(a, *b)| arguments" do
@p.arity_check { |(a, *b)| }.should == 1
end
end
it "returns 2 for a block taking |a, (b, c)| arguments" do
@p.arity_check { |a, (b, c)| }.should == 2
end
it "returns 2 for a block taking |a, (b, *c)| arguments" do
@p.arity_check { |a, (b, *c)| }.should == 2
end
it "returns 2 for a block taking |(a, b), c| arguments" do
@p.arity_check { |(a, b), c| }.should == 2
end
it "returns -2 for a block taking |(a, b), *c| arguments" do
@p.arity_check { |(a, b), *c| }.should == -2
end
it "returns 2 for a block taking |(a, *b), c| arguments" do
@p.arity_check { |(a, *b), c| }.should == 2
end
end
| true |
3bfa66038df527f6b5e37999fd9e71ad2af4c960 | Ruby | mqprogramming/classes-homework | /specs/family_class_specs.rb | UTF-8 | 1,439 | 3.03125 | 3 | [] | no_license | require('minitest/autorun')
require('minitest/reporters')
require_relative('../family_class')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
class TestFamily < MiniTest::Test
def setup()
members = [
{
name: "Matthew",
age: 22
},
{
name: "Jonathan",
age: 19
},
{
name: "Elizabeth",
age: 17
},
{
name: "Paul",
age: 55
},
{
name: "Mary",
age: 51
},
]
pets = ["Snack"]
@family = Family.new( "Quigley", members, pets )
end
def test_member_count()
assert_equal( 5, @family.members.count())
end
def test_family_name()
assert_equal( "Quigley", @family.name())
end
def test_find_member()
assert_equal( {name: "Jonathan", age: 19}, @family.find_member( "Jonathan" ))
end
def test_add_family_member()
@family.add_family_member( "Katie", 20 )
assert_equal( "Katie", @family.find_member( "Katie" )[:name] )
end
def test_increase_member_age()
@family.increase_member_age( "Matthew" )
assert_equal( 23, @family.find_member( "Matthew" )[:age] )
end
def test_add_or_remove_pets__add()
@family.add_or_remove_pet("Oreo")
assert_equal( "Oreo", @family.pets.last() )
end
def test_add_or_remove_pets__remove()
@family.add_or_remove_pet("Snack")
assert_nil( @family.pets.last() )
end
end
| true |
296f033603ab3fec18ad6bc86011d787e11613e1 | Ruby | germanlinux/Lemon-labs | /Ruby/cobol2java/explore_script.rb | UTF-8 | 1,629 | 2.609375 | 3 | [] | no_license | file = ARGV.shift
content = File.readlines(file)
h_nom={}
content.each do |ligne|
ligne.chomp!
tab = ligne.split('/')
nom_script = tab[-1]
h_nom[nom_script] = 1
pgm = tab[-3]
script = File.readlines(ligne)
taille = script.size
h_nom[nom_script] = taille
libelle ="TODO"
script1 =""
if taille == 1 then libelle = "VIDE"
elsif script[1]=~ /^rm/ then libelle ="suppression de fichier"
elsif script[1]=~ /^sort/ then libelle ="Tri fichier simple"
elsif script[1]=~ /^\\cp/ then libelle ="copie de fichier"
elsif script[1]=~ /^cat.+sort/ then libelle ="Tri fichier enchaine"
elsif script[1]=~ /EBCD/ then libelle ="Transformation EBCDIC"
elsif script[1]=~ /^>/ then libelle ="Redirection"
elsif script[1]=~ /^cut.+SEP/ then libelle ="Mise au format CSV"
elsif script[1]=~ /gawk.+sort/ then libelle ="Transformation et tri"
elsif script[1]=~ /gawk/ then libelle ="Transformation T1"
elsif script[1]=~ /export/ then libelle ="Copie de fichier"
elsif script[1]=~ /cut/ then libelle ="fichier tronqué"
elsif script[1]=~ /^awk/ then libelle ="Transformation T2"
elsif script[1]=~ /^sed.+sort/ then libelle ="Substitution et transformation"
elsif taille > 5 then libelle ="script complexe d eclatement et de Transformation"
else script1 = script
end
puts "#{pgm};#{nom_script};#{libelle}"
end
h_nom.keys.each do |k|
if h_nom[k] == 1 then libelle = "vide"
else
libelle = "ecrit"
end
puts "#{k};#{libelle}"
end
| true |
fdab2df2ca1f6369e25b0826ee5e96c655a2671c | Ruby | NicciTheNomad/Ruby-Coding-Dojo-Class | /RubyAssignments/Ruby_TDD/project/project.rb | UTF-8 | 582 | 3.3125 | 3 | [] | no_license | class Project
attr_accessor :name, :description, :team_member
def initialize name, description, team_member
@name = name
@description = description
@team_member = team_member
end
def elevator_pitch
"#{@name}, #{@description}"
end
def add_to_team
"team member: #{team_member}"
end
end
project = Project.new('Project Name', 'I am a project', "Nicci")
puts project.name = "Changed Name"
puts project.description = "RSpec Effort"
puts project
puts project.elevator_pitch
puts project.team_member = "Nicci"
puts project.add_to_team
| true |
f731872deff91b7d89354f076fd665937fc2cf53 | Ruby | WestDragonIroh/HANGMAN | /main.rb | UTF-8 | 529 | 3.71875 | 4 | [] | no_license | require_relative 'game'
require_relative 'display'
puts ' '
puts "\e[1;32mWelcome to console edition of Hangman !!! \e[0m"
puts ' '
def play
game = Game.new
game.start
play_again
end
def play_again
puts ''
puts "\e[1;32mWould you like to play again? Type \"Y\" or \"N\". \e[0m"
respond = gets.chomp
if respond == 'Y' || respond == 'y'
puts "\e[1;32mLet's play another game! \e[0m"
play
else
puts "\e[1;32mThanks for playing! \e[0m"
exit
end
end
play | true |
3d7ca2ac591e34c32c9dfd942c4802c39385e3f7 | Ruby | lolptdr/cars | /carcolor.rb | UTF-8 | 414 | 3.953125 | 4 | [] | no_license | class Car
@@repaint_count = 0
def initialize(my_color)
@my_color = my_color
end
def color
@my_color
end
def repaint_count
@@repaint_count
end
def paint(my_color)
@@repaint_count += 1
@my_color = my_color
end
end
c = Car.new("blue")
puts c.color # blue
puts c.repaint_count # 0
c.paint("red")
c.paint("green")
puts c.repaint_count # 2
puts c.color # green | true |
79c48416f3cb7a39ee7d1e7dbf50b95f9d561520 | Ruby | albertbahia/wdi_june_2014 | /w02/d02/francis_castillo/pets/lib/dog.rb | UTF-8 | 336 | 3.328125 | 3 | [] | no_license | class Dog < Pet
attr_reader(:ear_type)
def initialize(name, owner, age, ear_type)
# @name = name
# @owner = owner
# @age = age
# @food_eaten = []
super(name, age, owner)
@ear_type = ear_type
end
def eat(food)
super(food)
puts("woof")
end
def bark ()
return "woof woof"
end
end
| true |
e282f4d99ae4b45a77189f7b8097b4105a95f7c2 | Ruby | gillysayres/Meetadoc | /spec/models/patient_spec.rb | UTF-8 | 1,117 | 2.578125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Patient, type: :model do
it 'creates a patient' do
patient = Patient.new(
name: 'John Doe',
cpf: '532.345.501-52',
birth_date: 1988-05-20
)
expect(patient.name).to eql "John Doe"
expect(patient.cpf).to eql "532.345.501-52"
expect(patient.birth_date).to eql 1988-05-20
end
it 'patients name cannot be blank' do
patient = Patient.new(
name: nil,
cpf: '532.345.501-52',
birth_date: 1988-05-20
)
expect(patient).to_not be_valid
end
it 'only numbers for cpf' do
patient = Patient.new(
name: 'John Doe',
cpf: 'a32.345.501-52',
birth_date: 1988-05-20
)
expect(patient).to_not be_valid
end
it 'only 11 numbers for cpf' do
patient = Patient.new(
name: 'John Doe',
cpf: '232.345.501-520',
birth_date: 1988-05-20
)
expect(patient).not_to be_valid
end
it 'birth date cannot be blank' do
patient = Patient.new(
name: 'John Doe',
cpf: '532.345.501-52',
birth_date: nil
)
expect(patient).not_to be_valid
end
end
| true |
90db8594390952cf11b3611c8c1393286babbbb6 | Ruby | masc-ucsc/udsim | /lib/Org.rb | UTF-8 | 494 | 3.234375 | 3 | [
"MIT"
] | permissive |
module DesignSim
# Company organization class.
class Org
def initialize()
end
# Parse the org.xml file to find the people available on the pool for hiring
def parse!(xml)
end
# Look for a person with the best match to the following skills. All the
# skills have the same importance
def hire(skill)
end
# The project done by the person is done/cancelled. Add him/her again to the
# pool of free people
def fire(person)
end
end
end
| true |
bc6efa9871419cd20401c927edc10811de79576f | Ruby | KentaroKageyama/furima-35204 | /spec/models/user_spec.rb | UTF-8 | 6,220 | 2.640625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context 'ユーザー新規登録できる時' do
it 'nickname, email、password, password_confirmation, first_name, last_name, first_name_kana, last_name_kana, birthdayが存在すれば登録できる' do
expect(@user).to be_valid
end
it 'passwordとpassword_confirmationが6文字以上で半角英数字が混合されていれば登録できる' do
@user.password = 'abc456'
@user.password_confirmation = @user.password
expect(@user).to be_valid
end
it 'first_name, last_nameが全角(漢字・ひらがな・カタカナ)であれば登録できる' do
@user.first_name = '阿あア'
@user.last_name = '為いイ'
expect(@user).to be_valid
end
it 'first_name_kana, last_name_kanaが全角(カタカナ)であれば登録できる' do
@user.first_name = 'アイウエオ'
@user.last_name = 'カキクケコ'
expect(@user).to be_valid
end
end
context 'ユーザー新規登録できない時' do
it 'nicknameが空では登録できない' do
@user.nickname = ''
@user.valid?
expect(@user.errors.full_messages).to include('ニックネームを入力してください')
end
it 'emailが空では登録できない' do
@user.email = ''
@user.valid?
expect(@user.errors.full_messages).to include('Eメールを入力してください')
end
it 'passwordが空では登録できない' do
@user.password = ''
@user.valid?
expect(@user.errors.full_messages).to include('パスワードを入力してください')
end
it 'first_nameが空では登録できない' do
@user.first_name = ''
@user.valid?
expect(@user.errors.full_messages).to include('名を入力してください')
end
it 'last_nameが空では登録できない' do
@user.last_name = ''
@user.valid?
expect(@user.errors.full_messages).to include('姓を入力してください')
end
it 'first_name_kanaが空では登録できない' do
@user.first_name_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include('名(フリガナ)を入力してください')
end
it 'last_name_kanaが空では登録できない' do
@user.last_name_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include('姓(フリガナ)を入力してください')
end
it 'birthdayが空では登録できない' do
@user.birthday = ''
@user.valid?
expect(@user.errors.full_messages).to include('生年月日を入力してください')
end
it 'passwordが存在してもpassword_confirmationが空では登録できない' do
@user.password_confirmation = ''
@user.valid?
expect(@user.errors.full_messages).to include('パスワード(確認用)とパスワードの入力が一致しません')
end
it '重複したemailが存在する場合登録できない' do
@user.save
another_user = FactoryBot.build(:user)
another_user.email = @user.email
another_user.valid?
expect(another_user.errors.full_messages).to include('Eメールはすでに存在します')
end
it 'emailが@を含んでいなければ登録できない' do
@user.email = 'abcdefg.com'
@user.valid?
expect(@user.errors.full_messages).to include('Eメールは不正な値です')
end
it 'passwordが5文字以下では登録できない' do
@user.password = 'abc45'
@user.password_confirmation = @user.password
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは6文字以上で入力してください')
end
it 'passwordが数字だけでは登録できない' do
@user.password = '123456'
@user.password_confirmation = @user.password
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは英字と数字の両方を含めて設定してください')
end
it 'passwordが英字だけでは登録できない' do
@user.password = 'abcdef'
@user.password_confirmation = @user.password
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは英字と数字の両方を含めて設定してください')
end
it 'passwordが全角では登録できない' do
@user.password = 'あいうえお'
@user.password_confirmation = @user.password
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは英字と数字の両方を含めて設定してください')
end
it 'first_nameが全角(漢字・ひらがな・カタカナ)でなけれは登録できない' do
@user.first_name = 'aaaaa'
@user.valid?
expect(@user.errors.full_messages).to include('名は全角(漢字・ひらがな・カタカナ)で入力してください')
end
it 'last_nameが全角(漢字・ひらがな・カタカナ)でなけれは登録できない' do
@user.last_name = 'aaaaa'
@user.valid?
expect(@user.errors.full_messages).to include('姓は全角(漢字・ひらがな・カタカナ)で入力してください')
end
it 'first_name_kanaが全角(カタカナ)でなけれは登録できない' do
@user.first_name_kana = 'あああああ'
@user.valid?
expect(@user.errors.full_messages).to include('名(フリガナ)は全角(カタカナ)で入力してください')
end
it 'last_name_kanaが全角(カタカナ)でなけれは登録できない' do
@user.last_name_kana = 'あああああ'
@user.valid?
expect(@user.errors.full_messages).to include('姓(フリガナ)は全角(カタカナ)で入力してください')
end
end
end
end
| true |
76e8468306c06dfc0cb7f087bd5c8ebfdafda3c2 | Ruby | Zszywka/my_first_programms | /w2/initials.rb | UTF-8 | 809 | 3.671875 | 4 | [] | no_license | # Napisz metodę initials , która wypisuje inicjały osoby na podstawie jej pełnego imienia
# Wszystkie znaki inicjałów powinny być pisane z dużej litery.
# initials('Jan Kozlowski') => 'JK'
# metoda do bezposredniego wpsiania:
a = "tomasz kot"
array = a.scan(/\w+/)
name = [] << array[0]
surname = [] << array[1]
puts name.first.scan(/./).first + surname.first.scan(/./).first
# metoda z definicji:
def initial(a)
array = a.chomp.scan(/\w+/)
name = [] << array[0]
surname = [] << array[1]
puts name.first.scan(/./).first + surname.first.scan(/./).first
end
initial('jan kowalski')
# a = "cruel world"
# a.scan(/\w+/) #=> ["cruel", "world"]
# a.scan(/.../) #=> ["cru", "el ", "wor"]
# a.scan(/(...)/) #=> [["cru"], ["el "], ["wor"]]
# a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]
| true |
c0dc841f297acbb1a85366afa2d4722b7c51adb0 | Ruby | czcraig/pub_lab | /specs/pub_spec.rb | UTF-8 | 614 | 2.953125 | 3 | [] | no_license | require("minitest/autorun")
require_relative("../pub.rb")
require_relative("../drinks.rb")
class PubTest < MiniTest::Test
def setup
@drink1 = Drink.new("Tennants", 4.50)
@drink2 = Drink.new("Strongbow", 4.25)
@drink3 = Drink.new("Buckfast", 6.50)
@pub = Pub.new("The Standing Order", 500, [@drink1, @drink2, @drink3])
end
def test_pub_name
assert_equal("The Standing Order", @pub.pub_name)
end
def test_get_pubs_till_balance
assert_equal(500, @pub.till_balance)
end
def test_drinks_menu
assert_equal([@drink1, @drink2, @drink3], @pub.drinks_menu)
end
end
| true |
99739a4402db36f415f334f60b696660c41f1645 | Ruby | bureaucratix/count-elements-seattle-web-career-042219 | /count_elements.rb | UTF-8 | 210 | 3.5625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def count_elements(array)
counted_elements = {}
array.each do |element|
counted_elements[element] = 0 if counted_elements[element].nil?
counted_elements[element] += 1
end
counted_elements
end
| true |
22cd0bf653591f4b557f6f4701e04c0a995fe468 | Ruby | ha4gu/atcoder | /Other/2019/AISING/B.rb | UTF-8 | 164 | 3.203125 | 3 | [] | no_license | _n = gets
a, b = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i)
puts [ps.count { |p| p <= a }, ps.count { |p| p.between?(a+1, b) }, ps.count { |p| p > b }].min
| true |
072ba1f5a0c5ba9474d2163c257da81599ad2cd6 | Ruby | codykrieger/cube-ruby | /lib/cube.rb | UTF-8 | 3,073 | 3.078125 | 3 | [
"MIT",
"Ruby",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'cube/version'
module Cube
require 'date'
# We'll be sending data to Cube over a UDP socket.
require 'socket'
# Cube requires data to be in JSON format.
require 'json'
class Client
# A namespace to prepend to all Cube calls.
attr_accessor :namespace
# We'll use this to eliminate any unwanted/disallowed characters from our
# event type later on.
RESERVED_CHARS_REGEX = /[^\w\d]/
class << self
# Set to any logger instance that responds to #debug and #error (like the
# Rails or stdlib logger) to enable metric logging.
attr_accessor :logger
end
# Set 'er up with a host and port, defaults to `localhost:1180`.
#
# @param [String] The hostname to send metrics to.
# @param [Integer] The UDP port to send metrics to.
def initialize(host="localhost", port=1180)
@host, @port = host, port
end
# The primary endpoint for sending metrics to Cube.
#
# @param [String] The desired name of the new Cube event.
# @param [Array] A splat that takes an optional DateTime, an event id
# (typically an integer, but can be any object), and a Hash of data.
def send(type, *args)
time = nil
id = nil
data = nil
until args.empty?
arg = args.shift
case arg
when DateTime, Time
time ||= arg
when Hash
data ||= arg
else
id ||= arg
end
end
# Send off our parsed arguments to be further massaged and socketized.
actual_send type, time, id, data
end
private
# Actually send the given data to a socket, and potentially log it along
# the way.
#
# @param [String] The desired name of the new Cube event.
# @param [DateTime] Optional. A specific time when the Cube event occurred.
# @param [Object] Optional. Typically an integer, but can be any object.
# @param [Hash] Optional. Anything in this hash will be stored in the
# `data` subdocument of the Cube event.
def actual_send(type, time, id, data)
# Namespace support!
prefix = "#{@namespace}_" unless @namespace.nil?
# Get rid of any unwanted characters, and replace each of them with an _.
type = type.to_s.gsub RESERVED_CHARS_REGEX, '_'
# Start constructing the message to be sent to Cube over UDP.
message = {
type: "#{prefix}#{type}"
}
message[:time] = time.iso8601 unless time.nil?
message[:id] = id unless id.nil?
message[:data] = data unless data.nil?
# JSONify it, log it, and send it off.
message_str = message.to_json
self.class.logger.debug { "Cube: #{message_str}" } if self.class.logger
socket.send message_str, 0, @host, @port
rescue => err
self.class.logger.error { "Cube: #{err.class} #{err}" } if self.class.logger
end
# Helper for getting the socket. `@socket` can be set to a mock object to
# test without needing an actual UDP socket.
def socket ; @socket ||= UDPSocket.new ; end
end
end
| true |
19be8226ec7a9c0cc02e7fbf3293becc16f70480 | Ruby | Fishbone12/zadachi | /8.rb | UTF-8 | 486 | 2.96875 | 3 | [] | no_license | r1=Rational(1,2)
r2=Rational(1,3)
r3=Rational(1,8)
ro=Rational(1,r1+r2+r3)
puts ro.to_f
=begin Задача 8.
Три сопротивления R1, R2, R3 соединены параллельно. Найти
сопротивление соединения R0 по формуле:
1/R0 = 1/R1+ 1/R2+ 1/R3
Исходные данные взять из контрольного примера.
Контрольный пример: R1=2, R2=4, R3=8. Результат: R0=1.142857.
=end
| true |
3c8b0953aaf300245bfe2d7d06c2c565ff2656bd | Ruby | ellerynz/toy_robot_simulator | /lib/commands/null_command.rb | UTF-8 | 174 | 2.6875 | 3 | [] | no_license | class NullCommand < Command
def initialize(instruction)
@instruction = instruction
end
def execute
print "Unknown instruction '#{@instruction}'\n"
end
end
| true |
9d82cf6a6899c7d0fd24b331fe3557e559655d5e | Ruby | cheezenaan/procon | /atcoder/abc109/c.rb | UTF-8 | 146 | 2.75 | 3 | [] | no_license | # frozen_string_literal: true
n, x = gets.split.map(&:to_i)
xs = gets.split.map { |xi| (xi.to_i - x).abs }
puts xs.inject { |r, xi| r.gcd(xi) }
| true |
86f4170ba672dd2df4d6edbf35d66689d47b4caa | Ruby | Chanson9892/ruby-enumerables-reverse-each-word-lab-sea01-seng-ft-082420 | /reverse_each_word.rb | UTF-8 | 331 | 3.4375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(sentence)
string = sentence.split(" ")
new_sentence = []
new_sentence2 = []
string.each do |word|
new_sentence << word.reverse
end
result = new_sentence.join(" ")
result
string.collect do |word|
new_sentence2 << word.reverse
end
result2 = new_sentence2.join(" ")
result2
end
| true |
a889ee42435ed76f80c254c3106e7a47a9efc423 | Ruby | mitchellheiser/CA-challenges | /projects/mvc/view.rb | UTF-8 | 888 | 3.96875 | 4 | [] | no_license |
class StatsView
def greeting
puts "welcome to my awesome stats app"
end
def menu
puts "1. Insert numbers"
puts "2. List numbers"
puts "3. Show average"
puts "4. Quit"
gets.chomp.to_i
end
# def read_numbers
# values= []
# puts "please enter one number per line (-1 to end):"
# num = ''
# until num == 'end'
# num == gets.chomp
# values << num.to_i if num != 'end'
# end
# values
# end
def read_numbers
values = []
puts "Please enter one number per line ('end' to end):"
num = ''
until num == 'end'
num = gets.chomp
values << num.to_i if num != 'end'
end
values
end
def display_numbers(numbers)
puts "numbers: #{numbers}"
puts
end
def display_average(average)
puts "average: #{average}"
end
def quit
puts "Goodbye"
end
end | true |
6e0195ae3c99fef8c23d338fb6edc54da0a4fbb7 | Ruby | DeedaG/my-each-v-000 | /my_each.rb | UTF-8 | 201 | 3.1875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def my_each(words)
if block_given?
index = 0
while index < words.length
yield(words[index]) #
index = index + 1
end
words
else
prints "This block should not run!"
end
end
| true |
46f5ca401b7f370e734640d7201f9a27dedd8e85 | Ruby | Cireou/ruby-oo-practice-relationships-domains-yale-web-yss-052520 | /app/models/Easy/Bakery/ingredients.rb | UTF-8 | 398 | 3.203125 | 3 | [] | no_license | class Ingredient
attr_accessor :dessert, :name, :calorie
@@all = []
def initialize(args)
args.each{|key, val| self.send(("#{key}="), val)}
@@all << self
end
def bakery()
@dessert.bakery()
end
def self.find_all_by_name(name)
all().select{|ingredient| ingredient.name.include?(name)}
end
def self.all()
@@all
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.