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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4d7e6391807de8e358e804805cf0a59a5800b7e1 | Ruby | mwlang/kucoin-api | /spec/support/mock_websocket_server.rb | UTF-8 | 2,825 | 2.609375 | 3 | [
"MIT"
] | permissive | class MockWebsocketServer
HOST = '0.0.0.0'
PORT = 0
attr_accessor :connections, :response_message
def initialize
@connections = []
@response_message = {}
end
def _endpoint
port, host = Socket.unpack_sockaddr_in( EM.get_sockname( @signature ))
"wss://#{host}:#{port}/endpoint"
end
def start
@signature = EM.start_server(HOST, PORT, MockWebsocketConnection) do |mock_connection|
self.connections << mock_connection
mock_connection.server = self
end
end
def stop
EM.stop_server(@signature)
unless wait_for_connections_and_stop
# Still some connections running, schedule a check later
EM.add_periodic_timer(1) { wait_for_connections_and_stop }
end
end
def wait_for_connections_and_stop
if @connections.empty?
EM.stop
true
else
logger.debug "[MockWebsocketServer] -- Waiting for #{@connections.size} connection(s) to finish ..."
false
end
end
end
class MockWebsocketConnection < EventMachine::Connection
attr_accessor :server
attr_reader :driver
def initialize
@driver = WebSocket::Driver.server(self)
driver.on(:connect) do |e|
logger.debug '[WEBSOCKET - SERVER] CONNECT'
driver.start if WebSocket::Driver.websocket? driver.env
end
driver.on(:message) do |e|
logger.debug "[WEBSOCKET - SERVER] MESSAGE = #{e.data}"
driver.frame(server.response_message.merge(data: JSON.parse(e.data)).to_json)
close_connection_after_writing
end
driver.on(:close) do |e|
logger.debug '[WEBSOCKET - SERVER] CLOSE'
close_connection_after_writing
end
end
def post_init
logger.debug '[WEBSOCKET - SERVER] -- someone connected to the server!'
start_tls(verify_peer: true)
end
def write(data)
send_data(data)
end
def receive_data data
driver.parse(data)
end
def unbind
server.connections.delete(self)
end
end
def mock_websocket_server response_message=nil, &block
EM.run do
mock_server = MockWebsocketServer.new
mock_server.response_message = response_message || { foo: :bar }
mock_server.start
allow_any_instance_of(Kucoin::Api::Endpoints::Websocket::Response).to receive(:endpoint).and_return(mock_server._endpoint)
block.call(mock_server)
end
end
def mock_websocket_client_methods mock_server, response_message
error = proc { |e| logger.debug "[WEBSOCKET - CLIENT] ERROR : #{e.message}" }
close = proc { |e| logger.debug "[WEBSOCKET - CLIENT] CLOSED" }
open = proc { |e| logger.debug "[WEBSOCKET - CLIENT] OPEN" }
message = proc do |e|
logger.debug "[WEBSOCKET - CLIENT] : #{e.data}"
expect(JSON.parse(e.data)['data']).to eq(response_message)
mock_server.stop
end
{ open: open, message: message, error: error, close: close }
end
| true |
53a5b6e484eeec336915135f13b151e21967c954 | Ruby | botanicus/cart | /spec/cart/logger_stub_spec.rb | UTF-8 | 560 | 2.6875 | 3 | [
"MIT"
] | permissive | require File.join(File.dirname(__FILE__), '..', "spec_helper")
require "cart/logger_stub"
describe LoggerStub do
it "should works with lambdas" do
# just return the message
proc = lambda { |message| message }
logger = LoggerStub.new(proc)
logger.debug("Hey, it works!").should eql("Hey, it works!")
end
it "should works with methods" do
# just return the message
def just_return(message) ; message ; end
logger = LoggerStub.new(method(:just_return))
logger.debug("Hey, it works!").should eql("Hey, it works!")
end
end
| true |
28a37dd4be2761875053266647ebc050ef781985 | Ruby | mikeyhogarth/proplog | /spec/expressions/nonterminal_expressions/implication_spec.rb | UTF-8 | 615 | 2.765625 | 3 | [
"MIT"
] | permissive | require "spec_helper"
module Proplog
describe Expression::Implication do
subject { Expression::Implication.new("left", "right") }
describe "#to_s" do
it "returns the conjunction in string form" do
expect(subject.to_s).to eq "left → right"
end
end
describe "#premise" do
it "returns the 'left' side of the expression" do
expect(subject.premise).to eq subject.left
end
end
describe "#conclusion" do
it "returns the 'right' side of the expression" do
expect(subject.conclusion).to eq subject.right
end
end
end
end
| true |
f189f1a2a0b835c59c3b43a59e3f45be9f705800 | Ruby | PavloKuts/learn_ruby | /flat_search/bin/fs | UTF-8 | 2,559 | 2.78125 | 3 | [] | no_license | #! /usr/bin/env ruby
require 'logger'
require 'docopt'
require 'ruby-progressbar'
require_relative '../lib/flat_search'
require_relative '../lib/file_generator_factory'
require_relative '../lib/http_client'
require_relative '../lib/cache/sqlite_cache'
require_relative '../lib/ad_crawler'
class FlatSearchApp
DOC = 'Flat Search
Usage:
fs --version
fs --help
fs <olx_search_url> <file_path> [--format <format>] [--from <from>] [--to <to>]
Options:
--help, -h Show this screen
--version, -v Show the current app version
--format <format>, -f Output file format [default: txt]
--from <from> Start page [default: 1]
--to <to> Finish page'
def initialize(cache_class, http_client_class, file_generator, logger_class, logger_device, logger_level)
logger = logger_class.new(logger_device)
logger.level = logger_level
@docopt = Docopt.docopt(DOC)
format = @docopt['--format'].to_sym
@ad_crawler = AdCrawler.new(cache_class.new, http_client_class, logger)
@file_generator = FileGeneratorFactory.generator(format)
if @docopt['--version']
puts FlatSearch::VERSION
exit
end
ads = olx_crawl if @docopt['<olx_search_url>']
@file_generator.generate(@docopt['<file_path>'], ads)
rescue Docopt::Exit => e
puts e.message
end
private
def olx_crawl
url = @docopt['<olx_search_url>']
start_page = @docopt['--from'].to_i
finish_page = @docopt['--to'] ? @docopt['--to'].to_i : @docopt['--to']
last_page_number = @ad_crawler.last_page_number(url)
finish_page = last_page_number unless @docopt['--to']
if start_page > finish_page.to_i || start_page > last_page_number || start_page <= 0 || finish_page.to_i <= 0
error("--from must be <= --to and both must be > 0 and < #{last_page_number} for this URL")
end
progress_bar = nil
ads = @ad_crawler.ads(url, start_page, finish_page) do |count|
progress_bar ||= ProgressBar.create(
title: "Ads",
starting_at: 0,
total: count,
progress_mark: '▓',
length: 80,
format: '%t crawling: [%B] %p%% :: %a'
)
progress_bar.increment
end
error("Wrong URL (#{url}) given!") unless ads
ads
end
def error(message)
puts
puts "ERROR: #{message}!"
puts
exit
end
end
level = FlatSearch::DEBUG ? FlatSearch::DEBUG : Logger::UNKNOWN
FlatSearchApp.new(AdsSQLiteCache, HttpClient, FileGeneratorFactory, Logger, STDOUT, level)
| true |
feeb0c6099746a3f77bb2f4c7fded068d8bca5bc | Ruby | MetaArchive/educopia | /pln_admin/conspectus/ruby/app/models/content_provider_status_item.rb | UTF-8 | 1,189 | 2.53125 | 3 | [] | no_license | class ContentProviderStatusItem < ActiveRecord::Base
belongs_to :content_provider;
validates_presence_of :content_provider_id;
validates_presence_of :cache;
validates_presence_of :size;
# return size in MB
def size_mb()
return size / 1048576 #(1024 * 1024)
end
# update preservation status information of given content_provider
# deletes existing information and updates status of content provider collections
# and then propagtes the info
# if !StatusMonitor.Active this has the effect of deleting al existing status info
def self.update(content_provider)
content_provider.content_provider_status_items.each { |cs| cs.delete }
if (StatusMonitor.active?) then
cs = {};
content_provider.collections.each { |col|
col.collection_status_items.each { |csi|
if (cs[csi.cache].nil?) then
cs[csi.cache] = ContentProviderStatusItem.new(
:content_provider => content_provider,
:cache => csi.cache)
end
cs[csi.cache].size = cs[csi.cache].size + csi.size;
}
}
cs.each{ |k,v| v.save! }
end
end
end
| true |
fcd13dbdbcef1a5d34ef20671d772f29dd7cc922 | Ruby | popmedic/roku-buildbifs | /lib/poplib/IMDB.rb | UTF-8 | 9,435 | 2.71875 | 3 | [] | no_license | require 'uri'
require 'net/http'
module Poplib
module IMDB
# define our constants
$imdb_url = "http://www.imdb.com/"
$ask_uri_fmt = $imdb_url + "find?q=%s&s=tt" # url for the imdb search
$ask2_uri_fmt = $imdb_url + "search/title?title=%s"
$title_uri_fmt = $imdb_url + "title/tt%s/"
$block_regex_fmt = "<p><b>Titles \\(%s Matches\\)<\\/b> \\(Displaying ([0-9]+) Results{0,1}\\)<table><tr>(.*)<\\/tr><\\/table> <\\/p>"
$title_regex = /<a href="\/title\/tt([0-9]+)\/" onclick="\(new Image\(\)\)\.src\=\'\/rg\/find-title-[0-9]+\/title_.*\/images\/b\.gif\?link=\/title\/tt[0-9]+\/\'\;\">(.*)<\/a> \(([0-9]{4})\)/
$title_regex_pre = /<a href="\/title\/tt([0-9]+)\/" onclick="\(new Image\(\)\)\.src\=\'\/rg\/find-title-[0-9]+\/title_.{0,7}\/images\/b\.gif\?link=\/title\/tt[0-9]+\/\'\;\">/
$title_regex_post = /<\/a> \(([0-9]{4}).{0,4}\)/
$title_desc_regex_pre = /<p itemprop="description">/
$title_desc_regex_post = /<\/p>/
$title_image_regex_pre = /id="img_primary"/
$title_image_regex_post = /<img src="(.+)"[ \t\n\r]+style=/
$title_tt_regex = /"\/title\/tt([0-9]+)\/"/
$title_name_regex_pre = /<h1 class="header" itemprop="name">/
$title_name_regex_post = /<span/
$title_year_regex_pre = /<a href="\/year\//
$title_year_regex_post = /\/">/
class Title
attr_reader :id, :uri, :uri_str
TO_S_FMT = "%s (%s) [%s]\nDescription:\n\t%s\nImage: %s\n"
def initialize(id, title = nil, year = nil)
@title = title
@id = id
@year = year
@uri_str = $title_uri_fmt % @id
@uri = URI(@uri_str)
@html = nil
end
def ==(y)
if y.is_a? String
return @id == y
end
return false
end
def to_s
return TO_S_FMT % [self.title, self.year, self.uri_str, self.description, self.image_url]
end
def download
@html = Net::HTTP.get(@uri)
end
def description
self.download if @html == nil
d = @html.partition($title_desc_regex_pre)
(d[2] == nil) ? (return nil) : (return d[2].partition($title_desc_regex_post)[0].strip)
end
def image_url
self.download if @html == nil
i = @html.partition($title_image_regex_pre)
return nil if i[2] == nil
m = i[2].match($title_image_regex_post)
(m == nil) ? (return nil) : (return m[1])
end
def title
return @title if @title != nil
self.download if @html == nil
p1 = @html.partition($title_name_regex_pre)
return '' if(p1[2]) == nil
p2 = p1[2].partition($title_name_regex_post)
return '' if(p2[0] == nil)
@title = p2[0].strip
return @title
end
def year
return @year if @year != nil
self.download if @html == nil
p1 = @html.partition($title_year_regex_pre)
return '' if(p1[2]) == nil
p2 = p1[2].partition($title_year_regex_post)
return '' if(p2[0] == nil)
@year = p2[0].strip
return @year
end
def desc_to_mac_clipboard
IO.popen('pbcopy', 'w').write(self.description)
end
end
class Search
attr_reader :popular_titles, :exact_titles, :part_titles, :approx_titles, :search_str, :ask_uri, :ask_res
attr_writer :popular_titles, :exact_titles, :part_titles, :approx_titles
def initialize(search_str)
self.search_str(search_str)
@popular_titles = []
@exact_titles = []
@part_titles = []
@approx_titles = []
@titles = []
end
def search
# create our asking for uri
@ask_uri = URI($ask_uri_fmt % @search_str)
# get our result
@ask_res = Net::HTTP.get(@ask_uri)
self.search2
@popular_titles = parseBlock(/<p><b>Popular Titles<\/b> \(Displaying ([0-9]+) Results{0,1}\)<table><tr>.*/)
@exact_titles = parseBlock(/<p><b>Titles \(Exact Matches\)<\/b> \(Displaying ([0-9]+) Results{0,1}\)<table><tr>(.*)<\/tr><\/table> <\/p>/)
@part_titles = parseBlock(/<p><b>Titles \(Partial Matches\)<\/b> \(Displaying ([0-9]+) Results{0,1}\)<table><tr>.*<\/tr><\/table> <\/p>/)
@approx_titles = parseBlock(/<p><b>Titles \(Approx Matches\)<\/b> \(Displaying ([0-9]+) Results{0,1}\)<table><tr>.*<\/tr><\/table> <\/p>/)
end
def search_str str
@o_search_str = str
@search_str = str.gsub(/[ \n\t\c\r]/, '+')
@search_uri = URI($ask_uri_fmt % @search_str)
@search2_uri = URI($ask2_uri_fmt % @search_str)
end
def to_s
# puts "%s:\t%s" % [@ask_uri, @ask_res] if(self.nothing?)
rtn = "Search Results:\n"
if @popular_titles != nil
rtn += "Popular Matches:\n"
@popular_titles.each do |t|
rtn += "\t%s (%s) [%s]\n\tDescription:\n\t\t\t%s\n\tImage URL: %s\n" % [t.title, t.year, t.uri_str, t.description, t.image_url]
end
end
if @exact_titles != nil
rtn += "Exact Matches:\n"
@exact_titles.each do |t|
rtn += "\t%s (%s) [%s]\n\tDescription:\n\t\t\t%s\n\tImage URL: %s\n" % [t.title, t.year, t.uri_str, t.description, t.image_url]
end
end
if @part_titles != nil
rtn += "Partial Matches:\n"
@part_titles.each do |t|
rtn += "\t%s (%s) [%s]\n\tDescription:\n\t\t\t%s\n\tImage URL: %s\n" % [t.title, t.year, t.uri_str, t.description, t.image_url]
end
end
if @approx_titles != nil
rtn += "Approx Matches:\n"
@approx_titles.each do |t|
rtn += "\t%s (%s) [%s]\n\tDescription:\n\t\t\t%s\n\tImage URL: %s\n" % [t.title, t.year, t.uri_str, t.description, t.image_url]
end
end
if @titles != nil
rtn += "Title Search Matches:\n"
@titles.each do |t|
rtn += "\t%s (%s) [%s]\n\tDescription:\n\t\t\t%s\n\tImage URL: %s\n" % [t.title, t.year, t.uri_str, t.description, t.image_url]
end
end
return rtn
end
def getTop
if @titles != nil && @titles[0] != nil
return @titles[0]
elsif @popular_titles != nil && @popular_titles[0] != nil
return @popular_titles[0]
elsif @exact_titles != nil && @exact_titles[0] != nil
return @exact_titles[0]
elsif @part_titles != nil&& @part_titles[0] != nil
return @part_titles[0]
elsif @approx_titles != nil && @approx_titles[0] != nil
return @approx_titles[0]
else
return false
end
end
def openTop
cmd = nil
t = self.getTop
puts "Opening: %s" % t
cmd = "open \"%s\"" % t.image_url unless t === false
if cmd != nil
puts cmd
`#{cmd}`
end
puts "Placing Description in Clipboard: SUCCESS"
t.desc_to_mac_clipboard
end
def count
(@popular_titles == nil) ? (ptc = 0) : ptc = @popular_titles.length
(@exact_titles == nil) ? (etc = 0) : etc = @exact_titles.length
(@part_titles == nil) ? (prtc = 0) : prtc = @part_titles.length
(@approx_titles == nil) ? (atc = 0) : atc = @approx_titles.length
(@titles == nil) ? (ttc = 0) : ttc = @titles.length
return ptc + etc + prtc + atc + ttc
end
def results
rtn = Array.new()
unless @popular_titles == nil; rtn.concat(@popular_titles); end
unless @exact_titles == nil; rtn.concat(@exact_titles);end
unless @part_titles == nil; rtn.concat(@part_titles); end
unless @approx_titles == nil; rtn.concat(@approx_titles); end
unless @titles == nil; rtn.concat(@titles); end
return rtn
end
def nothing?
c = self.count
(c == 0) ? (return true) : (return false)
end
protected
def search2
# puts "Get " + @search2_uri.to_s
@ask_res = Net::HTTP.get(@search2_uri)
# puts "Got " + @search2_uri.to_s
s = @ask_res.dup
i = 0
while (m = s.match($title_tt_regex))
if(!@titles.include?(m[1]))
t = Title.new m[1]
@titles.push t
end
s = m.post_match
end
end
private
def getTitles(block)
rtn = Array.new
nb = String.new(block)
t = nb.partition $title_regex_pre
while t[0] != $title_regex_pre && t[1] != nil
id_m = t[1].match $title_regex_pre
break if id_m == nil
p = t[2].partition $title_regex_post
break if p[1] == nil
year_m = p[1].match $title_regex_post
year_m = "????" if year_m == nil
title = p[0]
t = t[2].partition $title_regex_pre
mov = Title.new id_m[1], title, year_m[1]
rtn.push mov
end
return rtn
end
def parseBlock(idx_on_regex)
m = @ask_res.match(idx_on_regex)
if m != nil
mb = m[0][0, m[0].index(/<\/tr><\/table>/)]
return getTitles(mb)
end
end
end
end
end | true |
c587b249fbb437e109fc5af6e2da34567e690aa3 | Ruby | mackenzie-km/ruby-collaborating-objects-lab-online-web-sp-000 | /lib/song.rb | UTF-8 | 372 | 3.21875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Song
attr_accessor :name, :artist
def initialize(name)
@name = name
end
def self.new_by_filename(input)
filename = input.split(" - ")
found_artist = Artist.find_or_create_by_name(filename[0])
filename[1] = Song.new(filename[1])
filename[1].artist = found_artist
found_artist.songs << filename[1].name
filename[1]
end
end | true |
e016d50af1fb6e7a1315baf0cbedd24eeba672fa | Ruby | gustaveH/programming-univbasics-4-intro-to-hashes-lab-atlanta-web-021720 | /intro_to_ruby_hashes_lab.rb | UTF-8 | 420 | 3.125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def new_hash
Hash.new
end
def my_hash
{ "name"=> "Gustave", "age" => "29"}
end
def pioneer
{name:"Grace Hopper"}
end
def id_generator
{id:3}
end
def my_hash_creator(key, value)
my_hash_creator = { key => value}
return my_hash_creator
end
def read_from_hash(hash, key)
hash[key]
end
def update_counting_hash(hash, key)
hash[key]
if hash[key]
hash[key] += 1
else
hash[key] = 1
end
hash
end
| true |
3dd08c87503fb7db67207398692a15ea83df9891 | Ruby | yalazad/ruby_challenges | /if_else.rb | UTF-8 | 808 | 3.921875 | 4 | [] | no_license | if 1 + 1 == 2
puts "1 and 1 does indeed equal 2"
end
puts "\n\nWhat is your name?"
my_name = gets.chomp
#my_name = 'Yasmin'
if (my_name == 'Skillcrush')
puts "Hellooooo, Skillcrush!"
else
puts "Oops, I thought your name was Skillcrush. Sorry about that, #{my_name}!"
end
puts "\n\nWhat is you favourite colour?"
fav_colour = gets.chomp
if (fav_colour == 'red')
puts "Red like fire!"
elsif (fav_colour == 'orange')
puts "Orange is the New Black!"
elsif (fav_colour == 'yellow')
puts "Yello daffodils are so pretty in the spring!"
elsif (fav_colour == 'green')
puts "Have you been to the Emerald city in Oz?"
elsif (fav_colour == 'blue')
puts "Blue like the sky!"
elsif (fav_colour == 'purple')
puts "Purple plums are the tastiest."
else
puts "Hmm, well I don't know what that colour is!"
end
| true |
2731935548c5bb4a7165d2ed5142dc357577994f | Ruby | xavierserena/ics_bc_s18 | /week4/recursion_practice/array_min.rb | UTF-8 | 240 | 3.828125 | 4 | [] | no_license | def array_min(array, len)
if len == 1
array[0]
else
last, s_to_last = array.pop, array[len - 2]
if last < s_to_last
array[len - 2] = last
end
array_min(array, len - 1)
end
end
puts array_min [1, 2, 3, 4], 4
| true |
43f37b2577e63d9f1e3c984ae12b43a1fa0549a0 | Ruby | jalexy12/new_shack | /ss_new.rb | UTF-8 | 716 | 4.21875 | 4 | [] | no_license | class Ingredient
attr_accessor :price
def initialize(name, price)
@name = name
@price = price
end
end
# Menu
banana = Ingredient.new("Banana", 2)
caramel = Ingredient.new("Caramel", 1)
berries = Ingredient.new("Berries", 3)
class MilkShake
def initialize
@base_price = 3
@ingredients = []
end
def add_ingredient(single_ingredient)
@ingredients.push(single_ingredient)
end
def total_price
total = @base_price
# Go through all of the ingredients
@ingredients.each do | single_ingredient |
total += single_ingredient.price
end
# Return the total
total
end
end
my_shake = MilkShake.new
my_shake.add_ingredient(banana)
my_shake.add_ingredient(berries)
puts my_shake.total_price
| true |
f6c8824bca54db9eeba3225778764e6c29834521 | Ruby | asimy/madeleine-1 | /samples/dictionary_server.rb | UTF-8 | 1,916 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | #
# A dictionary server using Distributed Ruby (DRb).
#
# All modifications to the dictionary are done as commands,
# while read-only queries (i.e 'lookup') are done directly.
#
# First launch this server in the background, then use
# dictionary_client.rb to look up and add items to the
# dictionary.
# You can kill the server at any time. The contents of the
# dictionary will still be there when you restart it.
#
# DRb is available at http://raa.ruby-lang.org/list.rhtml?name=druby
#
$LOAD_PATH.unshift(".." + File::SEPARATOR + "lib")
require 'madeleine'
require 'drb'
class Dictionary
def initialize
@data = {}
end
def add(key, value)
@data[key] = value
end
def lookup(key)
@data[key]
end
end
class Addition
def initialize(key, value)
@key, @value = key, value
end
def execute(system)
system.add(@key, @value)
end
end
class Lookup
def initialize(key)
@key = key
end
def execute(system)
system.lookup(@key)
end
end
class DictionaryServer
def initialize(madeleine)
@madeleine = madeleine
@dictionary = madeleine.system
end
def add(key, value)
# When adding a new key-value pair we modify the system, so
# this operation has to be done through a command.
@madeleine.execute_command(Addition.new(key, value))
end
def lookup(key)
# A lookup is a read-only operation, so we can do it as a non-logged
# query. If we weren't worried about concurrency problems we could
# have just called @dictionary.lookup(key) directly instead.
@madeleine.execute_query(Lookup.new(key))
end
end
madeleine = SnapshotMadeleine.new("dictionary-base") { Dictionary.new }
Thread.new(madeleine) {
puts "Taking snapshot every 30 seconds."
while true
sleep(30)
madeleine.take_snapshot
end
}
DRb.start_service("druby://localhost:1234",
DictionaryServer.new(madeleine))
DRb.thread.join
| true |
4f178f696165ebef60544af82068e7447ec034df | Ruby | d-theus/homemade | /app/helpers/orders_helper.rb | UTF-8 | 1,450 | 2.609375 | 3 | [] | no_license | module OrdersHelper
def statuses
Order::STATUS_TABLE
.keys
.select { |k| k.to_s != 'nil' }
.map { |st| [ I18n.t("activerecord.values.order.status.#{st}"), st ] }
.unshift(['любой', nil])
end
def payment_methods
Order::PAYMENT_METHODS
.map { |pm| [ I18n.t("activerecord.values.order.payment_method.#{pm}"), pm ] }
end
def intervals
[
["10:00 ― 13:00", "10-13"],
["13:00 ― 18:00", "13-18"],
["18:00 ― 21:00", "18-21"],
["10:00 ― 21:00", "10-21"]
]
end
def prices
price_method = Order.discount? ? :discount_price_for : :original_price_for
Order::PRICES.map do |count, prices_for_servings|
prices_for_servings.each do |servings, _|
["#{count} ужинов за #{send(price_method, count: count, servings: servings)} р.", "#{count} на #{servings}"]
end
end
end
def options_for_count
[
["5 ужинов", 5],
["3 ужинa", 3]
]
end
def options_for_servings
[
["На 2-x человек", 2],
["На 3-x человек", 3],
["На 4-x человек", 4]
]
end
def discount_price_for(hash)
(Order.price_for(hash) * (1.0 - Order::DISCOUNT)).floor
end
def original_price_for(hash)
Order.price_for(hash)
end
def discount?
@order_discount ||= Order.discount?
end
def discount
"#{(Order::DISCOUNT * 100).to_i}%" if Order::DISCOUNT
end
end
| true |
92ddf9cdbc9b22b7a5047cd60074be40686a8ef4 | Ruby | marofa/ruby-skillcrush-challenges | /fizzbuzz.rb | UTF-8 | 160 | 3.234375 | 3 | [] | no_license | i = 0
while i < 101
if i%3 ==0 && i%5==0
puts "FizzBuzz"
elsif i%3 == 0
puts "Fizz"
elsif i%5 == 0
puts "Buzz"
else
puts i
end
i+=1
end
| true |
2b5c6ef5311eeb9a515a1def3d3eb48d995a14b8 | Ruby | nemrow/fvc_server | /app/models/event.rb | UTF-8 | 946 | 2.6875 | 3 | [] | no_license | class Event < ActiveRecord::Base
attr_accessible :min_time, :max_time, :duration, :day_index, :description, :title, :all_fvc, :extra_cost, :reg_required
before_save :create_max_time
def create_max_time
duration_in_seconds = self.duration.hour.hours + self.duration.min.minutes
self.max_time = self.min_time + duration_in_seconds
end
def self.sorted_events
days_events_hash = {}
Event.all.each do |event|
day = DayMapper.new(event.day_index).day
days_events_hash.add_or_create_and_add(day, event)
end
Event.build_weeks_event_hash(days_events_hash)
end
def self.build_weeks_event_hash(days_events_hash)
Date.full_week_array.map do |day|
{
:day => day,
:events => Event.sort_days_event(days_events_hash[day])
}
end
end
def self.sort_days_event(events_array)
return [] if events_array.nil?
events_array.sort_by{|event| event.min_time}
end
end
| true |
fdcf338e97cdb5a0ba96e8a08443cdf6916645b8 | Ruby | ericgj/trackd | /lib/core_ext/struct.rb | UTF-8 | 244 | 2.671875 | 3 | [
"MIT"
] | permissive |
require 'json/pure'
class Struct
def to_h
self.members.inject({}) do |memo, m|
memo[m.to_sym] = self[m.to_sym]; memo
end
end
# for json-encoding without class name
def to_json(*a)
self.to_h.to_json(*a)
end
end
| true |
570fbd1a439a020d516214a1da08b2b4f0aff97f | Ruby | infectedfate/BlackJack | /dealer.rb | UTF-8 | 181 | 2.703125 | 3 | [] | no_license | require_relative 'player'
class Dealer < Player
def take_card?
card_sum < 17 && @hand.cards.size == 2
end
def hide_cards
@hand.cards.map { '*' }.join(' ')
end
end
| true |
9b68dc87a8d296884ba688dece6fda0931514679 | Ruby | grosser/language_sniffer | /lib/language_sniffer/language.rb | UTF-8 | 8,615 | 3.171875 | 3 | [
"MIT"
] | permissive | require 'yaml'
module LanguageSniffer
# Language names that are recognizable by GitHub. Defined languages
# can be highlighted, searched and listed under the Top Languages page.
#
# Languages are defined in `lib/language_sniffer/languages.yml`.
class Language
@languages = []
@overrides = {}
@index = {}
@name_index = {}
@alias_index = {}
@extension_index = {}
@filename_index = {}
# Valid Languages types
TYPES = [:data, :markup, :programming]
# Internal: Test if extension maps to multiple Languages.
#
# Returns true or false.
def self.ambiguous?(extension)
@overrides.include?(extension)
end
# Include?: Return overridden extensions.
#
# Returns extensions Array.
def self.overridden_extensions
@overrides.keys
end
# Internal: Create a new Language object
#
# attributes - A hash of attributes
#
# Returns a Language object
def self.create(attributes = {})
language = new(attributes)
@languages << language
# All Language names should be unique. Warn if there is a duplicate.
if @name_index.key?(language.name)
warn "Duplicate language name: #{language.name}"
end
# Language name index
@index[language.name] = @name_index[language.name] = language
language.aliases.each do |name|
# All Language aliases should be unique. Warn if there is a duplicate.
if @alias_index.key?(name)
warn "Duplicate alias: #{name}"
end
@index[name] = @alias_index[name] = language
end
language.extensions.each do |extension|
if extension !~ /^\./
warn "Extension is missing a '.': #{extension.inspect}"
end
unless ambiguous?(extension)
# Index the extension with a leading ".": ".rb"
@extension_index[extension] = language
# Index the extension without a leading ".": "rb"
@extension_index[extension.sub(/^\./, '')] = language
end
end
language.overrides.each do |extension|
if extension !~ /^\./
warn "Extension is missing a '.': #{extension.inspect}"
end
@overrides[extension] = language
end
language.filenames.each do |filename|
@filename_index[filename] = language
end
language
end
# Public: Get all Languages
#
# Returns an Array of Languages
def self.all
@languages
end
# Public: Look up Language by its proper name.
#
# name - The String name of the Language
#
# Examples
#
# Language.find_by_name('Ruby')
# # => #<Language name="Ruby">
#
# Returns the Language or nil if none was found.
def self.find_by_name(name)
@name_index[name]
end
# Public: Look up Language by one of its aliases.
#
# name - A String alias of the Language
#
# Examples
#
# Language.find_by_alias('cpp')
# # => #<Language name="C++">
#
# Returns the Language or nil if none was found.
def self.find_by_alias(name)
@alias_index[name]
end
# Public: Look up Language by extension.
#
# extension - The extension String. May include leading "."
#
# Examples
#
# Language.find_by_extension('.rb')
# # => #<Language name="Ruby">
#
# Returns the Language or nil if none was found.
def self.find_by_extension(extension)
@extension_index[extension]
end
# Public: Look up Language by filename.
#
# filename - The path String.
#
# Examples
#
# Language.find_by_filename('foo.rb')
# # => #<Language name="Ruby">
#
# Returns the Language or nil if none was found.
def self.find_by_filename(filename)
basename, extname = File.basename(filename), File.extname(filename)
@filename_index[basename] || @extension_index[extname]
end
# Public: Look up Language by its name.
#
# name - The String name of the Language
#
# Examples
#
# Language['Ruby']
# # => #<Language name="Ruby">
#
# Language['ruby']
# # => #<Language name="Ruby">
#
# Returns the Language or nil if none was found.
def self.[](name)
@index[name]
end
# Internal: Initialize a new Language
#
# attributes - A hash of attributes
def initialize(attributes = {})
# @name is required
@name = attributes[:name] || raise(ArgumentError, "missing name")
# Set type
@type = attributes[:type] ? attributes[:type].to_sym : nil
# Set aliases
@aliases = [default_alias_name] + (attributes[:aliases] || [])
# Set pygments lexer
@lexer = attributes[:lexer] || name
# Set legacy search term
@search_term = attributes[:search_term] || default_alias_name
# Set extensions or default to [].
@extensions = attributes[:extensions] || []
@overrides = attributes[:overrides] || []
@filenames = attributes[:filenames] || []
@primary_extension = attributes[:primary_extension] || default_primary_extension || extensions.first
# Prepend primary extension unless its already included
if primary_extension && !extensions.include?(primary_extension)
@extensions = [primary_extension] + extensions
end
# If group name is set, save the name so we can lazy load it later
if attributes[:group_name]
@group = nil
@group_name = attributes[:group_name]
# Otherwise we can set it to self now
else
@group = self
end
end
# Public: Get proper name
#
# Examples
#
# # => "Ruby"
# # => "Python"
# # => "Perl"
#
# Returns the name String
attr_reader :name
# Public: Get type.
#
# Returns a type Symbol or nil.
attr_reader :type
# Public: Get pygments lexer name.
#
# Returns a lexer name or nil.
attr_reader :lexer
# Public: Get aliases
#
# Examples
#
# Language['C++'].aliases
# # => ["cpp"]
#
# Returns an Array of String names
attr_reader :aliases
# Deprecated: Get code search term
#
# Examples
#
# # => "ruby"
# # => "python"
# # => "perl"
#
# Returns the name String
attr_reader :search_term
# Public: Get extensions
#
# Examples
#
# # => ['.rb', '.rake', ...]
#
# Returns the extensions Array
attr_reader :extensions
# Deprecated: Get primary extension
#
# Defaults to the first extension but can be overriden
# in the languages.yml.
#
# The primary extension can not be nil. Tests should verify this.
#
# This attribute is only used by app/helpers/gists_helper.rb for
# creating the language dropdown. It really should be using `name`
# instead. Would like to drop primary extension.
#
# Returns the extension String.
attr_reader :primary_extension
# Internal: Get overridden extensions.
#
# Returns the extensions Array.
attr_reader :overrides
# Public: Get filenames
#
# Examples
#
# # => ['Rakefile', ...]
#
# Returns the extensions Array
attr_reader :filenames
# Internal: Get default alias name
#
# Returns the alias name String
def default_alias_name
name.downcase.gsub(/\s/, '-')
end
# Internal: Get default primary extension.
#
# Returns the extension String.
def default_primary_extension
extensions.first
end
# Public: Get Language group
#
# Returns a Language
def group
@group ||= Language.find_by_name(@group_name)
end
# Public: Return name as String representation
def to_s
name
end
def ==(other)
eql?(other)
end
def eql?(other)
equal?(other)
end
def hash
name.hash
end
end
YAML.load_file(File.expand_path("../languages.yml", __FILE__)).each do |name, options|
Language.create(
:name => name,
:type => options['type'],
:aliases => options['aliases'],
:lexer => options['lexer'],
:group_name => options['group'],
:search_term => options['search_term'],
:extensions => options['extensions'],
:primary_extension => options['primary_extension'],
:overrides => options['overrides'],
:filenames => options['filenames']
)
end
end
| true |
26133cf7f0513ecfc4cc76cae13af2a43be4328d | Ruby | salman-karim/inject-challenge | /spec/inject_spec.rb | UTF-8 | 1,132 | 3.1875 | 3 | [] | no_license | require 'inject'
describe Array do
describe 'new_inject_block' do
it 'should use first element of array as default argument' do
expect([3,4,5].new_inject_block {|a,b| a + b}).to eq 12
end
it 'should use first element of array as default argument' do
expect([1,2,3].new_inject_block {|a,b| a + b}).to eq 6
end
it 'should accept an argument as a starting value' do
expect([3,4,5].new_inject_block(5) {|a,b| a + b}).to eq 17
end
it 'should work with string elements' do
word_array = %w{ cat sheep bear }
expect(word_array.new_inject_block { |memo, word| memo.length > word.length ? memo : word }).to eq "sheep"
end
it 'should accept a symbol(+)' do
expect([5,6,7,8,9,10].new_inject_sym(:+)).to eq 45
end
it 'should accept a symbol(*)' do
expect([3,4,5].new_inject_sym(:*)).to eq 60
end
it 'should accept a symbol(+) with an argument' do
expect([5,6,7,8,9,10].new_inject_sym(5,:+)).to eq 50
end
it 'should accept a symbol(*) with an argument' do
expect([3,4,5].new_inject_sym(2,:*)).to eq 120
end
end
end
| true |
da2bc661913c771b1340681920c4d00306cd46f4 | Ruby | tliff/systeminformation | /lib/systeminformation/linux/cpu.rb | UTF-8 | 1,177 | 2.578125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module SystemInformation
module Linux
class CPU
def initialize
@prev_data = read_data
end
def utilization
new_data = read_data
returnhash = {}
new_data.keys.each do |key|
difference = @prev_data[key].zip(new_data[key]).map{|i| i[1].to_f - i[0].to_f}
difference
sum = difference.inject{|a,b| a+b}
difference.map!{|i| i/sum}.map!{|i| i.nan? ? 0 : i}
returnhash[key] = {
:user => difference[0],
:nice => difference[1],
:system => difference[2],
:idle => difference[3],
:running => difference[4],
:iowait => difference[5],
:irq => difference[6],
:softirq => difference[7]
}
end
@prev_data = new_data
return returnhash
end
private
def read_data
data = {}
File.open('/proc/stat','r') do |f|
f.readlines.select{|l| l =~ /^(cpu\d*) /}.each do |l|
cpu, *rest = l.split
data[cpu] = rest
end
end
data
end
end
end
end
| true |
88ebdda06ac0541eabb2ed49b0bb69e8b0682354 | Ruby | mfilej/zerop | /lib/episode.rb | UTF-8 | 551 | 2.546875 | 3 | [] | no_license | require "forwardable"
class Episode
class << self
extend Forwardable
def_delegators :collection, :save, :find, :find_one
def collection
@collection ||= Zero.db_connection["episodes"].tap do |c|
c.create_index([[:pubdate, -1]])
end
end
KEY = "_id"
def [](id)
find_one(KEY => id.to_i)
end
def []=(id, attrs)
save attrs.merge(KEY => id.to_i)
end
def newest_first
find.sort ['pubdate', -1]
end
def latest(num)
newest_first.limit(num)
end
end
end
| true |
6f5f2666297b79a8c1e8299e166178b07351b0a5 | Ruby | cba1067950/sql-library-lab-dumbo-web-051319 | /lib/querying.rb | UTF-8 | 1,301 | 2.6875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def select_books_titles_and_years_in_first_series_order_by_year
"SELECT books.title, books.year
FROM books
JOIN series ON books.series_id = series.id
WHERE series.id = 1
ORDER BY books.year;"
end
def select_name_and_motto_of_char_with_longest_motto
"SELECT characters.name, characters.motto
FROM characters
WHERE LENGTH(characters.motto) = (SELECT max(LENGTH(characters.motto)) FROM characters);"
end
def select_value_and_count_of_most_prolific_species
"SELECT species, COUNT(species)
FROM characters
GROUP BY species
ORDER BY COUNT(species)
DESC LIMIT 1
;"
end
def select_name_and_series_subgenres_of_authors
"SELECT authors.name, subgenres.name
FROM subgenres
JOIN series ON subgenre_id = subgenres.id
JOIN authors ON authors.id = series.author_id
;"
end
def select_series_title_with_most_human_characters
"SELECT series.title
FROM series
JOIN characters ON series_id = series.id
WHERE characters.species = \"human\"
ORDER BY series.title
ASC LIMIT 1
;"
end
def select_character_names_and_number_of_books_they_are_in
"SELECT characters.name, COUNT(books.id)
FROM characters
JOIN character_books ON character_id = characters.id
JOIN books ON books.id = book_id
GROUP BY characters.name
ORDER BY COUNT(books.id) DESC
;"
end
| true |
12c06864e8006b1efd2e441592c8ea4c4972dbea | Ruby | Archethought/sapling | /lib/sapling/seed.rb | UTF-8 | 1,129 | 2.5625 | 3 | [
"MIT"
] | permissive | module Sapling
class Seed
attr_reader :name, :associations
def initialize(name)
@name = name
@attributes = []
@definition = Module.new
@associations = {}
end
def model_class
name.to_s.classify.constantize
end
def attributes
Hash[ @attributes.map {|attr| [attr, @definition.send(attr)]} ]
end
def sequence(name, &block)
sequence = Sequence.new("#{self.name}_#{name}", block)
Sapling.register_sequence(sequence)
seq_name = "#{@name}_#{name}"
define_attribute(name) do
Sapling.sequences.find(seq_name).next
end
end
def association(name, opts={})
opts[:class_name] ||= name.to_s.classify
@associations[opts[:class_name].constantize] = name
end
def method_missing(name, value=nil, opts={}, &block)
if value || block_given?
m = value ? proc { value } : block
define_attribute(name, &m)
else
super
end
end
def define_attribute(name, &block)
@definition.define_singleton_method(name, &block)
@attributes << name
end
end
end
| true |
e1098f7c4b050d24074d57ea2b7fb11206b58d9c | Ruby | optionalg/quick-logger | /lib/quick-logger.rb | UTF-8 | 694 | 2.796875 | 3 | [] | no_license | require 'logger'
module Quick
# quick and dirty logger: just inherit from here,
# set the filename attribute then you're ready to go
class Logger
class << self
attr_accessor :filename
def filename_path
if defined?(Rails)
File.join Rails.root, 'log', [@filename, Rails.env, 'log'].join('.')
else
[@filename, 'log'].join('.')
end
end
def method_missing(log_level, message)
@logger ||= ::Logger.new(filename_path)
if ::Logger::SEV_LABEL.include?(log_level.to_s.upcase)
@logger.send log_level, "[#{Time.now}] #{message}"
else
super
end
end
end
end
end
| true |
3ba8e698ca97417318520661e341d203d6c00091 | Ruby | tmbx/tbxsos-config | /lib/reseller.rb | UTF-8 | 631 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #
# Reseller class
#
require 'activator'
require 'license'
class Reseller
def Reseller.is_reseller?(org_id=nil)
begin
if org_id.nil?
org_kdn = Activator.main_org_id()
org_id = Organization.find(:first, {:condition => ["name = ?", org_kdn]}).org_id
end
if not org_id.nil?
license = License.from_org_id(org_id)
#KLOGGER.info("is reseller: #{license.is_reseller.to_s}")
return license.is_reseller
end
rescue Exception => ex
#
#KLOGGER.info("unable to check if org '#{org_id.to_s}' is a reseller: '#{ex.to_s}'")
end
return false
end
end
| true |
031e6074e254dc2c74629a0bba74cbad8b4d3c8f | Ruby | twopir/tnetstring-rb | /lib/tnetstring.rb | UTF-8 | 2,992 | 3.578125 | 4 | [
"MIT"
] | permissive | module TNetstring
def self.parse(tnetstring)
payload, payload_type, remain = parse_payload(tnetstring)
value = case payload_type
when '#'
payload.to_i
when ','
payload
when ']'
parse_list(payload)
when '}'
parse_dictionary(payload)
when '~'
assert payload.length == 0, "Payload must be 0 length for null."
nil
when '!'
parse_boolean(payload)
else
assert false, "Invalid payload type: #{payload_type}"
end
[value, remain]
end
def self.parse_payload(data)
assert data, "Invalid data to parse, it's empty."
length, extra = data.split(':', 2)
length = length.to_i
assert length <= 999_999_999, "Data is longer than the specification allows"
assert length >= 0, "Data length cannot be negative!"
payload, extra = extra[0, length], extra[length..-1]
assert extra, "No payload type: %s, %s" % [payload, extra]
payload_type, remain = extra[0,1], extra[1..-1]
assert payload.length == length, "Data is wrong length %d vs %d" % [length, payload.length]
[payload, payload_type, remain]
end
def self.parse_list(data)
return [] if data.length == 0
list = []
value, remain = parse(data)
list << value
while remain.length > 0
value, remain = parse(remain)
list << value
end
list
end
def self.parse_dictionary(data)
return {} if data.length == 0
key, value, extra = parse_pair(data)
result = {key => value}
while extra.length > 0
key, value, extra = parse_pair(extra)
result[key] = value
end
result
end
def self.parse_pair(data)
key, extra = parse(data)
assert extra, "Unbalanced dictionary store."
value, extra = parse(extra)
assert value, "Got an invalid value, null not allowed."
[key, value, extra]
end
def self.parse_boolean(data)
case data
when "false"
false
when "true"
true
else
raise "Boolean wasn't 'true' or 'false'"
end
end
def self.encode(obj)
if obj.kind_of?(Integer)
int_str = obj.to_s
"#{int_str.length}:#{int_str}#"
elsif obj.kind_of?(String)
"#{obj.length}:#{obj},"
elsif obj.is_a?(TrueClass) || obj.is_a?(FalseClass)
bool_str = obj.to_s
"#{bool_str.length}:#{bool_str}!"
elsif obj == nil
"0:~"
elsif obj.kind_of?(Array)
encode_list(obj)
elsif obj.kind_of?(Hash)
encode_dictionary(obj)
else
assert false, "Object must be of a primitive type"
end
end
def self.encode_list(list)
contents = list.map {|item| encode(item)}.join
"#{contents.length}:#{contents}]"
end
def self.encode_dictionary(dict)
contents = dict.map do |key, value|
assert key.kind_of?(String), "Dictionary keys must be Strings"
"#{encode(key)}#{encode(value)}"
end.join
"#{contents.length}:#{contents}}"
end
def self.assert(truthy, message)
raise message unless truthy
end
end
| true |
950ce157fd077d7d0a8d792b39b4b50854698c66 | Ruby | satanas/mango | /app/models/batch.rb | UTF-8 | 1,145 | 2.59375 | 3 | [] | no_license | class Batch < ActiveRecord::Base
belongs_to :order
belongs_to :schedule
belongs_to :user
has_many :batch_hopper_lot
validates_uniqueness_of :order_id, :scope => [:number]
validates_presence_of :order, :schedule, :user, :start_date, :end_date
validates_numericality_of :number, :only_integer => true, :greater_than_or_equal_to => 0
validates_associated :order, :schedule, :user
before_validation :check_associations
def check_associations
if order_id.kind_of?(Integer) && !Order.exists?(order_id)
errors[:order_id] << "doesn't exist"
end
if schedule_id.kind_of?(Integer) && !Schedule.exists?(schedule_id)
errors[:schedule_id] << "doesn't exist"
end
if user_id.kind_of?(Integer) && !User.exists?(user_id)
errors[:user_id] << "doesn't exist"
end
end
def self.get_real_batches(order_id)
return self.where(:order_id => order_id).count
end
def self.get_real_total(order_id)
total = 0
batches = self.where(:order_id => order_id)
batches.each do |b|
b.batch_hopper_lot.each do |bhl|
total += bhl.amount
end
end
return total
end
end
| true |
022e142597b5af9c0dda13d3601dfe72ab544d90 | Ruby | MamboZ/learn_ruby | /07_hello_friend/friend.rb | UTF-8 | 101 | 3.015625 | 3 | [] | no_license | class Friend
def greeting(who=nil)
return who.equal?(nil)?"Hello!": "Hello, #{who}!"
end
end
| true |
81972b6bd22449af22201dec06bd07423ee94652 | Ruby | domlet/phase-0-tracks | /ruby/secret_agents.rb | UTF-8 | 1,646 | 4.21875 | 4 | [] | no_license | def encrypt(string)
index = 0
encrypted_string = ""
while index < string.length
# respect space character
if string[index] == " "
encrypted_string += " "
else
# respect edge case of z's
if string[index] == "z"
encrypted_string += "a"
else
encrypted_string += string[index].next
end
end
index += 1
end
encrypted_string
end
# p encrypt("abc")
def decrypt(string)
alphabet = "abcdefghijklmnopqrstuvwxyz"
index = 0
decrypted_string = ""
while index < string.length
current_letter = string[index]
alphabet_index = alphabet.index(current_letter)
# respect space character
if current_letter == " "
decrypted_string += " "
else
previous_letter = alphabet[alphabet_index - 1]
decrypted_string += previous_letter
end
index += 1
end
decrypted_string
end
# test everything, trust no one
# these mehods are exact opposites, therefore calling them both equals no change.
# below, encrypt will run first, then decrypt will run second.
# p decrypt(encrypt("swordfish"))
# DRIVER CODE
# Ask user whether they would like to decrypt or encrypt a password
puts "Would you like to decrypt or encrypt a password?"
puts "Please enter 'decrypt' or 'encrypt'."
answer = gets.chomp
# Asks them for the password
puts "Please tell us the secret password."
password = gets.chomp
# Conduct the requested operation, print to the screen, exit.
if answer == "encrypt"
p encrypt(password)
else answer == "decrypt"
p decrypt(password)
end
# p encrypt("abc")
# p encrypt("zed")
# p decrypt("bcd")
# p decrypt("afe")
| true |
85a5d773071cbeea9edc6166a711d8decdb89781 | Ruby | NNCT18J/ruby-cercil | /kodomocurry.rb | UTF-8 | 1,476 | 3.578125 | 4 | [] | no_license | class Curry
def initialize(a=3,b=300) #初期値は辛さ3量は300
@karasa=a
@ryou=b
end
def setkarasa(a)
@karasa=a
end
def setryou(b)
if b<0
@ryou=300
puts "WARN:量として負の値は設定できません 勝手に初期値にします"
else
@ryou=b
end
end
def getkarasa
return(@karasa)
end
def getryou
return(@ryou)
end
end
class KodomoCurry < Curry #KodomoCurry extends Curry(継承)
@@c=true
def initialize(a=1,b=200) #新たにコンストラクタ
@karasa=a
@ryou=b
@c=true
end
def openOmake #おまけメソッド
if(@c==true)
puts "Omake OPEN!"
else
puts "もうおまけないよ"
end
@c=false
end
def setkarasa(a) #5を中辛とする
if a>=5
@karasa=4 #強制甘口変更
else
@karasa=a
end
end
end
dora=Curry.new(5)
nobi=KodomoCurry.new
unk=KodomoCurry.new
dora.setkarasa(9999)
puts "dora"
puts "karasa=#{dora.getkarasa}"
puts "ryou=#{dora.getryou}"
nobi.setkarasa(99999)
puts "nobi"
puts "karasa=#{nobi.getkarasa}"
puts "ryou=#{nobi.getryou}"
nobi.openOmake
nobi.openOmake
unk.openOmake
sizuka=KodomoCurry.new()
sizuka.setkarasa(3)
sizuka.setryou(-100)
puts "sizuka"
puts "karasa=#{sizuka.getkarasa}"
puts "ryou=#{sizuka.getryou}"
| true |
69c2d4a125dd320923faa4482d8530e2b37b5437 | Ruby | hamcodes/prime-ruby-online-web-pt-071519 | /prime.rb | UTF-8 | 269 | 3.34375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # first try
# def prime?(num)
# num = 0
# while num < 0
# return false if num % n == 0
# n += 1
# end
# true
# end
def prime? (n)
if n <= 1
false
elsif n == 2
true
else
(2..n/2).none? { |i| n % i == 0}
end
end
| true |
8e45cac70aece5cef2da63856e98305f482d50ce | Ruby | luca-montaigut/Archives_THP | /4.5_gossip_project/lib/view.rb | UTF-8 | 545 | 3.015625 | 3 | [] | no_license | # frozen_string_literal: true
# Get gossip parameters
class View
def create_gossip
puts "C'est quoi ton potion ?"
content = gets.chomp.to_s
puts "Hum intéressant ! Mais t'es qui au fait ?"
author = gets.chomp.to_s
return params = {content: content,author: author}
end
def index_gossips(all)
all.each do |gossip|
puts gossip.author + " : " + gossip.content
end
end
def delete_gossip
puts "Quel qossip veux tu supprimmer ?"
print "> "
index = gets.chomp
return index
end
end | true |
a798da3f103570299bb53a7cc46a74cb659b47de | Ruby | mikezila/GodMustAnswer | /rb/box2d.rb | UTF-8 | 2,257 | 3.375 | 3 | [] | no_license | class Box2D
attr_reader :left_foot, :right_foot, :height, :width
attr_accessor :origin, :highlight
def initialize(vec2, height, width)
@origin = vec2
@highlight = false
@height = height
@width = width
self.calc_points
end
def update
self.calc_points
end
# The "v" variables are the four points of the box going from
# top left, top right, bottom left, bottom right, OpenGL-style
def calc_points
# @origin would be v1, defined in the constructor, since its just the vector2 that was passed then.
@v2 = Vector2.new(self.origin.x + self.width, self.origin.y)
@v3 = Vector2.new(self.origin.x, self.origin.y + self.height)
@v4 = Vector2.new(self.origin.x + width, self.origin.y + self.height)
# These two are 1/3 and 2/3 along the bottom of the box, "feet".
# They way they're calculated is kind of ugly to look at, but works.
@left_foot = Vector2.new(@v3.x + (Vector2.distance(@v3,@v4)/3), @v3.y)
@right_foot = Vector2.new(@v3.x + ((Vector2.distance(@v3,@v4)/3)*2), @v3.y)
end
# Adapted to 2D from 3D from bestguigui's "fps" prototype
def collides?(other) # Other should be another Box2D object
if (other.origin.x >= self.origin.x + self.width) # to the right
return false
elsif (other.origin.x + other.width <= self.origin.x) # to the left
return false
elsif (other.origin.y >= self.origin.y + self.height) # it's under
return false
elsif (other.origin.y + other.height <= self.origin.y) # it's above
return false
else
return true
end
end
# Draw some debug lines so we can see the boxes and some references.
# Lines are drawn to points seemingly out-of-order so that we get a box instead of a Z
def draw
color = Gosu::Color::RED
color = Gosu::Color::GREEN if @highlight
$window.draw_line(self.origin.x,self.origin.y,color,@v2.x,@v2.y,color,Zorder::Dev)
$window.draw_line(@v2.x,@v2.y,color,@v4.x,@v4.y,color,Zorder::Dev)
$window.draw_line(@v4.x,@v4.y,color,@v3.x,@v3.y,color,Zorder::Dev)
$window.draw_line(@v3.x,@v3.y,color,self.origin.x,self.origin.y,color,Zorder::Dev)
$window.draw_line(@left_foot.x,@left_foot.y+3,color,@right_foot.x,@right_foot.y+3,color,Zorder::Dev)
end
end
| true |
86426c74e4e761f32ad4184ab98325108f911968 | Ruby | ondrejfuhrer/brew | /Library/Homebrew/dev-cmd/contributions.rb | UTF-8 | 4,517 | 2.65625 | 3 | [
"CC-BY-4.0",
"BSD-2-Clause"
] | permissive | # typed: true
# frozen_string_literal: true
require "cli/parser"
require "csv"
module Homebrew
extend T::Sig
module_function
SUPPORTED_REPOS = [
%w[brew core cask],
OFFICIAL_CMD_TAPS.keys.map { |t| t.delete_prefix("homebrew/") },
OFFICIAL_CASK_TAPS.reject { |t| t == "cask" },
].flatten.freeze
sig { returns(CLI::Parser) }
def contributions_args
Homebrew::CLI::Parser.new do
usage_banner "`contributions` <email|name> [<--repositories>`=`] [<--csv>]"
description <<~EOS
Contributions to Homebrew repos for a user.
The first argument is a name (e.g. "BrewTestBot") or an email address (e.g. "brewtestbot@brew.sh").
EOS
comma_array "--repositories",
description: "Specify a comma-separated (no spaces) list of repositories to search. " \
"Supported repositories: #{SUPPORTED_REPOS.map { |t| "`#{t}`" }.to_sentence}." \
"Omitting this flag, or specifying `--repositories=all`, will search all repositories."
flag "--from=",
description: "Date (ISO-8601 format) to start searching contributions."
flag "--to=",
description: "Date (ISO-8601 format) to stop searching contributions."
switch "--csv",
description: "Print a CSV of a user's contributions across repositories over the time period."
named_args number: 1
end
end
sig { void }
def contributions
args = contributions_args.parse
results = {}
all_repos = args.repositories.nil? || args.repositories.include?("all")
repos = all_repos ? SUPPORTED_REPOS : args.repositories
repos.each do |repo|
if SUPPORTED_REPOS.exclude?(repo)
return ofail "Unsupported repository: #{repo}. Try one of #{SUPPORTED_REPOS.join(", ")}."
end
repo_path = find_repo_path_for_repo(repo)
unless repo_path.exist?
opoo "Repository #{repo} not yet tapped! Tapping it now..."
Tap.fetch("homebrew", repo).install
end
results[repo] = {
commits: git_log_author_cmd(T.must(repo_path), args),
coauthorships: git_log_trailers_cmd(T.must(repo_path), "Co-authored-by", args),
signoffs: git_log_trailers_cmd(T.must(repo_path), "Signed-off-by", args),
}
end
puts "The user #{args.named.first} has made #{total(results)} contributions #{time_period(args)}."
puts generate_csv(args.named.first, results) if args.csv?
end
sig { params(repo: String).returns(Pathname) }
def find_repo_path_for_repo(repo)
return HOMEBREW_REPOSITORY if repo == "brew"
Tap.fetch("homebrew", repo).path
end
sig { params(args: Homebrew::CLI::Args).returns(String) }
def time_period(args)
if args.from && args.to
"between #{args.from} and #{args.to}"
elsif args.from
"after #{args.from}"
elsif args.to
"before #{args.to}"
else
"in all time"
end
end
sig { params(user: String, results: Hash).returns(String) }
def generate_csv(user, results)
CSV.generate do |csv|
csv << %w[user repo commits coauthorships signoffs total]
results.each do |repo, counts|
csv << [
user,
repo,
counts[:commits],
counts[:coauthorships],
counts[:signoffs],
counts.values.sum,
]
end
csv << [user, "*", "*", "*", "*", total(results)]
end
end
sig { params(results: Hash).returns(Integer) }
def total(results)
results
.values # [{:commits=>1, :coauthorships=>0, :signoffs=>3}, {:commits=>500, :coauthorships=>2, :signoffs=>450}]
.map(&:values) # [[1, 0, 3], [500, 2, 450]]
.sum(&:sum) # 956
end
sig { params(repo_path: Pathname, args: Homebrew::CLI::Args).returns(Integer) }
def git_log_author_cmd(repo_path, args)
cmd = ["git", "-C", repo_path, "log", "--oneline", "--author=#{args.named.first}"]
cmd << "--before=#{args.to}" if args.to
cmd << "--after=#{args.from}" if args.from
Utils.safe_popen_read(*cmd).lines.count
end
sig { params(repo_path: Pathname, trailer: String, args: Homebrew::CLI::Args).returns(Integer) }
def git_log_trailers_cmd(repo_path, trailer, args)
cmd = ["git", "-C", repo_path, "log", "--oneline"]
cmd << "--format='%(trailers:key=#{trailer}:)'"
cmd << "--before=#{args.to}" if args.to
cmd << "--after=#{args.from}" if args.from
Utils.safe_popen_read(*cmd).lines.count { |l| l.include?(args.named.first) }
end
end
| true |
03c5a5993987314c24f0ee32e03df8fe664e4641 | Ruby | NicGiles/battle_with_nic_and_cameron | /spec/game_spec.rb | UTF-8 | 782 | 2.84375 | 3 | [] | no_license | require 'game'
RSpec.describe Game do
let(:jack) {double :david}
let(:jill) {double :goliath}
subject { described_class.new(jack, jill) }
it "should attack player 2" do
allow(jill).to receive(:get_attacked).and_return(true)
expect(subject.player_1_attack).to eq true
end
it "should attack player 1" do
allow(jack).to receive(:get_attacked).and_return(true)
expect(subject.player_2_attack).to eq true
end
it "be game over when player 1 loses" do
allow(jack).to receive(:lost?).and_return(true)
expect(subject.game_over).to eq [jack, jill]
end
it "be game over when player 2 loses" do
allow(jack).to receive(:lost?).and_return(false)
allow(jill).to receive(:lost?).and_return(true)
expect(subject.game_over).to eq [jill, jack]
end
end
| true |
3a5202b8754050dee79967efaa844dbf10dc9ec3 | Ruby | Khetti/weekend_homework_1 | /pet_shop.rb | UTF-8 | 5,133 | 3.953125 | 4 | [] | no_license | # function purpose: "What is the shop name?"
# access the data(hash) and return the value attached to :name
def pet_shop_name(shop_name)
return shop_name[:name]
end
# function purpose: "How much cash does the shop have?"
# access the data(hash) and return the value attached to :total_cash
def total_cash(shop_cash)
return shop_cash[:admin][:total_cash]
end
# function purpose: ""
# the test is providing us with the arguments "10" for one test and "-10"
# for another. there's probably a better way to perform a subtraction that
# doesn't require input of a negative number, but for now we just need
# to add whatever the argument is to our total.
def add_or_remove_cash(shop_cash, cash)
return shop_cash[:admin][:total_cash] += cash
end
# access the data(hash) and return the value attached to :pets_sold
def pets_sold(pets_total)
return pets_total[:admin][:pets_sold]
end
def increase_pets_sold(current_sold, new_sold)
return current_sold[:admin][:pets_sold] += new_sold
end
def stock_count(stock)
return stock[:pets].length()
end
# function purpose: "How many of this breed do we have?"
# the test is going to perform the count method with the string argument
# "british shorthair" for whatever we produce, so we need to return an array
# with all instances of that argument to be counted.
# can only seem to return an empty string, unsure how to fix that
# function now returns a count of 3, when it should be 2 - i have no idea why
def pets_by_breed(all_pets, shorthair)
search_results = []
for pet in all_pets
if all_pets[:pets][0][:breed] == shorthair
search_results << shorthair
end
end
return search_results
end
# look for a pet named "Arthur" and if found, return that name as a string
# likely need to use index method, as this returns nil if there is no match
# however, i think the test will return as a failure because it won't accept
# an index, it's looking for a string. maybe .to_s would work?
# error: undefined method '[]' for nil:NilClass
def find_pet_by_name(all_names, name_to_find)
for name in all_names
if all_names[:pets][0] == name_to_find
return all_names[:pets][0].index
else
return nil
end
end
end
# this function should remove a given pet from the array and return
# a nil. a return shouldn't be required, as the test will check the hash
# value once run.
# the .delete method works based on index values, so i might need to
# run .index first to locate the pet, then delete it using that value
def remove_pet_by_name(all_pets, removed_pet)
pet_location = all_pets[:pets][0].index(removed_pet)
all_pets[:pets][0].delete(pet_location)
end
# push a new hash entry into our pets array of hashes
def add_pet_to_stock(current_stock, pet_to_add)
current_stock[:pets] << pet_to_add
end
# i think the test is asking to check the cash of the first customer in
# the array, so at index 0. the below function does that, as the index
# value is being passed in as an argument from @customer[0]
def customer_cash(customer)
return customer[:cash]
end
# we're subtracting cash from the first customer in the array
# i don't think a return is needed here, as the test is accessing the
# hash value to verify the result
def remove_customer_cash (customer, cash_for_removal)
customer[:cash] -= cash_for_removal
end
# this test wants to know how many pets a customer owns and is expecting
# a return of "0". i think returning the array contents will result in a
# 'nil' value, so performing the .length method is likely the best way
# to proceed
# update: tested without .length method, function returns empty string
# not a nil, but test does not accept this. length returns 0 and passes
def customer_pet_count(customer)
return customer[:pets].length
end
# we're adding a pet to the customer at index 0, and using our previous
# function to check, expecting an array length of 1. pushing the new pet
# onto the array should accomplish this
def add_pet_to_customer(customer, pet_to_add)
customer[:pets] << pet_to_add
end
# this function will compare the value held for :cash in a given customer,
# to the :price of a given pet. In this case, we're comparing cash 1000
# to a price of 100, so we will expect a value of true.
# i'm going to try a "greater than or equal to" comparison in an if.
# the function should also work if the customer cannot afford the pet
def customer_can_afford_pet(customer, pet)
return customer[:cash] >= pet[:price]
end
# here a customer is buying a pet, and the test is checking to see that their
# total number of pets, the number of pets the shop has sold, the customer's
# cash and the shop's cash are being appropriately altered to their new
# values
# the function should push arthur onto the customer's pets array,
# subtract his price from the customer's cash, and add that cash to the
# shop total cash.
def sell_pet_to_customer(all_pets, buy_pet, customer_buying)
customer_buying[:pets] << buy_pet
all_pets[:admin][:pets_sold] + 1
customer_buying[:cash] = customer_buying[:cash] - buy_pet[:price]
all_pets[:admin][:total_cash] = all_pets[:admin][:total_cash] + buy_pet[:price]
end
| true |
565438f55b6496dfd69c04757c61c672d33810df | Ruby | StevenYee123/AAHomeworks | /W4D3/simon/lib/simon.rb | UTF-8 | 1,084 | 3.609375 | 4 | [] | no_license | class Simon
COLORS = %w(red blue green yellow)
attr_accessor :sequence_length, :game_over, :seq
def initialize
@sequence_length = 1
@game_over = false
@seq = []
end
def play
until game_over
take_turn
end
game_over_message
reset_game
end
def take_turn
show_sequence
sleep(5)
require_sequence
round_success_message
@sequence_length += 1
end
def show_sequence
add_random_color
end
def require_sequence
arr = seq.dup
until arr.empty
print 'Follow the sequence you just saw'
input = gets.chomp
if input != arr.first
@game_over = true
else
round_success_message
sequence_length += 1
arr.shift
end
end
end
def add_random_color
num = rand(0...COLORS.length)
@seq << COLORS[num]
end
def round_success_message
print 'Congrats! Moving on...'
end
def game_over_message
print 'Too bad, you lost...'
end
def reset_game
@sequence_length = 1
@game_over = false
@seq = []
end
end
| true |
cc4bd6a28ede62f5a9385a25ad94b69abc2dd273 | Ruby | tsmsogn/AOJ | /Volume_000/0030_Sum_of_Integers.rb | UTF-8 | 186 | 3.09375 | 3 | [] | no_license | a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
while line = gets
n, s = line.chomp.split.map(&:to_i)
break if n == 0 && s == 0
puts a.combination(n).select { |x| s == x.inject(:+) }.size
end
| true |
3e43ff1a06ba2d14716073d6c850747d5eacd42c | Ruby | anhtran910/Ruby | /banking.rb | UTF-8 | 1,387 | 4.03125 | 4 | [] | no_license | class Account
attr_reader :name, :balance
def initialize(name, balance=100)
@name = name
@balance = balance
end
def display_balance(pin_number)
puts pin_number == pin ? "Balance: $#{@balance}." : pin_error
end
def withdraw(pin_number, amount)
if pin_number == pin
@balance -= amount
puts "Withdraw #{amount}. New balance: $#{@balance}."
else
puts pin_error
end
end
private
def pin
@pin = 1234
end
def pin_error
"Access denied: incorrect PIN."
end
end
puts "Input your name"
name=gets.chomp;
puts "Input your balance"
balance=gets.chomp.to_f
my_account = Account.new(name, balance)
puts "Input your pin"
pin=gets.chomp.to_i
puts "Here is your account:"
my_account.display_balance(pin)
puts "What do you want to do"
puts "Type 'w' to withdraw"
puts "Type 'b' to display new balance"
puts "Type 'e' to exit"
choice=gets.chomp.downcase
Case choice
when 'w'
puts "what the amount you want to withdraw"
amount=gets.chomp.to_f
my_account.withdraw(pin,amount)
puts "New balance after withdrawal:"
my_account.display_balance(pin)
end
when 'b'
puts "Your new balance is:"
my_account.display_balance(pin)
my_account.withdraw(1234, 500_000)
my_account.display_balance(1234)
| true |
df27f43b84c4c68585ac6f7cb393057f275fc4f3 | Ruby | wijet/backup | /lib/backup/storage/scp.rb | UTF-8 | 3,486 | 2.640625 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
##
# Only load the Net::SSH and Net::SCP library/gems
# when the Backup::Storage::SCP class is loaded
Backup::Dependency.load('net-ssh')
Backup::Dependency.load('net-scp')
module Backup
module Storage
class SCP < Base
##
# Server credentials
attr_accessor :username, :password
##
# Server IP Address and SCP port
attr_accessor :ip, :port
##
# Path to store backups to
attr_accessor :path
##
# This is the remote path to where the backup files will be stored
def remote_path
File.join(path, TRIGGER, @time)
end
##
# Performs the backup transfer
def perform!
super
transfer!
cycle!
end
private
##
# Set configuration defaults before evaluating configuration block,
# after setting defaults from Storage::Base
def pre_configure
super
@port ||= 22
@path ||= 'backups'
end
##
# Adjust configuration after evaluating configuration block,
# after adjustments from Storage::Base
def post_configure
super
@path = path.sub(/^\~\//, '')
end
##
# Establishes a connection to the remote server
# and yields the Net::SSH connection.
# Net::SCP will use this connection to transfer backups
def connection
Net::SSH.start(
ip, username, :password => password, :port => port
) {|ssh| yield ssh }
end
##
# Transfers the archived file to the specified remote server
def transfer!
connection do |ssh|
create_remote_directories(ssh)
files_to_transfer do |local_file, remote_file|
Logger.message "#{storage_name} started transferring " +
"'#{local_file}' to '#{ip}'."
ssh.scp.upload!(
File.join(local_path, local_file),
File.join(remote_path, remote_file)
)
end
end
end
##
# Removes the transferred archive file from the server
def remove!
messages = []
transferred_files do |local_file, remote_file|
messages << "#{storage_name} started removing '#{local_file}' from '#{ip}'."
end
Logger.message messages.join("\n")
errors = []
connection do |ssh|
ssh.exec!("rm -r '#{remote_path}'") do |ch, stream, data|
errors << data if stream == :stderr
end
end
unless errors.empty?
raise Errors::Storage::SCP::SSHError,
"Net::SSH reported the following errors:\n" +
errors.join("\n"), caller(1)
end
end
##
# Creates (if they don't exist yet) all the directories on the remote
# server in order to upload the backup file. Net::SCP does not support
# paths to directories that don't yet exist when creating new directories.
# Instead, we split the parts up in to an array (for each '/') and loop through
# that to create the directories one by one. Net::SCP raises an exception when
# the directory it's trying ot create already exists, so we have rescue it
def create_remote_directories(ssh)
path_parts = Array.new
remote_path.split('/').each do |path_part|
path_parts << path_part
ssh.exec!("mkdir '#{path_parts.join('/')}'")
end
end
end
end
end
| true |
64237dbd50dd56c59c397cb22d8cd8e364ad594a | Ruby | MarvinProg/film_selection | /lib/film_parser.rb | UTF-8 | 575 | 2.890625 | 3 | [] | no_license | require 'nokogiri'
require 'open-uri'
require_relative 'film'
module FilmParser
WIKI_LINK = 'https://ru.wikipedia.org/wiki/250_лучших_фильмов_по_версии_IMDb'.freeze
extend self
def from_wiki
html = open_request(WIKI_LINK)
doc = Nokogiri::HTML(html)
films_list = doc.css('tbody/tr')[1..]
films_list.map do |tr|
cells = tr.css('td/a')
Film.new(
cells[0].text,
cells[2].text,
cells[1].text.to_i
)
end
end
private
def open_request(url)
URI.open(URI.escape(url))
end
end
| true |
c2c28731a63c40b7f0ee2f62662c1ab5ca02d5a3 | Ruby | daamnathaniel/cliapi | /lib/apicli/cliapi.rb | UTF-8 | 429 | 2.625 | 3 | [] | no_license | # CLI controller, responsible for user interaction
class WordSelector::CLI
def call
WordFinder::Request.new.find_words
list_options
menu
end
def list_options
SAY.(Statment.greeting)
sleep 1
SAY.(Statement)
sleep 2
DISPLAY(request.response)
DISPLAY = -> (data, method, part) { data.method {|d| puts d[part]}}
request.response.each do |res|
puts res["word"]
end
| true |
6fabcb47732e3d92eea88fc8f8a2d216205478ae | Ruby | baezanat/Launch_School_bootcamp | /exercises/RB101_109/easy/easy9_5.rb | UTF-8 | 839 | 4.40625 | 4 | [] | no_license | =begin
Write a method that takes a string argument, and returns true if all of the alphabetic characters inside the string are uppercase, false otherwise. Characters that are not alphabetic should be ignored.
Examples:
uppercase?('t') == false
uppercase?('T') == true
uppercase?('Four Score') == false
uppercase?('FOUR SCORE') == true
uppercase?('4SCORE!') == true
uppercase?('') == true
=end
def uppercase?(str)
alphabetic_arr = str.chars.select { |char| char.match(/[a-z]/i) }
alphabetic_arr.all? { |char| char.match(/[A-Z]/) }
end
uppercase?('t') == false # => true
uppercase?('T') == true # => true
uppercase?('Four Score') == false # => true
uppercase?('FOUR SCORE') == true # => true
uppercase?('4SCORE!') == true # => true
uppercase?('') == true # => true
# SIMPLER SOLUTION:
def uppercase_?(str)
str == str.upcase
end
| true |
5a3ee8d032156fee314f1e9186d1683a1498b62e | Ruby | MousbahFil/Web-Workspace | /Ruby/SubStrings.rb | UTF-8 | 248 | 3.015625 | 3 | [] | no_license | def substrings(word, strings)
result=Hash.new
word=word.downcase
strings.each do |s|
if(word.include? s.downcase)
result.store(s, word.downcase.scan(s.downcase).length)
end
end
result
end | true |
d469cae940e6229de71401091fd8ac3579e12f83 | Ruby | merongivian/library-management | /lib/library_management/order_manager.rb | UTF-8 | 1,642 | 3.203125 | 3 | [] | no_license | module LibraryManagement
class OrderManager
attr_reader :name, :id, :order_date, :pick_date, :penalty, :picked
def initialize(order)
@name = order.book.name
@order_date = order.created_at
@pick_date = if order.picked_up_at
order.picked_up_at
else
calculate_pick_date(order.created_at)
end
@penalty = order.book.penalty
@picked = order.picked
@id = order.id
@pick_days = order.pick_days
@loan_days = order.loan_days
end
def self.transform_orders(orders)
orders.map do |order|
OrderManager.new order
end
end
def days_left_to_pick
(@pick_date - Date.current).to_i
end
def days_left_to_return
(calculate_return_date - Date.current).to_i
end
def never_picked?
!still_has_days_left_to_pick? && !@picked
end
def never_returned?
days_left_to_return <= 0
end
def status
if never_picked?
"never picked up"
else
if !still_has_days_left_to_pick?
never_returned? ? "never returned" : "#{days_left_to_return} days left to return"
else
"#{days_left_to_pick} days left to pick"
end
end
end
def total_penalty
if @picked && never_returned?
@penalty * days_left_to_return.abs
end
end
def ==(order_manager)
self.name == order_manager.name
end
private
def calculate_pick_date(start_date)
start_date + PICK_DAYS
end
def calculate_return_date
@pick_date + LOAN_DAYS
end
def still_has_days_left_to_pick?
days_left_to_pick > 0
end
end
end
| true |
d85aaf3114e5245b54c847719dba0d97952e52dd | Ruby | JoshCheek/object_model_8th_light | /challenges/flight_of_the_conchords.rb | UTF-8 | 967 | 3.703125 | 4 | [] | no_license | # ===== Silence!! DEstroy him!! =====
# Dew! Bew! Dew-dew-dew! Bew!
module InSpace
attr_reader :current_status
def initialize(current_status, *whatevz)
@current_status = current_status
super(*whatevz)
end
end
class Human
attr_reader :name
def initialize(name)
@name = name
end
end
class Student < Human
include InSpace
attr_reader :lesson
def initialize(lesson, *o_O)
@lesson = lesson
super *o_O
end
end
students_in_space = Student.new(
"The future is quite different to the present",
"Though one thing we have in common with the present is we still call it the present, even though its the future",
"What you call 'the present', we call 'the past', so... you guys are way behind"
)
#*****
# We used poisonous gasses, (with traces of lead)
# and we poisoned their asses (actually, their lungs)
# students_in_space.current_status # =>
# students_in_space.name # =>
# students_in_space.lesson # =>
| true |
2eb3ae29021c0621862b3f35e4b870ec9b4b9c29 | Ruby | sfgeorge/loquacious | /examples/nested.rb | UTF-8 | 1,749 | 2.515625 | 3 | [
"MIT"
] | permissive | # Here we show how to used nested configuration options by taking a subset
# of some common Rails configuration options. Also, descriptions can be give
# before the option or they can be given inline using Ruby hash notation. If
# both are present, then the inline description takes precedence.
#
# Multiline descriptions are provided using Ruby heredocs. Leading
# whitespace is stripped and line breaks are preserved when descriptions
# are printed using the help object.
require 'loquacious'
include Loquacious
Configuration.for(:nested) {
root_path '.', :desc => "The application's base directory."
desc "Configuration options for ActiveRecord::Base."
active_record {
colorize_logging true, :desc => <<-__
Determines whether to use ANSI codes to colorize the logging statements committed
by the connection adapter. These colors make it much easier to overview things
during debugging (when used through a reader like +tail+ and on a black background),
but may complicate matters if you use software like syslog. This is true, by default.
__
default_timezone :local, :desc => <<-__
Determines whether to use Time.local (using :local) or Time.utc (using :utc)
when pulling dates and times from the database. This is set to :local by default.
__
}
log_level :info, :desc => <<-__
The log level to use for the default Rails logger. In production mode,
this defaults to :info. In development mode, it defaults to :debug.
__
log_path 'log/development.log', :desc => <<-__
The path to the log file to use. Defaults to log/\#{environment}.log
(e.g. log/development.log or log/production.log).
__
}
help = Configuration.help_for :nested
help.show :values => true
| true |
d299bbf65c427ff40029b9f3471917dd728eb67b | Ruby | ess/belafonte | /examples/cmd | UTF-8 | 1,007 | 2.875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'belafonte'
class TrueApp < Belafonte::App
title "true"
summary "Just like system true"
description "All this does is exit with a 'true' value"
def handle
kernel.exit(0)
end
end
class Echo < Belafonte::App
title "echo"
summary "Just like system echo"
description "This prints all of its arguments to the terminal"
switch :no_newline,
short: 'n',
description: "Suppresses the newline at the end of output"
arg :string, times: :unlimited
def handle
stdout.print arg(:string).map(&:to_s).join(' ') + newline
end
def newline
switch_active?(:no_newline) ? '' : "\n"
end
end
class Cmd < Belafonte::App
title "cmd"
summary "A wrapper for a command suite"
option :face,
short: 'f',
long: 'face',
description: 'adds a funny face to output',
argument: 'FACE'
mount Echo
mount TrueApp
def handle
stdout.puts "This should not get executed"
kernel.exit(1)
end
end
exit Cmd.new(ARGV).execute!
| true |
25482c756b8631e0614463430f6c17c093b0182c | Ruby | brianseitel/oasis-rubymud | /modules/level.rb | UTF-8 | 1,755 | 3.4375 | 3 | [] | no_license |
#
# Module to handle level definitions, calculate level gains, modify attributes, and so on.
#
# def gain_exp
# def gain_level
# @author [brianseitel]
#
class Level
EXP_TO_LEVEL = 1000
#
# Calculate the amount of experience and increase the player's exp count/
# @param player Player the player gaining experience
# @param victim Mob|Player the victim
#
# @return [type] [description]
def self.gain_exp(player, victim)
experience = victim.level * Random.rand(50) + Random.rand(100)
p = MudServer.get_player player
if (p)
p.client.puts "You gain #{experience} experience points!"
end
player.experience += experience
player.save
if self.enough_to_level? player
self.gain_level player
end
end
#
# Does the player have enough experience to level? Possibly add other criteria here.
# @param player Player the player we're checking
#
# @return Boolean whether the player has enough xp to level
def self.enough_to_level?(player)
return player.experience > EXP_TO_LEVEL
end
#
# Increase the level of the player, modify stats if necessary
# Output the level up screen
#
# @param player Player the player who leveled up!
#
def self.gain_level(player)
player.level += 1
player.experience = 0
player.save
self.show_level_message player
end
#
# Display the level up screne for the player, if they're logged in
# @param player Player the player who has leveled up
#
def self.show_level_message(player)
if (MudServer.logged_in? player)
MudServer.clients.each do |client|
if (client.player == player)
client.puts View.render_template('player.levelup', player.level)
end
end
end
end
def self.til_next(player)
return EXP_TO_LEVEL - player.experience
end
end | true |
a2cd2e5ac4c107b32699833b68d9e38b7edd6239 | Ruby | IlyaMur/ruby_learning | /RubyRush_school/Lesson7/reverse.rb | UTF-8 | 535 | 3.4375 | 3 | [] | no_license | array_to_invert = [1, 2, 3, 4, 5, 6, 7]
puts "Исходный массив: #{array_to_invert.to_s}"
flag = false
buff = 0
until flag == true
flag = true
0.upto(array_to_invert.size - 2) do |i|
if array_to_invert[i] < array_to_invert[i+1]
buff = array_to_invert[i]
array_to_invert[i] = array_to_invert[i+1]
array_to_invert[i+1] = buff
flag = false
end
end
end
puts "Новый массив, полученный от исходного: #{array_to_invert.to_s}"
| true |
afd9e60668df52928100eda54df81e5ac5656478 | Ruby | Jennythompson17/codebar_projects | /Write to file examples/write_to_csv.rb | UTF-8 | 470 | 2.875 | 3 | [] | no_license | require "open-uri"
remote_base_url = "http://en.wikipedia.org/wiki"
remote_page_name = "Ada_Lovelace"
remote_full_url = remote_base_url + "/" + remote_page_name
puts "Downloading from:" + remote_full_url
remote_data = open(remote_full_url).read
my_local_filename = "my_copy_of-" + remote_page_name + ".csv"
puts "Writing to: " + my_local_filename
my_local_file = open(my_local_filename, "w")
my_local_file.write(remote_data)
my_local_file.close | true |
d8ffcf7790a8a10109a202b5b1b44adb9f9cc8b6 | Ruby | Marti-Dolce-Flatiron-School-Projects/ruby-oo-complex-objects-putting-the-pieces-together | /lib/shoe.rb | UTF-8 | 395 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # frozen_string_literal: true
# brand: Martinique Dolce
# Course: Flatiron School 2020, November 9 - 20201, April 2021
# Contact: me@martidolce.com | https://modis.martidolce.com
#
# shoe.rb
class Shoe
attr_reader :brand
attr_accessor :material, :size, :color, :condition
def initialize(brand)
@brand = brand
end
def cobble
@condition = 'new'
puts 'Your shoe is as good as new!'
end
end
| true |
33f4d3accc0bdbf2526ae9d618cf91f033003307 | Ruby | elthariel/radioschlag | /lib/sox/audio_file.rb | UTF-8 | 2,412 | 2.53125 | 3 | [] | no_license | #! /usr/bin/ruby
## audio_file.rb
## Login : <opp2@opp2-devsrv>
## Started on Tue Dec 1 23:32:27 2009 opp2
## $Id$
##
## Author(s):
## - opp2 <>
##
## Copyright (C) 2009 opp2
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
module Sox
class AudioFile
attr_reader :infos
def self.parse(path)
begin
f = AudioFile.new(path)
f
rescue
puts $!
nil
end
end
def self.parse_vorbis_comments(path, verbose = false)
puts "-> Executing 'soxi -a \"#{path}\"'" if verbose
vc_out = `soxi -a "#{path}"`
puts "-> Got vorbiscomment out:" if verbose
comments = {}
puts vc_out if verbose
vc_out.each do |line|
s = line.split '='
s[0].downcase!
s[1].gsub!(/[;&'"$%^|]*!~#/, '')
s[1].chomp!
if comments.has_key? s[0]
comments[s[0]] += ', ' + s[1]
else
comments[s[0]] = s[1]
end
end
comments
end
protected
def initialize(path)
@infos = Hash.new
if (!File.readable?(path))
raise "Not a file"
end
@infos[:path] = File.expand_path(path)
if (`soxi "#{@infos[:path]}" 2>&1` =~ /soxi FAIL/)
raise "Not an audio file"
end
@infos[:type] = `soxi -t "#{@infos[:path]}"`.chomp
@infos[:rate] = `soxi -r "#{@infos[:path]}"`.chomp.to_i
@infos[:chans] = `soxi -c "#{@infos[:path]}"`.chomp.to_i
@infos[:duration] = `soxi -D "#{@infos[:path]}"`.chomp.to_i
@infos[:bitrate] = `soxi -B "#{@infos[:path]}"`.chomp.to_i
@infos[:comments] = self.parse_vorbis_comments(path)
end
end
end
if ($0 == __FILE__)
f = Sox::AudioFile.parse(ARGV[0])
f.infos.each {|k, v| p "#{k}=#{v}"}
end
| true |
a88474d45a29222b2c247ab67750283bb8d9fc47 | Ruby | paulvidal/web-crawler | /src/static_assets_parser.rb | UTF-8 | 1,047 | 2.796875 | 3 | [] | no_license | require_relative 'url_parser'
module StaticAssetsParser
def StaticAssetsParser.find_static_assets(parsed_html, crawler)
asset_links = []
script_assets = parsed_html.css('script')
script_assets.each do |script|
asset_links << script['src']
end
link_assets = parsed_html.css('link')
link_assets.each do |link|
if link['rel'] == 'stylesheet'
asset_links << link['href']
end
end
images = parsed_html.css('img')
images.each do |img|
asset_links << img['src']
end
# Remove nils and local static files
asset_links.reject! { |asset_link| !asset_link || asset_link.start_with?('//') }
format_static_assets(asset_links, crawler)
end
def StaticAssetsParser.format_static_assets(assets, crawler)
static_asset_urls = []
assets.each do |asset|
unless asset.start_with?('/')
asset = '/' + asset
end
static_asset_url = crawler.base_url + asset
static_asset_urls << static_asset_url
end
static_asset_urls
end
end | true |
f21094e49f4959ce174e74cb5ce783e0fa286e1e | Ruby | onigra/slice_by_indexes | /spec/extention/array_spec.rb | UTF-8 | 1,930 | 2.71875 | 3 | [
"MIT"
] | permissive | require File.expand_path(File.join('../', 'spec_helper'), File.dirname(__FILE__))
describe Array do
describe '#indexes' do
context 'case1' do
let(:ary) { [1, 2, 3, 1, 2] }
subject { ary.indexes 1 }
it { should eq [0, 3] }
end
context 'case2' do
let(:ary) { [1, 2, 3, 1, 2, 1, 1, 3, 2, 1] }
subject { ary.indexes 1 }
it { should eq [0, 3, 5, 6, 9] }
end
context 'case3' do
let(:ary) { ["foo", "bar", "baz", "foo", "baz", "foo"] }
subject { ary.indexes "foo" }
it { should eq [0, 3, 5] }
end
context 'case4' do
let(:ary) { ["foo", 1, 2, "foo", 3, "foo"] }
subject do
ary.indexes do |i|
i.class == String
end
end
it { should eq [0, 3, 5] }
end
context 'case5' do
let(:ary) { ["foo", 1, 2, "foo", 3, "foo"] }
subject { ary.indexes }
it { should eq [] }
end
end
describe '#slice_by_indexes' do
context 'case1' do
let(:ary) { [1, 2, 3, 1, 2] }
subject { ary.slice_by_indexes 1 }
it { should eq [[1, 2, 3], [1, 2]] }
end
context 'case2' do
let(:ary) { [1, 2, 3, 1, 2, 1, 1, 3, 2, 1] }
subject { ary.slice_by_indexes 1 }
it { should eq [[1, 2, 3], [1, 2], [1], [1, 3, 2], [1]] }
end
context 'case3' do
let(:ary) { ["foo", "bar", "baz", "foo", "baz", "foo"] }
subject { ary.slice_by_indexes "foo" }
it { should eq [["foo", "bar", "baz"], ["foo", "baz"], ["foo"]] }
end
context 'case4' do
let(:ary) { ["foo", 1, 2, "foo", 3, "foo"] }
subject do
ary.slice_by_indexes do |i|
i.class == String
end
end
it { should eq [["foo", 1, 2], ["foo", 3], ["foo"]] }
end
context 'case5' do
let(:ary) { ["foo", 1, 2, "foo", 3, "foo"] }
subject { ary.slice_by_indexes }
it { should eq [] }
end
end
end
| true |
43469fe6ede17a9b6b626d63931f9af949ff6b9e | Ruby | hamza3202/repositext | /lib/repositext/validation/utils/reporter_json.rb | UTF-8 | 2,751 | 2.734375 | 3 | [
"MIT"
] | permissive | class Repositext
class Validation
# This Reporter collects data during validation and once the validation is
# complete, it prints the data as JSON to $stdout so it can be consumed
# by the calling process.
class ReporterJson < Reporter
attr_reader :errors, :warnings, :stats
VALIDATION_JSON_OUTPUT_MARKER = "**** REPOSITEXT_VALIDATION_JSON_DATA_"
VALIDATION_JSON_OUTPUT_START_MARKER = VALIDATION_JSON_OUTPUT_MARKER + "START ****"
VALIDATION_JSON_OUTPUT_END_MARKER = VALIDATION_JSON_OUTPUT_MARKER + "END ****"
# Parses the console output generated in #write method to JSON.
# This method is called by the calling process for converting console output
# to a Ruby data structure.
# @param console_output [String] std_error captured by calling process
# @return [Array<Hash>] An array of Hashes, one for each Reported block
# surrounded by JSON output markers.
def self.parse_console_output(console_output)
start_marker_rx = Regexp.new(Regexp.escape(VALIDATION_JSON_OUTPUT_START_MARKER))
end_marker_rx = Regexp.new(Regexp.escape(VALIDATION_JSON_OUTPUT_END_MARKER))
json_blocks = []
inside_json_block = false
s = StringScanner.new(console_output)
while !s.eos? do
if !inside_json_block
if s.skip_until(start_marker_rx)
# We found and consumed start of JSON block
inside_json_block = true
else
# No further start of JSON block found
s.terminate
end
else
# We're inside a JSON block, consume it
if (json_block = s.scan_until(/(?=#{ end_marker_rx })/))
json_blocks << json_block
s.skip(end_marker_rx) # consume the end marker
inside_json_block = false
else
raise "No matching end marker found!"
end
end
end
json_blocks.map { |e| JSON.parse(e) }
end
# Prints report to $stderr as JSON
# @param marker [String] to identify this validation. Typically the validation class name
# @param _report_file_path [String, nil] not used.
def write(marker, _report_file_path)
r = {
summary: {
validation: marker,
errors_count: @errors.count,
stats_count: @stats.count,
warnings_count: @warnings.count,
},
details: group_reportables_by_class,
}
r = JSON.generate(r, JSON_FORMATTING_OPTIONS)
$stderr.puts(VALIDATION_JSON_OUTPUT_START_MARKER)
$stderr.puts(r)
$stderr.puts(VALIDATION_JSON_OUTPUT_END_MARKER)
end
end
end
end
| true |
0fb9c15e135bfc1aca97baccb840bef64244cdce | Ruby | ThaiNguyen-wakumo/testing | /Maths.rb | UTF-8 | 195 | 3.21875 | 3 | [] | no_license | require 'pry'
class Maths
class DivZeroError < StandardError; end
def sum(a, b)
a + b
end
def div(a, b)
raise DivZeroError if b == 0
a / b
end
end
binding.pry
puts "Done" | true |
6d94beeb2c593a6b9f20753da4ac76e751cdc729 | Ruby | hackforchange/igotugot | /lib/models.rb | UTF-8 | 1,815 | 2.671875 | 3 | [] | no_license | require 'rubygems'
require 'active_record'
dbconfig = YAML.load(File.read('./config/database.yml'))
env = ENV['SINATRA_ENV'] || 'production'
ActiveRecord::Base.establish_connection (dbconfig['production'])
class User < ActiveRecord::Base
has_many :tags, :through => :taggings
has_many :taggings
has_many :posts
end
require 'digest/sha1'
class Post < ActiveRecord::Base
before_create :set_edit_url
has_many :tags, :through => :taggings
has_many :taggings, :dependent => :destroy
default_scope where(:deleted => false)
belongs_to :user
def set_edit_url
# is it awesome to random?
self.secret_id = Digest::SHA1.hexdigest("#{rand}")
end
end
class Tag < ActiveRecord::Base
has_many :posts, :through => :taggings
has_many :users, :through => :taggings
has_many :taggings
after_create :kill_memos
def self.list
@tags ||= self.all.collect{|tag| tag.name}
end
def kill_memos
@tags = nil
end
end
class Tagging < ActiveRecord::Base
belongs_to :post
belongs_to :user
belongs_to :tag
validates_uniqueness_of :tag_id, :scope => :post_id
end
require 'json'
require 'open-uri'
class Location
def self.from_postalcode(postcode)
#there is apparently a postalcode thing
puts "getting postcode #{postcode}"
location = {}
begin
url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=#{postcode}"
json = open(url).read
parsed_json = JSON(json)
parsed_location = parsed_json["results"].first['geometry']['location']
location['lat'] = parsed_location['lat'].to_s
location['lng'] = parsed_location['lng'].to_s
puts 'donewithallthat'
rescue
end
lat = location['lat'] || "0"
lng = location['lng'] || "0"
{:lat => lat, :lng => lng}
end
end | true |
d1c535b20699b2d963b46122b86c555b583e3ded | Ruby | iExperience/session0202_exercises | /JoshBroomberg-JoshBroomberg/d2/2B/Leapyears.rb | UTF-8 | 269 | 3.9375 | 4 | [] | no_license | puts "Enter a starting year:"
startYear = gets.chomp.to_i
puts "Enter an ending year:"
endYear = gets.chomp.to_i
puts "The leap years are:"
for year in (startYear..endYear)
if year%4==0
if year%100!=0
puts year
elsif year%400 ==0
puts year
end
end
end
| true |
ec7f33d697db84b62c4799d13cea8b561f402c7a | Ruby | coq-bench/make-html | /result.rb | UTF-8 | 2,504 | 2.578125 | 3 | [
"MIT"
] | permissive | require_relative 'status'
# The result of a bench.
class Result
attr_reader :status, :context,
:lint_command, :lint_status, :lint_duration, :lint_output,
:dry_with_coq_command, :dry_with_coq_status, :dry_with_coq_duration, :dry_with_coq_output,
:dry_without_coq_command, :dry_without_coq_status, :dry_without_coq_duration, :dry_without_coq_output,
:deps_command, :deps_status, :deps_duration, :deps_output,
:package_command, :package_status, :package_duration, :package_output,
:uninstall_command, :uninstall_status, :uninstall_duration, :uninstall_output,
:missing_removes, :mistake_removes, :install_sizes
def initialize(*arguments)
name, version, status, @context,
@lint_command, @lint_status, @lint_duration, @lint_output,
@dry_with_coq_command, @dry_with_coq_status, @dry_with_coq_duration, @dry_with_coq_output,
@dry_without_coq_command, @dry_without_coq_status, @dry_without_coq_duration, @dry_without_coq_output,
@deps_command, @deps_status, @deps_duration, @deps_output,
@package_command, @package_status, @package_duration, @package_output,
@uninstall_command, @uninstall_status, @uninstall_duration, @uninstall_output,
@missing_removes, @mistake_removes, @install_sizes =
arguments
@status = Status.new(name, version, status, @dry_without_coq_output, @deps_output, @package_output)
@missing_removes = @missing_removes.split("\n")
@mistake_removes = @mistake_removes.split("\n")
@install_sizes &&= @install_sizes.split("\n").each_slice(2).to_a
end
# A short message for the status.
def short_message
case @status.status
when "Success"
@package_duration.to_i.duration
when "NotCompatible"
"NC"
when "BlackList"
"BL"
when "LintError"
"Lint"
when "DepsError"
"Deps"
when "Error"
"Error"
when "UninstallError"
"Uninstall"
else
raise "unknown status #{@status.inspect}"
end
end
# A long message for the status.
def long_message
case @status.status
when "Success"
@package_duration.to_i.duration + " 🏆"
when "NotCompatible"
"Not compatible 👼"
when "BlackList"
"Black list 🏴☠️"
when "LintError"
"Lint error 💥"
when "DepsError"
"Error with dependencies 🚒"
when "Error"
"Error 🔥"
when "UninstallError"
"Uninstallation error 🌪️"
else
raise "unknown status #{@status}"
end
end
end
| true |
d971636b594fda821c04e8c853161b3ce688dd79 | Ruby | raglub/sea_battle | /lib/sea_battle/board.rb | UTF-8 | 4,003 | 3.3125 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
require_relative "cell"
require_relative "random_ship"
require_relative "support"
class SeaBattle
# It's Board of game Sea Battle
class Board
include ::SeaBattle::Support
attr_reader :board, :vertical, :horizontal, :status
def initialize(board = "1" * 100, status = :initialized)
@horizontal, @vertical = 10, 10
load_board(board)
@status = status
check_board
end
# When all ships are on board then board can be activated
# Return true when board was activated
def activate_board
result = 0
@board.flatten.each do |cell|
result += 1 if cell.is_in_ship?
end
return false unless result == 20
@status = :activated
true
end
def attack(row, column)
if @status == :activated
board[row][column].attack
is_sunken_ship?(row, column)
is_finished?
end
end
def is_attacked?(row, column)
board[row][column].is_attacked?
end
def is_in_ship?(row, column)
board[row][column].is_in_ship?
end
# Return true if on position (row, column) is the ship which is sunked
# Return false if on position (row, column) is not the ship which is sunked
# or don't exist the ship
def is_sunken_ship?(row, column)
positions = ship_positions(row, column)
return false if positions.empty?
is_sunk = true
positions.each do |position_row, position_column|
is_sunk = false unless board[position_row][position_column].is_attacked?
end
if is_sunk
positions.each do |position_row, position_column|
board[position_row][position_column].sunk
end
end
is_sunk
end
# Return position to attack (have not attacked)
def random_position
mixed_board_positions.each do |row, column|
return [row, column] unless is_attacked?(row, column)
end
end
# Set ships on the board (random positions)
def random_ships
return unless @status == :initialized
reset_board
[1, 1, 1, 1, 2, 2, 2, 3, 3, 4].each do |length|
RandomShip.new(self, length).add_ship
end
end
# Return array of position ship if it will be on position [row, column]
def ship_positions(row, column)
horizontal = horizontal_ship_position(row, column)
vertical = vertical_ship_position(row, column)
return horizontal if horizontal.size > vertical.size
vertical
end
private
# It should raise error when @board isn't Array
def check_board
raise "The board is not Array class" unless @board.size == 10
end
def is_finished?
is_finished = true
board.each do |line|
line.each do |cell|
is_finished = false if cell.is_in_ship? and not cell.is_sunk?
end
end
@status = :finished if is_finished
is_finished
end
# it should return array of ship position
# for horizontal line with position [row, column]
def horizontal_ship_position(row, column)
result = []
10.times do |position|
if @board[position][column].is_in_ship?
result << [position, column]
else
break if result.include?([row, column])
result = []
end
end
result
end
def load_board(board)
@board = board.split("").map do |status|
Cell.new(status.to_i)
end.each_slice(10).to_a
end
def reset_board
board.each do |line|
line.each do |cell|
cell.reset_cell
end
end
end
# it should return array of ship position
# for vertical line with position [row, column]
def vertical_ship_position(row, column)
result = []
10.times do |position|
if @board[row][position].is_in_ship?
result << [row, position]
else
break if result.include?([row, column])
result = []
end
end
result
end
end
end
| true |
86f822531b28784c5038ebd36b1afe9def851371 | Ruby | richo225/battleships_tech_test | /lib/game.rb | UTF-8 | 732 | 3.921875 | 4 | [] | no_license | class Game
attr_accessor :ships, :computer
def initialize
@ships = []
@computer = []
end
def position(cell)
@ships << cell
end
def start
(@computer << random_ships).flatten!
end
def fire(cell)
hit?(cell)? sink_ship(cell) : fire_back(random_shot)
end
def fire_back(cell)
@ships.delete(cell) if hit_back?(cell)
puts "You have lost!" if @ships.empty?
end
def sink_ship(cell)
@computer.delete(cell)
puts "You are victorious!" if @computer.empty?
end
private
def random_ships
(1..100).to_a.sample(5)
end
def random_shot
rand(101)
end
def hit?(cell)
@computer.include?(cell)
end
def hit_back?(cell)
@ships.include?(cell)
end
end
| true |
cb2dacf612b911ffceec61bdee01bd760479121b | Ruby | rock-core/tools-pocolog | /lib/pocolog/stream_aligner.rb | UTF-8 | 24,733 | 2.765625 | 3 | [] | no_license | module Pocolog
class StreamAligner
attr_reader :use_rt
attr_reader :use_sample_time
attr_reader :base_time
attr_reader :streams
# Provided for backward compatibility only
def count_samples
Pocolog.warn "StreamAligner#count_samples is deprecated. Use #size instead"
size
end
# Returns the number of samples one can get out of this stream aligner
#
# This is the sum of samples available on each of the underlying streams
#
# @return [Integer]
attr_reader :size
# Whether there are no samples in the aligner
def empty?
size == 0
end
# The index of the current sample
attr_reader :sample_index
# A per-stream mapping from the stream index to the global position of
# the last of this stream's samples
#
# @see first_sample_pos
attr_reader :global_pos_first_sample
# A per-stream mapping from the stream index to the global position of
# the first of this stream's samples
#
# @see last_sample_pos
attr_reader :global_pos_last_sample
# The full aligned index
#
# This is a mapping from a global position in the aligned stream to
# information about the sample at that stream
#
# @return [Array<IndexEntry>]
attr_reader :full_index
# The time of the first and last samples in the stream, in logical time
#
# @return [(Time,Time)]
attr_reader :interval_lg
def time_interval
Pocolog.warn_deprecated "StreamAligner#time_interval is deprecated in favor of #interval_lg"
interval_lg
end
def initialize(use_rt = false, *streams)
@use_sample_time = use_rt == :use_sample_time
@use_rt = use_rt
@global_pos_first_sample = Array.new
@global_pos_last_sample = Array.new
@size = 0
@interval_lg = Array.new
@base_time = nil
@stream_state = Array.new
@streams = Array.new
@sample_index = -1
add_streams(*streams)
end
# Returns the time of the last played back sample
#
# @return [Time]
def time
if (sample_index != -1) && (entry = full_index[sample_index])
StreamIndex.time_from_internal(entry.time, base_time)
end
end
# Tests whether reading the next sample will return something
#
# If {eof?} returns true, {#advance} and {#step} are guaranteed to return
# nil if called.
def eof?
sample_index >= size - 1
end
# Rewinds the stream aligner to the position before the first sample
#
# I.e. calling {#next} after {#rewind} would read the first sample
def rewind
@sample_index = -1
nil
end
IndexEntry = Struct.new :time, :stream_number, :position_in_stream, :position_global
# Add new streams to the alignment
def add_streams(*streams)
return if streams.empty?
if sample_index != -1
if eof?
eof = true
current_entry = full_index[-1]
else
current_entry = full_index[sample_index]
end
end
streams_size = streams.inject(0) { |s, stream| s + stream.size }
size = (@size += streams_size)
Pocolog.info "adding #{streams.size} streams with #{streams_size} samples"
tic = Time.now
unless base_time
@base_time = streams.map { |s| s.stream_index.base_time }.compact.min
end
sort_index = []
all_streams = (@streams + streams)
if base_time
all_streams.each_with_index do |stream, i|
stream.stream_index.base_time = base_time
times = stream.stream_index.raw_each_time.map { |t| t * size + i }
sort_index.concat(times)
end
end
Pocolog.info "concatenated indexes in #{"%.2f" % [Time.now - tic]} seconds"
tic = Time.now
sort_index.sort!
@global_pos_first_sample = Array.new
@global_pos_last_sample = Array.new
current_positions = Array.new(all_streams.size, 0)
@full_index = Array.new(size)
position_global = 0
for sort_code in sort_index
time = sort_code / size
stream_index = sort_code % size
position_in_stream = current_positions[stream_index]
current_positions[stream_index] = position_in_stream + 1
entry = IndexEntry.new(time, stream_index, position_in_stream, position_global)
global_pos_first_sample[entry.stream_number] ||= position_global
global_pos_last_sample[entry.stream_number] = position_global
@full_index[position_global] = entry
position_global += 1
end
@streams = all_streams
update_interval_lg
Pocolog.info "built full index in #{"%.2f" % [Time.now - tic]} seconds"
if current_entry
@sample_index = @full_index.
index do |e|
e.stream_number == current_entry.stream_number &&
e.position_in_stream == current_entry.position_in_stream
end
if eof
step
end
end
end
# Remove the given streams in the stream aligner
#
# The index-to-stream mapping changes after this. Refer to {#streams} to
# map indexes to streams
def remove_streams(*streams)
# First, build a map of the current stream indexes to the new
# stream indexes
stream_indexes = Array.new
for_removal = Array.new
streams.each do |s|
s_index = stream_index_for_stream(s)
stream_indexes << s_index
for_removal[s_index] = true
end
index_map = Array.new
new_index = 0
self.streams.size.times do |stream_index|
if for_removal[stream_index]
index_map[stream_index] = nil
else
index_map[stream_index] = new_index
new_index += 1
end
end
if eof?
eof = true
elsif sample_index != -1
current_entry = full_index[sample_index]
changed_sample = for_removal[current_entry.stream_number]
end
# Then, transform the index accordingly
@global_pos_first_sample = Array.new
@global_pos_last_sample = Array.new
global_position = 0
@full_index = full_index.find_all do |entry|
if current_entry && (current_entry == entry)
@sample_index = global_position
current_entry = nil # speedup comparison for the rest of the filtering
end
if new_index = index_map[entry.stream_number]
global_pos_first_sample[new_index] ||= global_position
global_pos_last_sample[new_index] = global_position
entry.position_global = global_position
entry.stream_number = new_index
global_position += 1
end
end
@stream_state.clear
if @full_index.empty?
@sample_index = -1
elsif eof
@sample_index = size
elsif @sample_index != -1
sample_info = seek_to_pos(@sample_index, false)
end
# Remove the streams, and update the global attributes
stream_indexes.reverse.each do |i|
s = @streams.delete_at(i)
@size -= s.size
end
update_interval_lg
if sample_info && changed_sample && (sample_index != full_index.size)
return *sample_info, single_data(sample_info[0])
end
end
# @api private
#
# Update {#interval_lg} based on the information currently in
# {#full_index}
def update_interval_lg
if full_index.empty?
@interval_lg = []
else
@interval_lg = [
StreamIndex.time_from_internal(full_index.first.time, base_time),
StreamIndex.time_from_internal(full_index.last.time, base_time)
]
end
end
# Seek at the given position or time
#
# @overload seek(pos, read_data = true)
# (see seek_to_pos)
# @overload seek(time, read_data = true)
# (see seek_to_time)
def seek(pos, read_data = true)
if pos.kind_of?(Time)
seek_to_time(pos, read_data)
else
seek_to_pos(pos, read_data)
end
end
# Seek to the first sample after the given time
#
# @param [Time] time the reference time
# @param [Boolean] read_data whether the sample itself should be read or not
# @return [(Integer,Time[,Typelib::Type])] the stream index, sample time
# and the sample itself if read_data is true
def seek_to_time(time, read_data = true)
if empty?
raise RangeError, "#{time} is out of bounds, the stream is empty"
elsif time < interval_lg[0] || time > interval_lg[1]
raise RangeError, "#{time} is out of bounds valid interval #{interval_lg[0]} to #{interval_lg[1]}"
end
target_time = StreamIndex.time_to_internal(time, base_time)
entry = @full_index.bsearch { |e| e.time >= target_time }
seek_to_index_entry(entry, read_data)
end
# Seeks to the sample whose global position is pos
#
# @param [Integer] pos the targetted global position
# @param [Boolean] read_data whether the sample itself should be read or not
# @return [(Integer,Time[,Typelib::Type])] the stream index, sample time
# and the sample itself if read_data is true
def seek_to_pos(pos, read_data = true)
if empty?
raise RangeError, "empty stream"
elsif pos < 0 || pos > size
raise RangeError, "#{pos} is out of bounds [0..#{size}]."
end
seek_to_index_entry(@full_index[pos], read_data)
end
# @api private
#
# This is a private helper for {seek_to_time} and {seek_to_pos}. It
# seeks the stream aligner to the given global sample
#
# @param [IndexEntry] entry index entry of the global sample we want to
# seek to
def seek_to_index_entry(entry, read_data = true)
if !entry
@sample_index = size
return
end
@sample_index = entry.position_global
stream_idx = entry.stream_number
@stream_state[stream_idx] = entry
if read_data
return stream_idx, time, single_data(stream_idx)
else
return stream_idx, time
end
end
# Return the stream object at the given stream index
#
# @param [Integer] stream_idx
# @return [DataStream]
def stream_by_index(stream_idx)
@streams[stream_idx]
end
# Returns the stream index for the given stream
def stream_index_for_stream(stream)
streams.index(stream)
end
# Returns the stream index of the stream with this name
#
# @param [String] name
# @return [Integer,nil]
def stream_index_for_name(name)
streams.index { |s| s.name == name }
end
# Returns the stream index of the stream whose type has this name
#
# @param [String] name
# @return [Integer,nil]
# @raise [ArgumentError] if more than one stream has this type
def stream_index_for_type(type)
if type.respond_to?(:name)
type = type.name
end
match_i = streams.index { |s| s.type.name == type }
if match_i
rmatch_i = streams.rindex { |s| s.type.name == type }
if match_i != rmatch_i
raise ArgumentError, "There exists more than one stream with type #{type}"
end
match_i
end
end
# Advances one step in the joint stream, and returns the index of the
# updated stream as well as the time and the data sample
#
# The associated data sample can also be retrieved by
# single_data(stream_idx)
#
# @return [(Integer,Time,Typelib::Type)]
# @see advance
def step
stream_idx, time = advance
if stream_idx
return stream_idx, time, single_data(stream_idx)
end
end
# Advances one step in the joint stream, and returns the index of the
# update stream as well as the time but does not decode the data
# sample_index like {#step} or {#next} does
#
# The associated data sample can then be retrieved by
# single_data(stream_idx)
#
# @return [(Integer,Time)]
# @see step
def advance
if eof?
@sample_index = size
return
end
seek_to_pos(@sample_index + 1, false)
end
# Decrements one step in the joint stream, an returns the index of the
# updated stream, its time as well as the sample data
#
# @return [(Integer,Time,Typelib::Type)]
def step_back
if @sample_index == 0
@sample_index = -1
return nil
end
seek_to_pos(sample_index - 1)
end
# Defined for compatibility with DataStream#next
#
# Goes one sample further and returns the sample's logical and real
# times as well as the stream index and the sample data
#
# @return [(Time,Time,(Integer,Typelib::Type)),nil]
def next
stream_index, time, data = step
if stream_index
return time, time, [stream_index, data]
end
end
# Defined for compatibility with DataStream#previous
#
# Goes back one sample and returns the sample's logical and real
# times as well as the stream index and the sample data
#
# @return [(Time,Time,(Integer,Typelib::Type)),nil]
def previous
stream_index, time, data = step_back
if stream_index
return time, time, [stream_index, data]
end
end
def pretty_print(pp)
pp.text "Stream aligner with #{streams.size} streams and #{size} samples"
pp.nest(2) do
pp.breakable
pp.seplist(streams.each_with_index) do |s, i|
pp.text "[#{i}] "
s.pretty_print(pp)
end
end
end
# exports all streams to a new log file
# if no start and end index is given all data are exported
# otherwise the data are truncated according to the given global indexes
#
# the block is called for each sample to update a custom progress bar if the block
# returns 1 the export is canceled
def export_to_file(file,start_index=0,end_index=size,&block)
output = Pocolog::Logfiles.create(file)
streams.each do |s|
stream_start_index = first_sample_pos(s)
stream_end_index = last_sample_pos(s) + 1
# Ignore the stream if it is empty
next if !stream_start_index
# Ignore the stream if there are no samples intersecting with
# the required interval
next if start_index >= stream_end_index || end_index <= stream_start_index
stream_start_index = [start_index, stream_start_index].max
stream_end_index = [end_index, stream_end_index].min
first_stream_pos = find_first_stream_sample_at_or_after(
stream_start_index, s)
last_stream_pos = find_first_stream_sample_at_or_after(
stream_end_index, s)
next if first_stream_pos == last_stream_pos
index = 0
number_of_samples = stream_end_index-stream_start_index+1
stream_output = output.create_stream(s.name, s.type)
result = s.copy_to(first_stream_pos,last_stream_pos,stream_output) do |i|
if block
index +=1
block.call(index,number_of_samples)
end
end
break if !result
end
output.close
end
# Returns the stream-local index of the first sample that is either at
# or just after the given global position
#
# @param [Integer] position_global a global position
# @param [DataStream] stream the data stream
def find_first_stream_sample_at_or_after(position_global, stream)
if !(entry = full_index[position_global])
return stream.size
end
stream_number = stream_index_for_stream(stream)
if entry.stream_number == stream_number
return entry.position_in_stream
end
find_first_stream_sample_after(position_global, stream)
end
# Returns the stream-local index of the first sample strictly after the
# sample at the given global position
#
# @param [Integer] position_global a global position
# @param [DataStream] stream the data stream
def find_first_stream_sample_after(position_global, stream)
if !(entry = full_index[position_global])
return stream.size
end
stream_number = stream_index_for_stream(stream)
# First things first, if entry is a sample of stream, we just have
# to go forward by one
if entry.stream_number == stream_number
return entry.position_in_stream + 1
end
# Otherwise, we need to search in the stream
time = entry.time
search_pos = stream.stream_index.sample_number_by_internal_time(time)
if search_pos == stream.size
return search_pos
end
# If the sample we found has the same time than the entry at
# position_global, We now have to figure out whether it is before or
# after position global
#
# We do a linear search in all samples that have the same time than
# the reference time. This basically assumes that you don't have a
# million samples with the same time. I believe it fair.
search_time = stream.stream_index.internal_time_by_sample_number(search_pos)
if search_time != time
return search_pos
end
while entry && entry.time == time
if entry.stream_number == stream_number
return entry.position_in_stream
end
entry = @full_index[position_global += 1]
end
return search_pos + 1
end
private def validate_stream_index_from_stream(stream)
unless stream_idx = streams.index(stream)
raise ArgumentError, "#{stream.name} (#{stream}) is not aligned in "\
"#{self}. Aligned streams are: #{streams.map(&:name).sort.join(", ")}"
end
stream_idx
end
# Returns the global sample position of the first sample
# of the given stream
#
# @param [Integer,DataStream] the stream
# @return [nil,Integer]
def first_sample_pos(stream)
if stream.kind_of?(DataStream)
stream = validate_stream_index_from_stream(stream)
end
@global_pos_first_sample[stream]
end
# Returns the global sample position of the last sample of the given
# stream
#
# @param [Integer,DataStream] the stream
# @return [nil,Integer]
def last_sample_pos(stream)
if stream.kind_of?(DataStream)
stream = validate_stream_index_from_stream(stream)
end
@global_pos_last_sample[stream]
end
# Returns the information necessary to read a stream's sample later
#
# @param [Integer] stream_idx the index of the stream
# @return [(DataStream,Integer),nil] if there is a current sample on
# this stream, this is the stream and the position on the stream,
# suitable to be passed to {DataStream#read_one_raw_data_sample}.
# Otherwise, returns nil.
#
# @example
# stream_idx, time = aligner.advance
# @read_later = aligner.sample_info(stream_idx)
# ...
# if @read_later
# stream, position = *@read_later
# stream.read_one_raw_data_sample(position)
# end
def sample_info(stream_idx)
if state = @stream_state[stream_idx]
return streams[stream_idx], state.position_in_stream
end
end
# Returns the current data sample for the given stream index
# note stream index is the index of the data stream, not the
# search index !
#
# @param [Integer] index index of the stream
# @param [Typelib::Type,nil] sample if given, the sample will be decoded
# in this object instead of creating a new one
# @return [Object,nil]
def single_data(index, sample = nil)
if (raw = single_raw_data(index, sample))
return Typelib.to_ruby(raw)
end
end
# Returns the current raw data sample for the given stream index
# note stream index is the index of the data stream, not the
# search index !
#
# @param [Integer] index index of the stream
# @param [Typelib::Type,nil] sample if given, the sample will be decoded
# in this object instead of creating a new one
# @return [Typelib::Type]
def single_raw_data(index, sample = nil)
stream, position = sample_info(index)
if stream
stream.read_one_raw_data_sample(position)
end
end
# Enumerate all samples in this stream
#
# @param [Boolean] do_rewind whether {#rewind} should be called first
# @yieldparam [Integer] stream_idx the stream in which the sample is
# contained
# @yieldparam [Time] time the stream time
# @yieldparam [Object] sample the sample itself
def raw_each(do_rewind = true)
return enum_for(__method__, do_rewind) unless block_given?
rewind if do_rewind
while (stream_idx, time = advance)
yield(stream_idx, time, single_raw_data(stream_idx))
end
end
# Enumerate all samples in this stream
#
# @param [Boolean] do_rewind whether {#rewind} should be called first
# @yieldparam [Integer] stream_idx the stream in which the sample is
# contained
# @yieldparam [Time] time the stream time
# @yieldparam [Object] sample the sample itself
def each(do_rewind = true)
return enum_for(__method__, do_rewind) unless block_given?
raw_each(do_rewind) do |index, time, raw_sample|
yield(index, time, Typelib.to_ruby(raw_sample))
end
end
end
end
| true |
945fd6271f1a8467d666c46b5f14580ec7453491 | Ruby | TeresaCreech/CSCI3308 | /Ruby Assignment/4b_RockPaperScissors.rb | UTF-8 | 1,516 | 4.15625 | 4 | [] | no_license | # Part4b: Rock Paper Scissors
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
def rps_game_winner(game)
# Winning moves
gamewinning = { "r" => "s", "s" => "p", "p" => "r" }
game[0][1] = game[0][1].downcase
game[1][1] = game[1][1].downcase
# Make sure there is the correct amount of players
raise WrongNumberOfPlayersError unless game.length == 2
# Check to make sure each player made a valid move
raise NoSuchStrategyError unless ["r", "p", "s"].include? game[0][1] and game[0][1].length == 1
raise NoSuchStrategyError unless ["r", "p", "s"].include? game[1][1] and game[1][1].length == 1
# If both players chose the same the first player wins
if game[0][1] == game[1][1]
return game[0]
# If the first player beats the second player
elsif gamewinning[game[0][1]] == game[1][1]
return game[0]
# If the second player beats the first player
elsif gamewinning[game[1][1]] == game[0][1]
return game[1]
end
end
def rps_tournament_winner(games)
# Base Case - Check to see if only two players (one round) is left
if games[0][0].is_a? String
return rps_game_winner(games)
end
# Continue Recursion if more than two players are left
return rps_game_winner([rps_tournament_winner(games[0]), rps_tournament_winner(games[1])])
end
print rps_tournament_winner([[[ ["Armando", "P"], ["Dave", "S"] ], [ ["Richard", "R"], ["Michael", "S"] ],],[[ ["Allen", "S"], ["Omer", "P"] ],[ ["David E.", "R"], ["Richard X.", "P"] ]]])
| true |
8db4ba59be6d16a0fd8579f8fa4277c91ee9e948 | Ruby | Jeantirard/exo | /exo_15.rb | UTF-8 | 184 | 3.625 | 4 | [] | no_license | puts "Quelle est ton année de naissance?"
année= gets.chomp
année= année.to_i
x = 0
while année <= 2017
puts "En #{année} tu avais #{x} ans."
année += 1
x += 1
end | true |
373d3c09735a88b267414c2270f3be91d05dfb02 | Ruby | leonimanuel/prime-ruby-online-web-sp-000 | /prime.rb | UTF-8 | 203 | 3.171875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require "pry"
def prime?(num)
if num <= 1
return false
end
i = 2
divisors = []
while i <= (num / 2)
divisors << i
i += 1
end
divisors.all? {|x| num % x != 0}
end
# binding.pry
| true |
4d7c4fe79d05f7b2b5de0e43af3bdd728fc9292b | Ruby | VarvaraBabkova/oo-relationships-practice | /app/models/user.rb | UTF-8 | 494 | 3.171875 | 3 | [] | no_license | class User
attr_accessor :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def pledges
Pledge.all.select {|p| p.pledger == self}
end
def projects
pledges.map {|p| p.project}
end
def self.highest_pledge
Pledge.all.max {|p, b| p.money <=> b.money}.pledger
end
def self.multi_pledger
all.select {|u| u.pledges.size > 1}
end
def self.project_creator(project)
all.select {|u| u.projects.include?(project)}
end
end | true |
4d88c74ed8154d43985111e1f6f51ac051cfc9e2 | Ruby | agirdler-lumoslabs/my_bar | /juice_bar_spec.rb | UTF-8 | 5,084 | 2.578125 | 3 | [] | no_license | require 'juice_bar'
describe '#juicer_gimme' do
subject { juicer_gimme(my_request, at) }
context 'beet juice' do
let(:my_request) { {'Beet Juice' => 1} }
context 'regular hours' do
let(:at) { '13:00' }
let(:my_drinks) { ['Beet Juice'] }
let(:my_bill) { 5.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'half price mango hours' do
let(:at) { '15:00' }
let(:my_drinks) { ['Beet Juice'] }
let(:my_bill) { 5.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'free cleansing shot hours' do
let(:at) { '21:00' }
let(:my_drinks) { ['Beet Juice', 'Cleansing Shot'] }
let(:my_bill) { 5.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
end
context 'mangotini' do
let(:my_request) { { 'Mangotini' => 1 } }
context 'regular hours' do
let(:at) { '13:00' }
let(:my_drinks) { ['Mangotini'] }
let(:my_bill) { 7.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'free cleansing shot hour' do
let(:at) { '21:00' }
let(:my_drinks) { ['Mangotini'] }
let(:my_bill) { 7.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'half price mango hours' do
let(:at) { '15:00' }
let(:my_drinks) { ['Mangotini'] }
let(:my_bill) { 3.5 }
it { is_expected.to match([my_drinks, my_bill]) }
end
end
context 'mangohattan' do
let(:my_request) { { 'Mangohattan' => 1 } }
context 'regular hours' do
let(:at) { '17:00' }
let(:my_drinks) { ['Mangohattan'] }
let(:my_bill) { 7.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'free cleansing shot hour' do
let(:at) { '21:00' }
let(:my_drinks) { ['Mangohattan'] }
let(:my_bill) { 7.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'half price mango hours' do
let(:at) { '15:00' }
let(:my_drinks) { ['Mangohattan'] }
let(:my_bill) { 3.5 }
it { is_expected.to match([my_drinks, my_bill]) }
end
end
context 'cleansing shot' do
let(:my_request) { { 'Cleansing Shot' => 1 } }
context 'regular hours' do
let(:at) { '13:00' }
let(:my_drinks) { ['Cleansing Shot'] }
let(:my_bill) { 3.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'half price mango hours' do
let(:at) { '15:00' }
let(:my_drinks) { ['Cleansing Shot'] }
let(:my_bill) { 3.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'free cleansing shot hours' do
let(:my_request) do
{
'Beet Juice' => 1,
'Cleansing Shot' => 1
}
end
let(:at) { '21:00' }
let(:my_drinks) { ['Beet Juice', 'Cleansing Shot', 'Cleansing Shot'] }
let(:my_bill) { 8.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
end
context 'multiple drinks' do
context 'regular hours' do
let(:my_request) do
{
'Beet Juice' => 1,
'Cleansing Shot' => 1,
'Mangotini' => 1,
'Mangohattan' => 1
}
end
let(:at) { '13:00' }
let(:my_drinks) do
a_collection_containing_exactly('Beet Juice', 'Cleansing Shot', 'Mangohattan', 'Mangotini')
end
let(:my_bill) { 22.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'free cleansing shot hours' do
let(:my_request) do
{
'Beet Juice' => 2,
'Cleansing Shot' => 1
}
end
let(:at) { '21:00' }
let(:my_drinks) { ['Beet Juice', 'Beet Juice', 'Cleansing Shot', 'Cleansing Shot', 'Cleansing Shot'] }
let(:my_bill) { 13.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
end
context 'future promo' do
let(:my_request) do
{
'Mangotini' => 1,
'Mangohattan' => 1
}
end
let(:my_drinks) { ['Mangohattan', 'Mangotini'] }
context 'during Half Price Mangos' do
skip 'This works but only because we do not support the new promotion'
let(:at) { '14:15' }
let(:my_bill) { 7.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'during Free Cleansing Shots' do
skip 'This works but only because we do not support the new promotion'
let(:my_request) do
{
'Mangotini' => 1,
'Mangohattan' => 1,
'Beet Juice' => 1
}
end
let(:my_drinks) { ['Beet Juice', 'Cleansing Shot', 'Mangohattan', 'Mangotini'] }
let(:at) { '20:15' }
let(:my_bill) { 19.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
context 'during no other happy hours' do
before do
pending 'This does not work since we do not support the new promotion'
end
let(:at) { '16:15' }
let(:my_bill) { 10.0 }
it { is_expected.to match([my_drinks, my_bill]) }
end
end
end
| true |
2fefb05144862a08077ad36a1245be1213f22d83 | Ruby | jackrobbins1/prime-ruby-chicago-web-career-040119 | /prime.rb | UTF-8 | 250 | 3.3125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def prime?(int)
if int < 2
return false
elsif int == 2
return true
else
array = Array(2...int)
array.each do |el|
if int % el == 0
return false
else
next
end
end
return true
end
end
| true |
0486501bd36167d263063f1717f6c1aa1bd05b13 | Ruby | ii-lo/pelp | /spec/helpers/pastel_helper_spec.rb | UTF-8 | 724 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'rails_helper'
# Specs in this file have access to a helper object that includes
# the PastelHelper. For example:
#
# describe PastelHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
RSpec.describe PastelHelper, :type => :helper do
it "returns color for string" do
regexp = /\A#[0-9a-f]{3,6}\z/i
expect(helper.string_to_pastel("asdf")).to match regexp
expect(helper.string_to_pastel("")).to match regexp
end
it "does not return the same color for other string" do
expect(helper.string_to_pastel("asdf")).not_to eq helper.string_to_pastel("asdfr1")
end
end
| true |
60f604fee18ff984f443f87493168463c621ed72 | Ruby | LinaGallardo/RubyExercises | /class_exercise7.rb | UTF-8 | 963 | 3.8125 | 4 | [] | no_license | # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
class SquaresNumber
def initialize(num)
@num = num
end
def squares
square_sum = (1..@num).sum ** 2
sum_square = (1..@num).map { |num| num ** 2 }.sum
difference = (square_sum - sum_square)
end
end
#----------------Test------------------
require 'minitest/autorun'
class SquaresNumberTest < Minitest::Test
def setup
@number = SquaresNumber.new(100)
end
def test_instance_of_squares_number
assert_instance_of(SquaresNumber, @number)
end
def test_squares
assert_equal(25164150, @number.squares)
end
end
#----------------TestSpecs------------------
describe SquaresNumber do
before do
@num = SquaresNumber.new(10)
end
describe "when insert a number" do
it "must gets the value of the difference of the squares" do
@num.squares.must_equal 2640
end
end
end
| true |
cfa9409ea42d216095c2f189011e613d25ae0921 | Ruby | jwarchol/soulmate-goliath | /lib/soulmate/loader.rb | UTF-8 | 1,401 | 2.8125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module Soulmate
class Loader < Base
def load(items)
# delete the sorted sets for this type
# wrap in multi/exec?
phrases = Soulmate.redis.smembers(base)
phrases.each do |p|
Soulmate.redis.del("#{base}:#{p}")
end
Soulmate.redis.del(base)
# Redis can continue serving cached requests for this type while the reload is
# occuring. Some requests may be cached incorrectly as empty set (for requests
# which come in after the above delete, but before the loading completes). But
# everything will work itself out as soon as the cache expires again.
# delete the data stored for this type
Soulmate.redis.del(database)
items_loaded = 0
items.each_with_index do |item, i|
id = item["id"]
term = item["term"]
score = item["score"]
if id and term
# store the raw data in a separate key to reduce memory usage
Soulmate.redis.hset(database, id, JSON.dump(item))
prefixes_for_phrase(term).each do |p|
Soulmate.redis.sadd(base, p) # remember this prefix in a master set
Soulmate.redis.zadd("#{base}:#{p}", score, id) # store the id of this term in the index
end
items_loaded += 1
end
puts "added #{i} entries" if i % 100 == 0 and i != 0
end
items_loaded
end
end
end | true |
a67f8a606469a432c97b0a376bf249eff24c6e2d | Ruby | berfarah/config | /bin/run | UTF-8 | 2,184 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env ruby
case ARGV.first
when "encrypt"
from = "decrypted"
to = "encrypted"
nodiff = true
when "decrypt"
from = "encrypted"
to = "decrypted"
flags = "-d"
else
puts "Usage: #{__FILE__} [encrypt|decrypt]"
exit 1
end
require "fileutils"
require "pathname"
ROOT_PATH = Pathname.new(File.expand_path("../../", __FILE__)).freeze
# Load keys
encryption_keys = Dir[ROOT_PATH.join("*.key")].map do |key_path|
environment = File.basename(key_path).chomp(".key")
value = File.read(key_path)
[environment.to_sym, value]
end.to_h
# Mirror directory structure
Dir[ROOT_PATH.join("#{from}/**/*/")].each do |dir|
encrypted_dir = dir.sub(from, to)
FileUtils.mkdir_p(encrypted_dir)
end
class Diff
attr_reader :destination_file, :backup_file, :diff_file
def initialize(destination_file)
@destination_file = destination_file
@backup_file = destination_file + ".old"
@diff_file = destination_file.sub("/decrypted/", "/diff/")
backup
end
def self.call(destination_file, noop: false)
return yield if noop
instance = new(destination_file)
yield
instance.call
end
def call
return unless File.file?(backup_file)
write_diff unless diff.empty?
cleanup
end
private
def diff
@diff ||= `diff #{backup_file} #{destination_file}`
end
def backup
FileUtils.mv(destination_file, backup_file) if File.file?(destination_file)
end
def cleanup
File.delete(backup_file) if File.file?(backup_file)
end
def header
"#{Time.now}\n< Previous\n> Current"
end
def create_diff_directory
FileUtils.mkdir_p(File.dirname(diff_file))
end
def write_diff
create_diff_directory
File.open(diff_file, "a") do |file|
file.puts header
file.puts diff
file.puts "\n"
end
end
end
# Decrypt each environment using the appropriate key
encryption_keys.each do |environment, key|
Dir[ROOT_PATH.join("#{from}/**/*.yml")].each do |file|
destination_file = file.sub(from, to)
Diff.call(destination_file, noop: nodiff) do
system("openssl enc -aes-256-cbc #{flags} -salt -in #{file} -out #{destination_file} -k #{key}")
end
end
end
| true |
0d7c16d74966b2c8a5e9e65450c7af419e12ea0c | Ruby | whatalnk/cpsubmissions | /atcoder/ruby/abc097/abc097_a/2624137.rb | UTF-8 | 430 | 3.109375 | 3 | [] | no_license | # Contest ID: abc097
# Problem ID: abc097_a ( https://atcoder.jp/contests/abc097/tasks/abc097_a )
# Title: A. Colorful Transceivers
# Language: Ruby (2.3.3)
# Submitted: 2018-06-06 01:36:29 +0000 UTC ( https://atcoder.jp/contests/abc097/submissions/2624137 )
a, b, c, d = gets.chomp.split(" ").map(&:to_i)
if (a - c).abs <= d then
puts "Yes"
elsif (a - b).abs <= d && (b - c).abs <= d then
puts "Yes"
else
puts "No"
end
| true |
c82a832544b77b1ceaa67221f73d931ae2ae2a09 | Ruby | remylombard/fullstack-challenges | /02-OOP/05-Food-Delivery-Day-One/01-Food-Delivery/app/controllers/sessions_controller.rb | UTF-8 | 556 | 2.75 | 3 | [] | no_license | require_relative "../views/sessions_view"
class SessionsController
def initialize(employee_repo)
@employee_repo = employee_repo
@view = SessionsView.new
end
def sign_in
# 1. Ask the username
username = @view.ask_for_username
# 2. Ask the password
password = @view.ask_for_password
# 3. Look for an employee that matches
employee = @employee_repo.find_by_username(username)
if employee && employee.password == password
# ok
return employee
end
@view.wrong_credentials
sign_in
end
end
| true |
ef3b03e29cce6cb9d121742713d5fcda6e7b65b9 | Ruby | tblanchard01/Boris_Bikes | /spec/docking_station_spec.rb | UTF-8 | 503 | 2.625 | 3 | [] | no_license | require 'docking_station'
describe DockingStation do
describe '#release_bike' do
it 'releases a bike' do
bike = Bike.new
subject.dock(bike)
expect(subject.release_bike).to eq bike
end
it 'raises an error when there are no bikes available' do
expect{subject.release_bike}.to raise_error 'No bikes are available'
end
end
it 'shows a docked bike' do
expect(subject).to respond_to :bike
end
it 'docks bike' do
expect(subject).to respond_to(:dock).with(1).argument
end
end
| true |
f62690a26978544924b7351efedd5814f8b6e740 | Ruby | msrashid/Exercise-sets-for-101-109---Small-Problems | /easy5/ex2.rb | UTF-8 | 357 | 3.515625 | 4 | [] | no_license | def time_of_day(integer)
hours = integer / 60 % 24
minutes = integer % 60
p "#{hours.to_s.rjust(2, "0")}:#{minutes.to_s.rjust(2, "0")}"
end
p time_of_day(0) == "00:00"
p time_of_day(-3) == "23:57"
p time_of_day(35) == "00:35"
p time_of_day(-1437) == "00:03"
p time_of_day(3000) == "02:00"
p time_of_day(800) == "13:20"
p time_of_day(-4231) == "01:29" | true |
83f7e396618359479ec317ff9ef4d304ccc7a394 | Ruby | reakiro/codebreaker-gem | /lib/codebreaker/game.rb | UTF-8 | 762 | 3.125 | 3 | [] | no_license | require_relative 'validations'
require_relative 'comparing'
module Codebreaker
class Game
include Validations
include Comparing
attr_reader :secret_number, :attempts_number, :hints_number
def initialize(attempts_number, hints_number)
@secret_number = secret_number_generate
@attempts_number = attempts_number
@hints_number = hints_number
end
def process(input_number)
@attempts_number -= 1
comparing(input_number)
end
def lost?
@attempts_number.zero?
end
def hint
return unless @hints_number.positive?
@hints_number -= 1
@secret_number.sample
end
def secret_number_generate
(1..4).inject([]) { |number| number << rand(1..6) }
end
end
end
| true |
63ef823f38297728cf9afb1ed151cb648a34d697 | Ruby | rubiety/battleship | /app/models/game.rb | UTF-8 | 1,885 | 2.8125 | 3 | [] | no_license | class Game < ActiveRecord::Base
has_many :ships, dependent: :destroy
has_many :rounds, dependent: :destroy
has_many :fires, through: :rounds
after_create :create_ships
ROUNDS = 6
FIRES_PER_ROUND = 5
SIZE = 16
def points
value = points_from_sinking_ships - fires.where("rounds.fires_count >= 5").where(hit: false).count
value < 0 ? 0 : value
end
def points_from_sinking_ships
ships_sunk.map(&:points).sum
end
def ships_sunk
ships.to_a.select(&:sunk?)
end
def all_ships_sunk?
ships_sunk.size == ships.size
end
def fire(x, y)
return false if completed?
current_round.fires.create(x: x, y: y)
end
def completed?
fires.count >= FIRES_PER_ROUND * ROUNDS
end
def fire_at?(x, y)
fires.where(x: x, y: y).exists?
end
def hit_at?(x, y)
fires.where("rounds.fires_count >= 5").where(hit: true, x: x, y: y).exists?
end
def ship_at?(x, y)
ship_coordinates.any? do |coords|
coords[0] == x and coords[1] == y
end
end
def current_round
if rounds.empty?
rounds.create
elsif rounds.last.fires.count < 5
rounds.last
else
rounds.create
end
end
def ship_coordinates
ships.map(&:coordinates).flatten(1)
end
def create_ships
Ship::TYPES.each do |name, values|
ship = nil
begin
start_at = [(1..Game::SIZE).to_a.sample, (1..Game::SIZE).to_a.sample]
if rand > 0.5
end_at = [start_at[0], start_at[1] + values[:size] - 1]
else
end_at = [start_at[0] + values[:size] - 1, start_at[1]]
end
ship = Ship.new(
name: name,
start_x: start_at[0],
start_y: start_at[1],
end_x: end_at[0],
end_y: end_at[1],
)
ship.game = self
end while !ship.valid?
ship.save!
end
ships.reload
end
end
| true |
88601acdd7a1a0e3b52370f663b4de7ee9cfa9fd | Ruby | eladmeidar/diakonos | /lib/diakonos/buffer/delete.rb | UTF-8 | 4,295 | 2.515625 | 3 | [
"MIT"
] | permissive | module Diakonos
class Buffer
# x and y are given window-relative, not buffer-relative.
def delete
if selection_mark
delete_selection
else
row = @last_row
col = @last_col
if ( row >= 0 ) and ( col >= 0 )
line = @lines[ row ]
if col == line.length
if row < @lines.length - 1
# Delete newline, and concat next line
join_lines( row )
cursor_to( @last_row, @last_col )
end
else
take_snapshot( TYPING )
@lines[ row ] = line[ 0...col ] + line[ (col + 1)..-1 ]
set_modified
end
end
end
end
def delete_line
remove_selection( DONT_DISPLAY ) if selection_mark
row = @last_row
take_snapshot
retval = nil
if @lines.length == 1
retval = @lines[ 0 ]
@lines[ 0 ] = ""
else
retval = @lines[ row ]
@lines.delete_at row
end
cursor_to( row, 0 )
set_modified
retval
end
def delete_to_eol
remove_selection( DONT_DISPLAY ) if selection_mark
row = @last_row
col = @last_col
take_snapshot
if @settings[ 'delete_newline_on_delete_to_eol' ] and col == @lines[ row ].size
next_line = @lines.delete_at( row + 1 )
@lines[ row ] << next_line
retval = [ "\n" ]
else
retval = [ @lines[ row ][ col..-1 ] ]
@lines[ row ] = @lines[ row ][ 0...col ]
end
set_modified
retval
end
def delete_from_to( row_from, col_from, row_to, col_to )
take_snapshot
if row_to == row_from
retval = [ @lines[ row_to ].slice!( col_from, col_to - col_from ) ]
else
pre_head = @lines[ row_from ][ 0...col_from ]
post_tail = @lines[ row_to ][ col_to..-1 ]
head = @lines[ row_from ].slice!( col_from..-1 )
tail = @lines[ row_to ].slice!( 0...col_to )
retval = [ head ] + @lines.slice!( row_from + 1, row_to - row_from ) + [ tail ]
@lines[ row_from ] = pre_head + post_tail
end
set_modified
retval
end
def delete_to( char )
remove_selection( DONT_DISPLAY ) if selection_mark
first_row = row = @last_row
index = @lines[ @last_row ].index( char, @last_col+1 )
while row < @lines.length - 1 && index.nil?
row += 1
index = @lines[ row ].index( char )
end
if index
delete_from_to( first_row, @last_col, row, index )
end
end
def delete_from( char )
remove_selection( DONT_DISPLAY ) if selection_mark
first_row = row = @last_row
index = @lines[ @last_row ].rindex( char, @last_col-1 )
while row > 0 && index.nil?
row -= 1
index = @lines[ row ].rindex( char )
end
if index
deleted_text = delete_from_to( row, index+1, first_row, @last_col )
cursor_to( row, index+1 )
deleted_text
end
end
def delete_to_and_from( char, inclusive = NOT_INCLUSIVE )
remove_selection( DONT_DISPLAY ) if selection_mark
start_char = end_char = char
case char
when '('
end_char = ')'
when '{'
end_char = '}'
when '['
end_char = ']'
when '<'
end_char = '>'
when ')'
end_char = '('
when '}'
end_char = '{'
when ']'
end_char = '['
when '>'
end_char = '<'
end
row = @last_row
start_index = @lines[ @last_row ].rindex( start_char, @last_col )
while row > 0 && start_index.nil?
row -= 1
start_index = @lines[ row ].rindex( start_char )
end
start_row = row
row = @last_row
end_index = @lines[ row ].index( end_char, @last_col+1 )
while row < @lines.length - 1 && end_index.nil?
row += 1
end_index = @lines[ row ].index( end_char )
end
end_row = row
if start_index && end_index
if inclusive
end_index += 1
else
start_index += 1
end
cursor_to( start_row, start_index )
delete_from_to( start_row, start_index, end_row, end_index )
end
end
end
end
| true |
ffbabf73ddab32a4a160dd122cb9f0f733491a6e | Ruby | jkriss/yesorno | /yesorno.rb | UTF-8 | 1,284 | 2.625 | 3 | [] | no_license | require 'rubygems'
require 'bundler'
Bundler.setup
Bundler.require
require 'open-uri'
def latest_tweet(screen_name)
screen_name = screen_name[0,15]
begin
json = open("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=#{screen_name}&count=1").read
tweet = JSON.parse(json)[0]
text = tweet['text']
@tweet_url = "https://twitter.com/#{screen_name}/status/#{tweet['id_str']}"
# @tweet_time = Time.parse(tweet['created_at'])
text
rescue
'MAYBE'
end
end
get '/' do
@screen_name = ENV["SCREEN_NAME"] || request.host.split('.').first
yes_or_no
end
get '/:screen_name' do
@screen_name = params[:screen_name]
yes_or_no
end
def yes_or_no
cache_control :public, :max_age => 30
@answer = latest_tweet(@screen_name)
@answer = @answer =~ /yes/i ? 'YES' : 'NO' unless @answer == 'MAYBE'
haml :index
end
__END__
@@ layout
%html
%head
%title #{@screen_name}?
:css
* { margin: 0 ; padding: 0 }
.time { color: #aaa; font-size: 12px }
body { margin-top: 80px; text-align:center; font-family: Helvetica, Arial, sans-serif }
h1 { margin-bottom: 10px; font-size: 48pt }
h1, h1 a { color: #000; text-decoration: none }
%body
= yield
@@ index
%h1
%a{ :href => @tweet_url }
= @answer
| true |
a9803df03cf462cf6201d30dabce4abdb72cf186 | Ruby | adbeel92/rails-challenge | /app/concepts/links/operations/update.rb | UTF-8 | 589 | 2.515625 | 3 | [] | no_license | # frozen_string_literal: true
module Links
module Operations
class Update
attr_reader :link
def initialize(link:, original_url:)
@link = link
@original_url = URI.decode_www_form_component(original_url.strip)
end
def run
assign_attributes
return true unless link.changed?
return false unless link.valid?
link.save
end
private
attr_reader :original_url
def assign_attributes
link.assign_attributes(
original_url: original_url
)
end
end
end
end
| true |
c18550a33022505d63abbba6ef3b0feec1ee85c2 | Ruby | tddycks/dynamic-orm-lab-v-000 | /lib/interactive_record.rb | UTF-8 | 1,663 | 2.890625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative "../config/environment.rb"
require 'active_support/inflector'
require 'pry'
class InteractiveRecord
def self.table_name
self.to_s.downcase.pluralize
end
def self.column_names
#end result is "column_name_one", "column_name_two" etc
DB[:conn].results_as_hash = true
sql = "PRAGMA table_info ('#{table_name}')"
table_info = DB[:conn].execute(sql)
#returns array of hashes
c_names = []
table_info.each do |hash|
c_names << hash["name"]
end
c_names.compact
#binding.pry
end
def initialize(attributes={})
attributes.each do |key, value|
self.send("#{key}=", value)
end
end
def table_name_for_insert
self.class.table_name
end
def col_names_for_insert
self.class.column_names.delete_if {|name| name == 'id'}.join(", ")
end
def values_for_insert
#return example: "'Sam', '11'"
values = []
self.class.column_names.each {|name| values << "'#{self.send(name)}'" unless self.send(name).nil?}
values.join(", ")
end
def save
sql = "INSERT INTO #{table_name_for_insert} (#{col_names_for_insert}) VALUES (#{values_for_insert})"
DB[:conn].execute(sql)
@id = DB[:conn].execute("SELECT last_insert_rowid() FROM #{table_name_for_insert}")[0][0]
end
def self.find_by_name(name)
#returns the matching row from a name argument
sql = "SELECT * FROM #{table_name} WHERE #{table_name}.name = name"
DB[:conn].execute(sql)
end
def self.find_by(hash)
hash.map do |key, value|
DB[:conn].execute("SELECT * FROM #{table_name} WHERE #{key.to_s} = '#{value}'")
#binding.pry
end.first
end
end | true |
277c5f2b1eb8d8b484e5df8bfddedaffcabe47a9 | Ruby | dlonra22/operators-online-web-pt-081219 | /lib/operations.rb | UTF-8 | 171 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def unsafe?(speed)
if (speed > 39) && (speed < 61)
return false
else return true
end
end
def not_safe?(speed)
((speed > 39) && (speed < 61))? false : true
end
| true |
e924ccb0855b5c4b4ea92cbdcf72a31d98fd39e2 | Ruby | marceloluizleite/shortener_of_url | /shortener.rb | UTF-8 | 548 | 2.6875 | 3 | [] | no_license | require 'sinatra'
get '/' do erb :index; end
__END__
@@ layout
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Encurtador de URL</title>
</head>
<body>
<%= yield %>
</body>
</html>
@@ index
<h1 align="center">Encurtador de URL'S:</h1>
<h2>
<form action="/" method="post", align="center">
<label for="insert_url">Insira a URL:</label>
<input type="text" class="input" name="encurtar" id="encurtar" />
<input type="submit" name="GERAR" class="button" value="Gerar"/>
</form>
</h2> | true |
ef822845ca7bc837b585aa4f09ee7e9b7c3572b8 | Ruby | dqmrf/dive-in-ruby | /sandbox/errors_handling/resque/base.rb | UTF-8 | 183 | 3.859375 | 4 | [] | no_license | print 'Enter a number: '
n = gets.to_i
begin
result = 100 / n
rescue ZeroDivisionError
puts "Your number didn't work. Was it zero???"
exit
end
puts "100/#{n} is a #{result}"
| true |
2a3feeffe4d8ace460f00bcbc39f7b9393ed074a | Ruby | eebbesen/minutes_maid | /vendor/cache/ruby/2.5.0/gems/ruby-hmac-0.4.0/test/test_hmac.rb | UTF-8 | 2,322 | 2.578125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
$: << File.dirname(__FILE__) + "/../lib"
require "hmac-md5"
require "hmac-sha1"
begin
require "minitest/unit"
rescue LoadError
require "rubygems"
require "minitest/unit"
end
MiniTest::Unit.autorun
class TestHmac < MiniTest::Unit::TestCase
def test_s_digest
key = "\x0b" * 16
text = "Hi There"
hmac = HMAC::MD5.new(key)
hmac.update(text)
assert_equal(hmac.digest, HMAC::MD5.digest(key, text))
end
def test_s_hexdigest
key = "\x0b" * 16
text = "Hi There"
hmac = HMAC::MD5.new(key)
hmac.update(text)
assert_equal(hmac.hexdigest, HMAC::MD5.hexdigest(key, text))
end
def test_hmac_md5_1
assert_equal(HMAC::MD5.hexdigest("\x0b" * 16, "Hi There"),
"9294727a3638bb1c13f48ef8158bfc9d")
end
def test_hmac_md5_2
assert_equal(HMAC::MD5.hexdigest("Jefe", "what do ya want for nothing?"),
"750c783e6ab0b503eaa86e310a5db738")
end
def test_hmac_md5_3
assert_equal(HMAC::MD5.hexdigest("\xaa" * 16, "\xdd" * 50),
"56be34521d144c88dbb8c733f0e8b3f6")
end
def test_hmac_md5_4
assert_equal(HMAC::MD5.hexdigest(["0102030405060708090a0b0c0d0e0f10111213141516171819"].pack("H*"), "\xcd" * 50),
"697eaf0aca3a3aea3a75164746ffaa79")
end
def test_hmac_md5_5
assert_equal(HMAC::MD5.hexdigest("\x0c" * 16, "Test With Truncation"),
"56461ef2342edc00f9bab995690efd4c")
end
# def test_hmac_md5_6
# assert_equal(HMAC::MD5.hexdigest("\x0c" * 16, "Test With Truncation"),
# "56461ef2342edc00f9bab995")
# end
def test_hmac_md5_7
assert_equal(HMAC::MD5.hexdigest("\xaa" * 80, "Test Using Larger Than Block-Size Key - Hash Key First"),
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd")
end
def test_hmac_md5_8
assert_equal(HMAC::MD5.hexdigest("\xaa" * 80, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"),
"6f630fad67cda0ee1fb1f562db3aa53e")
end
def test_reset_key
hmac = HMAC::MD5.new("key")
hmac.reset_key
assert_raises(RuntimeError) { hmac.update("foo") }
end
def test_set_key
hmac = HMAC::MD5.new
assert_raises(RuntimeError) { hmac.update("foo") }
hmac.reset_key
assert_raises(RuntimeError) { hmac.update("foo") }
end
end
| true |
c4217c0ab345d348c9fcd7d9bcaf805ca6f59064 | Ruby | codism15/rwin | /remove-qoutes.rb | UTF-8 | 2,388 | 2.921875 | 3 | [] | no_license | # pgAdmin 3 double quote the data being copied. This script is to remove the double
# quotation marks before paste
require 'clipboard'
require 'optparse'
require 'logger'
Encoding.default_internal = Encoding::UTF_8
$log = Logger.new(STDERR)
options = OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename(__FILE__)} [options]"
opts.on('-h', '-?', '--help', 'display help') do
puts opts
puts <<EOF
Example:
Read from console and write to clipboard
ruby sqlin.rb -i console -o clip
EOF
exit
end
opts.on('-i', '--input=FILE', 'read input from file; default is clipboard') do |file|
$input_filename = file
end
opts.on('-o', '--output=FILE', 'output to file; default is console') do |file|
$output_filename = file
end
opts.on('-l', '--logger [LEVEL]', 'trun on logger') do |level|
level ||= 'info'
$log.level =
if level.casecmp('info') == 0 then Logger::INFO
elsif level.casecmp('debug') == 0 then Logger::DEBUG
else abort "unknown log level #{level}"
end
end
end
options.parse!
# load source
$lines = []
def load_source_line(line)
$lines.push line
end
if defined? $input_filename
if $input_filename.casecmp('console') == 0
$stdin.each {|line|load_source_line(line)}
else
File.foreach($input_filename) {|line|load_source_line(line.chomp)}
end
else
# load from clipboard
str = Clipboard.paste
$log.debug "clipboard text encoding: #{str.encoding}"
str = str.encode('utf-8', :invalid => :replace, :undef => :replace, :replace => '')
ending = str.index("\0")
if ending != nil && ending >= 0
str = str.slice(0, ending)
end
if $log.debug?
$log.debug "clipboard text length: #{str.length}"
str.bytes.each_slice(8) {|row|
$log.debug row.map{|b|sprintf(" 0x%02X",b)}.join
}
end
str.split(/\r?\n/).each {|line|load_source_line(line)}
end
abort 'no data is found' if $lines.length == 0
if $log.debug?
$lines.each {|line|
$log.debug("#{line.length}, #{line}")
}
end
# detect data type
# generate output
$output_lines = []
$lines.each_with_index {|line, index|
newline = line.gsub(/^"|"$/, '')
$output_lines.push newline
}
# output
if defined? $output_filename
if $output_filename.casecmp('clip') == 0
Clipboard.copy $output_lines.join("\n")
else
File.write($output_filename, $output_lines.join("\n"))
end
else
puts $output_lines
end
| true |
c407317f0b3b023975979f095c8f0a23d4b62e82 | Ruby | oaxacarb/ruby_blocks | /04_lambdas_y_procs/02_creacion_y_ejecucion_de_lambdas_y_procs_con_parametros.rb | UTF-8 | 153 | 3.546875 | 4 | [] | no_license | variable_lambda = lambda { |x| puts x }
variable_proc = Proc.new { |x| puts x }
variable_lambda.call("hola")
# hola
variable_proc.call("mundo")
# mundo
| true |
45391114d0fd03fefa88ba6ea5e2840ef6ba12cd | Ruby | itacademy-ruby/nevgeniy_lake | /ducks_lake.rb | UTF-8 | 1,233 | 3.171875 | 3 | [] | no_license | # encoding: utf-8
# Duck
module Flying
def fly
'Flying'
end
def reactive_fly
"reactive_fly"
end
def mechanical_fly
"mechanical_fly"
end
end
module Quacking
def quacking
'Quacking'
end
end
module Swiming
def swiming
'Swiming'
end
end
module Eating
def eating
'Eating'
end
end
class Duck
def fly
"Can't Fly"
end
def swiming
"Can't swim"
end
def quacking
"Can't quack"
end
def eating
"Can't Eating"
end
def reactive_fly
"Can't reactive_fly"
end
def mechanical_fly
"Can't mechanical_fly"
end
end
class RealDuck < Duck
include Flying
include Quacking
include Swiming
include Eating
end
class RubberDuck < Duck
include Quacking
include Swiming
end
class WoodDuck < Duck
include Swiming
end
class RobotsDuck < Duck
include Flying
include Quacking
include Swiming
include Eating
end
ducks ||= []
ducks << RealDuck.new
ducks << RubberDuck.new
ducks << WoodDuck.new
ducks << RobotsDuck.new
ducks.each do |duck|
puts "#{duck.class} #{duck.swiming}"
puts "#{duck.class} #{duck.quacking}"
puts "#{duck.class} #{duck.reactive_fly}"
puts "#{duck.class} #{duck.mechanical_fly}"
puts "#{duck.class} #{duck.eating}"
end | true |
32b7cce3a11c529075377bb74645e8cae6e6ec32 | Ruby | igorsimdyanov/ruby | /class_methods/ticket_set_get.rb | UTF-8 | 245 | 3.171875 | 3 | [] | no_license | class Ticket
def initialize(date:, price: 500)
@price = price
@date = date
end
def set_price(price)
@price = price
end
def price
@price
end
def set_date(date)
@date = date
end
def date
@date
end
end
| true |
6cda342dcca85528c044d10c6bf73d53a98cec46 | Ruby | Varunram/Compiler | /parser.rb | UTF-8 | 1,381 | 2.859375 | 3 | [] | no_license | require_relative 'parserbase'
require_relative 'sexp'
class Parser < ParserBase
def initialize s
@s = s
@sexp = SEXParser.new(s)
end
def parse_name
@s.expect(Atom)
end
def parse_arglist
rest = false
if (@s.expect("*"))
rest = true
@s.ws
end
name = parse_name
raise "Expected argument name" if rest && !name
return nil if !name
args = [(rest ? [name.to_sym,:rest] : name.to_sym)]
@s.nolfws
return args if (!@s.expect(","))
@s.ws
more = parse_arglist
raise "Expected argument" if !more
return args + more
end
def parse_args
@s.nolfws
if (@s.expect("("))
@s.ws
args = parse_arglist
@s.ws
raise "Expected ')'" if !@s.expect(")")
return args
end
return parse_arglist
end
def parse_defexp
@s.ws
@sexp.parse
end
def parse_def
return nil if !@s.expect("def")
@s.ws
raise "Expected function name" if !(name = parse_name)
args = parse_args
@s.ws
exps = [:do] + zero_or_more(:defexp)
raise "Expected expression of 'end'" if !@s.expect("end")
return [:defun, name, args, exps]
end
def parse_sexp; @sexp.parse; end
def parse_exp
@s.ws
parse_def || parse_sexp
end
def parse
res = [:do] + zero_or_more(:exp)
@s.ws
raise "Expected EOF" if @s.peek
return res
end
end
| true |
0e5232463959a589f3b33360bcd3bca50148ff7b | Ruby | javibolibic/napakalaki1516 | /Napakalaki_Ruby/pkg/Napakalaki_Ruby-0.0.1/lib/monster.rb | UTF-8 | 1,354 | 2.890625 | 3 | [] | no_license | # encoding: utf-8
=begin
********************************************************************
** _ _ _ _ _ _ **
** | \ | | __ _ _ __ __ _| | ____ _| | __ _| | _(_) **
** | \| |/ _` | '_ \ / _` | |/ / _` | |/ _` | |/ / | **
** | |\ | (_| | |_) | (_| | < (_| | | (_| | <| | **
** |_| \_|\__,_| .__/ \__,_|_|\_\__,_|_|\__,_|_|\_\_| **
** |_| **
** Creado por Javier Bolívar Valverde <javibolivar@correo.ugr.es> **
** Programación y Diseño Orientado a Objetos **
** Grado en Ingeniería Informática (Universidad de Granada) **
********************************************************************
=end
module Napakalaki
class Monster
def initialize(n, l, b, p)
@name = n
@combat_level = l
@bad_consequence = b
@prize = p
end
attr_reader :name, :combat_level, :bad_consequence
#Devuelve el número de niveles ganados proporcionados por su buen rollo.
def get_levels_gained
return @prize.levels
end
#Devuelve el número de tesoros ganados proporcionados por su buen rollo.
def get_treasures_gained
return @prize.treasures
end
def to_s
"Nombre: #{@name} \n Nivel de combate: #{@combat_level}"
end
end
end
| true |
db2c8f504f320f185f37a7c615078c01df3692ef | Ruby | Telixia/leetcode-3 | /Easy/1700-Number of Students Unable to Eat Lunch/Simulation.rb | UTF-8 | 524 | 3.265625 | 3 | [] | no_license | # @param {Integer[]} students
# @param {Integer[]} sandwiches
# @return {Integer}
def count_students(students, sandwiches)
students = Containers::Queue.new(students)
count = [0, 0]
i = 0
students.each do |prefer|
count[prefer] += 1
end
until students.empty?
prefer = students.pop
if prefer == sandwiches[i]
i += 1
count[prefer] -= 1
elsif count[0] == 0 || count[1] == 0
students.push(prefer)
break
else
students.push(prefer)
end
end
students.size
end
| true |
34d8dbd9247a4a9026d7102ad03fe82d66c02cb5 | Ruby | kientn123/programming_problems | /epi/Ruby/list_05.rb | UTF-8 | 758 | 3.34375 | 3 | [] | no_license | =begin
determine if a singly linked list is cyclic
=end
require "libraries"
def is_cyclic(l)
return nil if l.next.nil? or l.next.next.nil?
runner1 = l
runner2 = l
while true
if runner2.next.nil? or runner2.next.next.nil?
return "nil"
else
runner1 = runner1.next
runner2 = runner2.next.next
if runner1 == runner2
break
end
end
end
runner1 = l
while runner1 != runner2
runner1 = runner1.next
runner2 = runner2.next
end
runner1
end
l = Node.new(nil, Node.new(1, Node.new(2, Node.new(3, nil))))
tail = Node.new(8, nil)
start = Node.new(5, Node.new(6, Node.new(7, tail)))
tail.next = start
f = Node.new(nil, Node.new(1, Node.new(2, Node.new(3, Node.new(4, start)))))
puts is_cyclic(l)
| true |
b0067983e5dd2a13bb8fc1687c2ff604b8516d54 | Ruby | kevinmacarthur/math_game | /player.rb | UTF-8 | 231 | 3.4375 | 3 | [] | no_license | class Player
attr_accessor :lives, :name, :points
def initialize(name)
@name = name
@lives = 3
@points = 0
end
def lose_life
@lives -= 1
end
def add_point
@points += 1
end
end | true |
8f741414edebd57c8f88dcba0b84b968f4a22ea3 | Ruby | savardd/material-icons | /gen/generate.rb | UTF-8 | 5,118 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | require "rubygems"
require "active_support/core_ext/hash"
require "active_support/inflector"
require "fileutils"
# Constants
# =========
ROOT = %x`git rev-parse --show-toplevel`.chomp
SOT_DIR = File.join ROOT, "tmp", "sot"
OUT_DIR = File.join ROOT, "tmp", "out"
SKIP_CATS = %w(iconfont sprites)
# Setup
# =====
# Clean up output directory
FileUtils.rm_rf OUT_DIR
FileUtils.mkdir_p OUT_DIR
# Source of truth
if Dir.exist? SOT_DIR
Dir.chdir SOT_DIR
%x`git pull origin master`
Dir.chdir ROOT
else
%x`git clone git@github.com:google/material-design-icons.git #{SOT_DIR}`
end
# Categories
# (ie. absolute paths of the categories)
CATEGORIES = %x`ls -d #{SOT_DIR}/*/`.split("\n")
# Utils
# =====
def append_to_file(path_to_file, content)
File.open(path_to_file, "a") { |f| f << content }
end
def get_icon_name(cat, icon_path)
base = icon_path.scan(/.*\/ic_(.*)_\d*x?\d+px\.svg$/)[0][0]
# lookup table
case "#{cat}/#{base}"
when "Action/3d_rotation"; "three_d_rotation"
when "Action/account_balance_wallet"; "account_balance_with_wallet"
when "Action/settings_applications"; "settings_application"
when "Hardware/keyboard_backspace"; "keyboard_arrow_backspace"
when "Hardware/keyboard_capslock"; "keyboard_arrow_capslock"
when "Hardware/keyboard_hide"; "keyboard_arrow_hide"
when "Hardware/keyboard_return"; "keyboard_arrow_return"
else
if base[0] =~ /\d/
raise "An icon can't have a number as the first character"
else
base
end
end
end
def process_node(tag_name, content)
regex = /<#{tag_name} ([^>]+)>/
# Find nodes
nodes = regex.match(content)&.captures || []
nodes = nodes.map { |p| p.sub(/\s*\/*$/, "") }
nodes = nodes.map { |p| p.split(/" +/).map { |a| a.chomp("\"").split("=\"") }}
nodes = nodes.map { |p| Hash[*p.flatten] }
# Remove nodes from content
content_without_nodes = content.gsub(/<#{tag_name}[^>]*>/, "").gsub(/<\/#{tag_name}>/, "")
# Nodes format:
# > [ [{ "d" => "VALUE", ... }], ...]
return nodes, content_without_nodes
end
def process_attributes(attributes, pick)
attributes
.slice(*pick)
.to_a
.map { |a| ActiveSupport::Inflector.camelize(a[0].underscore, false) + " \"" + a[1] + "\"" }
.join(", ")
end
def elm_node(node_fn_name, attributes, pick)
at = process_attributes(attributes, pick)
"#{node_fn_name} [ #{at} ] []"
end
# File generation
# ===============
CATEGORIES.each do |cat_path|
cat_base = File.basename(cat_path, "/")
cat = cat_base.camelize
cat_out = File.join(OUT_DIR, "#{cat}.elm")
# some aren't really cats
next if SKIP_CATS.include?(cat_base)
# find icons
svg_files_with_duplicates = %x`ls #{cat_path}svg/production/*.svg`.split("\n")
svg_files = svg_files_with_duplicates.reverse.reduce([]) do |acc, svg_path|
scan = svg_path.scan(/_(\d+x)?(\d+)px\.svg$/).first
height = scan[1]
width = scan[0]&.chomp("x") || height
name = get_icon_name(cat, svg_path)
obj = {
name: name,
path: svg_path,
view_box: "0 0 #{width} #{height}"
}
if acc.find_index { |x| x[:name] == name }
then acc
else acc + [obj]
end
end
svg_files.sort_by! { |x| x[:name] }
# {log}
puts "Processing #{cat}"
# {file} Pt. 1
append_to_file cat_out, "module Material.Icons.#{cat} exposing ("
svg_files.each_with_index do |obj,index|
icon_name = obj[:name]
if index > 0
append_to_file cat_out, ", "
end
append_to_file cat_out, "#{icon_name}"
end
append_to_file cat_out, <<~HERE
)
{-|
# Icons
HERE
# {file} Pt. 2
svg_files.each do |obj|
icon_name = obj[:name]
append_to_file cat_out, "@docs #{icon_name}\n"
end
# {file} Pt. 3
append_to_file cat_out, <<~HERE
-}
import Color exposing (Color)
import Svg exposing (Svg)
import Svg.Attributes exposing (cx, cy, d, fillOpacity, r)
import Material.Icons.Internal exposing (icon)
HERE
# {file} Pt. 4
svg_files.each do |obj|
icon_name = obj[:name]
svg_path = obj[:path]
view_box = obj[:view_box]
# {log}
puts "Processing #{cat}/#{icon_name}"
# svg contents
icon = File.read(svg_path).sub(/<svg[^>]*>/, "").sub(/<\/svg>/, "")
# `<path>`
paths, icon = process_node("path", icon)
paths = paths.map do |attributes|
elm_node "Svg.path", attributes, %w(d fill-opacity)
end
# `<circle>`
circles, icon = process_node("circle", icon)
circles = circles.map do |attributes|
elm_node "Svg.circle", attributes, %w(cx cy r)
end
# ignore other nodes
_, icon = process_node("g", icon)
# did we forget anything?
if icon.strip.length > 0
puts icon.inspect
raise "You forgot something."
end
# write to file
append_to_file cat_out, <<~HERE
{-|-}
#{icon_name} : Color -> Int -> Svg msg
#{icon_name} = icon "#{view_box}" [ #{(paths + circles).join(", ")} ]
HERE
end
end
# Move
# ====
%x`mv #{OUT_DIR}/* #{ROOT}/src/Material/Icons`
%x`rm -rf #{OUT_DIR}`
# Run elm-format
# ==============
begin
%x`elm-format #{ROOT}/src --yes`
rescue Errno::ENOENT
end
| true |
c096e576c697f14a7af49a37030fbca33327f46d | Ruby | lbredeso/crashfinder | /lib/tasks/crash.rake | UTF-8 | 3,445 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'mn/crash_converter'
require 'mn/location_generator'
require 'nd/crash_converter'
require 'sd/crash_converter'
require 'set'
require 'csv'
BATCH_SIZE = 1000
namespace :crash do
desc "Load crash data"
task :load, [:state, :start_year, :end_year] => :environment do |t, args|
state = args.state
state_module = self.class.const_get(state.upcase.to_sym)
start_year = args.start_year.to_i
end_year = args.end_year ? args.end_year.to_i : start_year
(start_year..end_year).each do |year|
crash_converter = state_module::CrashConverter.new year
year_file = File.join Rails.root, "lib", "data", state, crash_converter.file_name
puts "Loading crash data from #{year_file}"
crashes = []
File.open(year_file).each_line do |line|
crash = crash_converter.convert(line)
crashes << crash if crash
if crashes.size % BATCH_SIZE == 0
puts "Saving..."
state_module::Crash.collection.insert crashes
crashes = []
end
end
puts "Saving..."
state_module::Crash.collection.insert crashes
end
end
desc "Load crash data from a file"
task :load_file, [:state, :file] => :environment do |t, args|
state = args.state
state_module = self.class.const_get(state.upcase.to_sym)
file = args.file
crash_converter = state_module::CrashConverter.new
crashes = []
File.open("lib/data/#{state}/#{file}").each_line do |line|
crash = crash_converter.convert(line)
crashes << crash if crash
if crashes.size % BATCH_SIZE == 0
puts "Saving..."
state_module::Crash.collection.insert crashes
crashes = []
end
end
puts "Saving..."
state_module::Crash.collection.insert crashes
end
desc "Generate location file"
task :generate_location_file, [:state, :start_year, :end_year] => :environment do |t, args|
state = args.state
start_year = args.start_year.to_i
end_year = args.end_year ? args.end_year.to_i : start_year
location_generator = self.class.const_get(state.upcase.to_sym)::LocationGenerator.new
(start_year..end_year).each do |year|
location_generator.generate year.to_s
end
end
desc "Update locations from given file"
task :update_locations, [:state, :file] => :environment do |t, args|
state = args.state
file = args.file
puts "Updating locations for #{state} from #{file}"
CSV.foreach("lib/data/#{state}/location/#{file}") do |row|
if row[1]
crash = Crash.find row[0]
puts "Update crash location for accn #{crash.id}"
crash.update_attributes lng: row[1].to_f, lat: row[2].to_f
end
end
end
desc "Build crash map reduce collections"
task :map_reduce => :environment do
puts "Creating state_crashes collection..."
StateCrash.build
puts "Creating county_crashes collection..."
CountyCrash.build
puts "Creating city_crashes collection..."
CityCrash.build
end
desc "Build clusters"
task :build_clusters, [:start_year, :end_year, :zoom] => :environment do |t, args|
start_year = args.start_year.to_i
end_year = args.end_year ? args.end_year.to_i : start_year
zoom = args.zoom
(start_year..end_year).each do |year|
if zoom
Cluster.build year.to_s, [zoom.to_i]
else
Cluster.build year.to_s, (5..16)
end
end
end
end | true |
7df01b1ffa9747a568d0b369fdff8b6da7062bfe | Ruby | jfangonilo/tv_network_1909 | /lib/character.rb | UTF-8 | 267 | 3.25 | 3 | [] | no_license | class Character
attr_reader :name, :actor
def initialize(attributes)
@name = attributes[:name] unless nil
@actor = attributes[:actor] unless nil
@salary = attributes[:salary] unless nil
end
def salary
@salary.to_s.delete("_").to_i
end
end
| true |
dc4da674f140ce66c9f50b68f7210bdd94e8adab | Ruby | kid/torrentui | /app/models/downloaded_file.rb | UTF-8 | 734 | 2.578125 | 3 | [] | no_license | require 'unrar'
class DownloadedFile < ActiveRecord::Base
attr_accessible :length, :path
belongs_to :torrent
validates_presence_of :path
def file_name
File.split(path).last
end
def is_archive?
file_name.end_with? '.rar'
end
def absolute_path
File.expand_path File.join(AppSettings.transmission_download_dir, self.path)
end
def extract
unrar = Unrar::new(absolute_path)
unrar.list.each do |f|
if unrar.extract(f[:path], AppSettings.extract_files_destination)
extracted = ExtractedFile::new(f)
raise "File not found." unless File.exist? extracted.absolute_path
torrent.extracted_files << extracted
torrent.save
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.