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
30f722995586b23c59601226561a0acf9cc723e2
Ruby
louman/sales_taxes
/lib/sales_taxes/model/taxable_item.rb
UTF-8
193
2.671875
3
[]
no_license
require_relative 'tax' class TaxableItem attr_reader :item def initialize(item) @item = item @item.taxes << Tax.new(self.class.name, @item.price * rate) if applicable? end end
true
06a296219796897891f85f80ce91a0b98228efe2
Ruby
AndrewLosseff/codewars
/8-kyu/004-string-repeat/index.rb
UTF-8
771
3.875
4
[]
no_license
# Solution def repeat_str (n, s) newString = '' n.times do |i| newString += s end newString end # Solution def repeat_str (n, s) newString = '' for i in 1..n newString += s end newString end # Solution def repeat_str (n, s) s * n end # Solution def repeat_str (n, s) newString = "" n.times{newString += s} newString end # Solution def repeat_str (n, s) n > 1 ? s + repeat_str(n - 1, s) : s end # Solution def repeat_str (n, s) array = [] n.times do |i| array.push(s) end array.join end # Solution def repeat_str (n, s) array = [] n.times do |i| array << s end array.join end # Solution def repeat_str (n, s) Array.new(n+1).join(s) end print(repeat_str(5, 'Hello'))
true
6a0ca06d7d68467c210bd3cb3e4febc08d196521
Ruby
bobgreenshields/start-spideroak
/spec/tmux/session_spec.rb
UTF-8
1,228
2.796875
3
[]
no_license
require "tmux/session" describe Tmux::Session do describe "#initialize" do subject(:session) { Tmux::Session.new(session_string) } context "with a good session string" do let(:session_string) { "spideroak: 1 windows" } it "returns a Session object" do expect(session).to be_an_instance_of Tmux::Session end end context "with an invalid session string" do let(:session_string) { "blah blah blah" } it "raises an error" do expect{ session }.to raise_error(ArgumentError, "badly formatted session string: blah blah blah" ) end end end describe "#name" do let(:session_string) { "spideroak: 1 windows" } subject(:session) { Tmux::Session.new(session_string) } it "takes the name from the session string" do expect(session.name).to eq "spideroak" end end describe "#name?" do subject(:session) { Tmux::Session.new("spideroak: 1 windows") } context "when the value is the name from the session string" do it "returns true" do expect(session.name?("spideroak")).to be_truthy end end context "when the value is not the name from the session string" do it "returns false" do expect(session.name?("blah")).to be_falsey end end end end
true
3548bba3322eee0e82965f4a006708cbc3d73d43
Ruby
jwharrow/backpack
/dumb_picker.rb
UTF-8
764
3.234375
3
[]
no_license
require_relative 'backpack' class DumbPicker def self.run(items, capacity) self.new.run(items, capacity) end def run(items, capacity) backpacks = all_backpacks(items) backpacks.reject{ |backpack| backpack.cost > capacity } .sort(&:value) .first end def all_backpacks(items) ## gathering combinations backpacks = [] items.each_with_index do |item, index| backpacks << [item] if index < items.length - 1 sub_backpacks = all_backpacks(items.slice((index + 1)..items.length)) sub_backpacks.each do |sub_backpack| # backpacks << sub_backpack backpacks << [item] + sub_backpack end end end backpacks end end ## simplex tableau
true
7942b54e8f7213a3df808a610d9e3417ac5094ec
Ruby
moh-alsheikh/rubypractice
/rubyp2.rb
UTF-8
65
2.9375
3
[]
no_license
vage = gets.chomp unless vage.to_i == 50 print "ok \n" end
true
4cd9ed789a0439ecb7bd9f6e4058d4debb91d9ae
Ruby
johnfelipe/mapa76
/aphrodite/app/services/link_service.rb
UTF-8
708
2.8125
3
[]
no_license
require 'tempfile' require 'open-uri' class LinkService attr_reader :file_url, :user def initialize(file_url, user=nil) @file_url = file_url @user = user end def call begin Tempfile.open(filename, encoding: 'ascii-8bit') do |file| open(file_url, 'rb') do |read_file| file.write(read_file.read) file.rewind document = Document.new document.original_filename = filename document.file = file.path document.save user.documents << document if user end end true rescue Errno::ENOENT => e false end end def filename @filename ||= file_url.split('/')[-1] end end
true
d536fdaa3550bf0c7968f623275bb67e82c56a0c
Ruby
karlwitek/launch_school_rb101
/lesson1/small_problems/Easy_4/convert_to_signed.rb
UTF-8
1,850
4.4375
4
[]
no_license
# Add to this method so the return value is a positive # or negative number, depending on the string passed in, # (if there is a '+' or '-' sign before the number) HASH = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 } def string_to_integer2(string) sign = '' digits = [] array = string.split('') if array[0] == '-' || array[0] == '+' sign = array.shift end index = 0 while index < array.length digits << HASH[array[index]] index += 1 end value = 0 digits.each { |digit| value = 10 * value + digit } if sign "#{sign}#{value}" else value end end puts string_to_integer2('-543') # -543 puts string_to_integer2('+500') # +500 puts string_to_integer2('4') # 4 # this method doesn't work in the LS solution when called # within method with the case statement # because of [1..-1] part. In my method, the first # character is removed(.shift) if it is a + or _. # works. LS --> def string_to_integer3(string) digits = string.chars.map { |char| HASH[char] } value = 0 digits.each { |digit| value = 10 * value + digit } value end def string_to_signed_integer(string) case string[0] when '-' then -string_to_integer3(string[1..-1]) when '+' then string_to_integer3(string[1..-1]) else string_to_integer3(string) end end puts string_to_signed_integer('-4444') # works. Further Exploration # Refactor method so string[1..-1] and string_to_integer2 # is only called once each. def string_to_signed_integer2(string) if string[0] == '-' || string[0] == '+' oper = string.slice!(0) end new_string = string_to_integer3(string) if oper "#{oper}#{new_string}" else new_string end end puts string_to_signed_integer2('-34') puts string_to_signed_integer2('+100') puts string_to_signed_integer2('2')
true
5e7e6b3a106a0d24fe9410d7006aa39453edd868
Ruby
Thatguy560/Banktechtest
/lib/bankstatement.rb
UTF-8
578
3.234375
3
[]
no_license
class Bankstatement def print(transaction_history) @transaction_history = transaction_history puts "date || credit || debit || balance\n" print_transactions end def convert_to_2dp(number) number == 0 ? "" : "%.2f" % number end def print_transactions transaction_array = @transaction_history.map do |transaction| "#{transaction.date} || #{convert_to_2dp(transaction.credit)} || "\ "#{convert_to_2dp(transaction.debit)} || #{convert_to_2dp(transaction.current_balance)}\n" end puts transaction_array.reverse.join("") end end
true
c249a6e9a26389c267a5cf382faca41a2520f51a
Ruby
octonion/hockey
/uscho/scrapers/uscho_games.rb
UTF-8
2,179
2.640625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'csv' require 'mechanize' agent = Mechanize.new{ |agent| agent.history.max_size=0 } agent.user_agent = 'Mozilla/5.0' d1_base = 'https://www.uscho.com/scoreboard/division-i-men' d3_base = 'https://www.uscho.com/scoreboard/division-iii-men' first_year = ARGV[0].to_i last_year = ARGV[1].to_i #//*[@id="teamsked"]/tbody/tr[498] #path = '//tr[@role="row"]' #'//section[@id="scoreboard"]/table/tr' path = '//*[@id="teamsked"]/tbody/tr' (first_year..last_year).each do |year| print "Pulling #{year}\n" games = CSV.open("csv/uscho_games_#{year}.csv","w") url = "#{d1_base}/#{year-1}-#{year}/composite-schedule/" begin page = agent.get(url) rescue print " -> #{year} not found\n" next end page.parser.xpath(path).each do |tr| #print(tr) row = [year] tr.xpath('td').each_with_index do |td,i| if ([4,7].include?(i)) a = td.xpath("a").first if (a==nil) if (td.text.size==0) row += [nil,nil,nil] else row += [td.text.strip,nil,nil] end else href = a.attribute("href").text team_id = href.split('/')[2] row += [td.text.strip,team_id,href] end end if (td.text.size==0) row += [nil] else row += [td.text.strip] end end games << row end games.flush url = "#{d3_base}/#{year-1}-#{year}/composite-schedule/" begin page = agent.get(url) rescue # print " -> #{year} not found\n" next end page.parser.xpath(path).each do |tr| row = [year] tr.xpath('td').each_with_index do |td,i| if ([4,7].include?(i)) a = td.xpath("a").first if (a==nil) if (td.text.size==0) row += [nil,nil,nil] else row += [td.text.strip,nil,nil] end else href = a.attribute("href").text team_id = href.split('/')[2] row += [td.text.strip,team_id,href] end end if (td.text.size==0) row += [nil] else row += [td.text.strip] end end games << row end games.close end
true
d8e8c5f8f88b1de5db19e58466cf138d21a0016e
Ruby
katylee228/phase-0-tracks
/ruby/secret_agents.rb
UTF-8
600
3.515625
4
[]
no_license
def encrypt(str) i=0 while i<str.length if str[i]=="z" print str[i]="a" i+=1 end print str[i].next i+=1 end end def decrypt(str) i=0 while i<str.length if str[i]=="a" print str[i]="z" i+=1 end print (str[i].ord-1).chr i+=1 end end puts "would you like to decrypt or encrypt your password?" input=gets.chomp puts "Enter your password" password=gets.chomp if input=="decrypt" decrypt(password) elsif input=="encrypt" encrypt(password) end #release 4 did not work for us. We were getting an error about defining a method for length.
true
090f8153bbf6ebed2545c56bf984142e9df4b34e
Ruby
shawn42/chessbox
/src/actors/bishop.rb
UTF-8
271
2.796875
3
[]
no_license
class Bishop < ChessPiece def move_valid?(to_file, to_row, ignore_check_rules = false) if valid_diagonal_move? to_file, to_row if ignore_check_rules return true else return !move_puts_self_in_check?(to_file, to_row) end end return false end end
true
2be9357329ab2302988674e01079c38c288b40d6
Ruby
poolug/rubi-1
/escape.rb
UTF-8
84
2.734375
3
[]
no_license
g = ARGV[0].to_i r = ARGV[1].to_i velocidad = Math.sqrt(2*g*r) puts velocidad
true
bb3e1df26f12080f55d279e971fdccbe8a24af88
Ruby
jaym/braindump
/lib/braindump/status.rb
UTF-8
2,443
3.03125
3
[]
no_license
module Braindump module Status class Queued attr_reader :status_info def initialize(status_info) @status_info = status_info end def to_s 'queued' end end class Running attr_reader :status_info def initialize(status_info="") @status_info = status_info end def to_s 'running' end end class Finished attr_reader :status_info def initialize(status_info="") @status_info = status_info end end class Succeeded < Finished attr_reader :status_info def initialize(status_info="") @status_info = status_info end def to_s 'succeeded' end end class Failed < Finished attr_reader :status_info def initialize(status_info="") @status_info = status_info end def to_s 'failed' end end class Unknown attr_reader :status_type attr_reader :status_info def initialize(status_type, status_info="") @status_type = status_type @status_info = status_info end def to_s 'unknown' end end def self.from_file(status_file) if File.exists?(status_file) data = File.read(status_file) status_type, status_info = data.split(' ', 2) case status_type when 'queued' Status::Queued.new(status_info) when 'succeeded' Status::Succeeded.new(status_info) when 'failed' Status::Failed.new(status_info) when 'running' Status::Running.new(status_info) else Status::Unknown.new(status_type, status_info) end else Status::Unknown.new(status_type, status_info) end end def self.to_file(status, status_file) data = case status when Status::Queued "queued #{status.status_info}" when Status::Succeeded "succeeded #{status.status_info}" when Status::Failed "failed #{status.status_info}" when Status::Running "running #{status.status_info}" when Status::Unknown raise "Cannot write an unknown status" end File.open(status_file, File::RDWR | File::CREAT) do |f| if !f.flock(File::LOCK_EX | File::LOCK_NB) raise "Concurrent Writers" end f.write(data) end end end end
true
51f93b5a1c16ca15e47811ec36c37b9baa9f007f
Ruby
yulu9206/ruby_fundamentals
/mammal.rb
UTF-8
144
3.28125
3
[]
no_license
class Mammal def initialize @health = 150 end def display_health puts @health end end # mammal1 = Mammal.new # mammal1.display_health
true
796a84e9caf586754636ca843be1bf66e52601e9
Ruby
rah00l/distance-calculator
/app/helpers/distances_helper.rb
UTF-8
292
2.515625
3
[]
no_license
module DistancesHelper def formatted_distance(dist) if dist['distance'].present? dist['distance'] elsif dist['error_code'].present? "You got error code of '#{dist['error_code']}' because of '#{dist['error_msg']}'" else "Somthing went wrong" end end end
true
51be0a1d871edde1f65bb2cf7d7ecc25973de084
Ruby
bashwork/project-euler
/029/029.rb
UTF-8
113
2.953125
3
[]
no_license
#!/usr/bin/env ruby require 'set' set = Set.new 2.upto(100) {|a| 2.upto(100) {|b| set.add(a**b) }} puts set.size
true
5ad5b8df1f2d1e32e8acab2ba39af25c0fa75afa
Ruby
mmarcolina/Ruby-Exercises
/Fundamentals/Hashes/bob.rb
UTF-8
377
4.3125
4
[]
no_license
# Given the following expression, how would you access the name of the person? person = {name: 'Bob', occupation: 'web developer', hobbies: 'painting'} p person.fetch(:name) # the fetch method returns a value for a specified key. In this case, the key we want to refer to is :name to obtain the value of Bob. # alternatively, we can use the simpler form of: p person[:name]
true
7a673818d523082180b295f2cbb0a7ffdbe45652
Ruby
JustinLove/gsl
/lib/gsl/historian.rb
UTF-8
822
2.875
3
[]
no_license
module GSL class Historian class Event def initialize(_historian, starting = {}) @historian = _historian @data = starting super() end def to_s "Event: " + @data.to_s end def record(what) case (what) when Resource; record_resource(what); else; raise "Can't record #{what.class}" end end def record_resource(what) @data[what.name] = what.value end def [](k) return @data[k] end end def initialize @events = [] super end def to_s "History:" end def event(starting = {}) x = Event.new(self, starting) @events << x x end def events @events.size end end end
true
78ec2525c60ee4ddbc7d019a07b326289ef1f354
Ruby
techno-tanoC/rubi_live
/lib/rubi_live/idol.rb
UTF-8
1,157
2.5625
3
[ "MIT" ]
permissive
module RubiLive class Idol < Hash include Hashie::Extensions::MethodAccess def ==(other) other.is_a?(self.class) && self.name == other.name end def birthday?(date = Date.today) month, day = birthday.split("/") birthday_date = Date.new(date.year, month.to_i, day.to_i) birthday_date == date end def units self[:units].map do |unit| RubiLive::Unit.find(unit) end end class << self ConfigPath = config_file = "#{File.dirname(__FILE__)}/../../config/idols.yml" private_constant :ConfigPath def config @config ||= YAML.load_file(ConfigPath).deep_symbolize_keys end def find(name) idol_name = name.to_sym raise UnknownIdolError.new("unknown idol: #{name}") unless valid?(idol_name) @cache ||= {} unless @cache[idol_name] idol_config = config[idol_name] @cache[idol_name] = RubiLive::Idol[idol_config] end @cache[idol_name] end def names config.keys end def valid?(idol_name) names.include?(idol_name) end end end end
true
b704ddc1fd4c0fcfa6de5327d3fd67883f3fbe23
Ruby
catman/ipreader
/test/test_database_utils2.rb
UTF-8
3,101
2.765625
3
[ "MIT" ]
permissive
require_relative "test_helper" require_relative "../ipreader/database_utils" require "sqlite3" class TestDatabaseUtils < Test::Unit::TestCase SMS_TABLE_CREATE = "CREATE TABLE message (rowid INTEGER, date TEXT, address TEXT, text TEXT, flags INTEGER)" class IpDbUtils include Ipreader::Database::Utils end def setup @db_name = File.join(File.dirname(__FILE__), "tmp/dummy.sqlite3") file_teardown(@db_name) if File.exists?(@db_name) @ipdbutils = IpDbUtils.new @db = SQLite3::Database.new @db_name end def teardown @db.close unless @db.closed? GC.start file_teardown(@db_name) end def file_teardown(file_name) File.delete(file_name) if File.exists?(file_name) end must "recognise an sms backup" do @db.execute SMS_TABLE_CREATE assert @ipdbutils.sms_db?(@db_name) end must "recognise when database is not an sms backup" do @db.execute "CREATE TABLE smerf (name VARCHAR(30))" refute @ipdbutils.sms_db?(@db_name) end must "fail gracefully if passed a file name that is not a SQLite3 database" do dummy_file = File.join(test_root, "tmp/empty.sqlite3") File.open(dummy_file, "w") { |df| df.puts " " } # "w" truncates existing db contents refute @ipdbutils.sms_db?(dummy_file) end must "fail gracefully if passed a nil reference" do refute @ipdbutils.sms_db?(nil) end def setup_testdb @db.execute SMS_TABLE_CREATE @test_sms = [] (1..4).each do |test_item| insert_sms = "INSERT INTO message (rowid, date, address, text, flags) VALUES( '#{test_item}', '2011-01-31 12:00:00', '+4479867#{test_item}#{test_item}#{test_item}#{test_item}', 'sms text #{test_item}', '2' );" @db.execute(insert_sms) @test_sms << { :rowid => test_item, :on_date => "2011/01/31", :at_time => "12:00:00", :address => "+4479867#{test_item}#{test_item}#{test_item}#{test_item}", :direction => 'to', :text => "sms text #{test_item}" } end end must "return all rows when no filter is applied" do setup_testdb test_result = @ipdbutils.read_sms_table(@db_name) assert_equal test_result, @test_sms assert_equal @test_sms.length, test_result.length end must "correctly use the options hash to filter sms data" do setup_testdb result = [] result << @test_sms.first options = { :address => "+44798671111" } test_result = @ipdbutils.read_sms_table(@db_name, options) assert_equal test_result, result assert_equal test_result.length, 1 end must "ignore case when filtering sms data" do setup_testdb options = { :text => "sms text 1" } assert_equal @ipdbutils.read_sms_table(@db_name, options).length, 1 options = { :text => "SMS TEXT 1" } assert_equal @ipdbutils.read_sms_table(@db_name, options).length, 1 end must "ignore surplus options without erroring" do setup_testdb options = { :telephone => "011232131232" } assert_raises(ArgumentError) { @ipdbutils.read_sms_table(@db_name, options) } end end
true
f2f1cbf2dcfe7f506f8c5672cbbf775a97aadd84
Ruby
angelicawink/Rails-Practice-Code-Challenge-Travelatr-dc-web-082718
/app/models/blogger.rb
UTF-8
413
2.640625
3
[]
no_license
class Blogger < ApplicationRecord has_many :posts has_many :destinations, through: :posts validates :name, uniqueness: true validates :age, numericality: {greater_than: 0} validates :bio, length: {minimum: 30} def total_likes total = 0 self.posts.each do |post| total += post.likes end total end def most_liked_post self.posts.order("likes desc").limit(1) end end
true
77120548d202c709ff559daf480212374fee1fd3
Ruby
marcinbunsch/isaac
/test/test_commands.rb
UTF-8
1,824
2.5625
3
[ "MIT" ]
permissive
require 'helper' class TestCommands < Test::Unit::TestCase test "raw messages can be send" do bot = mock_bot {} bot_is_connected bot.raw "PRIVMSG foo :bar baz" assert_equal "PRIVMSG foo :bar baz\r\n", @server.gets end test "messages are sent to recipient" do bot = mock_bot {} bot_is_connected bot.msg "foo", "bar baz" assert_equal "PRIVMSG foo :bar baz\r\n", @server.gets end test "actions are sent to recipient" do bot = mock_bot {} bot_is_connected bot.action "foo", "bar" assert_equal "PRIVMSG foo :\001ACTION bar\001\r\n", @server.gets end test "channels are joined" do bot = mock_bot {} bot_is_connected bot.join "#foo", "#bar" assert_equal "JOIN #foo\r\n", @server.gets assert_equal "JOIN #bar\r\n", @server.gets end test "channels are parted" do bot = mock_bot {} bot_is_connected bot.part "#foo", "#bar" assert_equal "PART #foo\r\n", @server.gets assert_equal "PART #bar\r\n", @server.gets end test "topic is set" do bot = mock_bot {} bot_is_connected bot.topic "#foo", "bar baz" assert_equal "TOPIC #foo :bar baz\r\n", @server.gets end test "modes can be set" do bot = mock_bot {} bot_is_connected bot.mode "#foo", "+o" assert_equal "MODE #foo +o\r\n", @server.gets end test "can kick users" do bot = mock_bot {} bot_is_connected bot.kick "foo", "bar", "bein' a baz" assert_equal "KICK foo bar :bein' a baz\r\n", @server.gets end test "quits" do bot = mock_bot {} bot_is_connected bot.quit assert_equal "QUIT\r\n", @server.gets end test "quits with message" do bot = mock_bot {} bot_is_connected bot.quit "I'm outta here!" assert_equal "QUIT :I'm outta here!\r\n", @server.gets end end
true
5cbe9a19dcfc1a57e9abacd6fc6849ae74d130d7
Ruby
andrerferrer/tibia-travel-planner
/test_codes/graph.rb
UTF-8
635
3.359375
3
[]
no_license
# I took this solution from this tutorial # https://www.rubyguides.com/2017/05/graph-theory-in-ruby/ require 'rgl/adjacency' require 'rgl/dijkstra' graph = RGL::DirectedAdjacencyGraph.new graph.add_vertices "Los Angeles", "New York", "Chicago", "Houston", "Seattle" edge_weights = { ["New York", "Los Angeles"] => 2445, ["Los Angeles", "Chicago"] => 2015, ["Los Angeles", "Houston"] => 1547, ["Chicago", "Houston"] => 939, ["Seattle", "Los Angeles"] => 1548 } edge_weights.each { |(city1, city2), w| graph.add_edge(city1, city2) } p graph.dijkstra_shortest_path(edge_weights, "New York", "Houston")
true
eebdecad116e1940157c1e518d2f3fd293bf45ae
Ruby
ahead123/ruby_Stuff
/join.rb
UTF-8
95
2.828125
3
[]
no_license
hip_hop = ["cool c", "cool b", "cool a", "cool j"] puts hip_hop puts puts hip_hop.join(', ')
true
6433b204fd521e97fe900e9d04d6a4b7e6c92342
Ruby
ess/absolution
/spec/absolution_spec.rb
UTF-8
2,281
2.890625
3
[ "MIT" ]
permissive
require 'spec_helper' require 'absolution' class Dummy include Absolution end describe Absolution do let(:klass) {Absolution} context 'when included' do let(:dummy) {Dummy.new} it 'knows about absolute URLs' do klass.instance_methods.each do |method| expect(dummy).to respond_to(method) end end end describe '.absolute_url?' do it 'is true when given a HTTP URI' do expect(klass.absolute_url?('http://fake.url')).to be_true end it 'is true when given a HTTPS URI' do expect(klass.absolute_url?('https://fake.url')).to be_true end it 'is false when given a schemeless path' do expect(klass.absolute_url?('/asset.file')).to be_false end end describe '.construct_absolute_url' do let(:base_url) {'http://fake.url'} it 'combines a base url with a path' do expect(klass.construct_absolute_url('http://fake.url', '/asset.file')). to eql('http://fake.url/asset.file') end it 'handles a base url with an existing path component' do extended_base_url = 'http://fake.url/base/path' asset_path = 'asset.file' expect(klass.construct_absolute_url(extended_base_url, asset_path)). to eql(extended_base_url + '/' + asset_path) end it 'separates the base url from the asset with at least 1 /' do asset_path = 'asset.file' expected_url = base_url + '/' + asset_path expect(klass.construct_absolute_url(base_url, asset_path)). to eql(expected_url) end it 'removes an extra / when both the base url and the asset path have it' do asset_path = '/asset.file' expected_url = base_url.chomp('/') + asset_path expect(klass.construct_absolute_url(base_url + '/', asset_path)). to eql(expected_url) end it 'handles query strings appropriately' do asset_path = '/asset.file?key=val' expected_url = base_url + asset_path expect(klass.construct_absolute_url(base_url, asset_path)). to eql(expected_url) end it 'handles fragments appropriately' do asset_path = '#fortytwo' expected_url = base_url + '/' + asset_path expect(klass.construct_absolute_url(base_url, asset_path)). to eql(expected_url) end end end
true
27745829351a248a613e767d46bcbadcb9197d13
Ruby
Haanyaj/music_in_the_way
/level5/main.rb
UTF-8
4,878
3.390625
3
[]
no_license
require 'json' require'date' class Rentals attr_accessor :id , :car_id, :start_date, :end_date, :distance def initialize(id, car_id, start_date, end_date, distance) @id = id @car_id = car_id @start_date = start_date @end_date = end_date @distance = distance end end class Cars attr_accessor :id, :price_per_day, :price_per_km def initialize(id, price_per_day, price_per_km) @id = id @price_per_day = price_per_day @price_per_km = price_per_km end end class Options attr_accessor :id, :rental_id, :type def initialize(id, rental_id, type) @id = id @rental_id = rental_id @type = type end end def calculate_date(start_date, end_date) result = (Date.parse(start_date)...Date.parse(end_date)).count + 1 return result end def calculate_price_km(price_km, distance) result = price_km * distance return result end def calculate_price_day(day, price) days_left = day result = 0 while (days_left > 0) if (days_left == 1) result = result + price end if (days_left > 1 && days_left <= 4) new_price = (price - (price * 10 / 100)) result = result + new_price end if (days_left > 4 && days_left <= 10) new_price = (price - (price * 30 / 100)) result = result + new_price end if (days_left > 10) new_price = (price - (price * 50 / 100)) result = result + new_price end days_left = days_left - 1 end return result end def file_parsing() file = File.read('data/input.json') data = JSON.parse(file) return data end def total_price(a, b) val = a + b return (val) end def commission(price, days, total_opt, add_ins) com = price * 30 / 100 insurance = com / 2 assistance = days * 100 drivy = com - insurance - assistance owner_real_amount = price - com json = { "who" => "driver", "type" => "debit", "amount" => price + total_opt + add_ins, }, { "who" => "owner", "type" => "credit", "amount" => owner_real_amount + total_opt }, { "who" => "insurance", "type" => "credit", "amount" => insurance }, { "who" => "assistance", "type" => "credit", "amount" => assistance }, { "who" => "drivy", "type" => "credit", "amount" => drivy + add_ins } return json end def get_options(option, rent_id) res = Array[] for i in (0...option.length) if (option[i].rental_id == rent_id) res.push(option[i].type) end end return res end def calculate_options(opt, option, days) total = 0 for i in (0...opt.length) if (opt[i] == "gps") total = total + 5 * days end if (opt[i] == "baby_seat") total = total + 2 * days end end return total * 100 end def calculate_insurance(opt, option, days) total = 0 for i in (0...opt.length) if (opt[i] == "additional_insurance") total = total + 10 * days end end return total * 100 end def do_all(cars, rentals, option) json = {"rentals" => []} for i in (0...rentals.length) for j in (0...cars.length) if (cars[j].id == rentals[i].car_id) days = calculate_date(rentals[i].start_date,rentals[i].end_date) price_km = calculate_price_km(cars[j].price_per_km,rentals[i].distance) price_day = calculate_price_day(days, cars[j].price_per_day) price = total_price(price_day,price_km) opt = get_options(option,rentals[i].id) total_opt = calculate_options(opt, option, days) add_ins = calculate_insurance(opt, option, days) com = commission(price, calculate_date(rentals[i].start_date,rentals[i].end_date), total_opt, add_ins) hash = { "id" => rentals[i].id, "options" => opt, "actions" => com } json["rentals"].push(hash) end end end return json end #parsing json input data = file_parsing() #do all object needed cars = data['cars'].inject([]) { |o,d,| o << Cars.new( d['id'], d['price_per_day'], d['price_per_km']) } rentals = data['rentals'].inject([]) { |o,d,| o << Rentals.new( d['id'],d['car_id'], d['start_date'], d['end_date'],d['distance']) } option = data['options'].inject([]) { |o,d,| o << Options.new( d['id'], d['rental_id'], d['type']) } #get final json res = do_all(cars, rentals, option) File.open("data/output.json", "w") do |f| f.write(JSON.pretty_generate(res)) end
true
d1d48992ee2892d33cdff066385d66a939ce1dea
Ruby
kmkr/moviemanage
/app/common/seconds_to_time_parser.rb
UTF-8
577
3.078125
3
[]
no_license
class SecondsToTimeParser def initialize(include_ms) @include_ms = include_ms end def parse (seconds) ss, ms = (1000*seconds).divmod(1000) mm, ss = ss.divmod(60) #=> [4515, 21] hh, mm = mm.divmod(60) #=> [75, 15] dd, hh = hh.divmod(24) #=> [3, 3] ms = ms.to_i hh = hh >= 10 ? hh : "0" + hh.to_s mm = mm >= 10 ? mm : "0" + mm.to_s ss = ss >= 10 ? ss : "0" + ss.to_s ms = ms >= 100 ? ms : (ms >= 10 ? "0" + ms.to_s : "00" + ms.to_s) out = "#{hh}:#{mm}:#{ss}" if @include_ms out = out + ".#{ms}" end out end end
true
0ba3e7733d1c9d1ba2fda6a7bc4220eb483e80f0
Ruby
beaucouplus/hospitalshifts
/level4/shift.rb
UTF-8
623
2.953125
3
[]
no_license
class Shift attr_reader :id, :planning_id, :worker_id attr_accessor :start_date def initialize(id,planning_id,worker_id,start_date) message = "Wrong type, parameter classes should be Int, Int, Int, Date" raise ArgumentError.new(message) unless id.is_a?(Integer) && planning_id.is_a?(Integer) && worker_id.is_a?(Integer) @id = id @planning_id = planning_id @worker_id = worker_id begin @start_date = Time.parse(start_date) rescue => e raise ArgumentError.new("Incorrect date format") end; end def week_end? @start_date.saturday? || @start_date.sunday? end end
true
da072cca1d661b494a6820238e0773376e97fe8a
Ruby
leandro-ikehara/nivelamento-aluno
/exercicios/08-exercicio-parte1.rb
UTF-8
556
4.3125
4
[]
no_license
# EXERCICIO 08 - parte 1 =begin 1) Faça um programa para calcular a boa e velha tabuada. Pergunte ao usuário qual o número que ele quer o cálculo da taboada e imprima na tela os resultados. Por exemplo: Se o usuário digitar 7, deve imprimir dessa forma: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 ... até 7 x 10 = 70 =end puts "Vamos calcular a tabuada" print "Digite o número que você quer exibir: " recebe_numero = gets.chomp.to_i for tabuada in (1..10) puts recebe_numero.to_s + " x " + tabuada.to_s + " = " + (recebe_numero * tabuada).to_s end
true
eebba3d2fdd21b9ffa1b76d05445b02531391125
Ruby
noma4i/telegrammer
/lib/telegrammer/data_types/inline_query_result/inline_query_result_cached_sticker.rb
UTF-8
992
2.578125
3
[ "MIT" ]
permissive
module Telegrammer module DataTypes # Telegram InlineQueryResultCachedSticker data type # # @attr [String] type Type of the result, must be sticker # @attr [String] id Unique identifier for this result, 1-64 Bytes # @attr [String] sticker_file_id A valid file identifier of the sticker # @attr [Telegrammer::DataTypes::InlineKeyboardMarkup] reply_markup Optional. An Inline keyboard attached to the message # @attr [Telegrammer::DataTypes::InputMessageContent] input_message_content Optional. Content of the message to be sent instead of the sticker # # See more at https://core.telegram.org/bots/api#inlinequeryresultcacheddocument class InlineQueryResultCachedSticker < Telegrammer::DataTypes::Base attribute :type, String, default: 'sticker' attribute :id, String attribute :sticker_file_id, String attribute :reply_markup, InlineKeyboardMarkup attribute :input_message_content, InputMessageContent end end end
true
f6c4c1f866dadf9a80f9c32ff016daaf3a09f42a
Ruby
hoesler/link_dupes
/link_dupes
UTF-8
2,394
2.96875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'pathname' require 'tempfile' require 'optparse' require 'logger' module Logging def initialize(logging_level) @logger = Logger.new(STDOUT) @logger.level = logging_level end # This is the magical bit that gets mixed into your classes def logger @logger end end class Dupes include Logging def process_fdupes_list(io) dupes = Array.new io.each_line do |line| if line.strip.empty? handle_dupes(dupes) dupes.clear else dupes << Pathname.new(line.strip) end end end private def handle_dupes(dupes) if (dupes.size > 1) link_all(dupes.first, dupes.drop(1)) end end def link_all(destination, files) logger.info("Linking #{files.size} files to #{destination}: #{files.map { |e| e.to_s }}") if !destination.file? logger.warn 'Expected #{destination} to be a file' return end files.each do |f| if !f.file? logger.warn 'Expected #{f} to be a file' next end tmp = f.dirname + ".dup_#{f.basename.to_s}" if tmp.exist? logger.warn "Cannot rename #{f} to temp file #{tmp}. Destination exists." next end begin f.rename(tmp) rescue Exception => e logger.warn "Skipping #{f}, because renaming to #{tmp} failed: #{e}" next end begin logger.debug "Linking: #{f} -> #{destination}" f.make_link(destination) rescue Exception => e logger.fatal "Failed to create link. Renaming #{tmp} to #{f}: #{e}" tmp.rename(f) or logger.warn "Renaming #{tmp} to #{f} failed" else if tmp.exist? tmp.unlink or logger.warn "Failed to delete #{tmp}" end end end end end options = {} dupes_source = nil OptionParser.new do |opts| options[:debug] = false opts.on("-d", "--[no-]debug", "Run with debug messages") do |v| options[:debug] = v end # parse options begin opts.parse! rescue OptionParser::ParseError => error puts "Error: " << error.message puts opts exit 1 end # parse config if ARGV.empty? dupes_source = STDIN else dupes_source = Pathname.new(ARGV.join) end end logging_level = if options[:debug] Logger::DEBUG else Logger::INFO end Dupes.new(logging_level).process_fdupes_list(dupes_source)
true
694e64d8da59a94a25695605ae1f522a821a9356
Ruby
bterkuile/couch_blog
/spec/support/end_with_matcher.rb
UTF-8
877
3.3125
3
[ "MIT" ]
permissive
module EndWithMatcher class EndWith def initialize(expected) @expected = expected end def matches?(target) @target = target @target =~ /#{@expected}$/ end def failure_message "expected <#{to_string(@target)}> to " + "end with <#{to_string(@expected)}>" end def negative_failure_message "expected <#{to_string(@target)}> not to " + "end with <#{to_string(@expected)}>" end # Returns string representation of an object. def to_string(value) # indicate a nil if value.nil? 'nil' end # join arrays if value.class == Array return value.join(", ") end # otherwise return to_s() instead of inspect() return value.to_s end end # Actual matcher that is exposed. def end_with(expected) EndWith.new(expected) end end
true
1574976613070c8a5f7f991212f9b62d22ebd9c9
Ruby
etdev/algorithms
/0_code_wars/enumerable_magic_true_fo.rb
UTF-8
203
3.09375
3
[ "MIT" ]
permissive
# http://www.codewars.com/kata/54598e89cbae2ac001001135 # --- iteration 1 --- def any?(list, &block) list.any?(&block) end # --- iteration 2 --- def any?(list, &block) list.send(:any?, &block) end
true
a9b749af642def8eeaf75afd2d2731b9f13583fd
Ruby
TrevorSeitz/prime-ruby-v-000
/prime.rb
UTF-8
156
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(integer) return false if integer <= 1 for n in 2..(integer - 1) if (integer % n) == 0 return false end end return true end
true
123bc5a0af50abc1c4020e19de10f7721b663e6f
Ruby
guy-murphy/jAcumen
/Acumen.CMS2/vendor/plugins/acumen/lib/wiki_behaviour.rb
UTF-8
4,286
2.6875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby #-- # # Author: Guy J. Murphy # Date: 20/01/2010 # Version: 0.1 #++ # # = WikiBehaviour - A behaviour for resolving wiki text. # require 'naiad' import 'acumen.map.model.IOccurence' import 'acumen.resource.store.MySqlFileStore' import 'acumen.resource.model.ResourceException' import 'acumen.util.StringUtil' module Behaviour class WikiBehaviour include Naiad attr_accessor :store def initialize(file_store=nil) @store = file_store end def create(occurence, opts={}) puts occurence.to_xml @store.start unless @store.resource_exists(occurence.reference) wiki_text = occurence.get_content || 'no data' @store.create_resource(occurence.get_reference, opts[:user_id], 'wiki', wiki_text) end ensure @store.stop end # We get the raw underlying textual representation # of the data being pointed to by the occurence. # # NOTE: This is not doable for all forms of occurence data. # This is mainly of use for Wikis and other types of DSL # that have a textual representation used for editting. def get_raw(occurence, version=nil) @store.start resource = nil if version.nil? resource = @store.get_most_recent_instance(occurence.get_reference) else resource = @store.get_resource_instance(occurence.get_reference, version) end resource == nil ? '*unable to find wiki for topic*' : resource.string_data ensure @store.stop end def get_version_info(occurence) @store.start ensure @store.stop end # We get the raw data being pointed to by # the occurence and then process it into # an 'end form' XML view and then place # it in the occurences content. def resolve!(occurence, version=nil) wiki_text = self.get_raw(occurence, version) unless wiki_text == nil parser = services[:wiki_parser] begin parser.text = wiki_text occurence.set_content '<content>'+ parser.parse + '</content>' end end end # We get a raw representation of the data being # pointed to by the occurence but we don't # process it into an XML view, we just set the occurences # content to the raw data for. We do however wrap the content # as CDATA so that any characters that are a problem in valid XML # don't blow up. # # NOTE: This is not doable for all forms of occurence data. # This is mainly of use for Wikis and other types of DSL # that have a textual representation used for editting. def resolve_raw!(occurence, version=nil) unparsed_text = self.get_raw(occurence,version) occurence.set_content("<![CDATA[#{unparsed_text}]]>") end def update_occurence!(occurence, wikitext, opts={}) begin @store.start begin resource = @store.open_resource_for_update(occurence.get_reference, 'some user id') if resource != nil puts "#> updating resource with (#{wikitext.class}): #{wikitext}" resource.set_string_data(wikitext) @store.update_resource(resource) else # The resource does not exist, so we must create it instead. @store.create_resource(occurence.get_reference, opts[:user_id], 'wiki', wikitext) end rescue ResourceException # The resource has either been locked or marked as deleted. if resource.get_locked_by.length == 'DELETED' # It has been marked as deleted. raise 'This wiki has been deleted.' else # It has been locked by somebody else. puts "#> unable to update wiki as it is locked" @store.create_resource(occurence.get_reference, 'some user id', 'wiki', wikitext) lock_info = PropertySet.new # acumen.util.PropertySet lock_info.put('id', resource.get_id) lock_info.put('name', resource.get_name) lock_info.put('locked_by', resource.get_locked_by) occurence.get_resolved_objects.put('lock', lock_info) end end ensure @store.stop end end end end
true
27de2fac364547c6747d1fdf25456fbb3dac21c9
Ruby
Rexman17/OO-FlatironMifflin-nyc-web-071519
/lib/Employee_Manager.rb
UTF-8
234
2.671875
3
[]
no_license
# JOIN TABLE class Employee_Manager attr_accessor :employee, :manager @@all = [] def initialize(employee, manager) @employee = employee @manager = manager @@all << self end def self.all @@all end end
true
0a1ecbb84718016517ff20d69e1ad68f495ded76
Ruby
neomort/lunch_lady
/menu.rb
UTF-8
2,006
3.890625
4
[]
no_license
#{name: 'string' price:float, ingredients:['rice', 'beans']} #dish would be an instance of class # Dish - handles both main and side dishes #sideDish class and mainDish class #app.rb to hanfle logic #resturaunt class? # peudo code: class Dish attr_accessor :food, :price #type = main/side #food = type of food served #price = price def initialize (food, price) @food = food @price = price end end @main_dishes = [ Dish.new( 'chicken', 10.99), Dish.new('pasta', 9.99), Dish.new( 'curry', 14.99),] @side_dishes = [ Dish.new('rice', 4.99), Dish.new('french_fries', 3.99), Dish.new('hush_puppies', 5.99)] def read_price @main_dishes.each do |dish| puts "#{dish.price}" end end def total_price total_price = 0 #accumulator variable-- @main_dishes.each do |dish| total_price += dish.price #accumulator pattern is for accumulating values end puts total_price total_price #return value end def read_dishes main_dish = "#{@main_dishes [1,2]}" @main_dishes.each_with_index do |main_dish, index| puts "main dish # #{index+1}) #{main_dish.food} price = #{main_dish.price}" end end def read_side_dishes side_dish = "#{@side_dishes[1,2]}" @side_dishes.each_with_index do |side_dish, index| puts "side dish # #{index+1}) #{side_dish.food} price = #{side_dish.price}" end end # total_price def display_menu puts '*' * 10 puts "menu" puts '*' * 10 puts "main dishes: " read_dishes puts puts "side dishes: " read_side_dishes puts '*' * 10 end def grab_main_dish end def order puts "what would you like to order?" puts "Main (pick one)" puts '*' * 10 read_dishes puts "enter the number corresponding to your dish of choice" # function that lets you enter a number relating to the correspronding menu item, then calls it-- variable? item_number +1 = gets.chomp main_dish = "#{@main_dishes}" @main_dishes.each do |main_dish, index| puts "you have chosen #{main_dish.item_number}" end end
true
8d46af4d15ccc0a1cfcb68dd945c0393e57b03a2
Ruby
NicoRB28/Ruby
/interpolation.rb
UTF-8
326
3.453125
3
[]
no_license
def interpolation(string) #esto se puede hacer si la frase esta entre "" "hola #{string}" #el valor retornado por un metodo en ruby es el valor de la última expresion, por eso #no es necesario el return (aunque puede ir) end puts interpolation "nico" puts 'hola #{si esta entre single cuotes no interpola}'
true
42a66931e315947789ce271c3c65c99f5aa6fbfb
Ruby
ardelapaz/algorithms
/introduction/fibonacci_iterative.rb
UTF-8
420
4.25
4
[]
no_license
def fib(n) puts "this is input: #{n}" return 0 if n == 0 return 1 if n == 1 fib_0 = 0 fib_1 = 1 for i in 2..n temp = fib_0 fib_0 = fib_1 fib_1 = temp + fib_1 end return fib_1 end puts fib(0) puts fib(1) puts fib(2) puts fib(3) puts fib(4) puts fib(5) puts fib(6) puts fib(7) puts fib(8) puts fib(9)
true
eb8b166223a3e46e4607abaf987062ff16f1ba05
Ruby
korney4eg/flats-crawler
/lib/flat-crawlers/tvoya-stolica.rb
UTF-8
1,866
2.828125
3
[]
no_license
require './lib/flat-crawlers/base.rb' # tvoya stalica crawler class TSCrawler < FlatCrawler def generate_urls(areas, price, step) page_urls = [] areas.each do |area| (price[0]..price[0]).step(step) do |pr| page_url = 'https://www.t-s.by/buy/flats/filter/' page_url += "district-is-#{area}/" # page_url += 'daybefore=1&' # page_url += "year[min]=#{years[0]}&year[max]=#{years[1]}&" # page_url += "price[min]=#{pr}&price[max]=#{pr + step}&keywords=" page_urls += [page_url] end end return page_urls end def parse_flats(page_urls) active_flats = [] page_urls.each do |url| @logger.info "Crawling on URL: #{url}" area = url.gsub(/^.*district-is-/,'').sub('/','') page = Nokogiri::HTML(open(url)) flats = page.search('[class="flist__maplist-item paginator-item js-maphover"]') @logger.info "Number of flats found: #{flats.size}" flats.each do |flat| address = flat.css('[class="flist__maplist-item-props-name"]').text.gsub(/^[^,]*, /, '').gsub(/ *$/,'').strip price = flat.css('[class="flist__maplist-item-props-price-usd"]').text.gsub(/[^\d]*/,'').to_i rooms = flat.css('[class="flist__maplist-item-props-name"]').text.gsub(/-.*$/,'').to_i year = flat.css('[class="flist__maplist-item-props-years"]').text.to_i code = flat.css('a')[0]['href'].gsub(/^.*-/, '').gsub(/[^\d]/, '') @logger.debug "Checking: |#{address}|#{rooms}|#{year}| -- #{price} $" if ! active_flats.include?(code) active_flats << code update_flat(code, area, address, price, rooms, year) else @logger.debug "Flat had been already parsed" end end # @logger.info "Updated #{active_flats.size}/#{flats.size}" end return active_flats end end
true
11129a40f9e6914a770044f14d6e98df2ca7a3f5
Ruby
kilimchoi/teamleada.com
/db/seeds/projects/018_sql_finance.rb
UTF-8
8,777
3
3
[]
no_license
main_page_content = [ ['text', "In this challenge you are tasked with quickly scraping a set of Yahoo data, and then storing the scraped data into a SQL database."], ['text', "The following are the steps you'll take to accomplish the task."], ['text', "1. Scrape Yahoo Finance data."], ['text', "2. Store the scraped data locally."], ['text', "3. Design a SQL database to store the data."], ['text', "4. Write a SQL script to load the data into the database."], ['text-success', "Let's get started!"], ] project = Project.create!( title:"Storing Financial Data in a SQL Database", description: main_page_content, short_description: "In this challenge, you will scrape a set of Yahoo finance data. After collecting the data, you will design a database schema and then store it into a SQL database.", number: 18, enabled: false, has_written_submit: true, uid: 18, difficulty: 'Intermediate', category: Project::CHALLENGE, is_new: true, deadline: 2.weeks, cover_photo: "scrape-finance", ) ################################################################################ #puts "============ Created project: #{project.title}." ################################################################################# project_overview_content_0 = [ ['text', "In this challenge you will quickly scrape a set of Yahoo data, and then store the scraped data into a SQL database."], ['text', "The following are the steps you'll take to accomplish the task."], ['text', "1. Scrape Yahoo Finance data."], ['text', "2. Store the scraped data locally."], ['text', "3. Design a SQL database to store the Data."], ['text', "4. Write a SQL script to load the data into the database."], ['next_steps', nil], ] project_overview = Lesson.create!( title: "Project Overview", project: project, lesson_id: 0, ) project_overview_slide0 = Slide.create!( content: project_overview_content_0, parent: project_overview, slide_id: 0, ) ################################################################################# ##### Scrape Data Lesson ######################################################## ################################################################################# collect_data_content_0 = [ ['text', "The first thing you must do is to collect the necessary financial data from Yahoo."], ['text', "You will scrape Yahoo finance historical data, which can be viewed here:"], ['link', "http://real-chart.finance.yahoo.com/table.csv?s=YHOO&d=7&e=1&f=2014&g=d&a=3&b=12&c=2000&ignore=.csv"], ['text-info', "Note that the text of the URL contains a series of parameters; scrape data from the years beginning in 1990."], ['text', "You're not given specific language requirement, but if you're unfamiliar with the work, we suggest Python."], ] collect_data_content_1 = [ ['text-info', "In order to scrape the relevant stock data, you must first get a list of stocks to scrape!"], ['text-success', "Get a list of NYSE symbols by searching on Google."], ['text', "You should be able to find a csv/excel table of all NYSE companies (and their stock symbols)."], ['text', "You should be able to find the list without having to register anywhere."], ['quiz', "finance_data_0"], ['text', "Good! Now you can use the list to iteratively scrape Yahoo Finance data."], ['text-info', "Write a script that will iteratively grab Yahoo Finance Data for each of the NYSE symbols you acquired."], ['text', "You're going to want to access the data by editing the sample link we gave (while altering some parameters)."], ] collect_data_content_2 = [ ['text', "Submit the code you used to collect the Yahoo data."], ['text', "If your code refers to an external file/csv, explain your comments what you expect the file to contain."], ['user_code', ""], ['text-warning', "Make sure to include relevant comments."], ['next_steps', ""], ] collect_data_lesson = Lesson.create!( title: "Data Collection", project: project, lesson_id: 1, ) collect_data_slide_0 = Slide.create!( content: collect_data_content_0, parent: collect_data_lesson, slide_id: 0, ) collect_data_slide_1 = Slide.create!( content: collect_data_content_1, parent: collect_data_lesson, slide_id: 1, ) collect_data_slide_2 = Slide.create!( content: collect_data_content_2, parent: collect_data_lesson, slide_id: 2, ) quiz_intro_pd = ExactAnswerQuiz.create!( quiz_id: "finance_data_0", answer: "3000", project: project, slide: collect_data_slide_1, question: "How long is the list you found of NYSE stocks? Round to the nearest thousands:", ) scraper_data_submission = SubmissionContext.create!( title: "Scraping Yahoo Finance", description: "User is asked to scrape Yahoo Finance.", slide: collect_data_slide_2, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ################################################################################# ##### SQL SCHEMA DESIGN/IMPLEMNT ################################################ ################################################################################# sql_overview_content = [ ['text', "Now that you have the collected historical data, you must store the data into a SQL database."], ['text', "You first must explain your database design."], ['text', "Once you design the database, you will write implementation code that will import the csv into the database."], ['lesson_links', ""], ] sql_lesson = Lesson.create!( title: "SQL Design/Implementation", project: project, lesson_id: 2, ) sql_overview_slide = Slide.create!( content: sql_overview_content, parent: sql_lesson, slide_id: 0, ) ################################################################################# sql_design_content_one = [ ['text', "We want to design a SQL database that will hold all of our historical data."], ['text', "There are many different ways to store the data."], ['text', "However, you want to keep the schema as maintainable as possible."], ['text', "For example, you might want to add more comapny information later."], ['text-info', "Design a set of schemas that you're going to store which include the historical data points and symbols you scraped."], ['text', "For each table, include the column data type and a brief comment on what the column holds."], ['user_response', ""], ['next_steps', ""], ] sql_design_step = Step.create!( title: "SQL Schema Design", lesson: sql_lesson, step_id: 0, ) sql_design_slide = Slide.create!( content: sql_design_content_one, parent: sql_design_step, slide_id: 0, ) sql_design_submission = SubmissionContext.create!( title: "Designing Financial Schema", description: "User is asked to design a schema to store the financial data scraped from YAHOO.", slide: sql_design_slide, submission_context_id: 0, submission_type: SubmissionContext::RESPONSE, ) ################################################################################# sql_code_content_one = [ ['text-info', "Now that you've designed your database, code up the schema."], ['text', "In addition to coding up the schema, also write a script that will load your scraped data into your schema."], ['user_code', ""], ['text-warning', "Make sure you've sufficiently commented in your code."], ['next_steps', ""], ] sql_code_step = Step.create!( title: "SQL Code", lesson: sql_lesson, step_id: 1, ) sql_code_slide = Slide.create!( content: sql_code_content_one, parent: sql_code_step, slide_id: 0, ) sql_code_submission = SubmissionContext.create!( title: "Coding Financial Schema [SQL]", description: "User is asked to code/load schema to store the financial data scraped from YAHOO.", slide: sql_code_slide, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ################################################################################# ##### SQL SCHEMA DESIGN/IMPLEMNT ################################################ ################################################################################# sql_conclusion_content = [ ['text-success', "You've completed the SQL finance challenge!"], ['text', "Now you have a set of financial data to which you can query and perform analysis on."], ['text', "In a future challenge, we'll re-visit the SQL database you created in order to do some in-depth analysis."], ['finish_project_button', 'http://www.surveygizmo.com/s3/1654603/Project-Feedback-Form'], ] sql_lesson = Lesson.create!( title: "SQL/Finance Conclusion", project: project, lesson_id: 3, ) sql_conclusion_slide = Slide.create!( content: sql_conclusion_content, parent: sql_lesson, slide_id: 0, ) #################################################################################
true
a4628681f79a6234c07f65c4c69471f42a521169
Ruby
paploo/sliderule_tester
/lib/generator/trig/polar.rb
UTF-8
1,480
3.328125
3
[ "BSD-3-Clause" ]
permissive
module Generator module Trig class Polar < Base def self.title return "Polar Coordinate Conversions" end def self.description return "Conversion to/from polar coordinates." end def self.instructions return <<-INST A. Convert into rectangular coordinates via: 1. x = r * cos(theta) 2. y = r * sin(theta) B. Convert into polar coordinates via: 1. theta = atan(y/x) 2. Either - r = x / cos(theta) - r = y / sin(theta) It is important to calculate with the correct quadrant for theta. INST end def initialize @x = Random.float(0.0,20.0) - 10.0 @y = Random.float(0.0,20.0) - 10.0 @r = Math.sqrt(@x**2 + @y**2) @rad = Math.atan2(@y, @x) @deg = @rad.to_deg @to_polar = Random.bool @first_coord = Random.bool end def solution if(@to_polar) return (@first_coord ? @r : @deg) else return (@first_coord ? @x : @y) end end def to_s if(@to_polar) coord_name = (@first_coord ? 'r' : 'theta (deg); -180<=theta<=+180') return "[#{@x}, #{@y}] --> [r, theta]. What is the value of #{coord_name}?" else coord_name = (@first_coord ? 'x' : 'y') return "[#{@r}, #{@deg} deg] --> [x, y]. What is the value of #{coord_name}?" end end end end end
true
769cca1bb306a41f19c811136e41271d250711ea
Ruby
Coderdotnew/intro_web_apps_bs
/05_class/01_intro_to_arrays/code/01_array_methods/spec/array_methods_spec.rb
UTF-8
2,274
3.984375
4
[]
no_license
require_relative './spec_helper' require_relative '../array_methods.rb' describe "#sort_words" do it "sorts an array of words alphabetically and returns the sorted array" do words = ["watermelon", "strawberry", "apple", "banana", "peach"] expect(sort_words(words).first).to eq("apple") expect(sort_words(words).last).to eq("watermelon") expect(sort_words(words)[2]).to eq("peach") end end describe "#sort_nums" do it "sorts an array of numbers from smallest to largest and returns the sorted array" do nums = [5, 15, 104, 23, 19] expect(sort_nums(nums).first).to eq(5) expect(sort_nums(nums).last).to eq(104) expect(sort_nums(nums)[2]).to eq(19) end end describe "#include_method" do it "checks if team that is passed in as argument is included in the teams array" do teams = ["real madrid", "chelsea", "manchester united", "arsenal", "liverpool"] team1 = "arsenal" team2 = "manchester city" team3 = "real madrid" expect(include_method(teams, team1)).to eq(true) expect(include_method(teams, team2)).to eq(false) expect(include_method(teams, team3)).to eq(true) end end describe "#reverse_method" do it "returns the array of cities in reverse order" do cities = ["phoenix", "new york", "seattle", "los angeles", "miami"] expect(reverse_method(cities)).to eq(["miami", "los angeles", "seattle", "new york", "phoenix"]) end end describe "#first_method" do it "returns the first item in the cities array" do cities = ["phoenix", "new york", "seattle", "los angeles", "miami"] expect(first_method(cities)).to eq("phoenix") end end describe "#last_method" do it "returns the last item in the cities array" do cities = ["phoenix", "new york", "seattle", "los angeles", "miami"] expect(last_method(cities)).to eq("miami") end end describe "#count_method" do it "returns the count of the number of items in the cities array" do cities = ["phoenix", "new york","seattle", "los angeles", "miami"] expect(count_method(cities)).to eq(5) end end describe "#to_array_method" do it "returns the count of the number of items in the cities array" do range = (1..10) expect(to_array_method(range)).to eq([1,2,3,4,5,6,7,8,9,10]) end end
true
b3427d5abcc1dffded0fe8276f3652edf820abb3
Ruby
bmoises/saynews
/lib/downloader.rb
UTF-8
1,638
2.921875
3
[]
no_license
class Downloader attr_accessor :mech, :opts, :uri, :cached_file, :resume WORD_WRAP = 60 def initialize(opts = {}) @uri = opts[:uri] @mech = Mechanize.new { |agent| agent.user_agent_alias = 'Mac Safari' } end def download if !file_exists? puts "File does not exist: #{cached_file}" @mech.get(url) do |page| save!(parse(page.body)) end end end def save_resume_point!(line) File.open(resume_point_file, "w") do |file| puts "#{cached_file}||#{line}" file.puts "#{cached_file}||#{line}" end end def delete_resume_point! FileUtils.rm resume_point_file end def resume_point_file File.join(SAYNEWS_CACHE,"resume") end def resume_data begin @resume_data ||= File.open(resume_point_file).read.split("||") rescue @resume = false end end def url @uri end def parse(content) raise "Implement in your class" end def cached_file @cached_file ||= File.join(SAYNEWS_CACHE,Digest::MD5.hexdigest(url)) end def file_exists? File.exists?(cached_file) end def read_file resume_from = resume_data && resume_data[1] File.open(cached_file).each_line do |line| if @resume && line != resume_from next else @resume = false # stop fastforward end save_resume_point!(line) yield line end end def save!(content) if !File.exists?(SAYNEWS_CACHE) FileUtils.mkdir_p SAYNEWS_CACHE end puts cached_file File.open(cached_file,'w') do |file| file.puts content end end end
true
d34ce1ee528bb008ff7c7c8bc196ee975ff7f343
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/combine_anagrams_latest/12110.rb
UTF-8
222
3.421875
3
[]
no_license
def combine_anagrams(words) anagrams = {} words.each do |w| s = w.downcase.chars.sort.join if (anagrams[s]) anagrams[s] = (anagrams[s] << w) else anagrams[s] = [w] end end anagrams.values end
true
59e903738f13806a763d51d6691cce61cc6d0123
Ruby
Jeff-Adler/key-for-min-value-nyc01-seng-ft-071320
/key_for_min.rb
UTF-8
384
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) temp_min_price = nil temp_min_key = nil name_hash.each do |item,price| if temp_min_price == nil || price < temp_min_price temp_min_price = price temp_min_key = item end end temp_min_key end
true
cbc9ed11ba3aa65fbf611b0c464139c52de656da
Ruby
kennychong89/launch_school
/back_end/weekly_challenges/oop/medium_one/poker_incomplete.rb
UTF-8
3,859
3.953125
4
[]
no_license
=begin OO Exercises Launch School Kenny Chong 10/12/2016 12:34 pm https://launchschool.com/exercises/a1938086 =end class Card include Comparable attr_reader :rank, :suit def initialize(rank, suit) @rank = rank @suit = suit end def to_s "#{@rank} of #{@suit}" end def <=>(other_card) convert_rank <=> other_card.convert_rank end def convert_rank return 12 if rank == 'Ace' return 11 if %w(Jack Queen King).include? rank return rank end end class Deck RANKS = (2..10).to_a + %w(Jack Queen King Ace).freeze SUITS = %w(Hearts Clubs Diamonds Spades).freeze def initialize @deck = create_deck.shuffle end def draw @deck = create_deck.shuffle if @deck.size == 0 @deck.shift end private def create_deck RANKS.product(SUITS).map do |rank, suit| Card.new(rank, suit) end end end class PokerHand def initialize(deck) @hand = Array.new(5) { deck.draw } @card_count = initialize_hand_count #puts @card_count end def print puts @hand end def evaluate case when royal_flush? then 'Royal flush' when straight_flush? then 'Straight flush' when four_of_a_kind? then 'Four of a kind' when full_house? then 'Full house' when flush? then 'Flush' when straight? then 'Straight' when three_of_a_kind? then 'Three of a kind' when two_pair? then 'Two pair' when pair? then 'Pair' else 'High card' end end private def royal_flush? # Hand is a 10,Jack,Queen,King,Ace and suits are same end def straight_flush? # Hand is straight and suits are same end def four_of_a_kind? # Hand has 4 cards that are of same rank end def full_house? # three_of_a_kind + a pair three_of_a_kind? + pair? end def flush? # Hand has 5 cards that are of same suit end def straight? # Hand has cards that are +1 rank above the previous # card and card ranks are consecutive. keys = @card_count.values.flatten ranks = keys.map { |card| card.convert_rank } (keys.min.rank..(keys.min.rank)+4).to_a == ranks.sort end def three_of_a_kind? # Hand has at least 3 cards with same rank @card_count.each_value do |cards| return true if cards.size == 3 end false end def two_pair? count = 0 @card_count.each_value do |cards| count += 1 if cards.size == 2 end count == 2 end def pair? # Hand has at least two cards with same rank @card_count.each_value do |cards| return true if cards.size == 2 end false end private def initialize_hand_count hand = {} @hand.each do |card| if hand.has_key? card.rank hand[card.rank].push(card) else hand[card.rank] = [card] end end hand end end #hand = PokerHand.new(Deck.new) #hand.print #puts hand.evaluate # Danger danger danger: monkey # patching for testing purposes. class Array alias_method :draw, :pop end hand = PokerHand.new([ Card.new(8, 'Clubs'), Card.new(9, 'Diamonds'), Card.new(10, 'Clubs'), Card.new(7, 'Hearts'), Card.new('Jack', 'Clubs') ]) puts hand.evaluate == 'Straight' hand = PokerHand.new([ Card.new(3, 'Hearts'), Card.new(3, 'Clubs'), Card.new(4, 'Diamonds'), Card.new(3, 'Spades'), Card.new(6, 'Diamonds') ]) puts hand.evaluate == 'Three of a kind' hand = PokerHand.new([ Card.new(9, 'Hearts'), Card.new(9, 'Clubs'), Card.new(5, 'Diamonds'), Card.new(8, 'Spades'), Card.new(5, 'Hearts') ]) puts hand.evaluate == 'Two pair' hand = PokerHand.new([ Card.new(2, 'Hearts'), Card.new(2, 'Clubs'), Card.new(5, 'Diamonds'), Card.new(9, 'Spades'), Card.new(3, 'Diamonds') ]) puts hand.evaluate == 'Pair'
true
9b0eb511e15bb9d95ed208e9977866f93c5f0a13
Ruby
Tcom242242/t_learn
/examples/k_means.rb
UTF-8
282
2.5625
3
[ "MIT" ]
permissive
require "t_learn" k_means = TLearn::K_Means.new() data_list = JSON.load(open("./sample_1dim.json")) history = k_means.fit(data_list, c=3) # => {result:=> Array, history => Array} # history[:result][0] => {id=>cluster's number, :vec=>cluster's point, :v_list=> clustered data list}
true
d32afd2b0fc7de2debafdff244e9885a781480a8
Ruby
mindaslab/ilrx
/class_eval.rb
UTF-8
165
3.65625
4
[]
no_license
# class_eval.rb class Animal end dog = Animal.new dog.class.class_eval do def say_something "I am a dog" end end pig = Animal.new puts pig.say_something
true
8da297b09996149d56d84d711fe6796770ddc076
Ruby
abdibogor/Ruby
/1.Jake Day Williams/Ruby/11.1.counter index each do.rb
UTF-8
196
2.6875
3
[]
no_license
array_test = ["first_line", " second line", " third line"] for object in array_test print " Item one #{object}" end puts for surf in array_test.reverse print "#{surf} " end $end
true
f3feadf9359b9361f6435ef3f4045b72c73f21dd
Ruby
mliew21396/Project-Euler
/2_even_fibonacci_numbers.rb
UTF-8
822
4.5
4
[ "MIT" ]
permissive
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. def even_fibonacci_numbers(top_range) array = [1,2] i = 0 #Creates fibonacci array with values up to 4 million while array[i+1] < top_range array.push(array[i]+array[i+1]) i += 1 end if array[i+1] >= top_range array.pop end #Narrows array down to only even values even_array = [] array.each{|val| if val%2 == 0 even_array.push(val) end } #Adds even_array up sum = even_array.inject{|total, x| total + x} puts sum end even_fibonacci_numbers(4000000)
true
1f63227e382951bff7aa378a75fc11d7896925cb
Ruby
relevance/Facebook-Registration
/lib/rails/signed_request.rb
UTF-8
1,184
2.6875
3
[ "MIT" ]
permissive
require 'rubygems' require 'openssl' require 'base64' module FacebookRegistration class SignedRequest def self.parse(params) if params.is_a?(Hash) signed_request = params.delete('signed_request') else signed_request = params end unless signed_request raise "Missing signed_request param" end signature, signed_params = signed_request.split('.') unless signed_request_is_valid?(FACEBOOK_CONFIG['secret_key'], signature, signed_params) raise "Invalid signature" end signed_params = JSON.parse(base64_url_decode(signed_params)) return signed_params end private def self.signed_request_is_valid?(secret, signature, params) signature = base64_url_decode(signature) expected_signature = OpenSSL::HMAC.digest('SHA256', secret, params.tr("-_", "+/")) return signature == expected_signature end def self.base64_url_decode(str) str = str + "=" * (6 - str.size % 6) unless str.size % 6 == 0 return Base64.decode64(str.tr("-_", "+/")) end end end
true
dc2f954e02401cc74aac3bbe694bde1bc821ed82
Ruby
camsys/transam_core
/app/models/equipment.rb
UTF-8
2,968
2.609375
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
class Equipment < Asset # Callbacks after_initialize :set_defaults #------------------------------------------------------------------------------ # Associations common to all equipment assets #------------------------------------------------------------------------------ validates :quantity, :presence => true, :numericality => {:only_integer => true, :greater_than_or_equal_to => 1} validates :quantity_units, :presence => true #------------------------------------------------------------------------------ # Scopes #------------------------------------------------------------------------------ # set the default scope default_scope { where(:asset_type_id => AssetType.where(:class_name => self.name).pluck(:id)) } #------------------------------------------------------------------------------ # # Class Methods # #------------------------------------------------------------------------------ def self.allowable_params [ :quantity, :quantity_units ] end def transfer new_organization_id org = Organization.where(:id => new_organization_id).first transferred_asset = self.copy false transferred_asset.object_key = nil transferred_asset.disposition_date = nil transferred_asset.in_service_date = nil transferred_asset.organization = org transferred_asset.purchase_cost = nil transferred_asset.purchase_date = nil transferred_asset.purchased_new = false transferred_asset.service_status_type = nil transferred_asset.generate_object_key(:object_key) transferred_asset.asset_tag = transferred_asset.object_key transferred_asset.save(:validate => false) return transferred_asset end #------------------------------------------------------------------------------ # # Instance Methods # #------------------------------------------------------------------------------ # Render the asset as a JSON object -- overrides the default json encoding def as_json(options={}) super.merge( { :quantity => self.quantity, :quantity_units => self.quantity_units }) end # Creates a duplicate that has all asset-specific attributes nilled def copy(cleanse = true) a = dup a.cleanse if cleanse a end def searchable_fields a = [] a << super a += [ :description, :serial_number ] a.flatten end def cleansable_fields a = [] a << super a += [ :quantity ] a.flatten end # The cost of a equipment asset is the purchase cost def cost purchase_cost end #------------------------------------------------------------------------------ # # Protected Methods # #------------------------------------------------------------------------------ protected # Set resonable defaults for a suppoert facility def set_defaults super self.quantity ||= 1 self.quantity_units ||= Uom::UNIT end end
true
1fe1600b8d6b46ab7da54590a4577eac9878cc6b
Ruby
sharkham/oo-tic-tac-toe-online-web-pt-061019
/lib/tic_tac_toe.rb
UTF-8
2,718
4.375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class TicTacToe WIN_COMBINATIONS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [2, 4, 6] ] def initialize @board = Array.new(9, " ") end def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts "-----------" puts " #{@board[3]} | #{@board[4]} | #{@board[5]} " puts "-----------" puts " #{@board[6]} | #{@board[7]} | #{@board[8]} " end def input_to_index(num) index = num.to_i - 1 end def move(index, token = "X") @board[index] = token @board end def position_taken?(index) if @board[index] == " " false else true end end def valid_move?(index) if (0..8).include?(index) && @board[index] == " " true else false end end def turn_count filled_spaces = @board.reject{|space| space == " "} filled_spaces.count end def current_player if turn_count.even? "X" else "O" end end def turn puts "Your move." player_move = gets.chomp index = input_to_index(player_move) if valid_move?(index) == true move(index, current_player) display_board else puts "Not a valid move; please try again." player_move = gets.chomp end end def won? #maybe make arrays of the index for each X and for each O #and if one of those contains the winning numbers, then win? xs = [] os = [] win_combo = nil @board.each_with_index do |letter, index| # binding.pry if letter == "X" xs << index elsif letter == "O" os << index end end #check if the xs array or the os array has the same numbers #as any of the WIN_COMBINATIONS arrays #this returns true: #WIN_COMBINATIONS[3].all? {|num| xs.include?(num)} WIN_COMBINATIONS.each do |array| if array.all? {|num| xs.include?(num)} win_combo = array @winner = "X" elsif array.all? {|num| os.include?(num)} win_combo = array @winner = "O" else end end win_combo end def full? if @board.include?(" ") false else true end end def draw? if full? == true && won? == nil true elsif full? == true && won? == true false else false end end def over? if won? || draw? true else false end end def winner if won? @winner end @winner end def play until over? == true turn end if won? puts "Congratulations #{@winner}!" elsif draw? puts "Cat's Game!" else puts "Error." end end end
true
c8743880ccd51ac4fb495a7cd16af960efc8b4f6
Ruby
krpiatkowski/tidsreg-miner
/run.rb
UTF-8
1,935
2.703125
3
[]
no_license
require 'rubygems' require 'bundler/setup' require 'dotenv' require './tidsreg_service.rb' Dotenv.load service = TidsregService.new(ENV['TIDSREG_USERNAME'], ENV['TIDSREG_PASSWORD']) # d = Date.today - (ENV['TIDSREG_WEEKS'].to_i * 7) # now = Date.today d = Date.strptime('01-05-2015', '%d-%m-%Y') now = Date.strptime('01-05-2016', '%d-%m-%Y') result = {} while(d < now) result.merge!(service.hours(d, 7)) d += 7 end puts "date\t\tproject\tholly.\tIntern\t1st sd\tVac.\tSick" total_project = 0 total_hollyday = 0 total_internal_time = 0 total_childs_first_sickday = 0 total_vacation = 0 total_sick = 0 total_total = 0 result.keys.sort.each{|date| d = result[date] project = d[:project] total_project += project hollyday = d[:hollyday] total_hollyday += hollyday internal_time = d[:internal_time] total_internal_time = internal_time childs_first_sickday = d[:childs_first_sickday] total_childs_first_sickday += childs_first_sickday vacation = d[:vacation] total_vacation += vacation sick = d[:sick] total_sick += sick total = project + hollyday + internal_time + childs_first_sickday + vacation + sick total_total += total puts sprintf("%s\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t|\t%.2f", date, project, hollyday, internal_time, childs_first_sickday, vacation, sick, total) } c = result.keys.count puts "------------------------------------[ AVG ]--------------------------------------------------" puts sprintf("\t\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t|\t%.2f", total_project/c, total_hollyday/c, total_internal_time/c, total_childs_first_sickday/c, total_vacation/c, total_sick/c, total_total/c) puts "------------------------------------[TOTAL]--------------------------------------------------" puts sprintf("\t\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t|\t%.2f", total_project, total_hollyday, total_internal_time, total_childs_first_sickday, total_vacation, total_sick, total_total)
true
529eaff4f2d35eacd7e3089f4b8805671396fd6a
Ruby
njbbaer/exercism
/ruby/sieve/sieve.rb
UTF-8
253
2.8125
3
[]
no_license
class Sieve def initialize(max) @max = max end def primes primes = [] (2..@max).each do |i| primes.push i if primes.none? do |p| (i % p).zero? end end primes end end module BookKeeping VERSION = 1 end
true
cb19b0d0c94979eb5f3d86c89aa593ea44b64e66
Ruby
Coderman112/game-app
/lib/game.rb
UTF-8
474
3.328125
3
[]
no_license
require 'pry' class Game @@all = [] def initialize(hash) hash.each do |key, value| self.class.attr_accessor(key) self.send("#{key}=", value) if self.respond_to?("#{key}=") end @@all << self end def self.all @@all end def self.find_by_title(title) self.all.find do |game| if game.title == title puts game.platforms end end end end
true
ef5117521eafbc6be12b09ad88fdaa3554e0a56b
Ruby
RitamDey/Algorithms-and-Data-Structres
/Ruby/Bubble_Sort_Recursive.rb
UTF-8
642
3.84375
4
[ "MIT" ]
permissive
def is_sorted?(arr) len = arr.length 0.upto(len-2) do |x| if arr[x] > arr[x+1] return false end end return true end def bubble_sort(arr, len) if len <= 1 return arr end 0.upto(len -2 ) do |x| if arr[x] > arr[x+1] arr[x], arr[x+1] = arr[x+1], arr[x] end end arr = bubble_sort(arr, len-1) return arr end if __FILE__ == $0 arr = 10.times.map { |x| (Random.rand() * 100).to_i + x } puts "Array #{arr}. Sorted? #{is_sorted?(arr)}" arr = bubble_sort(arr, arr.length) puts "Array #{arr}. Sorted? #{is_sorted?(arr)}" end
true
a74f22fc222bfff5fe6201957686f7d865b8c6fa
Ruby
dalssoft/rsearch
/document.rb
UTF-8
1,973
3.265625
3
[]
no_license
#encoding: UTF-8 # rsearch: a vector model information retrieval implemented in Ruby # Author: David Lojudice Sobrinho # 22/11/2008 # <dalssoft@gmail.com>. # # info: # http://www.ruby-doc.org/docs/ProgrammingRuby/ # http://en.wikipedia.org/wiki/Vector_space_model # http://www.hray.com/5264/math.htm class Document attr_reader :name, :text, :terms, :most_common_term, :most_common_term_freq def initialize() @terms = Hash.new() @most_common_term = "" @most_common_term_freq = 0 end def process(stopwords) terms = text.scan(/\w+/) normalizedterms = Array.new terms.each {|term| normalizedterms << term.downcase} normalizedterms = normalizedterms - stopwords normalizedterms.each {|normalizedterm| @terms[normalizedterm] = DocumentTerm.new unless @terms.has_key?(normalizedterm) doc_term = @terms[normalizedterm] doc_term.term = normalizedterm doc_term.term_freq += 1 if doc_term.term_freq > @most_common_term_freq @most_common_term = normalizedterm @most_common_term_freq = doc_term.term_freq end } #normalize frequency @terms.each_value do |term| term.normalized_freq = term.term_freq / Float(@most_common_term_freq) end end end class DocumentTerm attr_reader :term, :term_freq, :normalized_freq, :term_weight attr_writer :term, :term_freq, :normalized_freq, :term_weight def initialize() @term_freq = 0 @normalized_freq = 0 @term_weight = 0 end end class DocumentFile < Document def initialize(filename) super() @filename = filename end def filename @filename end def readtext() text = "" File.open(@filename, 'rb') do |f1| while line = f1.gets text = text + " " + line.strip end end return text end def name filename end def text readtext() end end
true
9ba4425468815c5f2fccf3447a7b39b3f0274301
Ruby
apunko/TasksBoard
/app/models/draw_icon_module.rb
UTF-8
1,974
2.78125
3
[]
no_license
module DrawIconModule def draw_stat(image, user) image.combine_options do |c| c.pointsize '18' c.draw "text 20,20 TasksBoard#"+"#{user.name}" c.fill 'white' end image end def draw_achievement(background, achievement, user_id, x, y) image = Achievement.make_image(achievement, user_id) result = background.composite(image) do |c| c.compose "Over" # OverCompositeOp c.geometry "+#{x}+#{y}" # copy second_image onto first_image from (20, 20) end result end def make_image(achievement, id) image = MiniMagick::Image.open("#{Rails.root}/app/assets/images/"+achievement.image_url) record = AchievingRecord.find_by(user_id: id, achievement_id: achievement.id) if record image = Achievement.handle_image(image, record) else image.colorspace "Gray" image.resize "75x75" end image end def handle_image(image, record) handle_image = image if record.amount > 1 handle_image = Achievement.draw_text(image, record.amount) end handle_image.resize "75x75" handle_image end def draw_text(image, text) image.combine_options do |c| c.pointsize '18' c.draw "text 80,80 A" c.fill 'red' end image end def draw_image(bg, image, x, y) result = bg.composite(image) do |c| c.compose "Over" c.geometry "+#{x}+#{y}" end result end def generate_image(user) background = MiniMagick::Image.open("#{Rails.root}/app/assets/images/achieves/background.jpg") x = 5 y = 50 i = 0 Achievement.all.each do |achievement| i += 1 background = Achievement.draw_achievement(background, achievement, user, x, y) x += 80 if i == 6 y += 80 x = 5 end if i == 12 y += 80 x = 5 end end background = draw_stat(background, user) background.write "#{Rails.root}/app/assets/images/output.jpg" end end
true
721cac2de0617209f1ad07c3ce4d819d796ebfab
Ruby
github-luciano/tic_tac_toe
/tic_tac_toe.rb
UTF-8
3,007
3.28125
3
[]
no_license
$var1 = ' ' $var2 = ' ' $var3 = ' ' $var4 = ' ' $var5 = ' ' $var6 = ' ' $var7 = ' ' $var8 = ' ' $var9 = ' ' class X include Check @@class_name = 'X' def self.top_left $var1 = @@class_name puts X.new.check_table end def self.top $var2 = @@class_name puts X.new.check_table end def self.top_right $var3 = @@class_name puts X.new.check_table end def self.left $var4 = @@class_name puts X.new.check_table end def self.middle $var5 = @@class_name puts X.new.check_table end def self.right $var6 = @@class_name puts X.new.check_table end def self.bot_left $var7 = @@class_name puts X.new.check_table end def self.bot $var8 = @@class_name puts X.new.check_table end def self.bot_right $var9 = @@class_name puts X.new.check_table end end class O include Check @@class_name = 'O' def self.top_left $var1 = @@class_name puts O.new.check_table end def self.top $var2 = @@class_name puts O.new.check_table end def self.top_right $var3 = @@class_name puts O.new.check_table end def self.left $var4 = @@class_name puts O.new.check_table end def self.middle $var5 = @@class_name puts O.new.check_table end def self.right $var6 = @@class_name puts O.new.check_table end def self.bot_left $var7 = @@class_name puts O.new.check_table end def self.bot $var8 = @@class_name puts O.new.check_table end def self.bot_right $var9 = @@class_name puts O.new.check_table end end module Check def checks " |#{$var1}|#{$var2}|#{$var3}| |#{$var4}|#{$var5}|#{$var6}| |#{$var7}|#{$var8}|#{$var9}|" end def check_table if $var1 == $var2 && $var1 == $var3 && $var1 != ' ' puts checks puts "the winner is #{$var1}" reset_values elsif $var4 == $var5 && $var4 == $var6 && $var4 != ' ' puts checks puts "the winner is #{$var4}" reset_values elsif $var7 == $var8 && $var7 == $var9 && $var7 != ' ' puts checks puts "the winner is #{$var7}" reset_values elsif $var1 == $var4 && $var1 == $var7 && $var1 != ' ' puts checks puts "the winner is #{$var1}" reset_values elsif $var2 == $var5 && $var2 == $var8 && $var2 != ' ' puts checks puts "the winner is #{$var2}" reset_values elsif $var3 == $var6 && $var3 == $var9 && $var3 != ' ' puts checks puts "the winner is #{$var3}" reset_values elsif $var1 == $var5 && $var1 == $var9 && $var1 != ' ' puts checks puts "the winner is #{$var1}" reset_values elsif $var3 == $var5 && $var3 == $var7 && $var3 != ' ' puts checks puts "the winner is #{$var3}" reset_values else puts checks end end def reset_values $var1 = ' ' $var2 = ' ' $var3 = ' ' $var4 = ' ' $var5 = ' ' $var6 = ' ' $var7 = ' ' $var8 = ' ' $var9 = ' ' end end
true
3f8af28781628828ead86389cadb51a7e1d321b9
Ruby
calvinsettachatgul/freecodecamp
/basic_algorithm_scripting/largest_numbers_in_array.rb
UTF-8
1,304
4.3125
4
[]
no_license
# https://www.freecodecamp.org/challenges/return-largest-numbers-in-arrays # # Return Largest Numbers in Arrays # Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. # # Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i]. # # Remember to use Read-Search-Ask if you get stuck. Write your own code. # # Here are some helpful links: # # Comparison Operators # function largestOfFour(arr) { # // You can do this! # var arr_result; # # arr_result = arr.map( largest_of_arr); # # return arr_result; # } # # function largest_of_arr(arr){ # var largest = arr[0]; # for( var i = 0; i < arr.length; i++){ # if (arr[i] > largest ){ # largest = arr[i]; # } # } # return largest; # } # # console.log( largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])) def largest_of_arr(arr) largest = arr[0] arr.each do | number | if (number > largest) largest = number end end largest end def largestOfFour(arr) result = arr.map do | sub_arr | largest_of_arr(sub_arr) end result end p ( largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))
true
858071a79a5c960c276486224c7c809146d4deda
Ruby
DStorck/get-out
/lib/eventful_api_wrapper.rb
UTF-8
774
2.75
3
[]
no_license
require "httparty" module EventfulAPIWrapper BASE_URL = "http://api.eventful.com/json/events/search?&app_key=PNh8dcmkrJKGX8tx&keywords=" def self.search(term, current_user) city = current_user ? current_user.city : "seattle" initial_response = HTTParty.get(BASE_URL + term + "&location=#{city}", format: :json) response_array = initial_response["events"]["event"] if initial_response["total_items"] != "0" @event_instances = [] if initial_response["total_items"].to_i == 1 @event_instances << Event.create_from_eventful(response_array) elsif initial_response["total_items"].to_i > 1 response_array.each do |event| temp = Event.create_from_eventful(event) @event_instances << temp end end @event_instances end end
true
6dc23cfda29fbf5c6169af1c5801f89668cebcbd
Ruby
kdors007/gitprobz
/my_methods.rb
UTF-8
226
3.09375
3
[]
no_license
def add_nums(a, b) = return a + b end def fizzbuzz(num) if num % 3 == 0 && num % 5 == 0 "fizzbuzz" elsif num % 3 == 0 "fizz" elsif num % 5 == 0 "buzz" else num end end def suctract(b,a) a-b end
true
53849d5fa6ff9f5819ab044b33180963a278f9e5
Ruby
elikantor/sinatra-nested-forms-lab-superheros-nyc-clarke-web-100719
/app/controllers/application_controller.rb
UTF-8
1,209
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'sinatra/base' class App < Sinatra::Base set :views, Proc.new { File.join(root, "../views/") } get '/' do erb :new_team end # eate a Team and Heroes! </title> # <form method="POST" action="/team"> # <p>Team Name: <input type="text" name="name"></p> # <p>Motto: <input type="text" name="motto"></p> # <h1> Hero 1 </h1> # <p>Hero Name: <input type="text" name="name"></p> # <p>Hero Power: <input type="text" name="power"></p> # <p>Hero Biography: <input type="text" name="biography" post '/teams' do @team_name = params["team"]["name"] @motto = params["team"]["motto"] @hero1_name = params["team"]["members"][0]["name1"] @power1 = params["team"]["members"][0]["power1"] @bio1 = params["team"]["members"][0]["bio1"] @hero2_name = params["team"]["members"][0]["name2"] @power2 = params["team"]["members"][0]["power2"] @bio2 = params["team"]["members"][0]["bio2"] @hero3_name = params["team"]["members"][0]["name3"] @power3 = params["team"]["members"][0]["power3"] @bio3 = params["team"]["members"][0]["bio3"] # binding.pry erb :super_hero end end
true
61a79448eb08d9f744bfb1913330afa0cfbaea2c
Ruby
radkin/findme_demo
/lib/parse/startpage.rb
UTF-8
838
2.578125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require_relative '../parser' # startpage specific search engine parsing attributes and methods class Startpage def initialize(query_result) @parser = Parser.new(query_result) @query_result = query_result end def gather_all_links @links = @parser.gather_raw_links direct_links = [] search_queries = [] # filter these from list of direct links startpage_filters = ['www.startpage.com', 'support.startpage.com', 'www.startmail.com'] sf = Regexp.union(startpage_filters) # direct links @links.each do |link| direct_links.push(link) if link.match('https') && !link.match(sf) end all_links = { 'direct' => direct_links, 'search_queries' => search_queries } all_links end end
true
46d622b8ec14dd7f7111817bbcf6e583f3c5c2d4
Ruby
CodingMBA/lesson_5
/pp5.rb
UTF-8
572
3.5625
4
[]
no_license
munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } male_hash = munsters.select { |_, v| v["gender"] == "male" } male_age_sum = 0 male_hash.each do |_, v| male_age_sum += v["age"] end puts male_age_sum # Refactored male_age_sum = 0 munsters.each_value do |stats| male_age_sum += stats["age"] if stats['gender'] == 'male' end puts male_age_sum
true
260b39089242fa8e5222f79dd432113dd46f1d0c
Ruby
codehabit/stat_patient
/lib/live_state.rb
UTF-8
768
2.609375
3
[]
no_license
class LiveState class << self @@state = {} def latest(practitioner_id) @@state[practitioner_id] end def register_latest(practitioner_id, cases) @@state[practitioner_id] = cases end def diff(practitioner_id, cases) current = @@state[practitioner_id] current_hash = {}.tap {|memo| current.each {|c| memo[c.id] = c}} incoming_hash = {}.tap {|memo| cases.each {|c| memo[c.id] = c}} candidates = cases - current candidates.tap do |memo| current_hash.each do |k,v| candidate_for_diff = incoming_hash[k] if candidate_for_diff.present? && candidate_for_diff.updated_at > v.updated_at memo << candidate_for_diff end end end end end end
true
d038f9085c12fcdc4c7d352839de7802d482338a
Ruby
src256/imagetools
/lib/imagetools/imageblog.rb
UTF-8
4,813
2.84375
3
[ "MIT" ]
permissive
# coding: utf-8 # imagehugo: hugo用の画像処理。リネームとサムネイル&アイキャッチ画像の生成。 require 'imagetools/version' require 'imagetools/imagefilter' require 'rmagick' require 'optparse' require 'fileutils' module Imagetools class ImageItem attr_accessor :srcfile, :dstfile, :outfile def to_s "#{srcfile}=>#{dstfile}=>#{outfile}" end end class Imageblog def self.run(argv) STDOUT.sync = true opts = {} opt = OptionParser.new(argv) opt.version = VERSION opt.banner = "Usage: #{opt.program_name} [-h|--help] <dir> or <image1 image2 image3 ...>" opt.separator('') opt.separator("Examples:") opt.separator(" #{opt.program_name} ~/tmp # concat two recent IMG_*jpg images.") opt.separator(" #{opt.program_name} image1.jpg image2.jpg image3.jpg # concat specified images.") opt.separator('') opt.separator("Options:") opt.on_head('-h', '--help', 'Show this message') do |v| puts opt.help exit end opt.on('-v', '--verbose', 'Verbose message') {|v| opts[:v] = v} opt.on('--dry-run', 'Message only') {|v| opts[:dry_run] = v} opt.on('-o OUTDIR', '--output=OUTDIR', 'Output dir') {|v| opts[:o] = v} opt.on('-n NUM', '--number=NUM', 'Process image number') {|v| opts[:n] = v.to_i} opt.on('-b BASENAME', '--base=BASENAME', 'Output file basename') {|v| opts[:b] = v} opt.parse!(argv) opts[:b] ||= Time.now.strftime("%Y%m%d") dir, image_files = get_image_files(opts, argv) if image_files.size == 0 puts opt.help exit end command = Imageblog.new(opts) command.run(dir, image_files) end def self.get_image_files(opts, argv) image_files = [] # ディレクトリが処理対象かどうかを決める dir = nil if argv.size == 1 # 引き数が1個の場合は最初の引き数 path = File.expand_path(argv[0]) if FileTest.directory?(path) dir = path end elsif argv.size == 0 # 引き数がない場合カレントディレクトリ dir = File.expand_path('.') end if dir concat_number = opts[:n] || 2 # ディレクトリが指定されていた場合、指定ディレクトリ内のIMG_ファイルの最新n個を対象とする # 最新の基準は(ファイル名基準) match_files = Dir.glob("#{dir}/*.{jpg,jpeg,png}", File::FNM_CASEFOLD).sort # match_files.sort {|a, b| # File.mtime(a) <=> File.mtime(b) # } # 後ろからn個を取得(小さい方の数とする) count = [match_files.size, concat_number].min image_files = match_files[-count..-1] else # それ以外は指定された引き数を全て対象とする argv.each do |arg| arg = File.expand_path(arg) dir = File.dirname(arg) if FileTest.file?(arg) && (arg =~ /\.jpe?g$/i || arg =~ /\.png/i) image_files << arg end end end return dir, image_files end def initialize(opts) @opts = opts end def run(dir, image_files) outdir = dir if @opts[:o] outdir = @opts[:o] end rename_images(image_files, outdir) # concat_images(image_files, output_path) end private def rename_images(image_files, outdir) # サムネイルはhoge_0.jpg # アイキャッチはhoge_1.jpg hoge_2.jpg以降が通常の画像 items = [] thumbnal_item = nil # hoge_0.jpgとする image_files.each_with_index do |image_file, index| item = ImageItem.new item.srcfile = image_file src_basename = File.basename(image_file) extname = File.extname(src_basename) dst_basename = @opts[:b] item.dstfile = File.join(outdir, "#{dst_basename}_#{index + 1}#{extname}") if index == 0 thumbnal_item = ImageItem.new thumbnal_item.srcfile = image_file thumbnal_item.dstfile = File.join(outdir, "#{dst_basename}_0#{extname}") end items << item end items.each do |item| FileUtils.cp(item.srcfile, item.dstfile) end FileUtils.cp(thumbnal_item.srcfile, thumbnal_item.dstfile) #フィルタ実行 config = Config.new config.init_default opts = {} filter = Imagefilter.new(opts, config) items.each do |item| item.outfile = filter.run(item.dstfile) end # サムネイル config.resize_width = 400 filter = Imagefilter.new(opts, config) thumbnal_item.outfile = filter.run(thumbnal_item.dstfile) end end end
true
91a0ecc2549c4cae8d4b0153210ab19b7cfd9cbe
Ruby
gibbarko/Intro_to_ruby
/methods/method_chain.rb
UTF-8
408
3.9375
4
[]
no_license
=begin - this is method chaining def add_three(n) new_value = n + 3 puts new_value new_value end add_three(5).times { puts "this should print 8 times"} =end #Method calls as arguments def add(a, b) a + b end def subtract(a, b) a - b end def multiply(num1, num2) num1 * num2 end puts multiply(add(20, 45), subtract(80, 10)) puts add(subtract(80, 10), multiply(subtract(20, 6), add(30, 5)))
true
d5bff7b1d608f192be80505e2bcfdd7d13f05284
Ruby
chad-tung/week2_day3_snakes_ladders
/game.rb
UTF-8
1,435
3.78125
4
[]
no_license
class Game def initialize(name, players, board, dice) @name = name @players = players @board = board @dice = dice end def check_ladder(player) for number in @board.get_ladder_hash() if player.get_position == number[:start_point] player.set_position(number[:end_point]) puts "#{player.get_name} climbed up a ladder to #{player.get_position}!" end end return player.get_position end def check_snake(player) for number in @board.get_snake_hash() if player.get_position == number[:start_point] player.set_position(number[:end_point]) puts "#{player.get_name} was eaten by a snake and deficated to square #{player.get_position}. Oh strawberry!" end end return player.get_position end def check_win() for player in @players if player.get_position >= 100 puts "#{player.get_name} has won!" return true end end end def player_turn(player) player.roll_dice(@dice) check_ladder(player) check_snake(player) end def start() until check_win() == true for player in @players player_turn(player) puts player.get_position end end end end
true
f545f65d5fdf3239387ee275919648a381ee4b41
Ruby
paul-christmann/project-euler
/ruby/spec/unit/util/fibonacci_spec.rb
UTF-8
2,089
3.234375
3
[]
no_license
require 'project_euler/util/fibonacci' include ProjectEuler::Util describe Fibonacci do describe 'calculate fibonacci recursive' do it 'should calculate last' do f = Fibonacci.new(:count => 7) f.fibonacci.should == 13 end it 'should calculate last' do f = Fibonacci.new(:count => 7, :first => 1, :second => 2) f.fibonacci.should == 34 end it 'should calculate last' do Fibonacci.fibonacci(7).should == 13 end end describe 'calculate fibonacci' do it 'should initialize values' do f = Fibonacci.new(:maximum => 9) f.maximum.should == 9 f.count.should be_nil f = Fibonacci.new(:count => 10) f.count.should == 10 f.maximum.should be_nil f = Fibonacci.new(:count => 10, :maximum => 10) f.count.should == 10 f.maximum.should be_nil end it 'should initialize first/second' do f = Fibonacci.new(:count => 5) f.first.should == 0 f.second.should == 1 end it 'should be valid' do f = Fibonacci.new(:count => 5) f.valid?.should be_true end it 'should calculate series' do f = Fibonacci.new(:count => 6) f.series.length.should == 6 f.series[0].should == 0 f.series[1].should == 1 f.series[2].should == 1 f.series[3].should == 2 f.series[4].should == 3 f.series[5].should == 5 end it 'should calculate series with counters' do f = Fibonacci.new(:count => 4, :first => 3, :second => 20) f.series.length.should == 4 f.series[0].should == 3 f.series[1].should == 20 f.series[2].should == 23 f.series[3].should == 43 end it 'should calculate series with maximum' do f = Fibonacci.new(:maximum =>20) f.series.length.should == 8 f.series[0].should == 0 f.series[1].should == 1 f.series[2].should == 1 f.series[3].should == 2 f.series[4].should == 3 f.series[5].should == 5 f.series[6].should == 8 f.series[7].should == 13 end end end
true
c1c21a58f3e2ffee5bb587c1d45ffef631c8af42
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/88f94ccd33d44844af0a5a4f7837c459.rb
UTF-8
272
3.171875
3
[]
no_license
class Hamming def self.compute(seg1, seg2) return 0 unless seg1.length == seg2.length seg1_array = seg1.split('') seg2_array = seg2.split('') strands = seg1_array.zip(seg2_array) strands.collect{ |e,f| 1 if e != f }.compact.inject(:+) || 0 end end
true
4a8b5c21bf845c79db15675267434b002afa5666
Ruby
fiddler-crabs-2014/ESA
/view.rb
UTF-8
3,266
3.453125
3
[]
no_license
#require_relative 'controller.rb' class Interface ###Display attr_reader :username, :password def initialize end def self.who_are_you#(name) puts "Welcome to NYCSuggester!" puts "Create a new user with: new" #<username>" puts "Log in as a user with: login" # <username>" sign_in = gets.chomp Controller.authenticate(sign_in) end def self.ask_for_credentials @username = Interface.prompt_user("Please enter your username:") #@password = Interface.prompt_user("Please enter your password:") end def self.ask_for_new_credentials @username = Interface.prompt_user("Please enter your desired username:") @location = Interface.prompt_user("Please enter your current location:") credentials = [@username,@location] #@password = Interface.prompt_user("Please enter your password:") end def self.prompt_user(message) puts "#{message}" input = gets.chomp end def self.menu_options puts "\n" puts "Here are your options #{@username}:" puts "Add a new place to my own list: new" puts "Add/Rate a place I have visited: rate" puts "Randomly generate a place to visit: suggest" puts "Show all places in NYC: show all" puts "Show all places I have added: my list" puts "Show all places I have been to: visited" puts "Exit by typing: exit" choice = Interface.prompt_user("What would you like to do?:") if choice.match(/exit/i) Interface.end_app else Controller.menu_choice(choice) end Interface.menu_options end def self.add_place puts "\n" name = prompt_user("Please input the name of the location:") address = prompt_user("Please enter the address of the location:") category_id = prompt_user("What kind of place is this (please enter 1-3)?\n1. Bar\n2 .Restaurant\n3. Club") {name: name, address: address, category_id: category_id} end def self.rate_place puts "\n" name = prompt_user("What is the name of the location you'd like to rate?:") rating = prompt_user("What is the rating for this location between 1-5?:") {name: name, rating: rating} end def place_yet?(name) end def self.suggest_place(arg) puts "\n" puts "You should check #{arg} out!!!" end def self.display_table(*args) puts "\n" #p args args.each{ |item| puts item} end def self.end_app puts "\n" puts "Have a good day, #{@username}! Eat more!" abort end def self.user_error puts "I'm sorry, there seemed to a user with that username." Interface.ask_for_new_credentials end def self.place_error puts "I'm sorry, I don't believe that place is in our database." puts "You will have to enter it as a new place." Interface.menu_options end def self.sign_in_error puts "I'm sorry, there seemed to a problem with that username and/or password." Interface.ask_for_credentials #prompt_user("Please try again.") end def self.error puts "\n" puts "I'm sorry, there seemed to be a problem with that input." puts "\n" #Interface.menu_options end def delete_place(place) end end
true
8bf6a9de1b4d525bdb1758b0e63b612952d38faa
Ruby
zacharytwhite/project-euler-solutions
/project_euler_rb/problem_033.rb
UTF-8
559
3.5
4
[]
no_license
# The fraction 49/98 is a curious fraction, as an inexperienced mathematician, in attempting to # simplify it, may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. # We shall consider fractions like, 30/50 = 3/5, to be trivial examples. # There are exactly four non-trivial examples of this type of fraction, less than one in value, # and containing two digits in the numerator and denominator. # If the product of these four fractions is given in its lowest common terms, find the value of the denominator. # No
true
10bc81c8b6d0cd48ce0a18f142bfd1a20f3f9e9f
Ruby
miroosama/ruby-collaborating-objects-lab-web-010818
/lib/mp3_importer.rb
UTF-8
265
2.84375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class MP3Importer attr_accessor :path def initialize(path) @path = path end def files @files = Dir["#{path}/*.mp3"] @files.map{|file| file.split("/mp3s/")[1]} end def import files.each{|file| Song.new_by_filename(file)} end end
true
a0be27a5eeadf84d7b21eef48ac1426362c43c9a
Ruby
kamilsdz/radio
/api/server.rb
UTF-8
1,180
2.8125
3
[]
no_license
require "socket" require_relative "request" module Api class Server def initialize(port:, routing:) @port = port @routing = routing end def run server = TCPServer.new(port) while session = server.accept begin if process_request(session.recv(5000)) respond_ok(session) else respond_with_error(session) end rescue Errno::EPIPE ensure session.close end end end private attr_reader :port, :routing def process_request(raw_request) return false if raw_request.empty? request = Request.new(raw_request) route = routing.match(request) return false if route.nil? route.to.call true end def respond_ok(session) session.print "HTTP/1.1 200\r\n" session.print "Content-Type: text/html\r\n" session.print "\r\n" session.print "OK" end def respond_with_error(session) session.print "HTTP/1.1 422\r\n" session.print "Content-Type: text/html\r\n" session.print "\r\n" session.print "Unable to process command" end end end
true
d6a060f4cbc0752178e879adeb6d57efb5aea0b2
Ruby
laurentqro/command_line_games_inc
/lib/tic_tac_toe/computer.rb
UTF-8
1,285
3.3125
3
[]
no_license
require 'tic_tac_toe/game_state' class Computer attr_reader :mark def initialize(mark: nil) @mark = mark end def pick_move(board) minimax(game_state: GameState.new(board: board, current_player_mark: mark, max_player_mark: mark)) end private def minimax(game_state:, depth: 0, spot_scores: {}) return game_state.score if game_state.terminal? next_player_mark = (game_state.current_player_mark == "X" ? "O" : "X") game_state.board.available_spots.each do |spot| new_board = Board.new(grid: game_state.board.grid.dup) next_board = new_board.mark(spot, game_state.current_player_mark) next_game_state = GameState.new(board: next_board, current_player_mark: next_player_mark, max_player_mark: mark) spot_scores[spot] = minimax(game_state: next_game_state, depth: depth +=1, spot_scores: {}) end if depth == game_state.board.available_spots.length return spot_scores.max_by { |spot, score| score }[0] end if game_state.current_player_mark == mark return spot_scores.max_by { |spot, score| score }[1] end if game_state.current_player_mark == opponent_mark return spot_scores.min_by { |spot, score| score }[1] end end def opponent_mark mark == "X" ? "O" : "X" end end
true
a79e7356b34952c7fafa77ca6be332a666d25825
Ruby
sandagolcea/Ruby
/katas/anagrams.rb
UTF-8
687
3.90625
4
[]
no_license
def anagram(string1, string2) return false if string1.size != string2.size hash = {} string1.split(//).each do |letter| if !hash[letter] hash[letter] = 1 else hash[letter] += 1 end end string2.split(//).each do |letter| if !hash[letter] # not anagram puts('not an anagram') return false else hash[letter] -= 1 if hash[letter] == 0 # remove element hash.delete(letter) end end end hash.size == 0 end # puts "anagram" if anagram('dfsfa', 'dfsfa') # puts "anagram" if anagram('dfsfa', 'dafsf') # puts "anagram" if anagram('dfsfa', 'dfsddfa') # puts "anagram" if anagram('dfsfa', 'daf')
true
6e9ae4c1159fecc6c825e70e810c19e033d173f2
Ruby
mkrisher/katas
/ruby/balancer/1/balancer_spec.rb
UTF-8
1,188
3.234375
3
[]
no_license
require 'rspec' require 'pry' require_relative 'balancer' describe Balancer do let(:word) { "stead" } subject { Balancer.new(word) } describe "#run" do it "returns the word with the balance point delimited by spaces" do expect(subject.run).to eq("s t ead") end end context "private api" do describe "#letter_weight" do it "returns the weight of a letter based on position in the alphabet" do expect(subject.send(:letter_weight, "s")).to eq(19) end end describe "#left_side" do let(:index) { 1 } it "returns the weight of the letters on the left side of the expected balance point" do expect(subject.send(:left_side, index)).to eq(19) end end describe "#right_side" do let(:index) { 1 } it "returns the weight of the letters on the right side of the expected balance point" do expect(subject.send(:right_side, index)).to eq(19) end end describe "#balanced?" do let(:index) { 1 } it "returns true if the left side and right side scores are equal" do expect(subject.send(:balanced?, index)).to eq(true) end end end end
true
d8de606abba35e4e014bd77de769fcd81791e493
Ruby
anthonyb/scramble
/scramble_pair.rb
UTF-8
3,565
3.765625
4
[]
no_license
class ScramblePair EXCEPTIONS = [ "AI","AY","EA","EE","EO","IO","OA","OO","OY","YA", "YO","YU","BL","BR","CH","CK","CL","CR","DR","FL", "FR","GH","GL","GR","KL","KR","KW","PF","PL","PR", "SC","SCH","SCR","SH","SHR","SK","SL","SM","SN","SP", "SQ","ST","SW","TH","THR","TR","TW","WH","WR" ] #---------------------------------------------# def initialize(regular_text, scrambled_text) @regular_text = regular_text @scrambled_text = scrambled_text end #---------------------------------------------# def check_scramble_quality if !is_scrambled? puts "#{@scrambled_text} is not a scramble of #{@regular_text}" elsif is_poor_scramble? puts "#{@scrambled_text} is a poor scramble of #{@regular_text}" elsif is_good_scramble? puts "#{@scrambled_text} is a good scramble of #{@regular_text}" else puts "#{@scrambled_text} is a fair scramble of #{@regular_text}" end end #---------------------------------------------# def is_scrambled? @regular_text != @scrambled_text end #---------------------------------------------# def is_poor_scramble? if first_char_in_same_place? return true end if consecutive_chars_in_same_place? return true end false end #---------------------------------------------# def is_good_scramble? unless looks_real? return false end true end #---------------------------------------------# def looks_real? @scrambled_text.length.times do |index| next if @scrambled_text[index+1] == nil #check for two vowels or two consonant in a row if is_vowel?(@scrambled_text[index]) if is_vowel?(@scrambled_text[index+1]) if !meets_exception? index return false end end else #consonant by default if is_consonant? @scrambled_text[index+1] if !meets_exception? index return false end end end end true end #---------------------------------------------# def first_char_in_same_place? @regular_text[0] == @scrambled_text[0] end #---------------------------------------------# def consecutive_chars_in_same_place? @regular_text.split('').each_cons(2) do |chars| merged_chars = chars.join('') if @regular_text.index(merged_chars) == @scrambled_text.index(merged_chars) return true end end false end #---------------------------------------------# def any_chars_in_same_place? @regular_text.length.times do |index| if @regular_text[index] == @scrambled_text[index] return true end end false end #---------------------------------------------# def is_consonant?(letter) !is_vowel? letter end #---------------------------------------------# def is_vowel?(letter) "aeiouy".include? letter.downcase end #---------------------------------------------# def meets_exception?(index) char1 = @scrambled_text[index] char2 = @scrambled_text[index+1] char3 = @scrambled_text[index+2] #two consonants in a row are ok if they are the same if (char1 == char2) and (is_consonant?(char1) and is_consonant?(char1)) return true end composed_chars = char1+char2 if EXCEPTIONS.include? composed_chars return true end if char3 != nil composed_chars = composed_chars+char3 if EXCEPTIONS.include? composed_chars return true end end false end end
true
ed56f2ce2f35a1f655ec906b00dc9c2f31dfaef3
Ruby
IIIIIIIIll/RubyQuizess
/Quiz4/question20.rb
UTF-8
152
2.53125
3
[]
no_license
snowy_owl={ 'type'=>'bird', 'diet'=>'Carnivore', 'life_span'=>'10 years' } snowy_owl.select do |key,value| p value if key=='type' end
true
cf934e890c01b24550fd75dad3d9cc34cfca5129
Ruby
takagotch/o2
/thread/thread_safe.rb
UTF-8
2,467
2.921875
3
[]
no_license
class MyCommandHandler def initialize make_threadsafe_by_stateless end def call(cmd) local_var = cmd.something output(local_var) end private def make_threadsafe_by_stateless freeze end def output(local_var) puts(local_var) end end CMD_HANDLER = MyCommandHandler.new class MyComanndHandler def initialize make_threadsafe_by_stateless end def call(cmd) @ivar = cmd.something output end private def make_threadsafe_by_stateless freeze end def output puts(@ivar) end end class MyCommandHandler def initialize(repository, adapter) @repository = repository @adapter = adapter make_threadsafe_by_stateless end def call(cmd) obj = @repository.find(cmd.id) obj.do_something @repository.update(obj) @adapter.notify(SomethingHappened.new(cmd.id)) end private def make_threadsafe_by_stateless freeze end end require 'concurrent' class Subscribers def initialize @subscribers = Concurrent::ThreadLocalVar.new{ [] } end def add_subscriber(subscriber) @subscribers.value += [subscriber] end def notify @subscribers.value.each(&:call) end def remove_subscriber(subscriber) @subscribers.value -= [subscriber] end end SUBSCRIBERS = Subscribers.new require 'thread' class Subscribers def initialize @semaphore = Mutex.new @subscribers = [] end def add_subscriber(subscriber) @semaphore.synchronize do @subscribers += [subscriber] end end def notify @subscribers.each(&:call) end def remove_subscriber(subsriber) @semaphore.synchronize do @subscribers -= [subscriber] end end end SUBSCRIBERS = Subscribers.new require 'concurrent' class Subscribers def initialize @subscribers = Concurrent::Array.new end def add_subscriber(subscriber) @subscribers << subscriber end def notify @subscribers.each(&:call) end def remove_subscriber(subscriber) @subscribers.delete(subscriber) end end SUBSCRIBERS = Subscribers.new class MyCommandHandler def initialize(repository, adapter) @repository = repository @adapter = adapter end def call(cmd) @obj = @repository.find(cmd.id) @obj.do_something @repository.update(@obj) @adapter.notify(SomethingHappend.new(cmd.id)) end end CMD_HANDLER = -> (cmd) { MyCommandHandler.new(Repository.new, Adapter.new).call(cmd) }
true
beb7131b84b698107e4ab636b07ab570d55cb21a
Ruby
johnjvaughn/ls_ruby_intro
/exercises/ex04.rb
UTF-8
97
3.09375
3
[]
no_license
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts arr.inspect arr << 11 arr.unshift(0) puts arr.inspect
true
ee2c5bd631c606455f499d171508293e08e2da36
Ruby
prrn-pg/Shojin
/Practice/AOJ/ALDS1/ALDS1_03/ALDS1_03B/alds1_03b.rb
UTF-8
636
3.375
3
[]
no_license
# 余った分は考えないらしい n, q = gets.chomp.split.map(&:to_i) queue = [] n.times do queue.push(gets.chomp.split.map{|x| x.match?(/^\d+$/) ? x.to_i : x}) end # 入力された順に処理する # FIFOは頭からいれてケツから出すという意識があるので queue.reverse! count = 0 # 経過時間 loop do break if queue.size.zero? # rubyではケツから取り出すのはpop t = queue.pop count += [t[1], q].min t[1] = [0, t[1]-q].max if t[1].zero? puts "#{t[0]} #{count}" else # rubyでは先頭にぶちこむのはunshift queue.unshift(t) end end
true
d75aa54761338920fe99eeab11db77d7a7f5cf88
Ruby
novakun/CFstuff
/Ruby/program.rb
UTF-8
104
3.765625
4
[]
no_license
def greeting puts "Hey, man, what's your name?" name = gets.chomp puts "Hey " + name end greeting
true
cf0ff82fa63c019c307a9f9446a4f79c5903207c
Ruby
atownley/tecode-ruby
/lib/tecode/time.rb
UTF-8
4,702
3.15625
3
[]
no_license
#-- ###################################################################### # # Copyright (c) 2005-2016, Andrew S. Townley # All rights reserved. # # Permission to use, copy, modify, and disribute this software for # any purpose with or without fee is hereby granted, provided that # the above copyright notices and this permission notice appear in # all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL # WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE # AUTHORS BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT OR # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # File: time.rb # Author: Andrew S. Townley # Created: Mon Aug 22 19:01:26 IST 2005 # ###################################################################### #++ #++ # Add a tstamp method to the Time class because it doesn't # support sub-second values class Time # Print the timestamp with the optional precision (default # is 100ms). Minimum precision is 1ms def Time.tstamp(*args) prec = 4 time = nil if args.length == 0 time = Time.now else time = args[0] end if args.length == 2 prec = args[1] + 1 prec = 1 if prec < 1 end if prec == 0 sprintf("%04d-%02d-%02dT%02d:%02d:%02d", time.year, time.month, time.day, time.hour, time.min, time.sec) else sprintf("%04d-%02d-%02dT%02d:%02d:%02d%s", time.year, time.month, time.day, time.hour, time.min, time.sec, (time.to_f - time.to_i).to_s[1..prec]) end end # Ensure that the timstamp is UTC instead of local time def Time.tstampz(*args) if args.length == 0 args << Time.now.getutc end "#{Time.tstamp(*args)}Z" end def tstamp(*args) Time.tstamp(self, *args) end def tstampz(*args) Time.tstampz(self.getutc, *args) end end module TECode # This class is used to track processing time for a # particular object. class TimerDecorator attr_reader :created attr_reader :obj # This method is used to determine how long the object has # been timed. def elapsed Time.now - @created end def to_s "[TimerDecorator: created = #{@created}; elapsed = #{self.elapsed}; object=#{@obj}]" end # This method is used to wrap the object in an decorator # used to gather timing statistics. def initialize(obj = nil, &block) @created = Time.now @obj = obj if !block.nil? block.call end end # This method resets the time created for the object to # now. def reset @created = Time.now end def <=>(rhs) if rhs.is_a? TimerDecorator # puts "rhs: #{obj}: #{rhs.inspect}; #{self.created <=> rhs.created}" return self.created <=> rhs.created end super end def method_missing(method, *args, &block) @obj.send(method, *args, &block) end end SEC_IN_DAY = 86400 SEC_IN_HOUR = 3600 # This method returns a hash containing the number of # days, hours and minutes of uptime. def self.calc_uptime(seconds) result = {} # I'm sure there's a better way, but it's 2AM... x = seconds / 60 result["hours"] = (x / 60).to_i result["minutes"] = (x - (60 * result["hours"])).to_i result["days"] = (result["hours"] / 24).to_i result["hours"] = (result["hours"] - (24 * result["days"])).to_i result["seconds"] = seconds - (SEC_IN_DAY*result["days"] + SEC_IN_HOUR*result["hours"] + 60*result["minutes"]) result end def self.format_uptime(seconds) return "0s" if seconds == 0 ut = calc_uptime(seconds) s = "" s << "%dd" % ut["days"] if ut["days"] > 0 s << "%dh" % ut["hours"] if ut["hours"] > 0 s << "%dm" % ut["minutes"] if ut["minutes"] > 0 s << "%0.5fs" % ut["seconds"] end class TimingContext < TimerDecorator def to_s "%0.5f" % elapsed end def started "Task #{obj} started at #{@created}" end def status "Task #{obj} running for #{self}" end def completed "Task #{obj} completed in #{self}" end def puts(msg) STDOUT.puts "Task #{obj} at #{self}: #{msg}" end end def self.time(desc, verbose = false, &block) return if block.nil? tc = TimingContext.new(desc) puts tc.started if verbose rval = block.call(tc) puts tc.completed if verbose rval end end
true
0693bfd43c5de9a934682fe8550f1a6b8aa87e21
Ruby
pomidorus/bazis
/app/models/vipiska_file.rb
UTF-8
1,686
2.59375
3
[]
no_license
# encoding: utf-8 class VipiskaFile < ActiveRecord::Base attr_accessible :download_count, :file_name, :upload_at, :file_size, :file_for_data, :files_count_in M_RUS_SHORT = ['','янв','фев','мар','апр','май','июн','июл','авг','сен','окт','ноя','дек'] def month_short M_RUS_SHORT[file_for_data.month] end def year "#{file_for_data.year}" end def day "#{file_for_data.day}" end def date_ukr y = upload_at.year m = upload_at.month m_ukr = ['sicen','dod','sicen','sicen','sicen','sicen','sicen','sicen','sicen','sicen','sicen','sicen'] m_rus = ['','январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь'] d = upload_at.day return "#{d} #{m_rus[m]}" end def file_ext file_name[-3,3].downcase end def file_name_ex s = file_name.split('.') return s[0] end def file_upload_data "#{upload_at.day} #{upload_at.month_to_word} #{upload_at.year}" end def file_upload_data_small "#{upload_at.day}.#{upload_at.month}.#{upload_at.year}" end def file_data if !file_for_data.nil? "#{file_for_data.day} #{file_for_data.month_to_word} #{file_for_data.year}" elsif "" end end def file_data_small "#{file_for_data.day}.#{file_for_data.month}.#{file_for_data.year}" end def self.today_vp VipiskaFile.find_all_by_upload_at Date.today, :order => "created_at desc" end def self.last_vp(_limit) VipiskaFile.where("upload_at < :date", :date => Date.today).order("created_at desc").limit(_limit) end end
true
9c4beaf7e24e9775ed5aded01c49e04e2b0128ef
Ruby
comsi02/json-rpc-1-1
/lib/json_rpc_client.rb
UTF-8
8,147
2.78125
3
[]
no_license
# # This is the JSON-RPC Client, the handler for the client side of a JSON-RPC # connection. # class JsonRpcClient require 'json' require 'net/http' require 'uri' # # Our runtime error class. # class Error < RuntimeError; end class ServiceError < Error; end class ServiceDown < Error; end class NotAService < Error; end class ServiceReturnsJunk < Error; end # # Execute this "declaration" with a string or URI object describing the base URI # of the JSON-RPC service you want to connect to, e.g. 'http://213.86.231.12/my_services'. # NB: avoid DNS host names at all costs, since Net::HTTP can be slow in resolving them. # If there is a proxy, pass :proxy => 'http://123.45.32.45:8080' or similar. # If you pass :no_auto_config => true, no attempt will be made to contact the service # to obtain a description of its available services, which means POST will be used # for all requests. This is sometimes useful when a server is non-compliant and does not # provide a system.describe call. # def self.json_rpc_service(base_uri, opts={}) @uri = URI.parse base_uri @host = @uri.host @port = @uri.port @proxy = opts[:proxy] && URI.parse(opts[:proxy]) @proxy_host = opts[:proxy] && @proxy.host @proxy_port = opts[:proxy] && @proxy.port @procs = {} @get_procs = [] @post_procs = [] @no_auto_config = opts[:no_auto_config] @logger = opts[:debug] @uri end # # Changes the URI for this service. Used in setups where several identical # services can be reached on different hosts. # def self.set_host(newhost=nil, newport=nil, newproxy=nil) @uri.host = @host = newhost if newhost @uri.port = @port = newport if newport if newproxy @proxy = URI.parse(newproxy) @proxy_host = @proxy.host @proxy_port = @proxy.port end @uri end # # This allows us to call methods remotely with the same syntax as if they were local. # If your client object is +service+, you can simply evaluate +service.whatever(:a => 100, :b => [1,2,3])+ # or whatever you need. Positional and named arguments are fully supported according # to the JSON-RPC 1.1 specifications. You can pass a block to each call. If you do, # the block will be yielded to using the return value of the call, or, if there is # an exception, with the exception itself. This allows you to implement execution # queues or continuation style error handling, amongst other things. # def self.method_missing(name, *args) system_describe unless (@no_auto_config || @service_description) name = name.to_s @logger.debug "JSON-RPC call: #{self}.#{name}(#{args.join(',')})" if @logger req_wrapper = @get_procs.include?(name) ? Get.new(self, name, args) : Post.new(self, name, args) req = req_wrapper.req begin begin Net::HTTP.start(@host, @port, @proxy_host, @proxy_port) do |http| res = http.request req if res.content_type != 'application/json' @logger.debug "JSON-RPC server returned non-JSON data: #{res.body}" if @logger raise NotAService, "Returned #{res.content_type} (status code #{res.code}: #{res.message}) rather than application/json" end json = JSON.parse(res.body) rescue raise(ServiceReturnsJunk) raise ServiceError, "JSON-RPC error #{json['error']['code']}: #{json['error']['message']}" if json['error'] @logger.debug "JSON-RPC result: #{self.class}.#{name} => #{res.body}" if @logger return (block_given? ? yield(json['result']) : json['result']) end rescue Errno::ECONNREFUSED raise ServiceDown, "Connection refused" end rescue Exception => e block_given? ? yield(e) : raise(e) end end # # The basic path of the service, i.e. '/services'. # def self.service_path @uri.path end # # The hash of callable remote procs descriptions # def self.procs @procs end # # The logger # def self.logger @logger end # # Host and port as a string # def self.host_and_port "#{@host}:#{@port}" end # # This method is called automatically as soon as a client is created. It polls the # service for its +system.describe+ information, which the client uses to find out # whether to call a remote procedure using GET or POST (depending on idempotency). # You can of course use this information in any way you want. # def self.system_describe @service_description = :in_progress @service_description = method_missing('system.describe') raise "JSON-RPC server failed to return a service description" unless @service_description raise "JSON-RPC server failed to return a standard-compliant service description" unless @service_description['procs'].kind_of?(Array) @service_description['procs'].each do |p| @post_procs << p['name'] @get_procs << p['name'] if p['idempotent'] end @service_description['procs'].each { |p| @procs[p['name']] = p } @service_description end # # This is a simple class wrapper for Net::HTTP::Post and Get objects. # They require slightly different initialisation. # class Request attr_reader :req # # Sets the HTTP headers required for both GET and POST requests. # def initialize @req.initialize_http_header 'User-Agent' => 'Ruby JSON-RPC Client 1.1', 'Accept' => 'application/json' end end # # GET requests are only made for idempotent procedures, which allows these # requests to get cached, etc. (A procedure is declared idempotent on the # service side, by specifying :idempotent => true.) GET requests pass all # their args in the URI itself, as part of the query string. Positional # args are supported, as well as named args. If a call has only a hash # as its only argument, the key/val pairs are used as name/value pairs. # All other situations pass hashes in their entirety as just one of the args # in the arglist. # class Get < Request def initialize(klass, name, args) if args.length == 0 query = '' elsif args.length == 1 && args[0].is_a?(Hash) # If we get an array where the first and only element is a hash, we apply the hash (named args). pairs = [] args[0].each do |key, val| pairs << "#{key}=#{URI.encode val.to_s}" end query = '?' + pairs.join('&') else pairs = [] procpar = klass.procs[name]['params'] args.each_with_index do |val, i| key = procpar[i]['name'] pairs << "#{key}=#{URI.encode val.to_s}" end query = '?' + pairs.join('&') end uri = klass.service_path + '/' + name + query klass.logger.debug "JSON-RPC GET request to URI #{klass.host_and_port}#{uri}" if klass.logger @req = Net::HTTP::Get.new(uri) super() end end # # Unless we know that a procedure is idempotent, a POST call will be used. # In case anyone wonders, GET and POST requests are roughly of the same # speed - GETs require slightly more processing on the client side, while # POSTs require slightly more processing on the service side. Positional # args are supported, as well as named args. If a call has only a hash # as its only argument, the key/val pairs are used as name/value pairs. # All other situations pass hashes in their entirety as just one of the args # in the arglist. # class Post < Request def initialize(klass, name, args) @req = Net::HTTP::Post.new(klass.service_path) super() @req.add_field 'Content-Type', 'application/json' args = args[0] if args.length == 1 && args[0].is_a?(Hash) body = { :version => '1.1', :method => name, :params => args }.to_json @req.body = body klass.logger.debug "JSON-RPC POST request to URI #{klass.host_and_port}#{klass.service_path} with body #{body}" if klass.logger end end end # of JsonRpcClient
true
467d7e74b85e3744dd2ca724aa23ffafaf1f4c4d
Ruby
IanVaughan/twitter-scratch
/friends.rb
UTF-8
2,184
3.09375
3
[]
no_license
require 'rubygems' require 'twitter' require 'pp' def followers_of name print "Getting the followers..." r = Twitter::follower_ids(name) puts "...Done" r end def friends_of name print "Getting your friends..." r = Twitter::friend_ids(name) puts "...Done" r end def twitter copy_to httpauth = Twitter::HTTPAuth.new(copy_to[:name], copy_to[:pass]) Twitter::Base.new(httpauth) end def perform copy_from, copy_to #(user,pass, followers, user_from) followers = followers_of copy_from friends = friends_of copy_from puts "#{copy_from} has #{friends.size} followers, and #{followers.size} people following them..." # if size > 150 # puts '(You have more Friends to Follow than the Rate limit will allow within one hour!)' # end base = twitter copy_to begin base.update("This account is being copied from @#{copy_from} courtesy of @TwitDup") rescue end puts "Remaining hits : #{base.rate_limit_status.remaining_hits}" puts base.rate_limit_status puts "*** Adding follows... ***" count = 0 friends.each do |id| print "#{count+=1}/#{friends.size} - Add Follow #{id}..." #: \"#{Twitter.user(id).name}\"..." begin base.friendship_create(id) print " Done." rescue Exception => e print ' FAIL!' # puts e e.message e.backtrace.inspect end # puts " (Rate limit : #{base.rate_limit_status.remaining_hits})" # if base.rate_limit_status.remaining_hits <= 0 # puts 'No limit left!' # end end puts "*** Requesting friends... ***" followers = [5905182] count = 0 followers.each do |id| name = Twitter.user(id).screen_name print "#{count+=1}/#{followers.size} - Requesting #{id} : @#{name} follow you..." begin base.update("@#{name} Please could you follow me? I am copying this account from @#{copy_from}, many thanks. Courtesy of @TwitDup") puts " Done." rescue puts ' FAIL!' end end base.update('Done. Account has been copied from @#{user_from} courtesy of @TwitDup') end # @TwitDup # Account Duplicator copy_from = 'ianvaughan' copy_to = {:name => 'TwitDup', :pass =>''} perform copy_from, copy_to
true
3de3700d27c6b28e52f2fc50c397fa4eda950908
Ruby
sds/scss-lint
/lib/scss_lint/linter/space_between_parens.rb
UTF-8
3,846
2.859375
3
[ "MIT" ]
permissive
module SCSSLint # Checks for the presence of spaces between parentheses. class Linter::SpaceBetweenParens < Linter include LinterRegistry def check_node(node) check(node, source_from_range(node.source_range)) yield end alias visit_atroot check_node alias visit_cssimport check_node alias visit_function check_node alias visit_media check_node alias visit_mixindef check_node alias visit_mixin check_node alias visit_script_funcall check_node def feel_for_parens_and_check_node(node) source = feel_for_enclosing_parens(node) check(node, source) yield end alias visit_script_listliteral feel_for_parens_and_check_node alias visit_script_mapliteral feel_for_parens_and_check_node alias visit_script_operation feel_for_parens_and_check_node alias visit_script_string feel_for_parens_and_check_node private TRAILING_WHITESPACE = /\s*$/.freeze def check(node, source) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength @spaces = config['spaces'] source = trim_right_paren(source) return if source.count('(') != source.count(')') source.scan(/ \( (?<left>\s*) (?<contents>.*) (?<right>\s*) \) /x) do |left, contents, right| right = contents.match(TRAILING_WHITESPACE)[0] + right contents.gsub(TRAILING_WHITESPACE, '') # We don't lint on multiline parenthetical source. break if (left + contents + right).include? "\n" if contents.empty? # If we're looking at empty parens (like `()`, `( )`, `( )`, etc.), # only report a possible lint on the left side. right = ' ' * @spaces end if left != ' ' * @spaces message = "#{expected_spaces} after `(` instead of `#{left}`" add_lint(node, message) end if right != ' ' * @spaces message = "#{expected_spaces} before `)` instead of `#{right}`" add_lint(node, message) end end end # An expression enclosed in parens will include or not include each paren, depending # on whitespace. Here we feel out for enclosing parens, and return them as the new # source for the node. def feel_for_enclosing_parens(node) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity range = node.source_range original_source = source_from_range(range) left_offset = -1 right_offset = 0 if original_source[-1] != ')' right_offset += 1 while character_at(range.end_pos, right_offset) =~ /\s/ return original_source if character_at(range.end_pos, right_offset) != ')' end # At this point, we know that we're wrapped on the right by a ')'. # Are we wrapped on the left by a '('? left_offset -= 1 while character_at(range.start_pos, left_offset) =~ /\s/ return original_source if character_at(range.start_pos, left_offset) != '(' # At this point, we know we're wrapped on both sides by parens. However, # those parens may be part of a parent function call. We don't care about # such parens. This depends on whether the preceding character is part of # a function name. return original_source if character_at(range.start_pos, left_offset - 1).match?(/[A-Za-z0-9_]/) range.start_pos.offset += left_offset range.end_pos.offset += right_offset source_from_range(range) end # An unrelated right paren will sneak into the source of a node if there is no # whitespace between the node and the right paren. def trim_right_paren(source) source.count(')') == source.count('(') + 1 ? source[0..-2] : source end def expected_spaces "Expected #{pluralize(@spaces, 'space')}" end end end
true
ed5e23b3ccf74f84056599f12b6d3a2f60e0d9e6
Ruby
Bonemind/Queryfy
/lib/queryfy/filter_lexer/formatter.rb
UTF-8
1,312
2.796875
3
[ "MIT" ]
permissive
require 'queryfy/queryfy_errors' module FilterLexer class Filter # Converts a FilterLexer::Filter to an arel node def to_arel(arel_table) # Get the elements we want to operate on field = elements[0].text_value operator_method = elements[1].to_arel val = elements[2].text_value field = Queryfy.get_arel_field(arel_table, field) ast_node = arel_table[field.to_sym] # Build an arel node from the resolved operator, value and field return ast_node.send(operator_method, val) end end # The list below converts Filter::Operators to arel functions class AndOperator def to_arel return 'and' end end class OrOperator def to_arel return 'or' end end class EQOperator def to_arel return 'eq' end end class NEQOperator def to_arel return 'not_eq' end end class LTOperator def to_arel return 'lt' end end class LEOperator def to_arel return 'lteq' end end class GTOperator def to_arel return 'gt' end end class GEOperator def to_arel return 'gteq' end end class NotLikeOperator def to_arel return 'does_not_match' end end class LikeOperator def to_arel return 'matches' end end class StringLiteral def text_value val = super return val.gsub!(/\A["']|["']\Z/, '') end end end
true
b68f4833f3a8ef082c630100a0cbdc9523ee9df0
Ruby
sagarrat7/Scribe
/html/project/emigrant/bot-example.rb
UTF-8
4,126
2.9375
3
[ "MIT" ]
permissive
require 'open-uri' require 'json' require 'cgi' # Useful extension to Hash to create query strings: class Hash def to_params params = '' stack = [] each do |k, v| if v.is_a?(Hash) stack << [k,v] elsif v.is_a?(Array) stack << [k,Hash.from_array(v)] else params << "#{k}=#{v}&" end end stack.each do |parent, hash| hash.each do |k, v| if v.is_a?(Hash) stack << ["#{parent}[#{k}]", v] else params << "#{parent}[#{k}]=#{v}&" end end end params.chop! params end def self.from_array(array = []) h = Hash.new array.size.times do |t| h[t] = array[t] end h end end # Example Scribe bot class: class ScribeBot def initialize(scribe_endpoint) @classifications_endpoint = scribe_endpoint end # Post classification for a known subject_id def classify_subject_by_id(subject_id, workflow_name, task_key, data) params = { workflow: { name: workflow_name }, classifications: { annotation: data, task_key: task_key, subject_id: subject_id } } submit_classification params end # Post classification for subject specified by URL: def classify_subject_by_url(subject_url, workflow_name, task_key, data) params = { subject: { location: { standard: CGI::escape(subject_url) } }, workflow: { name: workflow_name }, classifications: { annotation: data, task_key: task_key } } submit_classification params end # Posts params as-is to classifications endpoint: def submit_classification(params) require 'uri' require "net/http" uri = URI(@classifications_endpoint) req = Net::HTTP::Post.new(uri.path, {'BOT_AUTH' => ENV['SCRIBE_BOT_TOKEN']}) req.body = params.to_params http = Net::HTTP.new(uri.host, uri.port) response = http.start {|http| http.request(req) } begin JSON.parse response.body rescue nil end end end # This simple script demonstrates use of the Scribe Classifications endpoint to generate data # # Useage: # ruby bot-example.rb [-scribe-endpoint="http://localhost:3000"] # options = Hash[ ARGV.join(' ').scan(/--?([^=\s]+)(?:=(\S+))?/) ] options["scribe-endpoint"] = "http://localhost:3000/classifications" if ! options["scribe-endpoint"] args = ARGV.select { |a| ! a.match /^-/ } bot = ScribeBot.new options["scribe-endpoint"] # The following generates generates two classfiications: One mark classification # and one transcription classification (applied to the subject generated by the # mark classification). # Specify subject by standard URL (since this is a bot classification, it will be created automatically if it doesn't exist) image_uri = "https://s3.amazonaws.com/scribe.nypl.org/emigrant-s4/full/619aed10-23fd-0133-16de-58d385a7bbd0.right-bottom.jpg" # Must manually specify workflow name ('mark'), and task_key ('mark_primary') classification = bot.classify_subject_by_url( image_uri, "mark", "mark_primary", { x: 100, y: 200, width: 300, height: 200, subToolIndex: 0 # Must specify subToolIndex (integer index into the tools array configured for workflow task) })['classification'] # Response should contain a classification with a nested child_subject: puts "Created classification: #{classification.to_json}" # Assuming above was successful, use the returned, generated subject_id to create next classification: mark_id = classification['child_subject']['id'] # Subjects generated in Mark tend to have `type`s that correspond to Transcribe task keys: transcribe_task_key = classification['child_subject']['type'] # Create transcription classification: classification = bot.classify_subject_by_id( mark_id, "transcribe", transcribe_task_key, { value: 'foo' }) # Response should contain a classification with a nested verify subject (or orphaned subject if there is no Verify workflow) puts "Created transcription classification: #{classification.to_json}"
true
97f1b2ecf9807007de8254ca4f338dfce6e8b84f
Ruby
gweng1t/exo_ruby
/exo_07.rb
UTF-8
413
3.46875
3
[]
no_license
user_name = gets.chomp puts user_name # gets demande à l'utilisateur d'entrer quelque chose #chomp retire le \n #Le premier programme demande d'entrer son nom puis affiche ce qu'a rentrer l'utilisateur #le 2eme programme demande d'entrer son nom puis affiche un > pour que l'utilisateur voit où il va ecrire #le 3eme n'affiche pas de texte, donc l'utilisateur ne sait pas ce qu'il doit ecrire et quand ecrire
true
8192c0f16f16087a9631a411efdc9fb4fc0da122
Ruby
OpenGotham/tickler
/lib/groper.rb
UTF-8
824
2.625
3
[]
no_license
require 'nokogiri' class Groper attr_reader :urls def initialize @urls = ["Estimizer_Daily_A.xml","Estimizer_Intraday_A.xml"] end def perform # file 1 filename = File.expand_path(File.join('..','..','tmp',Time.now.strftime("%Y%d%m%H%M%L.xml")), __FILE__) `wget -O #{filename} #{self.urls[0]}` parse(IntradayParser, filename) File.unlink(filename) # file 2 filename = File.expand_path(File.join('..','..','tmp',Time.now.strftime("%Y%d%m%H%M%L.xml")), __FILE__) `wget -O #{filename} #{self.url[1]}` parse(DailyParser, filename) File.unlink(filename) end def parse(klass, filename) raise "Unknown parser!" unless [IntradayParser, DailyParser].include?(klass) parser = Nokogiri::XML::SAX::Parser.new(klass.new) parser.parse(File.read(filename)) end end
true
0ff61b6156bb431962cddf2f53eaccb298b132ab
Ruby
randyjap/project-euler
/09.rb
UTF-8
469
3.28125
3
[]
no_license
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a2 + b2 = c2 # For example, 32 + 42 = 9 + 16 = 25 = 52. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. # Answer: 31875000 (1..1000).each do |a| (a..1000).each do |b| c = (1000 - a - b) break puts a * b * c if a * a + b * b == c * c && a + b + c == 1000 end end # real 0m0.221s # user 0m0.128s # sys 0m0.092s
true
e7b8189784dc457e7eb48fe57dcd0c71f6a96b50
Ruby
suturner/ruby-challenges
/test_example.rb
UTF-8
171
3.171875
3
[]
no_license
my_name = 'skillcrush' if my_name == 'skillcrush' puts "helloooooo, skillcrush!" else puts "Ooops, I thought your name was Skillcrush. Sorry about that, #{my_name}!" end
true
29a55baf0b80e9d83addbb7d2b8e39060be47b8f
Ruby
0xack13/panoptimon
/spec/util_spec.rb
UTF-8
1,033
2.546875
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env ruby require 'panoptimon/util' require 'ostruct' describe('os lookup string') { before(:each) { Panoptimon::Util.stub(:_os) { :plan9 } } it('returns correct string') { Panoptimon::Util.os.should == :plan9 } it('returns correct hash value') { Panoptimon::Util.os(plan9: 10, default: 0).should == 10 Panoptimon::Util.os(win32: 'twelve', plan9: 10, default: 0).should == 10 } it('falls-through to a default') { Panoptimon::Util.os(default: 'ok').should == 'ok' } it('dispatches to a proc') { Panoptimon::Util.os(plan9: ->(){7}, default: 0).should == 7 } it('dispatches to a default proc') { Panoptimon::Util.os(default: ->(){'ok'}).should == 'ok' } it('complains loudly if needed') { expect { Panoptimon::Util.os(linux: 7) }.to raise_exception(/^unsupported OS/) } it('can complain selectively') { expect { Panoptimon::Util.os(plan9: ->(){raise "unsupported OS: plan9"}, default: 'ok') }.to raise_exception(/^unsupported OS/) } }
true
d8f8761bf63dd84ea8cfe44f7204b1e5444abc9a
Ruby
ninjudd/priority_queue
/test/priority_queue_test.rb
UTF-8
1,319
2.796875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require File.dirname(__FILE__) + '/test_helper' class PriorityQueueTest < Test::Unit::TestCase should "shift values in priority order" do pq = PriorityQueue.new pq[1] << :important_foo pq[1] << :important_bar pq[0] << :very_important_foo pq[4] << :foo pq[4] << :bar assert_equal :very_important_foo, pq.shift assert_equal :important_foo, pq.shift assert_equal :important_bar, pq.shift assert_equal :foo, pq.shift assert_equal :bar, pq.shift assert_equal nil, pq.shift assert_equal nil, pq.shift end should "know it's own size" do pq = PriorityQueue.new pq[7] << :foo pq[7] << :fu pq[4] << :bar pq[9] << :baz pq[1] << :bap pq[0] << :zap assert_equal 6, pq.size 3.times { pq.shift } assert_equal 3, pq.size 3.times { pq.shift } assert_equal 0, pq.size 3.times { pq.shift } assert_equal 0, pq.size end should "know if it is empty" do pq = PriorityQueue.new assert pq.empty? pq[7] << :foo pq[7] << :fu pq[1] << :bap pq[0] << :zap assert !pq.empty? 3.times { pq.shift } assert !pq.empty? pq.shift assert pq.empty? pq.shift assert pq.empty? end end
true
3245a7394c73625446617b2688ab882a6b74a657
Ruby
IanPFoertsch/Proposition
/lib/proposition/sentence/binary/and.rb
UTF-8
1,588
2.8125
3
[]
no_license
module Proposition class And < BinarySentence def self.compliment Or end def operator_symbol "AND" end def contains_and? true end def to_conjunction_of_disjunctions @left.to_conjunction_of_disjunctions.conjoin(@right.to_conjunction_of_disjunctions) end #TODO this logic is replicated everywhere we are creating CNF sentences, #consolidate this into a module def to_conjunctive_normal_form push_not_down .push_or_down .to_conjunction_of_disjunctions .to_conjunctive_normal_form end def should_distribute_and? return @left.contains_or? || @right.contains_or? end def push_and_down #TODO: This is almost an exact duplicateof logic in push_or_down in the #or sentence class. Figure out a way to consolidate + reuse this logic return self unless should_distribute_and? #first pre-process the left and right subsentences if @left.should_distribute_and? return And.new(@left.push_and_down, @right).push_and_down elsif @right.should_distribute_and? return And.new(@left, @right.push_and_down).push_and_down else if @left.is_atomic? #base case of both atomic components caught by "should_distribute_and" return @right.distribute_and(@left).push_and_down elsif @right.is_atomic? return rotate.push_and_down else # both are non-atomic, we contain an and and should distribute @right.distribute_and(@left).push_and_down end end end end end
true