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
8ae00ce5905feb2bd43ced0274dfd4e69a01128e
Ruby
youngmanr/battle-tom
/spec/player_spec.rb
UTF-8
1,047
3.234375
3
[]
no_license
require 'player' describe Player do subject(:player_1) { described_class.new(player_1_name)} let(:player_1_name) {"Yev"} subject(:player_2) { described_class.new(player_2_name)} let(:player_2_name) {"Andy"} describe '#initialize' do it {is_expected.to respond_to(:name)} end describe '#hp' do it 'is expected to have default hit points' do expect(player_1.hp).to eq described_class::DEFAULT_HP end end describe '#receive_damage' do it 'should reduce the players hp by the amount specified' do expect{ player_1.receive_damage(10) }.to change{ player_1.hp }.by -10 end end describe '#lost?' do it 'returns true when @hp is 0 or less' do player_1.receive_damage(described_class::DEFAULT_HP) expect(player_1.lost?).to eq true end it 'returns false when @hp is above 0' do expect(player_1.lost?).to eq false end end describe '#heal' do it 'heals the player' do expect{ player_1.heal(10) }.to change{ player_1.hp }.by 10 end end end
true
78aa4ec787a85615affd5817519d8b039bd1d9a8
Ruby
AlexanderRD/rby-money
/lib/rby/converter.rb
UTF-8
936
3.125
3
[ "MIT" ]
permissive
module Rby class Converter attr_accessor :currency_hash def initialize(base_currency=nil, currency_hash={}) configure_rates(base_currency, currency_hash) end def configure_rates(base_currency, currency_hash={}) @currency_hash = currency_hash.merge({ base_currency => 1 }) end def determine_amount(account, target_currency) return if account.nil? || target_currency.nil? return account.amount if account.currency == target_currency return unless currency_defined?(target_currency) current_rate = rate_for_currency(account.currency) target_rate = rate_for_currency(target_currency) (account.amount * target_rate).fdiv(current_rate).round(2) end private def currency_defined? currency_name currency_hash.has_key? currency_name end def rate_for_currency currency_name currency_hash.fetch(currency_name, nil) end end end
true
83b77d6c937f566ccd871915a20eb7c9dc47fd6a
Ruby
harrifeng/leet-in-ruby
/086_partition_list.rb
UTF-8
759
3.140625
3
[]
no_license
require 'minitest/autorun' require_relative 'ds/list_node' # MiniTest class class MyTest < Minitest::Test def test_leet_086 a1 = ListNode.get_ln_from_array([1, 4, 3, 2, 5, 2]) e1 = ListNode.get_ln_from_array([1, 2, 2, 4, 3, 5]) assert ListNode.two_ln_equal(e1, partition(a1, 3)) end end # @param {ListNode} head # @param {Integer} x # @return {ListNode} def partition(head, x) return head if head.nil? || head.next.nil? small = ListNode.new(-1) tmp_s = small big = ListNode.new(-1) tmp_b = big until head.nil? if head.val < x small.next = head small = small.next else big.next = head big = big.next end head = head.next end big.next = nil small.next = tmp_b.next tmp_s.next end
true
37295fd77f70f8a5ca59b76684055a6a64a3466f
Ruby
bsingr/opal
/spec/language/string_spec.rb
UTF-8
667
3.46875
3
[ "MIT" ]
permissive
describe "Ruby character strings" do it "don't get interpolated when put in single quotes" do @ip = 'xxx' '#{@ip}'.should == '#{@ip}' end it 'get interpolated with #{} when put in double quotes' do @ip = 'xxx' "#{@ip}".should == "xxx" end it "interpolate instance variables just with the # character" #do # @ip = "xxx" # "#@ip".should == "xxx" # end it "interpolate global variables just with the # character" it "interpolate class variables with just the # character" it "allow underscore as part of a variable name in a simple interpolation" it "have characters [.(=?!# end simple # interpolation" end
true
f2ad62cc77e428d683d19d8531a91d0c08472480
Ruby
theoluyi/ruby-oo-fundamentals-instance-variables-lab-dumbo-web-010620
/lib/dog.rb
UTF-8
311
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Dog def name=(dog_name) @this_dogs_name = dog_name end def name @this_dogs_name end def bark puts "Woof!" end end lassie = Dog.new lassie.name = "Lassie" lassie.name #=> "Lassie" fido = Dog.new fido.name = "Fidospectacular"
true
eb9c47fff41a05951494f69078b1344df5cd5a8f
Ruby
juuh42dias/kind
/test/kind/maybe_test.rb
UTF-8
14,691
2.765625
3
[ "MIT" ]
permissive
require 'test_helper' class Kind::MaybeTest < Minitest::Test def test_maybe_constructor optional = Kind::Maybe.new(0) assert_equal(0, Kind::Maybe.new(optional).value) end def test_maybe_result object = Object.new maybe_result = Kind::Maybe::Result.new(object) assert_same(object, maybe_result.value) assert_raises(NotImplementedError) { maybe_result.none? } assert_raises(NotImplementedError) { maybe_result.some? } assert_raises(NotImplementedError) { maybe_result.map { 0 } } assert_raises(NotImplementedError) { maybe_result.try(:anything) } assert_raises(NotImplementedError) { maybe_result.try { |value| value.anything } } assert_raises(NotImplementedError) { maybe_result.value_or(2) } assert_raises(NotImplementedError) { maybe_result.value_or { 3 } } end def test_maybe_when_some assert_predicate(Kind::Maybe.new(2), :some?) refute_predicate(Kind::Maybe.new(nil), :some?) refute_predicate(Kind::Maybe.new(Kind::Undefined), :some?) end def test_maybe_when_none assert_predicate(Kind::Maybe.new(nil), :none?) assert_predicate(Kind::Maybe.new(Kind::Undefined), :none?) refute_predicate(Kind::Maybe.new(1), :none?) end def test_maybe_value optional1 = Kind::Maybe.new(2) assert_equal(2, optional1.value) # --- optional2 = Kind::Maybe.new(nil) assert_nil(optional2.value) # --- optional3 = Kind::Maybe.new(Kind::Undefined) assert_equal(Kind::Undefined, optional3.value) end def test_maybe_value_or_default assert_nil(Kind::Maybe[nil].value_or(nil)) # --- optional1 = Kind::Maybe.new(2) assert_equal(2, optional1.value_or(0)) assert_equal(2, optional1.value_or { 0 }) # --- optional2 = Kind::Maybe.new(nil) assert_equal(0, optional2.value_or(0)) assert_equal(1, optional2.value_or { 1 }) assert_raises_with_message( ArgumentError, 'the default value must be defined as an argument or block' ) { optional2.value_or } # --- optional3 = Kind::Maybe.new(Kind::Undefined) assert_equal(1, optional3.value_or(1)) assert_equal(0, optional3.value_or{ 0 }) assert_raises_with_message( ArgumentError, 'the default value must be defined as an argument or block' ) { optional3.value_or } end def test_maybe_map_when_none optional1 = Kind::Maybe.new(2) optional2 = optional1.map(&:to_s) optional3 = optional2.map { |value| value * 2 } assert_equal('2', optional2.value) assert_equal('22', optional3.value) assert_predicate(optional2, :some?) assert_predicate(optional3, :some?) refute_predicate(optional2, :none?) refute_predicate(optional3, :none?) refute_same(optional2, optional3) end def test_maybe_when_map_returns_nil optional1 = Kind::Maybe.new(2) optional2 = optional1.map { nil } optional3 = optional2.map { |value| value * 2 } assert_equal(2, optional1.value) assert_same(optional2, optional3) assert_nil(optional2.value) assert_nil(optional3.value) assert_predicate(optional2, :none?) assert_predicate(optional3, :none?) end def test_maybe_when_map_returns_undefined optional1 = Kind::Maybe.new(3) optional2 = optional1.map { Kind::Undefined } optional3 = optional2.map { |value| value * 3 } assert_equal(3, optional1.value) assert_same(optional2, optional3) assert_equal(Kind::Undefined, optional2.value) assert_equal(Kind::Undefined, optional3.value) assert_predicate(optional2, :none?) assert_predicate(optional3, :none?) end def test_maybe_constructor_alias assert_instance_of(Kind::Maybe::Some, Kind::Maybe[1]) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil]) assert_instance_of(Kind::Maybe::None, Kind::Maybe[Kind::Undefined]) # --- assert_instance_of(Kind::Maybe::Some, Kind::Maybe.wrap(1)) assert_instance_of(Kind::Maybe::None, Kind::Maybe.wrap(nil)) assert_instance_of(Kind::Maybe::None, Kind::Maybe.wrap(Kind::Undefined)) end def test_then_as_an_alias_of_map result1 = Kind::Maybe[5] .then { |value| value * 5 } .then { |value| value + 17 } .value_or(0) assert_equal(42, result1) # --- result2 = Kind::Maybe[5] .then { nil } .value_or { 1 } assert_equal(1, result2) # --- result3 = Kind::Maybe[5] .then { Kind::Undefined } .value_or(-2) assert_equal(-2, result3) end def test_the_try_method_without_bang assert_raises_with_message(Kind::Error, '"upcase" expected to be a kind of Symbol') do Kind::Maybe['foo'].try('upcase') end # --- assert_equal('FOO', Kind::Maybe['foo'].try(:upcase).value) assert_equal('FOO', Kind::Maybe['foo'].try { |value| value.upcase }.value) assert_instance_of(Kind::Maybe::Some, Kind::Maybe['foo'].try(:upcase)) assert_instance_of(Kind::Maybe::Some, Kind::Maybe['foo'].try { |value| value.upcase }) # - hash = {a: 1} assert_nil(Kind::Maybe[nil].try(:upcase).value) assert_nil(Kind::Maybe[hash].try(:upcase).value) assert_nil(Kind::Maybe[nil].try(:[], :b).value) assert_nil(Kind::Maybe[hash].try(:[], :b).value) assert_equal(1, Kind::Maybe[hash].try(:[], :a).value) assert_equal(0, Kind::Maybe[hash].try(:fetch, :b, 0).value) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil].try(:upcase)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[hash].try(:upcase)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil].try(:[], :b)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[hash].try(:[], :b)) assert_instance_of(Kind::Maybe::Some,Kind::Maybe[hash].try(:[], :a)) assert_instance_of(Kind::Maybe::Some, Kind::Maybe[hash].try(:fetch, :b, 0)) # --- assert_nil(Kind::Maybe[nil].try(:upcase).value) assert_nil(Kind::Maybe[nil].try { |value| value.upcase }.value) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil].try(:upcase)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil].try { |value| value.upcase }) # - assert_nil(Kind::Maybe[Kind::Undefined].try(:upcase).value) assert_nil(Kind::Maybe[Kind::Undefined].try { |value| value.upcase }.value) assert_instance_of(Kind::Maybe::None, Kind::Maybe[Kind::Undefined].try(:upcase)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[Kind::Undefined].try { |value| value.upcase }) end def test_the_dig_method [nil, 1, '', /x/].each do |data| assert_nil(Kind::Maybe[data].dig(:foo).value) assert_nil(Kind::Maybe[data].dig(:foom, :bar).value) end # --- a = [1, 2, 3] assert_equal(1, Kind::Maybe[a].dig(0).value) assert_equal(2, Kind::Maybe[a].dig(1).value) assert_equal(3, Kind::Maybe[a].dig(2).value) assert_equal(3, Kind::Maybe[a].dig(-1).value) assert_nil(Kind::Maybe[a].dig(3).value) assert_nil(Kind::Maybe[a].dig('foo').value) assert_nil(Kind::Maybe[a].dig(:foo, 'bar').value) assert_nil(Kind::Maybe[a].dig(:foo, :bar, 'baz').value) # --- h = { foo: {bar: {baz: 1}}} assert_equal({bar: {baz: 1}}, Kind::Maybe[h].dig(:foo).value) assert_equal({baz: 1}, Kind::Maybe[h].dig(:foo, :bar).value) assert_equal(1, Kind::Maybe[h].dig(:foo, :bar, :baz).value) assert_nil(Kind::Maybe[h].dig('foo').value) assert_nil(Kind::Maybe[h].dig(:foo, 'bar').value) assert_nil(Kind::Maybe[h].dig(:foo, :bar, 'baz').value) # -- g = { 'foo' => [10, 11, 12] } assert_equal([10, 11, 12], Kind::Maybe[g].dig('foo').value) assert_equal(10, Kind::Maybe[g].dig('foo', 0).value) assert_equal(11, Kind::Maybe[g].dig('foo', 1).value) assert_equal(12, Kind::Maybe[g].dig('foo', 2).value) assert_equal(12, Kind::Maybe[g].dig('foo', -1).value) assert_nil(Kind::Maybe[g].dig(:foo).value) assert_nil(Kind::Maybe[g].dig(:foo, 0).value) # -- i = { foo: [{'bar' => [1, 2]}, {baz: [3, 4]}] } assert_equal(1, Kind::Maybe[i].dig(:foo, 0, 'bar', 0).value) assert_equal(2, Kind::Maybe[i].dig(:foo, 0, 'bar', 1).value) assert_equal(2, Kind::Maybe[i].dig(:foo, 0, 'bar', -1).value) assert_nil(Kind::Maybe[i].dig(:foo, 0, 'bar', 2).value) assert_equal(3, Kind::Maybe[i].dig(:foo, 1, :baz, 0).value) assert_equal(4, Kind::Maybe[i].dig(:foo, 1, :baz, 1).value) assert_equal(4, Kind::Maybe[i].dig(:foo, 1, :baz, -1).value) assert_nil(Kind::Maybe[i].dig(:foo, 0, :baz, 2).value) # -- s = Struct.new(:a, :b).new(101, 102) o = OpenStruct.new(c: 103, d: 104) b = { struct: s, ostruct: o, data: [s, o]} assert_equal(101, Kind::Maybe[s].dig(:a).value) assert_equal(102, Kind::Maybe[b].dig(:struct, :b).value) assert_equal(102, Kind::Maybe[b].dig(:data, 0, :b).value) assert_equal(102, Kind::Maybe[b].dig(:data, 0, 'b').value) assert_equal(103, Kind::Maybe[o].dig(:c).value) assert_equal(104, Kind::Maybe[b].dig(:ostruct, :d).value) assert_equal(104, Kind::Maybe[b].dig(:data, 1, :d).value) assert_equal(104, Kind::Maybe[b].dig(:data, 1, 'd').value) assert_nil(Kind::Maybe[s].dig(:f).value) assert_nil(Kind::Maybe[o].dig(:f).value) assert_nil(Kind::Maybe[b].dig(:struct, :f).value) assert_nil(Kind::Maybe[b].dig(:ostruct, :f).value) assert_nil(Kind::Maybe[b].dig(:data, 0, :f).value) assert_nil(Kind::Maybe[b].dig(:data, 1, :f).value) end def test_the_try_method_with_bang assert_raises_with_message(Kind::Error, '"upcase" expected to be a kind of Symbol') do Kind::Maybe['foo'].try!('upcase') end # --- assert_equal('FOO', Kind::Maybe['foo'].try!(:upcase).value) assert_equal('FOO', Kind::Maybe['foo'].try! { |value| value.upcase }.value) assert_instance_of(Kind::Maybe::Some, Kind::Maybe['foo'].try!(:upcase)) assert_instance_of(Kind::Maybe::Some, Kind::Maybe['foo'].try! { |value| value.upcase }) # - hash = {a: 1} assert_raises(NoMethodError) { Kind::Maybe[hash].try!(:upcase) } assert_nil(Kind::Maybe[nil].try!(:[], :b).value) assert_nil(Kind::Maybe[hash].try!(:[], :b).value) assert_equal(1, Kind::Maybe[hash].try!(:[], :a).value) assert_equal(0, Kind::Maybe[hash].try!(:fetch, :b, 0).value) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil].try!(:[], :b)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[hash].try!(:[], :b)) assert_instance_of(Kind::Maybe::Some,Kind::Maybe[hash].try!(:[], :a)) assert_instance_of(Kind::Maybe::Some, Kind::Maybe[hash].try!(:fetch, :b, 0)) # --- assert_nil(Kind::Maybe[nil].try!(:upcase).value) assert_nil(Kind::Maybe[nil].try! { |value| value.upcase }.value) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil].try!(:upcase)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[nil].try! { |value| value.upcase }) # - assert_nil(Kind::Maybe[Kind::Undefined].try!(:upcase).value) assert_nil(Kind::Maybe[Kind::Undefined].try! { |value| value.upcase }.value) assert_instance_of(Kind::Maybe::None, Kind::Maybe[Kind::Undefined].try!(:upcase)) assert_instance_of(Kind::Maybe::None, Kind::Maybe[Kind::Undefined].try! { |value| value.upcase }) end def test_that_optional_is_an_maybe_alias assert_equal(Kind::Maybe, Kind::Optional) # --- result1 = Kind::Optional .new(5) .map { |value| value * 5 } .map { |value| value - 10 } .value_or(0) assert_equal(15, result1) # --- result2 = Kind::Optional[5] .then { |value| value * 5 } .then { |value| value + 10 } .value_or { 0 } assert_equal(35, result2) end def test_the_kind_none_method [Kind.None, Kind::None].each do |kind_none| assert_instance_of(Kind::Maybe::None, kind_none) assert_nil(kind_none.value) end assert_same(Kind::None, Kind.None) # -- assert_raises_with_message(ArgumentError, 'wrong number of arguments (given 1, expected 0)') do Kind::None(nil) end end def test_the_kind_some_method kind_some1 = Kind.Some(1) kind_some2 = Kind::Some(1) [kind_some1, kind_some2].each do |kind_some| assert_instance_of(Kind::Maybe::Some, kind_some) assert_equal(1, kind_some.value) end refute_same(kind_some1, kind_some2) # -- assert_raises_with_message(ArgumentError, 'wrong number of arguments (given 0, expected 1)') do Kind::Some() end # -- [nil, Kind::Undefined].each do |value| assert_raises_with_message(ArgumentError, "value can't be nil or Kind::Undefined") do Kind::Some(value) end end end Add_A = -> params do a, b = Kind.of.Hash(params, or: Empty::HASH).values_at(:a, :b) a + b if Kind.of.Numeric?(a, b) end Add_B = -> params do a, b = Kind.of.Hash(params, or: Empty::HASH).values_at(:a, :b) return Kind::None unless Kind.of.Numeric.instance?(a, b) Kind::Some(a + b) end Double_A = -> value {value * 2 if Kind.of.Numeric?(value) } Double_B = -> value {Kind.of.Numeric?(value) ? Kind::Some(value * 2) : Kind::None } def test_the_maybe_objects_in_a_chain_of_mappings assert_equal(3, Kind::Maybe.new(a: 1, b: 2).then(&Add_A).value_or(0)) assert_equal(6, Kind::Maybe.new(a: 1, b: 2).then(&Add_A).then(&Double_B).value_or(0)) [ [], {}, nil ].each do |value| assert_equal(0, Kind::Maybe.new(value).then(&Add_A).value_or(0)) assert_equal(0, Kind::Maybe.new(value).then(&Add_A).then(&Double_B).value_or(0)) end # -- assert_equal(3, Kind::Maybe.new(a: 1, b: 2).then(&Add_B).value_or(0)) assert_equal(6, Kind::Maybe.new(a: 1, b: 2).then(&Add_B).then(&Double_A).value_or(0)) [ [], {}, nil ].each do |value| assert_equal(0, Kind::Maybe.new(value).then(&Add_B).value_or(0)) assert_equal(0, Kind::Maybe.new(value).then(&Add_B).then(&Double_B).value_or(0)) end end def test_the_maybe_type_checker assert_predicate(Kind::Maybe(Hash)[''], :none?) assert_predicate(Kind::Maybe(Hash).new([]), :none?) assert_predicate(Kind::Maybe(Hash).wrap(''), :none?) assert_predicate(Kind::Maybe(Hash)[{}], :some?) assert_predicate(Kind::Maybe(Hash).new({}), :some?) assert_predicate(Kind::Maybe(Hash).wrap({}), :some?) # --- assert_predicate(Kind::Optional(Hash)[''], :none?) assert_predicate(Kind::Optional(Hash).new([]), :none?) assert_predicate(Kind::Optional(Hash).wrap(''), :none?) assert_predicate(Kind::Optional(Hash)[{}], :some?) assert_predicate(Kind::Optional(Hash).new({}), :some?) assert_predicate(Kind::Optional(Hash).wrap({}), :some?) end end
true
e966cfd87ede9eee7522783e39261d9097735cc8
Ruby
ocruse7/apples-and-holidays-onl01-seng-pt-110319
/lib/holiday.rb
UTF-8
1,710
3.703125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def second_supply_for_fourth_of_july( holiday_hash ) # given that holiday_hash looks like this: # { # :winter => { # :christmas => ["Lights", "Wreath"], # :new_years => ["Party Hats"] # }, # :summer => { # :fourth_of_july => ["Fireworks", "BBQ"] # }, # :fall => { # :thanksgiving => ["Turkey"] # }, # :spring => { # :memorial_day => ["BBQ"] # } # } # return the second element in the 4th of July array holiday_supplies[:summer][:fourth_of_july][1] end def add_supply_to_winter_holidays( holiday_hash, supply ) holiday_hash[:winter].each {|holiday, values| values << supply } end def add_supply_to_memorial_day( holiday_hash, supply ) holiday_hash[:spring][:memorial_day] << supply end def add_new_holiday_with_supplies (holiday_hash, season, holiday_name, supply_array ) holiday_hash[season][holiday_name] = supply_array holiday_hash end def all_winter_holiday_supplies( holiday_hash ) all_supplies = holiday_hash[:winter].collect{ |key,val| val} all_supplies.flatten end def all_supplies_in_holidays(holiday_hash) holiday_hash.each do |season, holiday| puts "#{season.to_s.capitalize}:" holiday.each do |key,val| supply = val.join(", ") capitalized_holiday = key.to_s.split("_").collect{|el| el.capitalize}.join(" ") puts " #{capitalized_holiday}: #{supply}" end end end def all_holidays_with_bbq(holiday_hash) result = [] holiday_hash.each do |season, holiday| holiday.each do |key, val| result << key if val.include?("BBQ") end end result end
true
c00f4bb18047be53539a038e2e83f72107dac433
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/word-count/db10dd4181c94c79a92936797397de12.rb
UTF-8
244
3.34375
3
[]
no_license
class Phrase def initialize(sentence) @words = sentence.split(/\W+/).map {|word| word.downcase } end def word_count @words.each_with_object(Hash.new(0)) do |word, counts| counts[word] = counts[word] + 1 end end end
true
7b0b30a74809b1d80e1658a974b4bfcbd2800d97
Ruby
FranklinHarry/aws-logs
/lib/aws_logs/tail.rb
UTF-8
4,963
2.546875
3
[ "MIT" ]
permissive
require "json" module AwsLogs class Tail include AwsServices def initialize(options={}) @options = options @log_group_name = options[:log_group_name] # Setting to ensure matches default CLI option @follow = @options[:follow].nil? ? true : @options[:follow] @loop_count = 0 @output = [] # for specs reset set_trap end def reset @events = [] # constantly replaced with recent events @last_shown_event_id = nil @completed = nil end # The start and end time is useful to limit results and make the API fast. We'll leverage it like so: # # 1. load all events from an initial since time # 2. after that load events pass that first window # # It's a sliding window of time we're using. # def run if ENV['AWS_LOGS_NOOP'] puts "Noop test" return end # We overlap the sliding window because CloudWatch logs can receive or send the logs out of order. # For example, a bunch of logs can all come in at the same second, but they haven't registered to CloudWatch logs # yet. If we don't overlap the sliding window then we'll miss the logs that were delayed in registering. overlap = 60*1000 # overlap the sliding window by a minute since, now = initial_since, current_now until end_loop? refresh_events(since, now) display since, now = now-overlap, current_now loop_count! sleep 5 if @follow && !ENV["AWS_LOGS_TEST"] end # Refresh and display a final time in case the end_loop gets interrupted by stop_follow! refresh_events(since, now) display rescue Aws::CloudWatchLogs::Errors::ResourceNotFoundException => e puts "ERROR: #{e.class}: #{e.message}".color(:red) puts "Log group #{@log_group_name} not found." end def refresh_events(start_time, end_time) @events = [] next_token = :start # TODO: can hit throttle limit if there are lots of pages while next_token options = { log_group_name: @log_group_name, # required start_time: start_time, end_time: end_time, # limit: 1000, # interleaved: true, } options[:log_stream_names] = @options[:log_stream_names] if @options[:log_stream_names] options[:log_stream_name_prefix] = @options[:log_stream_name_prefix] if @options[:log_stream_name_prefix] options[:filter_pattern] = @options[:filter_pattern] if @options[:filter_pattern] options[:next_token] = next_token if next_token != :start && !next_token.nil? resp = cloudwatchlogs.filter_log_events(options) @events += resp.events next_token = resp.next_token end @events end # Events canduplicated as events can be written to the exact same timestamp. # So also track the last_shown_event_id and prevent duplicate log lines from re-appearing. def display new_events = @events shown_index = new_events.find_index { |e| e.event_id == @last_shown_event_id } if shown_index new_events = @events[shown_index+1..-1] || [] end new_events.each do |e| time = Time.at(e.timestamp/1000).utc line = [time.to_s.color(:green), e.message] format = @options[:format] || "detailed" line.insert(1, e.log_stream_name.color(:purple)) if format == "detailed" say line.join(' ') end @last_shown_event_id = @events.last&.event_id check_follow_until! end def check_follow_until! follow_until = @options[:follow_until] return unless follow_until messages = @events.map(&:message) @@end_loop_signal = messages.detect { |m| m.include?(follow_until) } end def say(text) ENV["AWS_LOGS_TEST"] ? @output << text : puts(text) end def output @output.join("\n") + "\n" end def set_trap Signal.trap("INT") { puts "\nCtrl-C detected. Exiting..." exit # immediate exit } end # The stop_follow! results in a little waiting because it signals to break the polling loop. # Since it's in the middle of the loop process, the loop will finish the sleep 5 first. # So it can pause from 0-5 seconds. @@end_loop_signal = false def self.stop_follow! @@end_loop_signal = true end private def initial_since since = @options[:since] seconds = since ? Since.new(since).to_i : Since::DEFAULT (Time.now.to_i - seconds) * 1000 # past 10 minutes in milliseconds end def current_now (Time.now.to_i) * 1000 # now in milliseconds end def end_loop? return true if @@end_loop_signal max_loop_count && @loop_count >= max_loop_count end def loop_count! @loop_count += 1 end # Useful for specs def max_loop_count @follow ? nil : 1 end end end
true
94cd99053e3f17004afec170695b8c3697a4fe08
Ruby
esegredo/LPP_Pract_7
/test/fraction_spec.rb
UTF-8
5,199
3.796875
4
[]
no_license
require 'fraction' describe Fraction do it "Debe existir un numerador" do Fraction.new(1, 5).num.should == 1 end it "Debe existir un denominador" do Fraction.new(1, 5).denom.should == 5 end it "Debe de estar en su forma reducida" do Fraction.new(20, 30).should == Fraction.new(2, 3) Fraction.new(-30, 45).should == Fraction.new(-2, 3) end it "No puede existir un denominador que sea igual a cero" do expect { Fraction.new(1, 0) }.to raise_error(TypeError) end it "Se debe invocar al metodo num() para obtener el numerador" do Fraction.new(1, 5).respond_to?("num").should == true end it "Se debe invocar al metodo denom() para obtener el denominador" do Fraction.new(1, 5).respond_to?("denom").should == true end it "Se debe mostar por la consola la fraccion de la forma: a/b, donde a es el numerador y b el denominador" do Fraction.new(1, 5).to_s.should == "1/5" Fraction.new(35, 100).to_s.should == "7/20" Fraction.new(-3, 6).to_s.should == "-1/2" end it "Se debe mostar por la consola la fraccion en formato flotante" do Fraction.new(1, 5).to_f.should == 1/5 Fraction.new(35, 100).to_f.should == 7/20 Fraction.new(-3, 6).to_s.should == "-1/2" end it "Se debe comparar si dos fracciones son iguales con ==" do Fraction.new(14, 21).should == Fraction.new(2, 3) Fraction.new(2, 3).should == Fraction.new(-2, -3) Fraction.new(-2, 3).should == Fraction.new(2, -3) end it "Se debe calcular el valor absoluto de una fraccion con el metodo abs" do Fraction.new(-3, -5).abs.should == Fraction.new(3, 5) Fraction.new(-3, 5).abs.should == Fraction.new(3, 5) Fraction.new(20, -30).abs.should == Fraction.new(2, 3) end it "Se debe calcular el reciproco de una fraccion con el metodo reciprocal" do Fraction.new(20, 30).reciprocal.should == Fraction.new(3, 2) Fraction.new(-3, 4).reciprocal.should == Fraction.new(4, -3) Fraction.new(3, -4).reciprocal.should == Fraction.new(-4, 3) Fraction.new(-3, 4).reciprocal.should == Fraction.new(-4, 3) Fraction.new(-3, -4).reciprocal.should == Fraction.new(-4, -3) Fraction.new(-3, -4).reciprocal.should == Fraction.new(4, 3) end it "Se debe calcular el opuesto de una fraccion con -" do (-Fraction.new(1, 4)).should == Fraction.new(-1, 4) (-Fraction.new(1, 4)).should == Fraction.new(1, -4) (-Fraction.new(-1, 4)).should == Fraction.new(-1, -4) (-Fraction.new(-1, 4)).should == Fraction.new(1, 4) end it "Se debe sumar dos fracciones con + y dar el resultado de forma reducida" do (Fraction.new(1, 4) + Fraction.new(1, 6)).should == Fraction.new(5, 12) (Fraction.new(2, 5) + Fraction.new(4, 6)).should == Fraction.new(16, 15) (Fraction.new(1, 5) + Fraction.new(-4, 6)).should == Fraction.new(-7, 15) end it "Se debe restar dos fracciones con - y dar el resultado de forma reducida" do (Fraction.new(-3, 4) - Fraction.new(3, 2)).should == Fraction.new(9, -4) (Fraction.new(3, 4) - Fraction.new(3, 2)).should == Fraction.new(-3, 4) (Fraction.new(3, 4) - Fraction.new(3, 2)).should == Fraction.new(3, -4) end it "Se debe multiplicar dos fracciones con * y dar el resultado de forma reducida" do (Fraction.new(1, 2) * Fraction.new(1, 2)).should == Fraction.new(1, 4) (Fraction.new(-2, 4) * Fraction.new(3, 6)).should == Fraction.new(-1, 4) (Fraction.new(-2, 4) * Fraction.new(-3, 6)).should == Fraction.new(1, 4) end it "Se debe dividir dos fracciones con / y dar el resultado de forma reducida" do (Fraction.new(1, 2) / Fraction.new(1, 2)).should == Fraction.new(1, 1) (Fraction.new(-2, 4) / Fraction.new(3, 6)).should == Fraction.new(-1, 1) (Fraction.new(-2, 4) / Fraction.new(-3, 6)).should == Fraction.new(1, 1) (Fraction.new(2, 4) / Fraction.new(3, 17)).should == Fraction.new(17, 6) end it "Se debe calcular el resto dos fracciones con % y dar el resultado de forma reducida" do (Fraction.new(1, 2) % Fraction.new(1, 2)).should == Fraction.new(0, 1) (Fraction.new(-2, 4) % Fraction.new(3, 6)).should == Fraction.new(0, 1) (Fraction.new(-2, 4) % Fraction.new(-3, 6)).should == Fraction.new(0, 1) (Fraction.new(2, 4) % Fraction.new(3, 17)).should == Fraction.new(5, 34) end it "Se debe de poder comprobar si una fracion es menor que otra" do (Fraction.new(1, 3) < Fraction.new(1, 2)).should == true (Fraction.new(8, 6) < Fraction.new(4, 3)).should == false (Fraction.new(-1, 4) < Fraction.new(1, 2)).should == true end it "Se debe de poder comprobar si una fracion es mayor que otra" do (Fraction.new(1, 2) > Fraction.new(1, 3)).should == true (Fraction.new(4, 3) < Fraction.new(8, 6)).should == false (Fraction.new(1, 2) > Fraction.new(-1, 4)).should == true end it "Se debe de poder comprobar si una fracion es menor o igual que otra" do (Fraction.new(1, 3) <= Fraction.new(1, 2)).should == true (Fraction.new(4, 3) <= Fraction.new(1, 2)).should == false (Fraction.new(-1, 4) <= Fraction.new(1, -4)).should == true end it "Se debe de poder comprobar si una fracion es mayor o igual que otra" do (Fraction.new(1, 2) >= Fraction.new(1, 3)).should == true (Fraction.new(1, 2) >= Fraction.new(4, 3)).should == false (Fraction.new(1, -4) >= Fraction.new(-1, 4)).should == true end end
true
641093000aca20b93cbea73fb1be34ab3da90102
Ruby
MillsProvosty/dog_walker
/test/walker_test.rb
UTF-8
2,373
3.15625
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/dog' require './lib/walker' require 'pry' class WalkerTest < Minitest::Test def test_walker_exists @Jerimiah = Walker.new("Jerimiah", 10) assert_instance_of Walker, @Jerimiah end def setup @Jerimiah = Walker.new("Jerimiah", 10) @sodie = Dog.new("Sodie", 9, "Shih-Tzu", true) @max = Dog.new("Max", 11, "Cocker Spaniel", false) @oscar = Dog.new("Oscar", 2, "Pug", true) @daisy = Dog.new("Daisy", 4, "Pug", true) end def test_clients_default_empty assert_equal [], @Jerimiah.clients end def test_add_clients_returns_clients @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) assert_equal [@sodie, @max], @Jerimiah.clients end def test_walk_that_dog @Jerimiah.walk_that_dog(@sodie) assert_equal 9, @Jerimiah.poop_bags assert_equal 1, @sodie.walks end def test_client_number @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) assert_equal 2, @Jerimiah.client_number end def test_client_elderly? @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) assert_equal false, @Jerimiah.client_elderly?(@sodie) assert_equal true, @Jerimiah.client_elderly?(@max) end def test_list_clients @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) assert_equal ["Sodie", "Max"], @Jerimiah.list_clients end def test_client_name_ending_in_y_or_ie @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) assert_equal "Sodie", @Jerimiah.client_name_ending end def test_check_breed @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) assert_equal @max, @Jerimiah.check_breed("Cocker Spaniel") end def test_list_clients_by_breed @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) @Jerimiah.add_client(@oscar) @Jerimiah.add_client(@daisy) expected = { "Shih-Tzu" => [@sodie], "Cocker Spaniel" => [@max], "Pug" => [@oscar, @daisy] } assert_equal expected, @Jerimiah.clients_by_breed end def test_cant_add_same_client_twice @Jerimiah.add_client(@sodie) @Jerimiah.add_client(@max) @Jerimiah.add_client(@max) @Jerimiah.add_client(@oscar) @Jerimiah.add_client(@daisy) @Jerimiah.add_client(@daisy) assert_equal [@sodie, @max, @oscar, @daisy], @Jerimiah.clients end end
true
ef30e99a603df9a1d8e9f230832a262d39ca9a54
Ruby
jbedley/SiblingRivalry
/gin_rummy/Deck.rb
UTF-8
719
4.15625
4
[]
no_license
require "./Card.rb" class Deck def initialize() @cards = Array.new(52) card_index = 0; for suit in 0..3 for value in 1..13 @cards[card_index] = Card.new(suit, value) card_index = card_index + 1 end end end # Makes a string of the whole deck def to_s ret = "[" @cards.each do |card| ret << card.to_s << " " end ret.chop << "]" # remove (chop) the trailing space end def shuffle for i in 0..1000 # swap two random cards a lot of times k = rand(@cards.length) j = rand(@cards.length) tempcard = @cards[k]; @cards[k] = @cards[j]; @cards[j] = tempcard; end end end x = Deck.new() x.shuffle puts x.to_s
true
73a7e0623d55ebd67fb14b11926d733c758c1181
Ruby
rajkiransingh/Challenge
/features/support/helpers/pages_helper.rb
UTF-8
279
2.546875
3
[]
no_license
# Page Object helpers module PagesHelper def elem_name(name) name.to_s.downcase.tr(' ', '_') end def elem_with_name(name) send("#{elem_name(name)}_element") rescue NoMethodError raise NameError, "Undefined '#{name}' element for #{self.class} page" end end
true
bfa872fadbc1feeb107937ebf44f904fdb0f8891
Ruby
fentontaylor/sweater-weather
/app/models/forecast_summary.rb
UTF-8
180
2.71875
3
[]
no_license
class ForecastSummary def initialize(obj) @today = obj.summary_today @tonight = obj.summary_tonight @temp_high = obj.temp_high @temp_low = obj.temp_low end end
true
b8da9d2b9538f558accfa1fcddc1c11db5aa827c
Ruby
masa7303/mountain_hut
/db/seeds/development/entries.rb
UTF-8
634
2.609375
3
[]
no_license
body = "今日の天気は晴れでした。\n\n" + "登山客もいっぱい!。" + "周辺には高山植物も顔を出すようになりました。" + "周辺には高山植物も顔を出すようになりました。" + "周辺には高山植物も顔を出すようになりました。" + "周辺には高山植物も顔を出すようになりました。" + "今週末はぜひ立山ロッジへお越しください!" %w(Taro Jiro Hana).each do |name| 0.upto(9) do |idx| Entry.create( title: "今日の景色#{idx}", body: body, posted_at: 10.days.ago.advance(days: idx) ) end end
true
99b2de53cb0d7d7e161bb86009188011615a72a7
Ruby
Serenity911/week2-ruby-hw-fish-bear-river
/river.rb
UTF-8
307
3.53125
4
[]
no_license
class River attr_reader :name def initialize(name) @name = name @fish = Array.new() end def populate_with_fish(fish_names) for name in fish_names @fish << Fish.new(name) end end def lose_a_fish() @fish.shift() end def fish_counter @fish.length end end
true
6ec84aea89ca69456b39bcb5ccc1c81fc4af2775
Ruby
AAMani5/learn-to-program
/chap08/ex0.rb
UTF-8
218
3.34375
3
[]
no_license
#!/usr/bin/env ruby puts "please type as many words as you want but only one word per line" input = gets.chomp array = [] while (input.downcase !='') array.push input.downcase input = gets.chomp end puts array.sort
true
41266d797f4867f41e918325c6dbe47185e88c6a
Ruby
jwhitis/dintg
/app/domain/progress_calculator.rb
UTF-8
1,770
3.203125
3
[]
no_license
class ProgressCalculator attr_reader :dictionary def initialize(user, time_period, target) @user = user @dictionary = TimeRangeDictionary.new(time_period, target) end def on_pace_for_period? progress_score >= 1 end def progress_score unless @dictionary.period_in_progress? raise OutOfRangeError, "Cannot calculate progress score because time period is not in progress." end # A score of 1.0 indicates that a user is exactly on pace to meet their # goal for the time period. A score greater than 1.0 indicates that the # user is ahead of schedule to meet their goal. @score ||= fraction_of_goal_earned / fraction_of_period_elapsed end class OutOfRangeError < RuntimeError; end def fraction_of_goal_earned earned_for_period.to_f / goal_for_period.to_f end def earned_for_period time_range = @dictionary.time_range_for_period @user.gigs.within_time_range(time_range).sum(:pay) end def goal_for_period monthly_goal = @user.configuration.monthly_goal number_of_months = @dictionary.month_range_for_period.size monthly_goal * number_of_months end def fraction_of_period_elapsed current_day_in_period.to_f / days_in_period.to_f end private def current_day_in_period month_range = @dictionary.month_range_for_period previous_months = month_range.take_while { |month| month != Time.now.month } days_in_month_range(previous_months) + Time.now.day end def days_in_period month_range = @dictionary.month_range_for_period days_in_month_range(month_range) end def days_in_month_range(month_range) month_range.reduce(0) do |days, month| year = Time.now.year days + Time.new(year, month).end_of_month.day end end end
true
7f692b74cf6417ea159094c3c27c78e5c8c7fa95
Ruby
dtroydev/rails-mister-cocktail
/db/seeds.rb
UTF-8
2,984
3
3
[]
no_license
require 'open-uri' COCKTAIL_DB_API = 'http://www.thecocktaildb.com/api/json/v1/1/'.freeze INGREDIENTS = 'list.php?i=list'.freeze COCKTAILS = 'filter.php?c=Cocktail'.freeze COCKTAIL = 'lookup.php?i='.freeze cocktails__cache = {} define_method :cocktails_cache do cocktails__cache end def cdb_ingredients ingredients_json = URI.open("#{COCKTAIL_DB_API}#{INGREDIENTS}").read ingredients = JSON.parse(ingredients_json)['drinks'] converted_ingredients = ingredients.map do |ingredient| { name: ingredient['strIngredient1'].titleize } end converted_ingredients end def cdb_cocktail(cocktail_db_id) return cocktails_cache[cocktail_db_id] if cocktails_cache.key?(cocktail_db_id) cocktail_details_url = "#{COCKTAIL_DB_API}#{COCKTAIL}#{cocktail_db_id}" cocktail = JSON.parse(URI.open(cocktail_details_url).read)['drinks'][0] cocktails_cache[cocktail_db_id] = cocktail cocktail end # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/AbcSize def cdb_cocktails cocktails_json = URI.open("#{COCKTAIL_DB_API}#{COCKTAILS}").read cocktails = JSON.parse(cocktails_json)['drinks'] total = cocktails.length counter = 0 converted_cocktails = cocktails.map do |cocktail| puts "Cocktail Setup #{counter + 1} / #{total} done." counter += 1 { name: cocktail['strDrink'], image_url: cocktail['strDrinkThumb'], instructions: cdb_cocktail(cocktail['idDrink'])['strInstructions'], cocktail_db_id: cocktail['idDrink'] } end converted_cocktails end puts 'Seeding Ingredients...' Ingredient.create(cdb_ingredients) puts 'Seeding Cocktails...' Cocktail.create(cdb_cocktails) def normalize_ingredient_name(name) hyphens_to_spaces = name.tr('-', ' ') no_apostrophies = hyphens_to_spaces.delete("'") no_apostrophies.split.map(&:capitalize).join(' ') end def ingredient_id(ingredient) normalized_ingredient = normalize_ingredient_name(ingredient) ingredient_lookup = Ingredient.where(name: normalized_ingredient).first # some cocktails have ingredients that are not in the ingredient list return Ingredient.create(name: ingredient).id if ingredient_lookup.nil? ingredient_lookup.id end def cdb_cocktail_doses(cocktail_db_id, cocktail_id) doses = [] cocktail = cdb_cocktail(cocktail_db_id) 15.times do |n| ingredient = cocktail["strIngredient#{n + 1}"] next if ingredient.blank? measure = cocktail["strMeasure#{n + 1}"] description = measure.to_s.strip dose = { description: description, ingredient_id: ingredient_id(ingredient), cocktail_id: cocktail_id } doses << dose end doses end # rubocop:enable Metrics/MethodLength # rubocop:enable Metrics/AbcSize def cdb_doses counter = 0 total = Cocktail.count Cocktail.all.each do |cocktail| Dose.create(cdb_cocktail_doses(cocktail.cocktail_db_id, cocktail.id)) puts "Dose(s) for Cocktail #{counter + 1} / #{total} done." counter += 1 end end puts 'Seeding Doses...' cdb_doses
true
b34e5a13ca8551a3c3004e959299c4d338689a6f
Ruby
belinskidima/Rubyschool
/app.rb
UTF-8
1,795
2.53125
3
[ "MIT" ]
permissive
#encoding: utf-8 require 'rubygems' require 'sinatra' require 'sinatra/reloader' require 'sqlite3' db = SQLite3::Database.new 'barbershop.db' configure do db.execute 'CREATE TABLE IF NOT EXISTS " Users" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "username" TEXT, "phone" TEXT, "datestamp" TEXT, "barber" TEXT, "color" TEXT )' end get '/' do erb "Hello! <a href=\"https://github.com/bootstrap-ruby/sinatra-bootstrap\">Original</a> pattern has been modified for <a href=\"http://rubyschool.us/\">Ruby School</a>!!!" end get '/about' do erb :about end get '/visit' do erb :visit end post '/visit' do @username = params[:username] @phone = params[:phone] @datetime = params[:datetime] @barber = params[:barber] @color = params[:color] hh = { :username => 'Введите имя', :phone => 'Введите номер телефона', :datetime => 'Введите дату и время'} @error = hh.select {|key, _| params[key] == ""}.values.join(",") if @error != '' return erb :visit end db = SQLite3::Database.new 'barbershop.db' db.execute' insert into Users (username, phone, datestamp, barber, color) values (?,?,?,?,?)', [@username,@phone,@datetime,@barber,@color] @message = "Отлично! Уважаемый #{@username}, мы ждем вас в Barber Shop в #{@datetime} к #{@barber}! Цвет окрашивания: #{@color}" erb :message end #def get_db #return SQLite3::Database.new 'barbershop.db' #end get '/contacts' do erb :contacts end get '/success' do erb 'Спасибо за ваше обращение. Мы обязательно ответим на него в ближайшее время.' end get '/admin' do erb :pass end
true
5daeb9e49fb20d0b3d37e8da59f16ddfc202374b
Ruby
saqib-nadeem/sugar_utils
/lib/sugar_utils.rb
UTF-8
674
3.109375
3
[ "Apache-2.0" ]
permissive
# -*- encoding : utf-8 -*- require 'sugar_utils/version' require 'sugar_utils/file' module SugarUtils # @param [Object] value # # @return [Boolean] def self.ensure_boolean(value) return false if value.respond_to?(:to_s) && value.to_s.casecmp('false').zero? value ? true : false end # @param [String, Float, Integer] value # # @raise [ArgumentError] if the value is a string which cannot be converted # @raise [TypeError] if value is type which cannot be converted # # @return [Integer] def self.ensure_integer(value) return value if value.is_a?(Integer) return value.to_i if value.is_a?(Float) Float(value).to_i end end
true
a52211d7e6b4b4f210c05dd8214ef0523cad90d5
Ruby
metade/music_service_example
/music-cucumber/features/support/music_client.rb
UTF-8
3,923
2.515625
3
[]
no_license
require 'ostruct' require 'rest-client' module Music def self.destroy_all_users users = Music::User.all.inject({}){ |h,u| h[u.username] ||= u; h }.values users.each do |user| user.collections.each do |collection| collection.clips.each do |clip| RestClient.delete "#{Music::HOST}/collections/#{collection.to_param}/clips/#{clip.pid}", :content_type => :json, :accept => :json end collection.destroy end user.playlists.each do |playlist| # playlist.playlists_tracks.each do |track| # RestClient.delete "#{Music::HOST}/playlists/#{playlist.to_param}/tracks/#{track['id']}", :content_type => :json, :accept => :json # end playlist.destroy end user.destroy end end class Base < OpenStruct def self.all response = RestClient.get "#{Music::HOST}/#{collection_name}", :content_type => :json, :accept => :json JSON.parse(response.body)[collection_name].map { |u| self.new(u) } end def self.find(what, params={}) path = params[:from] || "/#{collection_name}/#{what}" response = RestClient.get "#{Music::HOST}#{path}", :content_type => :json, :accept => :json if (what == :all) JSON.parse(response.body)[collection_name].map { |h| self.new(h) } else self.new JSON.parse(response.body)[element_name] end end def self.create(params) response = RestClient.post "#{Music::HOST}/users", { :user => params }.to_json, :content_type => :json, :accept => :json self.new(JSON.parse(response)['user']) end def destroy RestClient.delete "#{Music::HOST}/#{self.class.collection_name}/#{to_param}", :content_type => :json, :accept => :json end protected def self.collection_name # TODO: use Rails Inflectors self.element_name + 's' end def self.element_name self.to_s.sub('Music::', '').downcase end end class User < Base def self.find_by_name(name) self.find(name.gsub(/\W/,'').downcase) end def to_param username end def collections Collection.find(:all, :from => "/users/#{to_param}/collections") end def playlists Playlist.find(:all, :from => "/users/#{to_param}/playlists") end end class Collection < Base def self.create(params) user = params.delete(:user) || User.new(:username => 'testuser') response = RestClient.post "#{Music::HOST}/users/#{user.to_param}/collections", { :collection => params }.to_json, :content_type => :json, :accept => :json Collection.new(JSON.parse(response)['collection']) end def to_param url_key end def clips Clip.find(:all, :from => "/collections/#{to_param}/clips") end end class Clip < Base def self.create(params) collection = params.delete(:collection) response = RestClient.post "#{Music::HOST}/collections/#{collection.to_param}/clips", { :clip => params }.to_json, :content_type => :json, :accept => :json Clip.new(JSON.parse(response)['clip']) end def to_param url_key end end class Playlist < Base def self.create(params) user = params.delete(:user) || User.new(:username => 'testuser') response = RestClient.post "#{Music::HOST}/users/#{user.to_param}/playlists", { :playlist => params }.to_json, :content_type => :json, :accept => :json Playlist.new(JSON.parse(response)['playlist']) end def to_param url_key end end class Track < Base def self.create(params) playlist = params.delete(:playlist) response = RestClient.post "#{Music::HOST}/playlists/#{playlist.to_param}/tracks", { :playlists_track => params }.to_json, :content_type => :json, :accept => :json Track.new(JSON.parse(response)['playlists_track']) end end end
true
478525f3ea2293231429b91cb06063cd01147784
Ruby
fkhalili/wdi
/w08/d03/Homework/bttf/back_to_the_future.rb
UTF-8
1,826
3.125
3
[]
no_license
require "./vehicle.rb" require "./train.rb" require "./skateboard.rb" require "./bicycle.rb" require "./car.rb" require "pry" #Vehicle v1 = Vehicle.new("horse and buggy", 4, "Burton, OH") v1.description #=> "horse and buggy" v1.passengers #=> [] v1.go_to('the barn dance!') #=> "This horse and buggy is empty!" v1.location #=> "Burton, OH" v1.add_passenger('Jacob Miller') v1.add_passenger('John Miller') v1.add_passenger('Isaac Miller') v1.add_passenger('Mark Yoder') v1.in_danger? #=> false v1.passengers #=> ['Jacob Miller','John Miller','Isaac Miller','Mark Yoder'] v1.add_passenger('Sarah Hershberger') v1.in_danger? #=> true v1.go_to('the barn dance!') #=> "The horse and buggy is off to the barn dance!" v2 = Vehicle.new('skateboard', 1, 'Asbury Park, NJ') v2.add_passenger('Jerry Viatelli') v2.go_to('the Boardwalk') # to grind... v2.location #=> the Boardwalk v2.add_passenger('Marky Longello') v2.in_danger? #=> true #Train orient_express = Train.new('passenger train', 100, 'Istanbul') orient_express.pull_the_rope #=> Woo woooo! #Skateboard my_sweet_deck = Skateboard.new('SantaCruz™', 'Washington Square Park') my_sweet_deck.grind #=> "This Santa Cruz skateboard is empty!" my_sweet_deck.add_passenger('PJ') my_sweet_deck.goofy? #=> false my_sweet_deck.goofy = true my_sweet_deck.goofy? #=> true my_sweet_deck.grind #=> "khkhkhkhkh klunck khkh" my_sweet_deck.kickflip #=> "Rad! I can kickflip!" my_sweet_deck.go_to('Chelsea Piers') #Bicycle hot_ride = Bicycle.new('Huffy', 'Milwaukee, WI') hot_ride.add_passenger('Travis') hot_ride.add_passenger('Taryn') # pegs! hot_ride.in_danger? #=> true hot_ride.go_to('Rich\'s Restaurant') #=> "Crash!!" hot_ride.passengers #=> [] #Car delorean = Car.new(2, 1981, 'DeLorean', 'DMC-12', 'gray', 'Hill Valley') delorean.add_passenger('Marty McFly') delorean.refuel delorean.go_to('the dance') #=> "You're now at the dance."
true
cb6006345ed9b71ea39e56bee1f726a8ad24a4a7
Ruby
ybakos/processing-sublime-util
/syntax_comparator.rb
UTF-8
1,449
3.078125
3
[ "MIT" ]
permissive
require 'open-uri' require 'nokogiri' class SyntaxComparator XML_NODE_NAME = "string" # Typically "string", which wraps the regex you're after. # There's got to be a better way to do this... EXTRACTION_REGEX = /\\b\((.*)\)\\b/ SPLIT_CHARACTER = '|' API_REFERENCE_DOM_SELECTOR = "a.ref-link" def initialize(api_url, tm_language_path) @api_url = api_url @tm_language_path = tm_language_path end def diff api_words = parse_api_words package_syntax_words = parse_package_syntax_words result = "Missing in package syntax definition:\n#{api_words - package_syntax_words}\n\n" result += "Defined in package but not in API:\n#{package_syntax_words - api_words}\n" return result end private def parse_api_words xml = Nokogiri::HTML(open(@api_url)) xml_content = xml.css(API_REFERENCE_DOM_SELECTOR).map { |e| e.content.match(/^(\w*)/)[1] }.reject(&:empty?) end def parse_package_syntax_words contents = File.open(@tm_language_path, "r") { |file| to_keyword_list(file) } end def to_keyword_list(file) extract_keywords_from_xml(Nokogiri::XML(file)) end # Highly sensitive to the structure of the tmLanguage xml tree def extract_keywords_from_xml(xml) xml_content = xml.css(XML_NODE_NAME) xml_content.map { |e| e.to_s.match(EXTRACTION_REGEX) }.compact!.map {|e| e[1].split(SPLIT_CHARACTER)}.flatten! end end
true
a504c89619c77e22e8f46f3b8b54fd5c0eea201f
Ruby
ValeriyaKunichik/MY_SQLITE
/my_sqlite_request.rb
UTF-8
4,303
2.984375
3
[]
no_license
require 'csv' require "./methods.rb" class MySqliteRequest def initialize @data_table = nil @file_name =nil @table_2 =nil @all_columns = [] @select_cols = [] @where_filter = [] @where_count = 0 @join_tables = [] @sort_data = [] @insert_new_row = false @insert_data = {} @update_data = {} @delete_data = false @query_response = [] class << self attr_accessor :query_response end end def from(table_name) if table_name.end_with?('.csv') @file_name = table_name else @file_name = table_name+'.csv' end return self end def select(column_name) if column_name.kind_of?(Array) @select_cols = column_name else @select_cols.push(column_name) end return self end def where(column_name, criteria) @where_count+=1 @where_filter.push(column_name) @where_filter.push(criteria) return self end def join(column_on_db_a, filename_db_b, column_on_db_b) if !filename_db_b.end_with?('.csv') filename_db_b = filename_db_b+'.csv' end data_arr_b = CSV.parse(File.read(filename_db_b)) column_titles_b = data_arr_b.shift @table_2 = create_table(column_titles_b, data_arr_b) @join_tables.push(column_on_db_a) @join_tables.push(column_on_db_b) return self end def order(order, column_name) @sort_data.push(order) @sort_data.push(column_name) return self end def insert(table_name) if table_name.end_with?('.csv') @file_name = table_name else @file_name = table_name+'.csv' end @insert_new_row = true return self end def values(data) @insert_data = data return self end def update(table_name) if table_name.end_with?('.csv') @file_name = table_name else @file_name = table_name+'.csv' end return self end def set(data) @update_data = data return self end def delete @delete_data = true return self end def run data_array = CSV.parse(File.read(@file_name)) @all_columns = data_array.shift @data_table = create_table(@all_columns, data_array) if @select_cols.length == 0 || @select_cols[0] == '*' @select_cols = @all_columns end filter_query_response() if !@update_data.empty? update_table() update_file() end if @delete_data == true delete_data() update_file() end if @insert_new_row == true insert_data() end #COMMENT PRINT IF GOING TO USE CLI print @query_response return @query_response end end #TESTCASES# #SELECT# =begin request = MySqliteRequest.new request = request.from('nba_player_data.csv') request = request.select('name') #request = request.order('ASC','name') request.run =end #SELECT WHERE# =begin request = MySqliteRequest.new request = request.from('nba_player_data.csv') request = request.select('name') request = request.where('college', 'University of Oklahoma') request.run =end #SELECT MULTIPLE WHERE# =begin request = MySqliteRequest.new request = request.from('nba_player_data.csv') request = request.select('name') request = request.where('college', 'Louisiana State University') request = request.where('year_start', '1991') request.run =end #INSERT# =begin request = MySqliteRequest.new request = request.insert('nba_player_data.csv') request = request.values('name' => 'Alaa Abdelnaby', 'year_start' => '1991', 'year_end' => '1995', 'position' => 'F-C', 'height' => '6-10', 'weight' => '240', 'birth_date' => "June 24, 1968", 'college' => 'Duke University') request.run =end #UPDATE# =begin request = MySqliteRequest.new request = request.update('nba_player_data.csv') request = request.where('name', 'Ivan Dulin') request = request.set(:name => 'Ivan Pupkov') request.run =end #DELETE# =begin request = MySqliteRequest.new request = request.delete request = request.from('nba_player_data.csv') request = request.where('name', 'Alaa Abdelnaby') request.run =end #JOIN# =begin request = MySqliteRequest.new request = request.from('nba_player_data.csv') request = request.select(['name','year_start','favorite_color']) request = request.join('name', 'nba_player_data1.csv', 'player') request.run =end
true
9d91becab62d71834370cd8c03a62c3d68198c54
Ruby
webdev1001/twss
/script/collect_twss.rb
UTF-8
515
2.765625
3
[]
no_license
require 'rubygems' require 'open-uri' require 'hpricot' # Grab the first 2000 stories from twssstories.com (10 per page) f = File.open(File.expand_path("../../data/twss.txt", __FILE__), "w") domain = "http://twssstories.com" 200.times do |i| url = domain + "/node?page=#{i}" puts url doc = Hpricot(open(url).read) doc.search('div.content p') do |story| # now pull out the good stuff... if story.to_plain_text =~ /\"(.*)?\"/ f.puts $1 end end f.flush sleep rand * 3.0 end f.close
true
5827145b6020b2196ad76a58c2734f185141d2a2
Ruby
pineman/code
/ruby/irb.rb
UTF-8
802
2.5625
3
[]
no_license
#!/usr/bin/env ruby require 'rubygems' begin gem 'listen' rescue Gem::LoadError Gem.install('listen') gem 'listen' end require 'listen' require 'irb' def reload(file) old = $VERBOSE $VERBOSE = nil load file $VERBOSE = old end def watch_and_reload(dir_path) listener = Listen.to(File.dirname(dir_path), only: /\.rb$/) do |modified, added, removed| (modified + added).each do |file| reload file end # 'unload' does not exist for removed... end listener.start end if ARGV.count != 2 STDERR.puts <<EOS Usage: irb.rb <main file> <dir to watch> Launch irb and auto-reload all files in dir for ultimate REPL prototyping à la rails console. EOS exit 1 end file = ARGV[0].dup dir = ARGV[1].dup reload file Thread.new { watch_and_reload(dir) } ARGV.clear IRB.start
true
d0c7090c4cff00e38645d3ff7019069680011731
Ruby
ruby/tk
/sample/demos-jp/browse2
UTF-8
2,244
3.171875
3
[ "BSD-2-Clause", "Ruby" ]
permissive
#!/usr/bin/env ruby # browse -- # This script generates a directory browser, which lists the working # directory and allow you to open files or subdirectories by # double-clicking. require 'tk' class Browse BROWSE_WIN_COUNTER = TkVariable.new(0) def initialize(dir) BROWSE_WIN_COUNTER.value = BROWSE_WIN_COUNTER.to_i + 1 # create base frame base = TkToplevel.new { minsize(1,1) title('Browse : ' + dir) } # Create a scrollbar on the right side of the main window and a listbox # on the left side. list = TkListbox.new(base, 'relief'=>'sunken', 'width'=>20, 'height'=>20, 'setgrid'=>'yes') {|l| TkScrollbar.new(base, 'command'=>proc{|*args| l.yview *args}) {|s| pack('side'=>'right', 'fill'=>'y') l.yscrollcommand(proc{|first,last| s.set(first,last)}) } pack('side'=>'left', 'fill'=>'both', 'expand'=>'yes') # Fill the listbox with a list of all the files in the directory (run # the "ls" command to get that information). open("|ls -a #{dir}", 'r'){|fid| fid.readlines}.each{|fname| l.insert('end', fname.chomp) } } # Set up bindings for the browser. base.bind('Destroy', proc{ Browse::BROWSE_WIN_COUNTER.value = \ Browse::BROWSE_WIN_COUNTER.to_i - 1 }) base.bind('Control-c', proc{base.destroy}) list.bind('Double-Button-1', proc{TkSelection.get.each{|f| self.browse dir, f}}) end # The method below is invoked to open a browser on a given file; if the # file is a directory then another instance of this program is invoked; if # the file is a regular file then the Mx editor is invoked to display # the file. def browse (dir, file) file = dir + File::Separator + file if dir != '.' type = File.ftype(file) if type == 'directory' Browse.new(file) else if type == 'file' if ENV['EDITOR'] system(ENV['EDITOR'] + ' ' + file + ' &') else system('xedit ' + file + ' &') end else STDOUT.print "\"#{file}\" isn't a directory or regular file" end end end end Browse.new(ARGV[0] ? ARGV[0] : '.') TkRoot.new { withdraw Browse::BROWSE_WIN_COUNTER.trace('w', proc{exit if Browse::BROWSE_WIN_COUNTER.to_i == 0}) } Tk.mainloop
true
091c00da1f0892c08cf734c0f7df6e3cc51e41da
Ruby
vladL2C/stockPicker
/stockPicker.rb
UTF-8
479
3.65625
4
[]
no_license
def stockPicker(array) best_buy = 0 best_sell = 0 best_profit = 0 array.each do |buy| array.each do |sell| profit = sell - buy if profit > best_profit best_profit = profit best_buy = array.index(buy) best_sell = array.index(sell) end end end puts "the best day to buy is #{best_buy} and the best day to sell is #{best_sell} for a total profit of #{best_profit}" end stockPicker([9,1,3,4,5,6,7,8,20])
true
6a3f54c00ca7aaa5329e5db8e0b48180897d38d8
Ruby
LucyMHall/Bookmark-Manager-2
/spec/bookmark_spec.rb
UTF-8
834
2.65625
3
[]
no_license
require 'bookmark' require 'spec_database_helper.rb' describe Bookmark do describe '::create' do it 'takes a url and a title as arguments and add them to the database' do Bookmark.create('www.fakeurl.com','FakeUrl') expect(Bookmark.create('www.fakeurl.com','FakeUrl')).to be_an_instance_of(PG::Result) expect(Bookmark.all).to include("FakeUrl") end end describe '::all' do it 'returns the title for all bookmarks which have been added' do Bookmark.create('http://www.makersacademy.com', 'Makers') Bookmark.create('http://www.destroyallsoftware.com', 'Destroy') Bookmark.create('http://www.google.com', 'Google') expect(Bookmark.all).to include("Makers") expect(Bookmark.all).to include("Google") expect(Bookmark.all).to include("Destroy") end end end
true
ecef019b2f50b7d30cd9a1aac9990eda67d94532
Ruby
eac/redio
/lib/redio/cluster.rb
UTF-8
1,702
2.703125
3
[]
no_license
module Redio class Cluster attr_accessor :nodes, :distributed_methods def initialize(nodes) @nodes = nodes end def method_missing(method_id, *args, &block) options = distributed_methods[method_id] command = DistributedCommand.new(nodes, options) command.execute(method_id, args, block) command.last_successful_response end def distribute(method_id, options) distributed_methods[method_id] = options end def distributed_methods @distributed_options ||= {} end end class DistributedCommand attr_accessor :failed_nodes, :successful_nodes, :nodes, :options def initialize(nodes, options) @nodes = nodes @options = options end def minimum options[:minimum] || 1 end def maximum options[:maximum] end def execute(method_id, args, block) nodes.each do |node| begin result = node.send(method_id, *args, &block) success!(node, result) break if done? rescue Exception => exception failure!(node, exception) end end raise exception if failed? end def done? maximum && maximum > successful_nodes.size end def failed? (nodes.size - failed_nodes.size) < minimum end def success!(node, result) self.successful_nodes[node] = result end def failure!(node, exception) self.failed_nodes[node] = exception end def last_successful_response successful_nodes.values.last end def failed_nodes @failed_nodes ||= {} end def successful_nodes @successful_nodes ||= {} end end end
true
7299df92dfe8cba0651102f4bdf7f2c774c36207
Ruby
londonbridges13/adevacademy
/app/helpers/topics_helper.rb
UTF-8
11,362
3.03125
3
[]
no_license
module TopicsHelper #Display articles def get_articles_from(topics) @size = topics.count * 3 @amount = 0 @articles = [] i = 0 # while @articles.count < @size topics.each do |t| i += 1 # unless i == topics.count #@articles.count < @size add_articles(t) #add_an_article(t) # else # present_articles # ship it # end end add_featured_articles(@amount) #present_articles # ship it # end end # def add_an_article(topic) # potential_articles = topic.articles.where(:publish_it => true).sort_by(&:created_at).reverse # if potential_articles.count > 0 # done = false # i = 0 # while i < potential_articles.count and done == false # # check if articles includes # unless @articles.include? potential_articles[i] # MAYBE HERE LYES THE PROBLEM # #doesn't contain this article, so add it # @articles.push(potential_articles[i]) # done = true # end # if potential_articles.count == 1 # done = true # end # i += 1 # present_articles # end # end # end # def add_articles(topic) # two_days_ago = Time.now - 22.days # change back to 2 # potential_articles = topic.articles.where('publish_it = ? AND article_date > ?', true ,two_days_ago) # # if potential_articles.count > 0 # # add each to @articles if they aren't in the article # potential_articles.each do |a| # unless @articles.include? a # # doesn't contain this article, add it # a.display_topic = topic.title # @articles.push(a) # end # end # # end # end def add_articles(topic) two_days_ago = Time.now - 3.days # change back to 2 # potential_articles = topic.articles.where('publish_it = ? AND article_date > ?', true ,two_days_ago) potential_articles = topic.articles.where('article_date > ?', two_days_ago).where(:publish_it => true) if potential_articles.count > 2 # 3 is enough # add each to @articles if they aren't in the article count = 0 potential_articles.each do |a| unless @articles.include? a or count == 3 # doesn't contain this article, add it a.display_topic = topic.title if a.desc == "" a.desc = "From #{a.resource.title}" end @articles.push(a) count += 1 end end else # Back up Query # potential_articles = topic.articles.where(:publish_it => true).limit(5).sort_by(&:created_at).reverse potential_articles = topic.articles.limit(5).where(:publish_it => true).order("article_date DESC")#.reverse # grabs five newest articles count = 0 ii = 0 while ii < potential_articles.count #collect 2 potential_articles add to @articles a = potential_articles[ii] unless @articles.include? a or count == 2 a.display_topic = topic.title @articles.push(a) count += 1 end ii += 1 end # the goal above is to collect two articles from this topics # the goal below is to collect another article that was featured # also if the potential_articles didn't give 2 articles, below will provide extra articles for @articles # the goal is to get three articles per topic @amount += 3 - count # featured_topic = Topic.where(:id => 12).first # the id of te featured_topic should be four 1/13/17 # # featured_articles = featured_topic.articles.where(:publish_it => true).limit(5).sort_by(&:created_at).reverse # featured_articles = featured_topic.articles.limit(10).where(:publish_it => true).order("article_date DESC") # # done = false # i = 0 # while i < featured_articles.count and done == false # a = featured_articles[i] # unless @articles.include? a # if count >= 3 # done = true # else # a.display_topic = featured_topic.title # @articles.push(a) # end # end # i += 1 # end end end def present_articles # if @articles.count >= @size present @articles # end end def add_featured_articles(amount) # this querys for the amount of featured articles needed featured_topic = Topic.where(:id => 12).first # the id of te featured_topic should be four 1/13/17 featured_articles = featured_topic.articles.limit(10).where(:publish_it => true).order("article_date DESC") i = 0 count = 0 while i < featured_articles.count and count < amount a = featured_articles[i] unless @articles.include? a a.display_topic = featured_topic.title @articles.push(a) count += 1 end i += 1 end present_articles end #Get New Articles def find_new_articles_from_topic(topic) #This grabs new articles from one topic #Take all the resources from the topic and searches them for new articles topic.resources.each do |r| check_resource(r) end end def check_resource(resource) #should be the same as ArticlesHelper if resource.resource_url.include? "youtube.com" # Check for videos in this resource get_youtube_videos(resource) elsif resource.resource_url.include? "autoimmunewellness.com" or resource.resource_type == "article-xml" # the weird articles that cause errors get_other_articles(resource) else # Check for articles in this resource get_articles(resource) end end # GET ARTICLES def get_youtube_videos(resource) # this gets the other a youtube channel's videos using Feedjira::fetch_and_parse # resource.resource_url.include? "youtube.com" , should be true # Check for videos in this resource #able_to_parse url = resource.resource_url#"http://feeds.feedburner.com/MinimalistBaker?format=xml" xml = Faraday.get(url).body.force_encoding('utf-8') feed = Feedjira::Feed.fetch_and_parse xml#resource.resource_url#force_encoding('UTF-8') feed.entries.each do |entry| i = 0 while i < 3 # Check if the entry is older than two days, and check if it exists in the articles database two_days_ago = Time.now - 3.days all_articles = Article.all.where('article_date > ?', two_days_ago) #works all_article_urls = [] all_articles.each do |u| all_article_urls.push(u.article_url) end if entry.published > two_days_ago # check if contained in Article Database unless all_article_urls.include? entry.url #good to Use # images = LinkThumbnailer.generate(entry.url) article_image_url = LinkThumbnailer.generate(entry.url).images.first.src.to_s # article_image_url = images.images.first.src.to_s new_article = resource.articles.build(:title => entry.title, :article_url => entry.url, :article_image_url => article_image_url, :desc => Sanitize.fragment(entry.summary), :resource_type => 'article', :article_date => entry.published, :publish_it => nil)#, :image) new_article.save end end i += 1 end end end def get_articles(resource) # this gets the other articles using Feedjira::parse # Check for articles in this resource url = resource.resource_url#"http://feeds.feedburner.com/MinimalistBaker?format=xml" xml = Faraday.get(url).body.force_encoding('utf-8') puts url feed = Feedjira::Feed.parse xml#url#resource.resource_url#force_encoding('UTF-8') feed.entries.each do |entry| i = 0 while i < 3 # Check if the entry is older than two days, and check if it exists in the articles database two_days_ago = Time.now - 3.days all_articles = Article.all.where('article_date > ?', two_days_ago) #works all_article_urls = [] all_articles.each do |u| all_article_urls.push(u.article_url) end if entry.published > two_days_ago # check if contained in Article Database unless all_article_urls.include? entry.url #good to Use # get_article_image_url(entry.url) max_retries = 3 times_retried = 0 begin article_image_url = LinkThumbnailer.generate(entry.url, attributes: [:images], image_limit: 1, image_stats: false).images.first.src.to_s rescue Net::ReadTimeout => error if times_retried < max_retries times_retried += 1 puts "Failed to <do the thing>, retry #{times_retried}/#{max_retries}" retry else puts "Exiting script. <explanation of why this is unlikely to recover>" exit(1) end end # images = LinkThumbnailer.generate(entry.url) # if LinkThumbnailer.generate(entry.url) # article_image_url = LinkThumbnailer.generate(entry.url).images.first.src.to_s # # article_image_url = images.images.first.src.to_s # else # article_image_url = nil # end new_article = resource.articles.build(:title => entry.title, :article_url => entry.url, :article_image_url => article_image_url, :desc => Sanitize.fragment(entry.summary), :resource_type => 'article', :article_date => entry.published, :publish_it => nil)#, :image) new_article.save end end i += 1 end end end def get_other_articles(resource) # this gets the other articles using Feedjira::fetch_and_parse url = resource.resource_url#"http://feeds.feedburner.com/MinimalistBaker?format=xml" # xml = Faraday.get(url).body.force_encoding('utf-8') puts url feed = Feedjira::Feed.fetch_and_parse url#resource.resource_url#force_encoding('UTF-8') feed.entries.each do |entry| i = 0 while i < 3 # Check if the entry is older than two days, and check if it exists in the articles database two_days_ago = Time.now - 3.days all_articles = Article.all.where('article_date > ?', two_days_ago) #works all_article_urls = [] all_articles.each do |u| all_article_urls.push(u.article_url) end if entry.published > two_days_ago # check if contained in Article Database unless all_article_urls.include? entry.url #good to Use # images = LinkThumbnailer.generate(entry.url) article_image_url = LinkThumbnailer.generate(entry.url, attributes: [:images], image_limit: 1, image_stats: false).images.first.src.to_s # article_image_url = images.images.first.src.to_s new_article = resource.articles.build(:title => entry.title, :article_url => entry.url, :article_image_url => article_image_url, :desc => Sanitize.fragment(entry.summary), :resource_type => 'article', :article_date => entry.published, :publish_it => nil)#, :image) new_article.save end end i += 1 end end end end
true
ae46cf41802ad742b7937319108b29e78556a39c
Ruby
slstevens/boris_bikes
/lib/garage.rb
UTF-8
259
2.703125
3
[]
no_license
require_relative 'bike_container' class Garage include BikeContainer def initialize(options = {}) self.capacity = options.fetch(:capacity, capacity) end def fix_broken_bike(broken_bike) broken_bikes.each do |bike| bike.fix! end end end
true
d2841f96e08e110c70f65434c5ae811e65e5872b
Ruby
zhangem/to_do_list_2_ruby
/to_do.rb
UTF-8
1,141
3.828125
4
[]
no_license
require './lib/to_do_list' @list = [] @done =[] def main_menu puts "Press 'A' to add a task" puts "Press 'L' to list all of your tasks" puts "Press 'D' to delete task" puts "Press 'X' to exit" puts "Press 'F' to show finished taskes" main_choice = gets.chomp if main_choice == 'a' add_task elsif main_choice == 'l' list_tasks elsif main_choice =='x' puts "Good-bye!" elsif main_choice == 'd' delete_task elsif main_choice == 'f' list_finished else puts "Sorry, that wasn't a valid option." main_menu end end def add_task puts "Enter a description of the new task:" user_description = gets.chomp @list << Task.new(user_description) puts "Task added.\n\n" main_menu end def list_tasks puts "Here are all of your tasks:" @list.each_with_index do |task, index| puts (index + 1).to_s + ". " + task.description end puts "\n" main_menu end def delete_task puts "Which task are finished?" user_input = gets.chomp.to_i - 1 @list.each_with_index do |task, index| if user_input == index @list.delete_at(index) end end list_tasks end main_menu
true
6441985f7c2982136d0485ad19456efb11d88322
Ruby
jrabeck/weekend_two
/demo.rb
UTF-8
1,205
3.734375
4
[]
no_license
class Superhero attr_accessor :name, :attack, :hitpoints, :alive, :has_secret_weapon def initialize(superhero) @name = superhero[:name] @hitpoints = superhero[:hitpoints] @attack = superhero[:attack] @alive = true @has_secret_weapon = false end def hits(opponent) opponent.hitpoints = opponent.hitpoints - @attack if opponent.hitpoints < 1 opponent.alive = false end end def grabs_item @has_secret_weapon = true @attack = @attack * 20 end end superman = Superhero.new({name: "Superman", hitpoints: 30, attack: 5, alive: true}) jake = Superhero.new({name: "Jake", hitpoints: 30, attack: 1, alive: true}) #FIGHT BEGINS!!! puts "FIGHT BEGINS!!!" puts puts "#{superman.name} hits #{jake.name}" superman.hits(jake) puts "#{jake.name} hits #{superman.name} 5 times!!!" 5.times do jake.hits(superman) end puts "#{superman.name} hits #{jake.name} 4 times!!!" 4.times do superman.hits(jake) end puts "#{jake.name} gets Kryptonite!!!" jake.grabs_item jake.hits(superman) puts "#{jake.name} hits #{superman.name}!!!" jake.hits(superman) puts "#{jake.name} hits #{superman.name}!!!" if superman.alive == false puts "Superman is dead." end
true
b67fa3934066f381747483da23bb67d2824a01d2
Ruby
tungnguyenvan/Ruby-Basic
/Baitap/phan5/cau1/tinh_toan.rb
UTF-8
329
3.328125
3
[]
no_license
a = 0 b = 0 f = File.open("in.txt", "r") f.each_line do |line| so = line.split(" ") a = so[0] b = so[1] end a = a.to_i b = b.to_i tong = a+b hieu = a-b tich = a*b thuong = a/b puts "tong cua 2 so a,b : #{tong}" puts "hieu cua 2 so a,b : #{hieu}" puts "tich cua 2 so a,b : #{tich}" puts "thuong cua 2 so a,b: #{thuong}"
true
d387b2f4adfbdce54a0f776394fe16dc55b9ef2f
Ruby
mgsx-dev/processing-glsl
/ProcessingSample/tomd.rb
UTF-8
5,205
2.578125
3
[]
no_license
require 'date' require 'fileutils' module GLSLParser class Context attr_accessor :site, :dir, :group, :text, :code, :file end def self.empty?(line) line.strip.empty? end def self.comment_begin?(line) line.strip.start_with?("/**") end def self.comment_end?(line) line.strip.end_with?("*/") end def self.add_code(context, line) context.code << line context.text << line end def self.add_text(context, line) context.text << line end def self.add_code_begin(context) context.text << '' context.text << '``` glsl' end def self.add_code_end(context) context.text << '```' context.text << '' end def self.filename_to_path(filename) filename.scan(/([0-9]+)-/).flatten.map{|s| s.to_i} end def self.path_to_filename(path) path.map{|i| "%03d" % i}.join("-") end def self.find_file(context, path) if not path.empty? then Dir.glob("#{context.dir}/*.glsl") .map{|file| File.basename(file)} .select{|file| filename_to_path(file) == path} .first else nil end end def self.remove_ext(filename) parts = filename.split(".") parts.first(parts.size-1) end def self.file_to_postfilename(file) date = date_from_file(file) "#{date.strftime("%Y-%m-%d")}-#{File.basename(file,File.extname(file))}" end def self.filename_to_postname(filename) name = File.basename(filename,File.extname(filename)) path = filename_to_path(filename) names = name.split('-') words = names.last(names.size - path.size).map{|word| word[0].upcase + word[1..(word.size)]}.join(' ') return path.join('.') + ' - ' + words end def self.post_datetime(file) date = date_from_file(file) "#{date.strftime("%Y-%m-%d %H:%M:%S")}" end def self.date_from_file(file) Date.new(2015, 7, 21) # File.mtime(file) end def self.eof(context) # find previous and next tutorial # first parse filename filename = File.basename(context.file) basename = File.basename(filename,File.extname(filename)) postname = filename_to_postname(filename) path = filename_to_path(filename) return if path.empty? parent_path = path.first(path.size-1) prev_path = parent_path + [path.last - 1] next_path = parent_path + [path.last + 1] child_path = path + [1] prev_file = find_file(context, prev_path) next_file = find_file(context, next_path) parent_file = find_file(context, parent_path) child_file = find_file(context, child_path) lines = [] preview_ext = File.extname(Dir.glob("#{context.site}/img/blog/#{context.group}/thumb/#{basename}.*").first) # Jekyll header lines << "---" lines << "layout: glsl" lines << "name: \"#{postname}\"" lines << "date: #{post_datetime(context.file)}" lines << "type: glsl" lines << "group: #{context.group}" lines << "preview: /img/blog/#{context.group}/thumb/#{basename}#{preview_ext}" lines << "screenshot: /img/blog/#{context.group}/#{basename}.png" lines << "excerpt: \"#{context.text.first}\"" unless context.text.empty? if prev_file and File.exists?("#{context.dir}/#{prev_file}") then lines << "before: #{filename_to_postname(prev_file)}" end if next_file and File.exists?("#{context.dir}/#{next_file}") then lines << "after: #{filename_to_postname(next_file)}" end if parent_file and File.exists?("#{context.dir}/#{parent_file}") then lines << "parent: #{filename_to_postname(parent_file)}" end if child_file and File.exists?("#{context.dir}/#{child_file}") then lines << "child: #{filename_to_postname(child_file)}" end lines << "---" # markdown layout lines << "## Explanations" lines << "" lines += context.text lines << "" lines << "## Full Code Source" lines << "" lines << "``` glsl" lines += context.code lines << "```" # make filename for jekyll folder = "#{context.site}/_posts/#{context.group}" FileUtils.makedirs(folder) File.write("#{folder}/#{file_to_postfilename(context.file)}.md", lines.join("\n")); end INIT = { file: lambda {|ctx, file| ctx.file = file ctx.code = [] ctx.text = [] FIRST }, eof: lambda {|ctx| INIT } } FIRST = { line: lambda {|ctx, line| case when empty?(line) then FIRST when comment_begin?(line) then TEXT else add_code_begin(ctx); add_code(ctx, line); CODE end }, eof: lambda {|ctx| eof(ctx) INIT } } CODE = { line: lambda {|ctx, line| case when comment_begin?(line) then add_code_end(ctx); TEXT else add_code(ctx, line); CODE end }, eof: lambda {|ctx| add_code_end(ctx) eof(ctx) INIT } } TEXT = { line: lambda {|ctx, line| case when comment_end?(line) then FIRST else add_text(ctx, line); TEXT end }, eof: lambda {|ctx| eof(ctx) INIT } } end context = GLSLParser::Context.new root = ARGV[0] context.site = ARGV[1] state = GLSLParser::INIT Dir.glob("#{root}/*").each do |group| if File.directory?(group) then context.dir = group context.group = File.basename(group) Dir.glob("#{group}/*.glsl").each do |file| content = File.read(file) state = state[:file].call(context, file) content.split("\n").each do |line| state = state[:line].call(context, line) end state = state[:eof].call(context) end end end
true
3412af84a909763976e6c27e7ce777f2c11f891c
Ruby
listiani13/coursera
/SaaS/week2/public/lib/rock_paper_scissors.rb
UTF-8
1,178
3.4375
3
[]
no_license
class RockPaperScissors # Exceptions this class can raise: class NoSuchStrategyError < StandardError ; end def self.winner(player1, player2) # YOUR CODE HERE w = ["RS", "PR", "SP"]; valid = ["R", "P", "S"]; if w.index(player1[1].upcase + player2[1].upcase) return player1 elsif !valid.index(player1[1].upcase) or !valid.index(player2[1].upcase) raise RockPaperScissors::NoSuchStrategyError,"Strategy must be one of R,P,S" elsif player1[1].upcase == player2[1].upcase return player1 else return player2 end end def self.tournament_winner(tournament) # YOUR CODE HERE if tournament[0][0].class.to_s == "String" return self.winner(tournament[0], tournament[1]) end if tournament.length == 1 p1 = self.winner(tournament[0][0][0], tournament[0][0][1]) p2 = self.winner(tournament[0][1][0], tournament[0][1][1]) return self.winner(p1, p2) end len = tournament.length # recursively solve the problem p1 = self.tournament_winner(tournament.slice(0, len/2)) p2 = self.tournament_winner(tournament.slice(len/2, len/2)) self.winner(p1, p2) end end
true
cd2f26e7b0954257381d25f3fab987840e122621
Ruby
mapi8808/practice-ruby
/add.rb
UTF-8
386
3.90625
4
[]
no_license
amounts = {"リンゴ"=>2, "イチゴ"=>5, "オレンジ"=>3} amounts.each do |fruit, amount| #ハッシュの内容を順にキーをfruit、値をamountに代入して繰り返す puts "#{fruit}は#{amount}個です。" end i = 1 while i <= 10 do if i == 5 puts "処理を終了します" break # iが5になると繰り返しから抜ける end puts i i += 1 end
true
840d704cd01bbd13e2e41ebee15c4eb6b7f4e90a
Ruby
nelyj/dagger
/lib/dagger.rb
UTF-8
6,209
2.65625
3
[ "MIT" ]
permissive
require 'dagger/version' require 'dagger/response' require 'dagger/parsers' require 'net/https' require 'base64' module Dagger REDIRECT_CODES = [301, 302, 303].freeze DEFAULT_RETRY_WAIT = 5.freeze # seconds DEFAULT_HEADERS = { 'Accept' => '*/*', 'User-Agent' => "Dagger/#{VERSION} (Ruby Net::HTTP Wrapper, like curl)" } module Utils def self.parse_uri(uri) raise ArgumentError.new("Empty URI") if uri.to_s.strip == '' uri = 'http://' + uri unless uri.to_s['http'] uri = URI.parse(uri) raise ArgumentError.new("Invalid URI: #{uri}") unless uri.is_a?(URI::HTTP) uri.path = '/' if uri.path == '' uri end def self.encode(obj, key = nil) if key.nil? && obj.is_a?(String) # && obj['='] return obj end case obj when Hash then obj.map { |k, v| encode(v, append_key(key,k)) }.join('&') when Array then obj.map { |v| encode(v, "#{key}[]") }.join('&') when nil then '' else "#{key}=#{URI.escape(obj.to_s)}" end end def self.append_key(root_key, key) root_key.nil? ? key : "#{root_key}[#{key.to_s}]" end end class Client def self.init(uri, opts) uri = Utils.parse_uri(uri) http = Net::HTTP.new(uri.host, uri.port) if uri.port == 443 http.use_ssl = true http.verify_mode = opts[:verify_ssl] === false ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER end [:open_timeout, :read_timeout, :ssl_version, :ciphers].each do |key| http.send("#{key}=", opts[key]) if opts.has_key?(key) end new(http) end def initialize(http) @http = http end def get(uri, opts = {}) opts[:follow] = 10 if opts[:follow] == true path = uri[0] == '/' ? uri : Utils.parse_uri(uri).request_uri path.sub!(/\?.*|$/, '?' + Utils.encode(opts[:query])) if opts[:query] and opts[:query].any? headers = opts[:headers] || {} headers['Accept'] = 'application/json' if opts[:json] request = Net::HTTP::Get.new(path, DEFAULT_HEADERS.merge(headers)) request.basic_auth(opts.delete(:username), opts.delete(:password)) if opts[:username] @http.start unless @http.started? resp, data = @http.request(request) if REDIRECT_CODES.include?(resp.code.to_i) && resp['Location'] && (opts[:follow] && opts[:follow] > 0) opts[:follow] -= 1 puts "Following redirect to #{resp['Location']}" return get(resp['Location'], opts) end @response = build_response(resp, data || resp.body) rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EINVAL, Timeout::Error, \ SocketError, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, OpenSSL::SSL::SSLError => e if retries = opts[:retries] and retries.to_i > 0 puts "Got #{e.class}! Retrying in a sec (#{retries} retries left)" sleep (opts[:retry_wait] || DEFAULT_RETRY_WAIT) get(uri, opts.merge(retries: retries - 1)) else raise end end def post(uri, data, options = {}) request(:post, uri, data, options) end def put(uri, data, options = {}) request(:put, uri, data, options) end def patch(uri, data, options = {}) request(:patch, uri, data, options) end def delete(uri, data, options = {}) request(:delete, uri, data, options) end def request(method, uri, data, opts = {}) if method.to_s.downcase == 'get' query = (opts[:query] || {}).merge(data || {}) return get(uri, opts.merge(query: query)) end uri = Utils.parse_uri(uri) headers = DEFAULT_HEADERS.merge(opts[:headers] || {}) query = if data.is_a?(String) data elsif opts[:json] headers['Accept'] = headers['Content-Type'] = 'application/json' Oj.dump(data, mode: :compat) # compat ensures symbols are converted to strings else # querystring, then Utils.encode(data) end if opts[:username] # opts[:password] is optional str = [opts[:username], opts[:password]].compact.join(':') headers['Authorization'] = "Basic " + Base64.encode64(str) end args = [method.to_s.downcase, uri.path, query, headers] args.delete_at(2) if args[0] == 'delete' # Net::HTTP's delete does not accept data @http.start unless @http.started? resp, data = @http.send(*args) @response = build_response(resp, data || resp.body) rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EINVAL, Timeout::Error, \ SocketError, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, OpenSSL::SSL::SSLError => e if method.to_s.downcase != 'get' && retries = opts[:retries] and retries.to_i > 0 puts "Got #{e.class}! Retrying in a sec (#{retries} retries left)" sleep (opts[:retry_wait] || DEFAULT_RETRY_WAIT) request(method, uri, data, opts.merge(retries: retries - 1)) else raise end end def response @response or raise 'Request not sent!' end def open(&block) @http.start do instance_eval(&block) end end def close @http.finish if @http.started? end private def build_response(resp, body) resp.extend(Response) resp.set_body(body) unless resp.body resp end end class << self def open(uri, opts = {}, &block) client = Client.init(uri, opts) client.open(&block) if block_given? client end def get(uri, options = {}) request(:get, uri, nil, options) end def post(uri, data, options = {}) request(:post, uri, data, options) end def put(uri, data, options = {}) request(:put, uri, data, options) end def patch(uri, data, options = {}) request(:patch, uri, data, options) end def delete(uri, data, options = {}) request(:delete, uri, data, options) end def request(method, url, data = {}, options = {}) Client.init(url, options).request(method, url, data, options) end end end
true
db8ccfeb69f42f777707e6db43efd3875d88e8bc
Ruby
TSSaint/ruby-misc
/ruby_conditionals.rb
UTF-8
558
3.9375
4
[]
no_license
# conditionals, allows code to react to some data # not the same as methods though # we can use statements like else and else if to add other conditions # chains start with plain ifs; new conditional statements result new outputs num = 3 # if num > 0 # puts "num is bigger than 0" # elsif num < 0 # puts "num is smaller than 0" # elsif num == 0 # puts "number IS zero :)" # end # all other conditionals are ignored once one is met if num > 0 && num % 2 == 0 puts "positive and even" elsif num % 2 != 0 puts "it is positive but odd" end
true
8da8484ceb787ff4d7494b01b9eab5dd8afea54d
Ruby
avitus/Assetcorrelation
/app/models/security.rb
UTF-8
5,774
3.03125
3
[]
no_license
class Security < ActiveRecord::Base has_many :price_quotes, :dependent => :destroy has_many :positions, :dependent => :destroy validates :ticker, :uniqueness => true # ---------------------------------------------------------------------------------------------------------- # Get historical prices and save to our database # ---------------------------------------------------------------------------------------------------------- def price_history(days = 30) #===== TODO: Need to check for a stock split # ------ Insert stock split check here ----- # Check whether we have the data in DB historical_prices = self.price_quotes.where("date >= ?", Date.today - days).order("date DESC") #===== Supplement missing data from Yahoo h = Array.new if historical_prices.empty? # We have no price history at all for this security h = YahooFinance::get_historical_quotes_days(ticker.upcase, days) else most_recent_date = historical_prices.first.date oldest_date = historical_prices.last.date if most_recent_date != Date.today # recent data is missing h += YahooFinance::get_historical_quotes_days( ticker.upcase, Date.today - most_recent_date) end if oldest_date != Date.today - days # older data is missing h += YahooFinance::get_historical_quotes( ticker.upcase, Date.today - days, oldest_date) end end #===== Save data from Yahoo into DB # TODO: extract this into a separate helper method h.each { |yahoo_quote| yahoo_date = Date.parse(yahoo_quote[0]) if self.price_quotes.exists?(:date => yahoo_date) # Skip else self.price_quotes.create(:date => yahoo_date, :price => yahoo_quote[6].to_f) end } return self.price_quotes.where("date >= ?", Date.today - days).order("date DESC") end # ---------------------------------------------------------------------------------------------------------- # Compare price history on Yahoo to our data in order to identify a stock split # ---------------------------------------------------------------------------------------------------------- def has_split? # Get oldest stock price oldest_quote_db = self.price_quotes.order("date ASC").first if oldest_quote_db oldest_date_db = oldest_quote_db.date unless !oldest_quote_db oldest_price_db = oldest_quote_db.price unless !oldest_quote_db oldest_quote_yahoo = YahooFinance::get_HistoricalQuotes( ticker.upcase, oldest_date_db, oldest_date_db ) if !oldest_quote_yahoo.blank? # we were able to get a quote for that date oldest_date_yahoo = Date.parse(oldest_quote_yahoo[0].to_a[1]) oldest_price_yahoo = oldest_quote_yahoo[0].to_a[7] # check that we're comparing prices from the same day return ( (oldest_date_yahoo == oldest_date_db) and (oldest_price_yahoo != oldest_price_db) ) else # Yahoo returned [] return true # we have data in our database that doesn't exist in the Yahoo DB --> throw out our data end else return false # we have no data so no need to do anything end end # ---------------------------------------------------------------------------------------------------------- # Latest closing price # ---------------------------------------------------------------------------------------------------------- def closing_price # Check whether we have the data in DB last_close = self.price_quotes.where("date >= ?", Date.today - 1).first # Get last 3 days to account for long weekends if !last_close Rails.logger.debug("*** Pinging Yahoo for closing price for #{self.ticker}") last_close = Array.new last_close += YahooFinance::get_historical_quotes_days( ticker.upcase, 3 ) Rails.logger.debug("*** Quote: #{last_close.inspect}") # ===== Save data from Yahoo into DB # TODO: extract this into a separate helper method last_close.each { |yahoo_quote| yahoo_date = Date.parse(yahoo_quote[0]) if self.price_quotes.exists?(:date => yahoo_date) # Skip else self.price_quotes.create(:date => yahoo_date, :price => yahoo_quote[6].to_f) end } if !last_close.empty? return last_close.first[6] # 6th element in array is adjusted closing price else return nil # handles case where Yahoo stops returning price history for a once valid security. Security should be removed end else return last_close.price end end # ---------------------------------------------------------------------------------------------------------- # Check whether security has any price history on Yahoo # ---------------------------------------------------------------------------------------------------------- def has_history? # Check with Yahoo Rails.logger.info("=== Querying Yahoo for security: #{self.ticker}") ticker = self.ticker quote_type = YahooFinance::StandardQuote quote = YahooFinance::get_quotes( quote_type, ticker ) # A valid return will result in quote[ticker].nil? and quote[ticker].blank? being false. # However, even if the ticker does not exist, the call to YahooFinance will result in a # valid quote but the date field will be "N/A" # 10/15/2008 -- Some money market funds return a valid date field but have no trading history if quote[ticker] # Check for 5 days of history and a valid date field has_history = YahooFinance::get_historical_quotes_days(ticker, 7).size > 0 return (quote[ticker].date != "N/A") && has_history else return false end end end # of class
true
2e44a2fe1b666c6d4043b2824677333a94bc2320
Ruby
zizhang/the_odin_project
/ruby_building_blocks/substrings.rb
UTF-8
482
3.6875
4
[]
no_license
def substrings(input_text, dictionary) substrings_found = Hash.new(0) words = input_text.downcase.split(" ") words.each do |word| dictionary.each do |dictionary_word| if word.include?(dictionary_word) substrings_found[dictionary_word] += 1 end end end return substrings_found end puts "Enter text" input = gets.chomp dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"] p substrings(input, dictionary)
true
1d125a494e7b5d59a0ddc1b4eab9306835f46b80
Ruby
wzcolon/listings_scraper
/app/services/create_scrape.rb
UTF-8
1,143
2.84375
3
[]
no_license
class CreateScrape CouldNotScrapeError = Class.new(StandardError) attr_reader :scrape_type, :scrape def initialize(scrape_type:) @scrape_type = scrape_type @listings = 0 end def call scrape! end private def scrape! begin while @listings < 1000 results.each do |result| Listing.create(new_listing(result)) @listings += 1 end visit_next_page end rescue => e raise CouldNotScrapeError.new(e) end scrape end def results page.css('.result-info') end def new_listing(result) { price: result.at_css('.result-price').try(:text), title: result.at_css('a').try(:text), date: result.at_css('.result-date').try(:text), link: result.at_css('a').attributes['href'].try(:value), scrape: scrape } end def visit_next_page agent.page.link_with(text: 'next > ').click end def scrape @scrape ||= Scrape.create(scrape_type: scrape_type) end def page agent.get(url) end def agent @agent ||= Mechanize.new end def url Scrape.url_for(scrape_type) end end
true
0578f9bcb31456002b6568ac734b2c58a3fa8464
Ruby
jstoebel/code-workout
/app/representers/exercise_representer.rb
UTF-8
2,274
2.515625
3
[]
no_license
require 'representable/hash' class ExerciseRepresenter < Representable::Decorator include Representable::Hash collection_representer class: Exercise, instance: lambda { |fragment, i, args| if fragment.has_key? 'external_id' e = Exercise.where(external_id: fragment['external_id']).first e || Exercise.new else Exercise.new end } property :name property :external_id property :is_public, setter: lambda { |val, *| self.is_public = val.to_b } property :experience property :language_list, getter: lambda { |*| language_list.to_s } property :style_list, getter: lambda { |*| style_list.to_s } property :tag_list, getter: lambda { |*| tag_list.to_s } property :exercise_family, getter: lambda { |*| exercise_family.andand.name }, setter: lambda { |val, *| if val.andand.length >= 1 if ExerciseFamily.where(name: val).any? self.exercise_family = ExerciseFamily.where(name: val).first else new_exercise_family = ExerciseFamily.new(name: val) self.exercise_family = new_exercise_family new_exercise_family.save! end end } property :current_version, class: ExerciseVersion, setter: lambda { |val, *| self.current_version = val self.exercise_versions << self.current_version self.current_version.exercise = self }, instance: lambda { |*| ExerciseVersion.new } do property :version, setter: lambda { |*| } property :creator, getter: lambda { |*| creator.andand.email }, setter: lambda { |val, *| if val self.creator = User.where(email: val).first end } property :stem, class: Stem do property :preamble end collection :prompts, render_filter: lambda { |val, *| val.map(&:specific) }, setter: lambda { |p_array, *| p_array.each do |p| p.exercise_version = self self.prompts << p end }, class: lambda { |hsh, *| hsh.has_key?('coding_prompt') ? CodingPrompt : MultipleChoicePrompt }, decorator: lambda { |o, *| o.is_a?(CodingPrompt) ? CodingPromptRepresenter : MultipleChoicePromptRepresenter } end end
true
84350cb87898eb87e48e7e85043bd78ef635f0f8
Ruby
piercus/XMPePer
/vendor/plugins/canhaschat/generators/chat_system/templates/mongrel_handler.rb
UTF-8
1,827
2.515625
3
[ "MIT" ]
permissive
require 'rubygems' require 'json' require 'drb' require 'erb' require 'yaml' # basic form of this file # taken from: # http://adam.blogs.bitscribe.net/ class PushHandler < Mongrel::HttpHandler def initialize config_file = File.read("config/chat_server.yml") evaluated = YAML.load(ERB.new(config_file).result) @config = evaluated[ENV["RAILS_ENV"] || "development"] @server = DRbObject.new(nil, @config["socket"]) @keepalive_secs = (@config["mongrel_keepalive"]) ? @config["mongrel_keepalive"].to_i : 30 end def process(request, response) params = Mongrel::HttpRequest.query_parse(request.params["QUERY_STRING"]) chat_id = params["chat_id"] from = params["from"] transport = params["transport"] messages = [] request_start = Time.now begin while messages.empty? messages = wait_for_messages(chat_id, from, transport) if (Time.now-request_start)<@keepalive_secs sleep(0.5) else break end end response.start(200) do |head, out| head["Content-type"] = "application/json" out.write messages.to_json end rescue response.start(500) do |head, out| head["Content-type"] = "text/plain" out.write "An error ocurred when fetching messages" end end end def wait_for_messages(chatid, from, transport) messages =nil begin messages = @server.check_for_messages(:id => chatid, :from => from, :transport => transport) rescue puts $!.to_s raise end return messages end end uri "/<%= controller_file_name %>/push", :handler => PushHandler.new, :in_front => true
true
f51abe38d0b2a018eab7e2907cf6926f988e3f21
Ruby
MariaVla/memcached
/spec/item_spec.rb
UTF-8
3,568
2.5625
3
[]
no_license
require_relative 'spec_helper' require_relative '../Memcached.rb' require_relative '../MemcachedValue.rb' memcached = Memcached.new("memcached") value_one = MemcachedValue.new() value_one.key = 'foo' value_one.time = 4444 value_one.bytes = 4 value_one.data = 'hola' value_two = MemcachedValue.new() value_two.key = 'bar' value_two.time = 4444 value_two.bytes = 4 value_two.data = 'chau' value_three = MemcachedValue.new() value_three.key = 'bar' value_three.time = 3333 value_three.bytes = 3 value_three.data = 'alo' value_four = MemcachedValue.new() value_four.key = 'foo' value_four.time = 3333 value_four.bytes = 3 value_four.data = 'aaa' value_two_four = MemcachedValue.new() value_two_four.key = 'foo' value_two_four.time = 4000 value_two_four.bytes = 6 value_two_four.data = 'ajoaaa' value_two_four.cas_unique = 5 value_two_four.modified = true value_five = MemcachedValue.new() value_five.key = 'foo' value_five.time = 3333 value_five.bytes = 3 value_five.data = 'bbb' value_two_four_five = MemcachedValue.new() value_two_four_five.key = 'foo' value_two_four_five.time = 4444 value_two_four_five.bytes = 9 value_two_four_five.data = 'bbbajoaaa' value_two_four_five.cas_unique = 6 value_two_four_five.modified = true value_six = MemcachedValue.new() value_six.key = 'otro' value_six.time = 333 value_six.bytes = 6 value_six.data = 'prueba' value_seven = MemcachedValue.new() value_seven.key = 'foo' value_seven.time = 4000 value_seven.bytes = 3 value_seven.data = 'ajo' value_seven.cas_unique = 1 value_seven_cas = MemcachedValue.new() value_seven_cas.key = 'foo' value_seven_cas.time = 4000 value_seven_cas.bytes = 3 value_seven_cas.data = 'ajo' value_seven_cas.cas_unique = 2 value_seven_cas.modified = true describe Memcached do it "add pair key value" do expect(memcached.add(value_one.key, value_one)).to eq(['STORED', value_one]) end it "store cas pair key value" do expect(memcached.cas(value_seven.key, value_seven)).to eq(['STORED', value_seven_cas]) end it "store cas pair key value" do expect(memcached.cas(value_seven.key, value_seven)).to eq(['EXISTS', value_seven_cas]) end it "set pair key value" do expect(memcached.set(value_two.key, value_two)).to eq(['STORED', value_two]) end it "get existing pair key value" do expect(memcached.get('foo')).to eq(value_seven_cas) end it "get non existing pair key value" do expect(memcached.get('aaa')).to eq(nil) end it "fail add pair key value" do expect(memcached.add(value_one.key, value_one)).to eq(['NOT_STORED', nil]) end it "fail replace pair key value" do expect(memcached.replace('aaaa', value_one)).to eq(['NOT_STORED', nil]) end it "replace pair key value" do expect(memcached.replace(value_three.key, value_three)).to eq(['STORED', value_three]) end it "append pair key value" do expect(memcached.append(value_four.key, value_four)).to eq(['STORED', value_two_four]) end it "fail append pair key value" do expect(memcached.append('rrr', value_four)).to eq(['NOT_STORED', nil]) end it "prepend pair key value" do expect(memcached.prepend(value_five.key, value_five)).to eq(['STORED', value_two_four_five]) end it "fail prepend pair key value" do expect(memcached.prepend('rrr', value_five)).to eq(['NOT_STORED', nil]) end it "fail cas pair key value" do expect(memcached.cas('eee', value_five)).to eq(['NOT_FOUND', nil]) end it "set pair key value" do expect(memcached.set(value_six.key, value_six)).to eq(['STORED', value_six]) end end
true
68382452243d29dae2586ac0e88768ac05f523d1
Ruby
canikwe/oo-counting-sentences-dc-web-career-010719
/lib/count_sentences.rb
UTF-8
380
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class String def sentence? self.end_with?(".") end def question? self.end_with?("?") end def exclamation? self.end_with?("!") end def count_sentences # binding.pry del = [".", "?", "!"] count = self.split(Regexp.union(del)) #looked up documentaion on splitting by specific characters count.delete("") count.length end end
true
47c19f0b24c65f2af6cf3f207f638f86bb432e24
Ruby
mojaz-io/mojaz-backend
/app/services/website_logo_service.rb
UTF-8
2,557
2.765625
3
[]
no_license
class WebsiteLogoService attr_reader :home_url def initialize(home_url = nil) @home_url = home_url end def call find_media_link end private def find_media_link return unless @home_url response = HTTP.follow(max_hops: 3).timeout(3).get(@home_url) html = Nokogiri::HTML(response.to_s) links = html.search(xpath) link = find_biggest_option(links) return unless link fix_link_relative_path(link, response.uri.to_s) end def xpath icon_names = ["icon", "shortcut icon", "apple-touch-icon-precomposed", "apple-touch-icon"] icon_names = icon_names.map do |icon_name| "//link[not(@mask) and translate(@rel, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = '#{icon_name}']" end icon_names.join(" | ") end def find_biggest_option(links) return if links.empty? # Try to find the best option based on size link = find_based_on_size(links) return link["href"] if link # Apple icons tends to have the best images, try to find one. link = find_based_on_apple_rel(links) return link["href"] if link # We couldn't determine which one is the best, so use the last one on the array links.last["href"] end def find_based_on_size(links) # Exact all the sizes including the nils. # [nil, "16x16", "32x32", "96x96", "192x192", "180x180"] sizes = links.map { |x| x["sizes"] } # Compact the array and check if it's empty, then we don't have sizes # and we need to for another way. return if sizes.compact.empty? # 1. map the array elements and convert them to width only, nil will be 0 # [nil, "16x16", "32x32", "96x96", "192x192", "180x180"] => [0, 16, 32, 96, 192, 180] # 2. find the index of the biggest width in the array index = sizes.map { |x| x.to_s.split("x").first.to_i }.each_with_index.max[1] return links[index] if index end def find_based_on_apple_rel(links) apple_name = %w[apple-touch-icon-precomposed apple-touch-icon] apple = links.detect { |x| apple_name.include?(x["rel"].downcase) } return apple if apple end # Some links when extracted from the page have relative paths # we need to fixed them by attaching the host and schema if needed. def fix_link_relative_path(link, domain_uri) fixed = URI.parse(link) return link if fixed.host && fixed.scheme original_domain = URI.parse(domain_uri) fixed.host = original_domain.host unless fixed.host fixed.scheme = original_domain.scheme unless fixed.scheme fixed.to_s end end
true
13bab92d48bab790ecb59e842a594db7a61bb59e
Ruby
mtwentyman/dotfiles
/git_template/hooks/commit-msg
UTF-8
1,108
2.796875
3
[]
no_license
#!/usr/bin/env ruby msg_file = ARGV[0] commit_msg = File.read(msg_file).to_s.strip def empty_commit?(commit_msg) return true if commit_msg.empty? commit_msg.split("\n").each do |line| # Lines starting with '#' will be ignored return false if commit_msg.strip[0] != '#' end true end # if the commit was canceled (no message) exit 0 if empty_commit?(commit_msg) branch_name = `git rev-parse --abbrev-ref HEAD`.to_s # remove line break added by the system call above branch_name.chomp! # remove git flow branch prefixes branch_name.gsub!('feature/', '') branch_name.gsub!('hotfix/', '') # skip when develop or master branches # or when the branch name is already in the beginning of the commit msg if %w[develop master].include?(branch_name) || commit_msg.start_with?(branch_name) exit 0 end # add the branch prefix following the Jira convention # https://confluence.atlassian.com/display/AOD/Processing+JIRA+issues+with+commit+messages commit_msg = "#{branch_name} #{commit_msg}" # update the commit msg with the branch name File.open(msg_file, 'w') { |f| f.write commit_msg }
true
263cd7d7cae04f371132c13b02b1dc54183b6f10
Ruby
vimalvnair/web_hunt
/rasp_push_act_broadband_usage.rb
UTF-8
5,079
2.65625
3
[]
no_license
#!/usr/bin/env ruby require "nokogiri" require 'net/http' require 'yaml' require 'logger' require 'time' require_relative './way2sms' AUTH_FILE = "#{Dir.home}/.act_broadband.yml" PUSH_BULLET_TOKEN = "#{Dir.home}/.push_bullet_token.yml" AUTH_EXPIRY = (2*60*60) # 5.hours LOG = Logger.new('act_broadband_usage.log', 10, 10024000) MOBILE_NUMBERS_FILE = "#{Dir.home}/.way2sms_recipients.yml" def get_with_cookie url, cookie uri = URI(url) req = Net::HTTP::Get.new(uri) req['Cookie'] = cookie req['User-Agent'] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" res = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end LOG.info "GET:#{res.code} #{url}" puts "GET: #{res.code}" res end def post_with_cookie url, data, cookie uri = URI(url) req = Net::HTTP::Post.new(uri) req.set_form_data(data) req['Cookie'] = cookie req['User-Agent'] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" res = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end LOG.info "POST:#{res.code} #{url}" puts "POST: #{res.code}" res end def get_auth_cookie login_url cookie, location = get_auth_from_file return cookie, location unless cookie.nil? get_auth_cookie_from_network login_url end def get_auth_from_file begin return nil unless File.exists?(AUTH_FILE) file = File.open(AUTH_FILE) data = YAML.load(file) return nil if Time.now > data[:time] LOG.info "Cookie from file..." puts "Cookie from file..." return data[:cookie], data[:location] rescue Exception => e nil end end def get_auth_cookie_from_network login_url response = get_with_cookie login_url, nil cookie = response.get_fields('Set-Cookie').map{|c| c.split('; ')[0] }.join("; ") file = File.open(AUTH_FILE, "w") YAML.dump({cookie: cookie, location: URI.escape(response['Location']), time: (Time.now + AUTH_EXPIRY)}, file) LOG.info "Cookie from network..." puts "Cookie from network..." return cookie, URI.escape(response['Location']) end def get_push_bullet_token unless File.exists?(PUSH_BULLET_TOKEN) LOG.fatal "Push bullet token file missing" puts "Push bullet token file missing" exit end YAML.load(File.open(PUSH_BULLET_TOKEN))[:token] end def get_averages usage begin time = Time.now no_of_days_in_month = Date.new(time.year, time.month, -1).day beginning_of_month = Date.new(time.year, time.month, 1).to_time elapsed_days = (time - beginning_of_month)/(60*60*24) data = usage.strip.delete('()GB').split("Quota").map(&:strip).map(&:to_f) return [data[0]/elapsed_days, data[1]/no_of_days_in_month].map{|i| i.round(2)} rescue Exception => e return ["", ""] end end begin LOG.info "Start..." retries ||= 0 cookie, login_url = get_auth_cookie "http://portal.actcorp.in/group/blr/myaccount" sleep 2 get_with_cookie login_url, cookie sleep 1 response3 = get_with_cookie "http://portal.actcorp.in/group/blr/myaccount", cookie html = Nokogiri::HTML(response3.body) usage_url = html.css("input[name='javax.faces.encodedURL']").map{|a|a.attributes["value"].text}.first h = {} html.css("form[id='A3220:j_idt35']").css("input[type='hidden']").each{|i| h[i['name']] = i['value'] } form_data = h.select{|k,v| !k.nil? } extra_params = {"javax.faces.source" => "A3220:j_idt35:j_idt39", "javax.faces.partial.event" => "click", "javax.faces.partial.execute" => "A3220:j_idt35:j_idt39 @component", "javax.faces.partial.render" => "@component", "org.richfaces.ajax.component" => "A3220:j_idt35:j_idt39", "A3220:j_idt35:j_idt39" => "A3220:j_idt35:j_idt39", "rfExt" => "null", "AJAX" => "EVENTS_COUNT:1", "javax.faces.partial.ajax" => "true"} response4 = post_with_cookie usage_url, form_data.merge(extra_params), cookie html = Nokogiri::HTML(response4.body) usage = html.css("table td").select{|t| t.text.include?('Quota')}.first.text curr_avg, req_avg = get_averages(usage) usage = usage + ", Curr. avg/day: #{curr_avg} GB, Req. avg: #{req_avg} GB" puts usage LOG.info "Usage #{usage}" LOG.info "Sending push notification" push_bullet_token = get_push_bullet_token `curl --header 'Access-Token: #{push_bullet_token}' --header 'Content-Type: application/json' --data-binary '{"body":"#{usage}","title":"ACT usage","type":"note", "channel_tag": "broadband"}' --request POST https://api.pushbullet.com/v2/pushes` if File.exists? MOBILE_NUMBERS_FILE numbers = YAML.load(File.open(MOBILE_NUMBERS_FILE)) numbers.each do |number| Way2Sms.send_sms number, "ACT broadband usage: #{usage}" sleep 5 end end rescue Exception => e LOG.error "Error: #{e.inspect}" puts e.inspect File.delete(AUTH_FILE) if File.exists?(AUTH_FILE) sleep 5 retry if (retries += 1 ) < 10 end
true
3da207613deb2ac48fe8e9492a674b798dca2ef7
Ruby
lucascppessoa/ruby-dev-test-1
/spec/models/directory_spec.rb
UTF-8
4,565
2.515625
3
[]
no_license
require 'rails_helper' RSpec.describe Directory, type: :model do context "with a clean slate" do it "accepts an initial orphaned record" do node = FactoryBot.build_stubbed(:directory) expect(node).to be_valid end it "refuses nameless records" do node = FactoryBot.build_stubbed(:directory, name: nil) expect(node).not_to be_valid end it "refuses a node with an invalid parent" do expect { FactoryBot.create(:directory, parent_id: -10) }.to raise_exception(ActiveRecord::RecordNotFound) end it "refuses a second orphan record" do og_root = FactoryBot.build(:directory) expect(og_root).to be_valid og_root.save bad_root = FactoryBot.build_stubbed(:directory) expect(bad_root).not_to be_valid end it "refuses an attempt to update both name and parent in one go" do node = FactoryBot.create(:directory) node2 = FactoryBot.create(:directory, parent: node) node3 = FactoryBot.create(:directory, parent: node2) expect { node3.update(name: 'its a me', parent: node) }.to throw_symbol(:abort) end it "allows us to update root's name" do node = FactoryBot.create(:directory, name: 'foo') node.update!(name: 'bar') expect(node.name).to eq('bar') end end context "with a populated tree" do let!(:root) { FactoryBot.create(:directory, name: 'root') } let!(:child_1) { FactoryBot.create(:directory, name: 'child1', parent: root) } let!(:child_2) { FactoryBot.create(:directory, name: 'child2', parent: root) } let!(:grandchild_1) { FactoryBot.create(:directory, name: 'grandchild1', parent: child_2) } let!(:grandchild_2) { FactoryBot.create(:directory, name: 'grandchild2', parent: child_2) } let!(:great_grandchild_1) { FactoryBot.create(:directory, name: 'great_grandchild1', parent: grandchild_2) } let!(:great_grandchild_2) { FactoryBot.create(:directory, name: 'great_grandchild2', parent: grandchild_2) } it "returns a node's children" do expect(root.children).to include(child_1, child_2) end it "updates a node's children when we move them around" do grandchild_2.update!(parent: root) expect(root.children).to include(grandchild_2) expect(child_2.children).not_to include(grandchild_2) end it "shows us the names of ancestors separated by /" do expect(great_grandchild_2.name_ancestors(and_self: true)).to eq('root/child2/grandchild2/great_grandchild2') expect(great_grandchild_1.name_ancestors).to eq('root/child2/grandchild2') end it "destroys nodes of deleted nodes" do expect(root.descendants).to include(great_grandchild_1, great_grandchild_2) grandchild_2.destroy expect(root.descendants).not_to include(great_grandchild_1, great_grandchild_2) expect(Directory.count).to eq(4) end end context "with name already taken" do let!(:root) { FactoryBot.create(:directory, name: 'root') } let!(:child_1) { FactoryBot.create(:directory, name: 'child1', parent: root) } it "renames a conflicting newly created node to name(2)" do child_11 = FactoryBot.create(:directory, name: 'child1', parent: root) expect(child_11.name).to eq('child1(2)') end it "renames a conflicting moved node to name(2)" do child_11 = FactoryBot.create(:directory, name: 'child1', parent: child_1) expect(root.children.where(name: 'child1').count).to eq(1) child_11.update!(parent: root) expect(root.children.where(name: 'child1').count).to eq(1) expect(root.children.where(name: 'child1(2)').count).to eq(1) end end context "when dealing with attachments" do let(:root) { FactoryBot.create(:directory) } let(:child_1) { FactoryBot.create(:directory, parent: root) } it "correctly deals with single attached file" do expect(root.files.attached?).to be_falsey root.files.attach(io: File.open('spec/fixtures/files/test.txt'), filename: 'test_file') expect(root.files.attached?).to be_truthy end it "purges files when the directory is destroyed, including dependants" do expect(root.files.attached?).to be_falsey expect(child_1.files.attached?).to be_falsey root.files.attach(io: File.open('spec/fixtures/files/test.txt'), filename: 'test_file') child_1.files.attach(io: File.open('spec/fixtures/files/test.txt'), filename: 'test_file_too') expect(ActiveStorage::Attachment.count).to eq(2) root.destroy expect(ActiveStorage::Attachment.count).to eq(0) end end end
true
a9aa532f17170c576d8097213ed4ef94936382ba
Ruby
pjpalla/collabora
/lib/tasks/tester.rb
UTF-8
7,212
2.59375
3
[]
no_license
require '../../config/environment' require_relative 'processor' @uids = User.where(:place => "medio campidano") indicator = "i8_1" i = Indicator.where(:uid => @uids).where("#{indicator} <> 0 and #{indicator} is not NULL").count puts i # lower_limit = 1 # upper_limit = 6 # sub_range = (lower_limit..upper_limit) # sub_indicators = Array.new(upper_limit, 0) # n = 8 # if n == 8 # sub_range.each do |i| # indicator = "i" + n.to_s # indicator += "_#{i}" # puts indicator # end # end # include SurveysHelper # NUM_OF_INDICATORS = 11 # NUM_OF_SUBINDICATORS = 6 # note = "note 1 i1:aaaa i2: bfdf fg i8_1: adflkdlfkjld i8_2: akdjflwo i8_5:slkdfjaslkdf i10: ckcdkddk, i11: akakakakk, i10: xxxxx" # counter = Array.new(NUM_OF_INDICATORS, 0) # i8_sub_counter = Array.new(NUM_OF_SUBINDICATORS, 0) # indicators = note.scan(/i[1-9]\d?_?[1-6]?/) # indicators.each do |indicator| # case indicator # when /i1\z/ # counter[0] += 1 # when /i2/ # counter[1] += 1 # when /i3/ # counter[2] += 1 # when /i4/ # counter[3] += 1 # when /i5/ # counter[4] += 1 # when /i6/ # counter[5] += 1 # when /i7/ # counter[6] += 1 # when /i8_?[1-6]?/ # counter[7] += 1 # if indicator =~ /i8_1/ # i8_sub_counter[0] += 1 # elsif indicator =~ /i8_2/ # i8_sub_counter[1] += 1 # elsif indicator =~ /i8_3/ # i8_sub_counter[2] += 1 # elsif indicator =~ /i8_4/ # i8_sub_counter[3] += 1 # elsif indicator =~ /i8_5/ # i8_sub_counter[4] += 1 # elsif indicator =~ /i8_6/ # i8_sub_counter[5] += 1 # end # when /i9/ # counter[8] += 1 # when /i10/ # counter[9] += 1 # when /i11/ # counter[10] += 1 # end # binding.pry # end # ind = Indicator.new do |i| # i.uid = 12324 # i.card = "B0000" # i.i1 = counter[0] # i.i2 = counter[1] # i.i3 = counter[2] # i.i4 = counter[3] # i.i5 = counter[4] # i.i6 = counter[5] # i.i7 = counter[6] # i.i8 = counter[7] # i.i9 = counter[8] # i.i10 = counter[9] # i.i11 = counter[10] # #### subindicators # i.i8_1 = i8_sub_counter[0] # i.i8_2 = i8_sub_counter[1] # i.i8_3 = i8_sub_counter[2] # i.i8_4 = i8_sub_counter[3] # i.i8_5 = i8_sub_counter[4] # i.i8_6 = i8_sub_counter[5] # end # ind_attributes = ind.attributes # ind_attributes.each do |i| # puts(i) # end # card_number = build_default_card_number # puts(card_number) # @location = "medio campidano" # if @location == "sardegna" # @uids = User.all.pluck(:uid) # elsif @location == "sardegna eccetto medio campidano" # @uids = User.where.not(place: 'medio campidano').pluck(:uid) # elsif @location == "altro" # @uids = User.where.not(place: @locations).pluck(:uid) ###### da sistemare --RVD!!!!!! # else # @uids = User.where(place: @location).pluck('uid') # end ### Qui ricaviamo gli intervistati che facendo uso di farmaci generici hanno avuto degli effetti indesiderati # w = Answer.distinct.where(qid: "5", subid: "0", uid: @uids).where.not(answer: nil).pluck(:uid) # #w = Answer.select('uid').distinct.where("qid = 5 and subid = 0 and answer is not null").map{|a| a.uid} # #to_remove = Answer.select('uid').distinct.where("qid = 1 and subid = 0 and (answer like 'n%' or answer like 'N%')").map{|a| a.uid} # to_remove = Answer.distinct.where(qid: "1", subid: "0", uid: @uids).where("answer like 'n%' or answer like 'N%'").pluck(:uid) # filtered_w = w - to_remove # all_positive_answers = Answer.distinct.where(qid: "1", subid: "0", uid: @uids).where("answer like 's%' or answer like 'S%'").pluck(:uid) # all_not_nil_5_answers = Answer.distinct.where(qid: "5", subid: "0", uid: @uids).where.not(answer: nil).pluck(:uid) # note = "i10: prima di prendere un farmaco, consulto sempre il bugiardino" # indicators = note.scan(/i[1-9]\d?./) # puts indicators # counter = Array.new(11, 0) # indicators.each do |indicator| # case indicator # when /i1\D/ # counter[0] += 1 # when /i2/ # counter[1] += 1 # when /i3/ # counter[2] += 1 # when /i4/ # counter[3] += 1 # when /i5/ # counter[4] += 1 # when /i6/ # counter[5] += 1 # when /i7/ # counter[6] += 1 # when /i8/ # counter[7] += 1 # when /i9/ # counter[8] += 1 # when /i10/ # counter[9] += 1 # when /i11/ # counter[10] += 1 # end # end # print counter # puts "" # ### The directory containing our data files # SOURCE_DIR = Rails.root.join('files4') # #questionnaire = Questionnaire.create(quid: 1, description: "Questionario progetto collabora") # # ### Here we load the questions into the database # # #questionnaire = Questionnaire.first # qst_file = File.join(SOURCE_DIR, 'I0757.docx') # qprocessor = Processor.new(qst_file) # # #binding.pry # # ### Get question, subquestions and notes # q, n, subs = qprocessor.get_question(1) # # ## Question # puts "question: #{q}" # puts "subs: #{subs}" # ## Note # puts "note: #{qprocessor.get_note(8)}" # # Question 8 # ### Subquestions # subs.each do |s| # puts "subquestion: #{s}" # end unless subs.nil? # ## Answers # answer = qprocessor.get_answer(1, 1) # puts "answer: #{answer}" # #user = qprocessor.get_user # #puts "User: #{user}" # # counter = Processor.get_indicators(2) # # puts counter # #Get indicators # choices = qprocessor.get_question_choices(8) # puts "choices: #{choices}" # #puts "Choices" # #puts choices[0] # # n, c, d = qprocessor.get_drug(choice) # # print n,c,d # # puts "*** Get answer ****" # #a = qprocessor.get_answer(1,1) # #puts "answer id: #{a.id}" # #puts "answer text: #{a.answer}" # #puts "answer: #{a}" # #user = qprocessor.get_user # #puts "user sex: #{user.sex}" # # puts "Answer length: #{a.length}" # # puts "is a Array?: #{a.is_a? Array}" # # note = qprocessor.get_note(6) # # puts "Note to question 6: #{note}"
true
9bdd1d155c8dff4c2108132da48b3d3320623b04
Ruby
nimam1992/programming-univbasics-4-square-array-nyc-web-030920
/lib/square_array.rb
UTF-8
140
3.15625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(array) i = 0 list = [] while i < array.length do list.push(array[i]*array[i]) i += 1 end return list end
true
8a1bd2a1ed8875a75418c26265afcb94c0af7ce6
Ruby
andrewbaldwin44/Rails_React_Library
/app/helpers/books_helper.rb
UTF-8
1,159
2.515625
3
[ "MIT" ]
permissive
module BooksHelper BOOK_FIELDS_SELECTION = [ 'title', 'authors', 'published_date', 'description', 'imageLinks', 'categories' ] private def safe_format_list(list) if list then list.join(", ") else "" end end public def adapt_books_response(search_response) if search_response[:error] && search_response[:error][:code] > 400 return helpers.error_response(search_response[:error][:code], search_response[:error][:message]) end adapted_response = search_response["items"].map do |book| volume_info = book["volumeInfo"] short_description = if book["searchInfo"] then book["searchInfo"]["textSnippet"] else "" end adapted_volume_info = volume_info .select { |book_field, book_data| BOOK_FIELDS_SELECTION.include?(book_field) } .merge({ "id": book["id"], "shortDescription": short_description, "authors": safe_format_list(volume_info["authors"]), "categories": safe_format_list(volume_info["categories"]) }) adapted_volume_info end {response: {"result": adapted_response}, "statusCode": 200} end end
true
cee8cfc15f0882be0b9d0ed10f3638080ae0c1df
Ruby
michaelklishin/kiev_ruby_barcamp_2009
/examples/04_module_included_multiple_times.rb
UTF-8
981
2.859375
3
[ "LicenseRef-scancode-public-domain-disclaimer" ]
permissive
#!/usr/bin/env ruby -Ku # # Example #4: # # Beware of Module.included being called multiple times when classes in large # application load via ActiveSupport's or Merb's classloaders. # # Imagine you have a.rb with reference to B, and b.rb with reference to A. # No matter what order you are going to load them, first time it will fail. # Class loaders handle LoadErrors for you and re-try. So, class body may # execute more than once, and so is Module.included. # # So if you do any kind of work that only must be done once (adding classes to # descendants list, for instance), remember about this possibility. # require "rubygems" require "extlib" require "set" module MostAwesomeExtensionEva def self.included(host) # host.extend(ClassMethods) end end # MostAwesomeExtensionEva class Entity # # Behaviors # # will cause MostAwesomeExtensionEva.included to be called # twice include MostAwesomeExtensionEva include MostAwesomeExtensionEva end # Entity
true
234bbf8511e08b1193a2ffca992ae0e915eabf12
Ruby
wookay/da
/ruby/ruby19/test_each.rb
UTF-8
350
3.4375
3
[]
no_license
# test_each.rb # wookay.noh at gmail.com def assert_equal expected, got puts expected == got ? "passed: #{expected}" : "Assertion failed\nExpected: #{expected}\nGot: #{got}" end class A include Enumerable def each yield 1 yield 2 end end for a in A.new assert_equal true, [1,2].include?(a) end
true
db49fbf569967fc02d9e7642d7d89e34f0c9ffcd
Ruby
JeffBenton/cartoon-collections-online-web-sp-000
/cartoon_collections.rb
UTF-8
404
3.234375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def roll_call_dwarves(arr) arr.each_with_index {|dwarf, i| puts "#{i+1}. #{dwarf}"} end def summon_captain_planet(arr) arr.collect {|x| "#{x.capitalize}!"} end def long_planeteer_calls(arr) arr.find {|x| x.length > 4} != nil end def find_the_cheese(arr) cheese_types = ["cheddar", "gouda", "camembert"] cheese_types.each do |cheese| return cheese if arr.include?(cheese) end nil end
true
1485144fb44d84f286b4718f8b3ade518ef4f655
Ruby
PatrickA226/get-help-with-tech
/app/services/responsible_body_exporter.rb
UTF-8
1,244
2.71875
3
[ "MIT" ]
permissive
require 'csv' require 'string_utils' class ResponsibleBodyExporter include StringUtils attr_reader :filename def initialize(filename = nil) @filename = filename end def export_responsible_bodies(query = responsible_bodies) if filename CSV.open(filename, 'w') do |csv| render(csv, query) end nil else CSV.generate(headers: true) do |csv| render(csv, query) end end end private def render(csv, query) csv << headings query.find_each do |rb| csv << [ rb.computacenter_identifier, *build_name_fields_for(rb), rb.address_1, rb.address_2, rb.address_3, rb.town, rb.postcode, ] end end def headings [ 'Responsible body URN', 'Responsible Body Name', 'Responsible Body Name (overflow)', 'Address line 1', 'Address line 2', 'Address line 3', 'Town/City', 'Postcode', ].freeze end def build_name_fields_for(responsible_body) split_string(responsible_body.computacenter_name, limit: 35) end def responsible_bodies ResponsibleBody.where.not(name: 'Department for Education').order(type: :asc, name: :asc) end end
true
616ced0f36c31a043e996659fff82f460cf8093d
Ruby
ddrscott/stocking
/lib/stocking/yahoo.rb
UTF-8
980
2.71875
3
[ "MIT" ]
permissive
module Stocking # Fetch data from Yahoo module Yahoo module_function def default_url 'https://finance.yahoo.com/quote/%s/financials' end def build_url(ticker) default_url % [ticker.upcase] end def ticker_cache @ticker_cache ||= {} end def fetch(ticker, url: build_url(ticker)) ticker_cache[ticker] ||= begin $stderr.puts "starting browser: #{url}" browser = Watir::Browser.start(url) $stderr.puts 'getting TRs...' trs = browser.elements(:css, 'section > div > table > tbody > tr') $stderr.puts 'getting texts...' trs.map { |tr| tr.elements(:css, 'td').map(&:text) }.tap do $stderr.puts 'done' end end end end end
true
2a6c5e5c310552284a55ac25b01e93ba586b85e7
Ruby
Eritiel/Ruby
/L1/3.rb
UTF-8
1,101
3.578125
4
[]
no_license
puts "Введите свой любимый язык программирования" name=gets.chomp() if name=="Ruby" puts "Иу, подлиза" elsif name=="Python" puts "А ты мне нравишься" elsif name=="R" puts "Согласна!" elsif name=="C++" puts "Плюсики в карму" elsif name=="C#" puts "Минус в карму, даже руби лучше" elsif name=="Petooh" puts "Ваши вкусы очень специфичны..." else puts "Хм, я такого даже не знаю. Ну ладно" end #или puts "Введите свой любимый язык программирования" name=gets.chomp() case name when "Ruby" puts "Иу, подлиза" when "Python" puts "А ты мне нравишься" when "R" puts "Согласна!" when "C++" puts "Плюсики в карму" when "C#" puts "Минус в карму, даже руби лучше" when "Petooh" puts "Ваши вкусы очень специфичны..." else puts "Хм, я такого даже не знаю. Ну ладно" end
true
7d31db68ae33e8d43d713f183ef58780c7ecb217
Ruby
mikekelly/blue_bank
/lib/blue_bank/account.rb
UTF-8
1,022
2.546875
3
[ "MIT" ]
permissive
module BlueBank class Account def initialize(id:, client:, json: nil) @id, @client, @json = id, client, json end def current? account_type == "Standard Current Account" end def savings? account_type == "Standard Current Account" end def account_type json.fetch("accountType") end def make_payment(account_number:, sort_code:, reference:, amount:) json = client.post( path: "/accounts/#{id}/payments", json: { "toAccountNumber" => account_number, "toSortCode" => sort_code, "paymentReference" => reference, "paymentAmount" => amount, } ) Payment.new(id: json.fetch("id"), account: self, client: client, json: json) end def transactions client.get("/accounts/#{id}/transactions") end def id @id ||= json.fetch("id") end private def json @json ||= client.get("/accounts/#{id}").first end attr_reader :client end end
true
0cfdf473a8e13d7fa8ee3edb39d54898c53f62b7
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/bob/e4abe8c64feb4aa68d3f624681469fe4.rb
UTF-8
443
3.703125
4
[]
no_license
class Bob def hey message @message = message.strip case when silence? return "Fine. Be that way!" when yelling? return "Woah, chill out!" when question? return "Sure." else return "Whatever." end end def silence? @message.empty? end def yelling? @message.upcase == @message end def question? @message.end_with? "?" end end
true
42071d1eda399b9edf3726d9bc7e019692501ebe
Ruby
anwarhamdani/nlp_arabic
/lib/nlp_arabic.rb
UTF-8
8,741
3.671875
4
[]
no_license
require "nlp_arabic/version" require "nlp_arabic/characters" module NlpArabic def self.stem(word) # This function stems a word following the steps of ISRI stemmer # Step 1: remove diacritics word = remove_diacritics(word) # Step 2: normalize hamza, ouaou and yeh to bare alef word = normalize_hamzaas(word) # Step 3: remove prefix of size 3 then 2 word = remove_prefix(word) # Step 4: remove suffix of size 3 then 2 word = remove_suffix(word) # Step 5: remove the connective waw word = remove_waw(word) # Step 6: convert inital alif (optional) word = convert_initial_alef(word) # Step 7: If the length of the word is higher than 3 if word.length == 4 word = word_4(word) elsif word.length == 5 word = pattern_53(word) word = word_5(word) elsif word.length == 6 word = pattern_6(word) word = word_6(word) elsif word.length == 7 word = short_suffix(word) word = short_prefix(word) if word.length == 7 if word.length == 6 word = pattern_6(word) word = word_6(word) end end return word end def self.clean_text(text) # cleans the text using a stop list tokenized_text = NlpArabic.tokenize_text(text) clean_text = (tokenized_text - NlpArabic::STOP_LIST) return clean_text.join(' ') end def self.stem_text(text) # Only stems the text using the ISRI algorithm tokenized_text = NlpArabic.tokenize_text(text) for i in (0..(tokenized_text.length-1)) tokenized_text[i] = stem(tokenized_text[i]) if NlpArabic.is_alpha(tokenized_text[i]) end return tokenized_text.join(' ') end def self.clean_and_stem(text) # Cleans the text using the stop list than stems it tokenized_text = NlpArabic.tokenize_text(text) clean_text = (tokenized_text - NlpArabic::STOP_LIST) for i in (0..(clean_text.length-1)) clean_text[i]= stem(clean_text[i]) if NlpArabic.is_alpha(clean_text[i]) end return clean_text.join(' ') end def self.tokenize_text(text) return text.split(/\s|(\?+)|(\.+)|(!+)|(\,+)|(\;+)|(\،+)|(\؟+)|(\:+)|(\(+)|(\)+)/).delete_if(&:empty?) end def self.wash_and_stem(text) clean_text = text.gsub(/[._,،\"\':–%\/;·&?؟()\”\“]/, '').split - NlpArabic::STOP_LIST new_text = [] for i in (0..(clean_text.length-1)) new_text << stem(clean_text[i]) if NlpArabic.is_alpha(clean_text[i]) end new_text -= NlpArabic::STOP_LIST return new_text.join(' ') end def self.is_alpha(word) # checks if a word is alphanumeric return !!word.match(/^[[:alpha:]]+$/) end def self.remove_na_characters(word) # cleans the word from non alphanumeric characters return word.strip.gsub(/[._,،\"\':–%\/;·&?؟()\”\“]/, '') end def self.remove_diacritics(word) # removes arabic diacritics (fathatan, dammatan, kasratan, fatha, damma, kasra, shadda, sukun) and tateel return word.gsub(/#{NlpArabic::DIACRITICS}/, '') end def self.convert_initial_alef(word) # converts all the types of ALEF to a bare alef return word.gsub(/#{NlpArabic::ALIFS}/, NlpArabic::ALEF) end def self.normalize_hamzaas(word) # Normalize the hamzaas to an alef return word.gsub(/#{NlpArabic::HAMZAAS}/, NlpArabic::ALEF) end def self.remove_prefix(word) # Removes the prefixes of length three than the prefixes of length two if word.length >= 6 return word[3..-1] if word.start_with?(*NlpArabic::P3) end if word.length >= 5 return word[2..-1] if word.start_with?(*NlpArabic::P2) end return word end def self.remove_suffix(word) # Removes the suffixes of length three than the prefixes of length two if word.length >= 6 return word[0..-4] if word.end_with?(*NlpArabic::S3) end if word.length >= 5 return word[0..-3] if word.end_with?(*NlpArabic::S2) end return word end def self.remove_waw(word) # Remove the letter و if it is the initial letter if word.length >= 4 return word[1..-1] if word.start_with?(*NlpArabic::DOUBLE_WAW) end return word end def self.word_4(word) # Processes the words of length four if NlpArabic::PR4[0].include? word[0] return word[1..-1] elsif NlpArabic::PR4[1].include? word[1] word[1] = '' elsif NlpArabic::PR4[2].include? word[2] word[2] = '' elsif NlpArabic::PR4[3].include? word[3] word[3] = '' else word = short_suffix(word) word = short_prefix(word) if word.length == 4 end return word end def self.word_5(word) # Processes the words of length four if word.length == 4 word = word_4(word) elsif word.length == 5 word = pattern_54(word) end return word end def self.pattern_53(word) # Helper function that processes the length five patterns and extracts the length three roots if NlpArabic::PR53[0].include? word[2] && word[0] == NlpArabic::ALEF word = word[1] + word[3..-1] elsif NlpArabic::PR53[1].include? word[3] && word[0] == NlpArabic::MEEM word = word[1..2] + word[4] elsif NlpArabic::PR53[2].include? word[0] && word[4] == NlpArabic::TEH_MARBUTA word = word[1..3] elsif NlpArabic::PR53[3].include? word[0] && word[2] == NlpArabic::TEH word = word[1] + word[3..-1] elsif NlpArabic::PR53[4].include? word[0] && word[2] == NlpArabic::ALEF word = word[1] + word[3..-1] elsif NlpArabic::PR53[5].include? word[2] && word[4] == NlpArabic::TEH_MARBUTA word = word[0..1] + word[3] elsif NlpArabic::PR53[6].include? word[0] && word[1] == NlpArabic::NOON word = word[2..-1] elsif word[3] == NlpArabic::ALEF && word[0] == NlpArabic::ALEF word = word[1..2] + word[4] elsif word[4] == NlpArabic::NOON && word[3] == NlpArabic::ALEF word = word[0..2] elsif word[3] == NlpArabic::YEH && word[0] == NlpArabic::TEH word = word[1..3] + word[4] elsif word[3] == NlpArabic::WAW && word[0] == NlpArabic::ALEF word = word[0] + word[2] + word[4] elsif word[2] == NlpArabic::ALEF && word[1] == NlpArabic::WAW word = word[0] + word[3..-1] elsif word[3] == NlpArabic::YEH_WITH_HAMZA_ABOVE && word[2] == NlpArabic::ALEF word = word[0..1] + word[4] elsif word[4] == NlpArabic::TEH_MARBUTA && word[1] == NlpArabic::ALEF word = word[0] + word[2..3] elsif word[4] == NlpArabic::YEH && word[2] == NlpArabic::ALEF word = word[0..1] + word[3] else word = short_suffix(word) word = short_prefix(word)if word.length == 5 end return word end def self.pattern_54(word) # Helper function that processes the length five patterns and extracts the length three roots if NlpArabic::PR53[2].include? word[0] word = word[1..-1] elsif word[4] == NlpArabic::TEH_MARBUTA word = word[0..3] elsif word[2] == NlpArabic::ALEF word = word[0..1] + word[3..-1] end return word end def self.word_6(word) # Processes the words of length four if word.length == 5 word = pattern_53(word) word = word_5(word) elsif word.length == 6 word = pattern_64(word) end return word end def self.pattern_6(word) # Helper function that processes the length six patterns and extracts the length three roots if word.start_with?(*NlpArabic::IST) || word.start_with?(*NlpArabic::MST) word = word[3..-1] elsif word[0] == NlpArabic::MEEM && word[3] == NlpArabic::ALEF && word[5] == NlpArabic::TEH_MARBUTA word = word[1..2] + word[4] elsif word[0] == NlpArabic::ALEF && word[2] == NlpArabic::TEH && word[4] == NlpArabic::ALEF word = word[1] + word[3] + word[5] elsif word[0] == NlpArabic::ALEF && word[3] == NlpArabic::WAW && word[2] == word[4] word = word[1] + word[4..-1] elsif word[0] == NlpArabic::TEH && word[2] == NlpArabic::ALEF && word[4] == NlpArabic::YEH word = word[1] + word[3] + word[5] else word = short_suffix(word) word = short_prefix(word) if word.length == 6 end return word end def self.pattern_64(word) # Helper function that processes the length six patterns and extracts the length four roots if word[0] == NlpArabic::ALEF && word[4] == NlpArabic::ALEF word = word[1..3] + word[5] elsif word = word[2..-1] end return word end def self.short_prefix(word) # Removes the short prefixes word[1..-1] if word.start_with?(*NlpArabic::P1) return word end def self.short_suffix(word) # Removes the short suffixes word[0..-2] if word.end_with?(*NlpArabic::S1) return word end end
true
6d6f115c9265871f8fc2affae03bad725e816280
Ruby
dmeskis/connect_four
/lib/board.rb
UTF-8
1,426
3.65625
4
[]
no_license
require './lib/win_conditions' class Board include WinConditions attr_reader :game_over, :column_key, :player_piece, :computer_piece attr_accessor :board def initialize @column_key = ["A", "B", "C", "D", "E", "F", "G"] @board = [[".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."]] @player_piece = "x" @computer_piece = "o" @game_over = false end def print_board puts @column_key.join @board.each {|line| puts line.join} end def place_piece(placement, piece) board = @board.reverse board.map! do |line| if line[placement] == '.' line[placement] = piece break else end end @board end def valid_move?(placement) @board[0][placement] == '.' end def board_full? @board[0].all? {|piece| piece != '.'} end def reset_board @board = [[".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", ".", "."]] end end
true
cbc1e6cf0eb17b69c8ff1d9167c338de09e71bd7
Ruby
joeainsworth/programming_exercises
/Tealeaf Academy - Object Oriented Ruby Exercises Workbook/Easy/Quiz 3/exercise_5.rb
UTF-8
535
3.921875
4
[]
no_license
# If I have the following class: class Television def self.manufacturer # method logic end def model # method logic end end # What would happen if I called the methods like shown below? tv = Television.new # instantiate a new Televesion object and assign to tv tv.manufacturer # error tv.model # calls the model method within the Television class Television.manufacturer # Calls the class method manufacturer Television.model # error because model is not a class method
true
05287700da4367924c6f3adf8fc3104d510a50d6
Ruby
esteedqueen/simple-http-server
/lib/path_response_parser.rb
UTF-8
830
2.953125
3
[]
no_license
class PathResponseParser def initialize(path) @path = path parse end def parse if root_path? handle_homepage_response elsif File.exist?(file_path) handle_file_response else handle_404_response end self end attr_reader :status_code, :content private def handle_homepage_response @content = File.binread('index.html') @status_code = 200 end def handle_file_response @content = if File.executable?(file_path) `#{file_path}` else File.binread(file_path) end @status_code = 200 end def handle_404_response @content = 'File not found' @status_code = 404 end def file_path (Dir.getwd + @path).gsub!(/\.+/, '.') end def root_path? file_path.nil? end end
true
5766a89c2499c44fc1da1821dff29941544b43e4
Ruby
waasifkhaan/prime-ruby-v-000
/prime.rb
UTF-8
232
3
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Add code here! def prime?(int) if int < 2 return false elsif int == 2 return true elsif (2..int-1).to_a.each do |num| if int % num == 0 return false end end return true end end
true
8b7711370234d534da9cb431e570491302c17492
Ruby
Lucasdfg07/OneBitExchange
/app/services/bitcoin_service.rb
UTF-8
459
2.796875
3
[]
no_license
require 'rest-client' require 'json' class BitcoinService def initialize(target_currency, amount) @target_currency = target_currency @amount = amount.to_f end def perform begin base_url = "https://blockchain.info/tobtc?currency=#{@target_currency}&value=#{@amount}" response = RestClient.get base_url value = JSON.parse(response.body) rescue RestClient::ExceptionWithResponse => e e.response end end end
true
fe7555dff57acc33b7b64a028ce6d620b161920a
Ruby
LLHolmes/spellwork_cli
/lib/spellwork_cli/cli.rb
UTF-8
8,199
3.5
4
[ "MIT" ]
permissive
class SpellworkCli::CLI def initialize @input = "menu!" end def start welcome build_encyclopedia while @input != "exit!" if @input == "menu!" self.menu elsif @input == "word" self.choose_keyword elsif @input == "type" self.choose_spell_type elsif @input == "search" self.choose_letter end end goodbye end def welcome puts Rainbow(" *").orange + Rainbow(" *").limegreen puts Rainbow(" ..").dimgray + Rainbow(" *").violet + Rainbow(" *").peru + Rainbow(" *").royalblue puts Rainbow(" . . .").dimgray + Rainbow(" *").olive + Rainbow(" *").mediumorchid puts Rainbow(" _").saddlebrown + Rainbow(". ..").dimgray + Rainbow(" *").cadetblue puts Rainbow(" //").saddlebrown puts Rainbow(" //").saddlebrown + " Welcome to Spellwork!" puts Rainbow(" //").saddlebrown puts Rainbow("//").saddlebrown + " A collection of known Harry Potter spells." puts Rainbow("-").saddlebrown # puts <<~HEREDOC # * * # .. * * * # . . . * * # _. .. * # // # // Welcome to Spellwork! # // # // A collection of known Harry Potter spells. # - # HEREDOC end def build_encyclopedia SpellworkCli::Scraper.scrape_fandom_wiki_index end def menu puts <<~HEREDOC \nHow would you like to select a spell to learn about? Enter "word" to use a keyword or name of a spell. Enter "type" to chose from a list of spell types. Enter "search" to look through the encyclopedia alphabetically. To leave the program at any time, type "exit!". HEREDOC while @input != "word" && @input != "type" && @input != "search" && @input != "exit!" @input = gets.chomp.downcase if @input != "word" && @input != "type" && @input != "search" && @input != "exit!" puts "\nI'm not sure what you mean. Please enter \"word\", \"type\", \"search\",or \"exit!\"" end end end # If @input == "word" def choose_keyword while @input != "menu!" && @input != "exit!" puts "\nEnter a keyword and I'll search the encyclopedia for you:" puts "(Enter \"menu!\" for the main menu, or \"exit!\" to leave the program.)" @input = gets.chomp.downcase if @input != "menu!" && @input != "exit!" self.search_by_keyword end end end def search_by_keyword if @input.match(/^[[:alpha:][:blank:]]+$/) == nil puts "\nPlease only use letters and try again." else @spells_by_keyword = SpellworkCli::Spell.search(@input) if @spells_by_keyword == [] puts "\nThere are no spells that include \"#{@input}\"." elsif @spells_by_keyword.length == 1 puts "\nI have found one entry:" SpellworkCli::Spell.request_info_by_spell(@spells_by_keyword[0]) else self.choose_spell_from_keyword end end end def list_spells_by_keyword puts "\nMultiple spells matched your search!:" @spells_by_keyword.each.with_index(1) { |spell, i| puts "#{i}. #{spell.name} - #{spell.description}" } end def choose_spell_from_keyword self.list_spells_by_keyword while @input != "menu!" && @input != "exit!" puts "\nEnter the number of a spell to get more information:" puts "(Enter \"list!\" to repeat the list, \"word!\" to search by another keyword, \"menu!\" for the main menu, or \"exit!\" to leave the program.)" @input = gets.chomp.downcase if @input != "menu!" && @input != "exit!" if @input.to_i > 0 && @input.to_i <= @spells_by_keyword.length SpellworkCli::Spell.request_info_by_spell(@spells_by_keyword[@input.to_i-1]) elsif @input == "list!" self.list_spells_by_keyword elsif @input == "word!" self.choose_keyword else self.search_by_keyword self.choose_keyword end end end end # If @input == "type" def choose_spell_type self.list_spell_types unless @input == "exit!" while @input != "menu!" && @input != "exit!" puts "\nEnter a number to list spells of that kind:" puts "(Enter \"list\" for the list of spell types, \"menu!\" for the main menu, or \"exit!\" to leave the program.)" @input = gets.chomp.downcase if @input != "menu!" && @input != "exit!" if @input.to_i > 0 && @input.to_i <= @types.length choose_spell_from_type("#{@types[@input.to_i-1]}") elsif @input == "list" self.list_spell_types else puts "\nI'm not sure what you mean. Please try again." end end end end def list_spell_types @types = SpellworkCli::Spell.types puts "\nTypes of spells:" @types.each.with_index(1) { |type, i| puts "#{i}. #{type}" } end def list_spells_of_a_type(type) @spells_by_type = SpellworkCli::Spell.find_by_type(type) puts "\nAll #{type.downcase} spells:" list_generic(@spells_by_type) end def choose_spell_from_type(type) self.list_spells_of_a_type(type) unless @input == "exit!" while @input != "menu!" && @input != "exit!" puts "\nEnter the number of a spell to get more information:" puts "(Enter \"list\" for the list of #{type.downcase} spells, \"type\" for the list of spell types, \"menu!\" for the main menu, or \"exit!\" to leave the program.)" @input = gets.chomp.downcase if @input != "menu!" && @input != "exit!" if @input.to_i > 0 && @input.to_i <= @spells_by_type.length SpellworkCli::Spell.request_info_by_spell(@spells_by_type[@input.to_i-1]) elsif @input == "list" self.list_spells_of_a_type(type) elsif @input == "type" self.choose_spell_type else puts "\nI'm not sure what you mean. Please try again." end end end end # If @input == "search" def choose_letter puts "\nEnter a letter to search spells that begin with that letter:" unless @input == "exit!" || @input == "menu!" puts "(Enter \"menu!\" for the main menu, or \"exit!\" to leave the program.)" unless @input == "exit!" || @input == "menu!" while @input != "menu!" && @input != "exit!" @input = gets.chomp.downcase self.search_by_letter end end def search_by_letter if @input != "menu!" && @input != "exit!" if ("a".."z").include?(@input) @spells_by_letter = SpellworkCli::Spell.find_in_encyclopedia(@input) if @spells_by_letter == [] puts "There are no spells that begin with the letter #{@input.upcase}. Please choose another." else self.choose_spell_from_letter end else puts "\nI'm not sure what you mean. Please try again." end end end def list_spells_by_letter puts "\nAll spells that begin with the letter #{@input.upcase}:" list_generic(@spells_by_letter) end def list_generic(spell_list) spell_list.each.with_index(1) { |spell, i| puts "#{i}. #{spell.name}" } end def choose_spell_from_letter self.list_spells_by_letter while @input != "menu!" && @input != "exit!" puts "\nEnter the number of a spell to get more information:" puts "(Enter \"list\" to repeat the list, \"search\" to search by another letter, \"menu!\" for the main menu, or \"exit!\" to leave the program.)" @input = gets.chomp.downcase if @input != "menu!" && @input != "exit!" if @input.to_i > 0 && @input.to_i <= @spells_by_letter.length SpellworkCli::Spell.request_info_by_spell(@spells_by_letter[@input.to_i-1]) elsif ("a".."z").include?(@input) self.search_by_letter self.choose_letter elsif @input == "list" self.list_spells_by_letter elsif @input == "search" self.choose_letter else puts "\nI'm not sure what you mean. Please try again." end end end end def goodbye puts "\nThank you for visiting." puts "Nox!" end end
true
0dbbb10dba735bb126c704466a565576b5f76fa0
Ruby
gonzalotraverso/bcn_weather
/lib/bcn_weather/forecast.rb
UTF-8
468
3.3125
3
[ "MIT" ]
permissive
class Forecast attr_reader :city_name def initialize(where:, min_temps:, max_temps:) @city_name = where @min_temps = min_temps @max_temps = max_temps end def today { min: @min_temps[0][:forecast], max: @max_temps[0][:forecast] } end def week_min_avg avg(@min_temps) end def week_max_avg avg(@max_temps) end private def avg(temps) temps.inject(0) { |sum, temp| sum + temp[:forecast] } / 7 end end
true
a61c0fb5b589bce3299e82c190d7d2bf12931338
Ruby
JosemyAB/ruby-martian-robots
/test/helpers/command/move_fordward_command_test.rb
UTF-8
1,326
2.671875
3
[ "Apache-2.0" ]
permissive
require 'test_helper' require_all './app/models/landscape' require_all './app/helpers/command' require_relative '../../../app/models/vehicle/rover' class MoveForwardCommandTest < ActiveSupport::TestCase planet = Planet.new(5, 5) test "move forward from north" do position = Position.new(2, 3) rover = Rover.new(planet, position, OrientationNorth.new) move_forward_command = MoveForwardCommand.new move_forward_command.execute(rover) assert_equal '2 4 N', rover.location end test "move forward from south" do position = Position.new(2, 3) rover = Rover.new(planet, position, OrientationSouth.new) move_forward_command = MoveForwardCommand.new move_forward_command.execute(rover) assert_equal '2 2 S', rover.location end test "move forward from east" do position = Position.new(2, 3) rover = Rover.new(planet, position, OrientationEast.new) move_forward_command = MoveForwardCommand.new move_forward_command.execute(rover) assert_equal '3 3 E', rover.location end test "move forward from west" do position = Position.new(2, 3) rover = Rover.new(planet, position, OrientationWest.new) move_forward_command = MoveForwardCommand.new move_forward_command.execute(rover) assert_equal '1 3 W', rover.location end end
true
bb738dad135c1cdf83629ed9debba3518f5b804a
Ruby
sebapobletec/E7CP2A1
/Ejercicio2.rb
UTF-8
392
3.390625
3
[]
no_license
nombres = ["Violeta", "Andino", "Clemente", "Javiera", "Paula", "Pia", "Ray"] b = nombres.select { |e| e.length >5 } print b puts '' min = nombres.map { |e| e.downcase } print min puts '' withp = nombres.select { |e| e[0] == 'P' } print withp puts '' length = nombres.map { |e| e.length } print length puts '' withoutv = nombres.map { |e| e.gsub(/[aeiou]/,'') } print withoutv puts ''
true
aebe9f28319a0c9ea59e31734c13f893e4512f6f
Ruby
sashite/gan.rb
/lib/sashite/gan/piece.rb
UTF-8
3,808
3.265625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Sashite module GAN # A piece abstraction. class Piece # The abbreviation of the piece. # # @!attribute [r] abbr # @return [String] The abbreviation of the piece. attr_reader :abbr # The piece's style. # # @!attribute [r] style # @return [String] The piece's style. attr_reader :style # Initialize a piece. # # @param type [String] The type of the piece. # @param is_king [Boolean] Is it a King (or a Xiangqi General), # so it could be checkmated? # @param is_promoted [Boolean] Is it promoted? # @param is_topside [Boolean] Is it owned by top-side player? # @param style [String] The piece's style. def initialize(type, is_king:, is_promoted:, is_topside:, style:) @abbr = Abbr.new(type, is_king: is_king, is_promoted: is_promoted) @is_topside = Boolean(is_topside) @style = StyleString(style) freeze end def king? abbr.king? end # Is it owned by top-side player? # # @return [Boolean] Returns `true` if the top-side player own the piece, # `false` otherwise. def topside? @is_topside end # Is it owned by bottom-side player? # # @return [Boolean] Returns `true` if the bottom-side player own the # piece, `false` otherwise. def bottomside? !topside? end # @see https://developer.sashite.com/specs/general-actor-notation # @return [String] The notation of the piece. def to_s topside? ? raw.downcase : raw.upcase end def inspect to_s end # @return [Piece] The top-side side version of the piece. def topside topside? ? self : oppositeside end # @return [Piece] The bottom-side side version of the piece. def bottomside topside? ? oppositeside : self end # @return [Piece] The opposite side version of the piece. def oppositeside self.class.new(abbr.type, is_king: abbr.king?, is_promoted: abbr.promoted?, is_topside: !topside?, style: style ) end # @return [Piece] The promoted version of the piece. def promote self.class.new(abbr.type, is_king: abbr.king?, is_promoted: true, is_topside: topside?, style: style ) end # @return [Piece] The unpromoted version of the piece. def unpromote self.class.new(abbr.type, is_king: abbr.king?, is_promoted: false, is_topside: topside?, style: style ) end def ==(other) other.to_s == to_s end def eql?(other) self == other end private # @return [String] The style and the abbreviation of the piece (without # case). def raw params.join(SEPARATOR_CHAR) end # @return [Array] The style and the abbreviation of the piece. def params [style, abbr] end # rubocop:disable Naming/MethodName # Ensures `arg` is a boolean, and returns it. Otherwise, raises a # `TypeError`. def Boolean(arg) raise ::TypeError, arg.class.inspect unless [false, true].include?(arg) arg end # Ensures `arg` is a style, and returns it. Otherwise, raises an error. def StyleString(arg) raise ::TypeError, arg.class.inspect unless arg.is_a?(::String) raise Error::Style, arg.inspect unless arg.match?(/\A[a-z_]+\z/i) arg end # rubocop:enable Naming/MethodName end end end require_relative 'abbr' require_relative 'error'
true
2fd05842ddc8da0b0d0210377d79165e2fa62337
Ruby
yovasx2/cars
/lib/cars/enemy_generator.rb
UTF-8
991
3.4375
3
[ "MIT" ]
permissive
module Cars class EnemyGenerator attr_reader :score, :level def initialize(window) @window = window @gap = 0 @enemies = [] @score = 0 @level = 1 end def update add_enemy if @gap % @window.height == 0 @gap += 2 update_enemies(level) delete_passed_enemies @level = 1 + @score / 50 end def draw draw_enemies end def collision?(player) collided = false @enemies.each do |enemy| collided ||= enemy.collision?(player) end collided end private def add_enemy @enemies << Enemy.new(@window) end def delete_passed_enemies @score += 10 unless @enemies.select { |enemy| enemy.passed? }.empty? @enemies.reject! { |enemy| enemy.passed? } end def draw_enemies @enemies.each { |enemy| enemy.draw } end def update_enemies(level) @enemies.each { |enemy| enemy.update(level) } end end end
true
1b26432a14522f59658ba179267a6975188006d0
Ruby
samstarling/creative-works
/lib/navigation.rb
UTF-8
448
3.109375
3
[]
no_license
class Navigation attr_reader :items def initialize items @items = items.sort end end class NavigationItem attr_reader :title, :path, :order def initialize title, path, order=0 @title = title @path = path @order = order end def active_for? request request.path == @path end def == other @title == other.title @path == other.path end def <=> other @order <=> other.order end end
true
445e8963f691845c6af53626fadb9e139d340f29
Ruby
akito1986/ocs
/lib/ocs/api_error.rb
UTF-8
657
2.546875
3
[ "MIT" ]
permissive
module Ocs class ApiError < OcsError attr_reader :api, :parameters, :error_response def initialize(api, parameters, error_response) @api = api @parameters = parameters @error_response = error_response end def error_code error_response.content[:cserrorcode] end def error_text error_response.content[:errortext] end def message { api: api, parameters: parameters, error_response: error_response.raw_body } end def status_code error_response.content[:errorcode] end def to_s "[#{error_code}] #{error_text}" end end end
true
b03e179ff92d10e1fbf27ad392f3f88cf8b63d3f
Ruby
sphilip/CSCI598-Elements_of_Computing_Systems
/project11/VMWriter.rb
UTF-8
1,834
3.203125
3
[]
no_license
# write VM command to file using VM command syntax class VMWriter attr_accessor :op_table, :write # create new file & open for writing def initialize(name) @op_table = { "+" => "add", "&" => "and", "|" => "or", "*" => "call Math.multiply 2", "/" => "call Math.divide 2", "-" => "neg", "~" => "not", ">" => "gt", "<" => "lt" } new_name = File.basename(name,".jack") + ".compiled.vm" dirname = name.gsub(/\w*\.\w*/,'') path = "./" + dirname + new_name @write = File.new(path,"w") end # write command for push # input: segment (const,arg,lcl,etc), index (int) def writePush(segment, index) @write.puts "push #{segment} #{index}" end # write command for pop # input: segment (const,arg,lcl,etc), index (int) def writePop(segment, index) @write.puts "pop #{segment} #{index}" end # write arithmetic command # input: command (add,sub,etc) def writeArithmetic(command) # if @op_table.include?(command) @write.puts "#{command}" # end end # write label # input: label (string) def writeLabel(label) @write.puts "label #{label}" end # write goto # input: label (string) def writeGoto (label) @write.puts "goto #{label}" end # write if-goto # input: label (string) def writeIf (label) @write.puts "if-goto #{label}" end # write call # input: name (string), number of args (int) def writeCall (name, numArg) @write.puts "call #{name} #{numArg.to_s}" # @write.puts "pop temp 0" end # write function # input: name (string), number of locals (int) def writeFunction (name, numLcl) @write.puts "function #{name} #{numLcl}" end # write return def writeReturn @write.puts "return" end # close output file def close end end
true
f4a7ccb7989ce96b10bbca878227432e0069b65d
Ruby
halokin/lrthw
/ex6.rb
UTF-8
1,474
4.09375
4
[]
no_license
# variable types_of_poeple avec valeur = a 10 types_of_people = 10 # variable x = au nombre de la varibale types_of_people, 10 # string inside a string : #{types_of_people} est dans le string enter guillemets x = "There are #{types_of_people} types of people." # variable binary correspond a la valeur binary binary = "binary" # la variable do_not est egale a don't do_not = "don't" # la variable y est = au resultat de la variable binary (binary) et de celle de do_not (don't) y = "Those who know #{binary} and those who #{do_not}." # afficher variable x puts x # afficher variable y puts y # afficher le contenu de la variable x puts "I said: #{x}." # afficher contenu variable y # string around a string puts "I also said: '#{y}'." # la variable hilarious est egale a la valeur flase hilarious = true # la variable joke evaluation est egale a la phrase suivie du contenu de hilarious soit false joke_evaluation = "Isn't that joke so funny?! #{hilarious}" #inscrire le résultat de la variable joke_evaluation puts joke_evaluation # la variable w est egale a la valeur presentee w = "This is the left side of..." # la variable e est egale a la valeur presentee e = "a string with a right side." #afficher resultat de somme de valeur w et e # addtionner les strings w et e donne un plus long string car on additionne les deux pour afficher la valeur de chacune a la suite puts w + e # les simples quotes servent a inscrire un string dans un string a double quote
true
fdb1d509fea9bb21dab982dc597916e446bdd94b
Ruby
cristianriano/reconciliaTIC
/app/helpers/sessions_helper.rb
UTF-8
469
2.734375
3
[]
no_license
module SessionsHelper #Loguea al usuario def log_in(user) session[:user_id] = user.id end #Almacena al usuario en la variable global "current_user" def current_user if(user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) end end #Elimina la session de las cookies def log_out session.delete(:user_id) @current_user = nil end #Verifica si el usuario se encuentra logueado def logged_in? !current_user.nil? end end
true
c6c351d6e466702f36ad5fa41f8a07a9dc1df9a6
Ruby
MASisserson/rb120
/practice_problems/easy_1/2.rb
UTF-8
957
4.5
4
[]
no_license
# What's the Output require 'pry' class Pet attr_reader :name def initialize(name) @name = name.to_s end def to_s @name.upcase! "My name is #{@name}." end end # name = 'Fluffy' # fluffy = Pet.new(name) # puts fluffy.name # Will output `Fluffy` ; If attr_reader is specified, calling puts on the name does not automatically call to_s on the instance variable. # puts fluffy # Will output "My name is FLUFFY" ; Calling puts on the class calls to_s automatically # puts fluffy.name # Will output `FLUFFY` # puts name # Will output `FLUFFY` name = 42 fluffy = Pet.new(name) name += 1 puts fluffy.name puts fluffy puts fluffy.name puts name =begin name is reassigned to `43` on `line 27`. `puts` only calls the instance method `to_s` when an object of the `Pet` class is passed to it as an argument. If any instance method in the object is invoked from, with, or in the object, the default Ruby `to_s` is used. =end
true
8941ebf7a1e5c45157ece25444d9f131e48eb79d
Ruby
zokioki/jun
/lib/jun/active_record/base.rb
UTF-8
1,070
2.640625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require_relative "../connection_adapters/sqlite_adapter" require_relative "./persistence" module ActiveRecord class Base include ActiveRecord::Persistence def initialize(attributes = {}) @attributes = attributes @new_record = true end def method_missing(name, *args) if self.class.connection.columns(self.class.table_name).include?(name) @attributes[name] else super end end def self.find(id) find_by_sql("SELECT * FROM #{table_name} WHERE id = #{id.to_i} LIMIT 1").first end def self.all ActiveRecord::Relation.new(self) end def self.where(*args) all.where(*args) end def self.find_by_sql(sql) connection.execute(sql).map do |attributes| object = new(attributes) object.instance_variable_set("@new_record", false) object end end def self.table_name name.downcase.pluralize end def self.connection @@connection ||= SqliteAdapter.new end end end
true
97ff4c0d4281ef5c13330d0cdc45d7717ff3e175
Ruby
cubicool/qimpy
/lib/qimpy.rb
UTF-8
4,775
2.765625
3
[]
no_license
# @todo: MAKE ALL OF THE RESPONSE-HANDLING ASYNCHRONOUS! This is so basic! Perhaps this means # creating a Qimpy::Connection and Qimpy::ASyncConnection, or something. require 'socket' require 'io/wait' require 'base64' require 'json' module Qimpy class Error < StandardError; end # @todo: Somehow make this in instance within the Connection? # @todo: puts, gets, etc? class File DEFAULT_COUNT = 1024 attr_reader :path def initialize(connection, path, mode) @path = path @conn = connection @handle = @conn.execute 'file-open', path: path, mode: mode end # @return { count: bytes, eof: true/false, buf-b64: ... } def read(count) @conn.execute 'file-read', handle: @handle, count: count end # @return { count: bytes, eof: true/false } def write(data) @conn.execute 'file-write', handle: @handle, 'buf-b64' => Base64.encode64(data) end # @return { position, eof: true/false } def seek(offset, whence) @conn.execute 'file-seek', handle: @handle, offset: offset, whence: whence end # def flush # @conn.execute 'file-flush', handle: @handle # end def close @conn.execute 'file-close', handle: @handle end # @todo: Add :binary mode. def readall(count = nil, mode = :text) fail NotImplementedError unless mode == :text # When :binary mode is implemented, this will likely be a different kind of object. data = '' # Decode up to 'count' bytes at a time, appending the result to data. loop do r = read(count || DEFAULT_COUNT) data += Base64.decode64(r['buf-b64']) break if r['eof'] end # Reset the file position to the beginning. seek 0, 0 data end end class Connection DEFAULT_PATH = '/tmp/qga.sock' DEFAULT_SYNCID = 311_411 attr_accessor :sock attr_reader :info Command = Struct.new :enabled, :name, :success_response Info = Struct.new :version, :supported_commands # Default path is the popular path used in QEMU documentation. def initialize(path = nil, syncid = nil) @sock = UNIXSocket.open path || DEFAULT_PATH # Clear out any leftover data (if there is any). @sock.gets if @sock.ready? # Synchronize our connection. syncid ||= DEFAULT_SYNCID fail IOError, "couldn't sync connection" unless execute('sync', id: syncid) == syncid # Issue a 'guest-info' command and store the results in our custom structures. This data will # be used later to verify the success/failure of subsequent executions. info = execute 'info' commands = info['supported_commands'].map do |v| Command.new v['enabled'], v['name'], v['success-response'] end @info = Info.new info['version'], commands end # Calls the passed-in command, returning only the 'return' key within QMP JSON response. Note # that the beginning 'guest-' portion of the command should be omitted, as it is automatically # prepended for you. No error-checking or verification is performed, and exceptions are allowed # to propogate. def execute(cmd, args = nil) # Write JSON data, with optional arguments. json = { execute: 'guest-' + cmd } json[:arguments] = args unless args.nil? @sock.puts json.to_json # Read back result. json = JSON.load @sock.gets if json.include? 'error' cls = json['error']['class'] desc = json['error']['desc'] fail Error, "#{desc} [#{cls}]" end json['return'] end def ping execute 'ping' end # "r", O_RDONLY # "rb", O_RDONLY | O_BINARY # "w", O_WRONLY | O_CREAT | O_TRUNC # "wb", O_WRONLY | O_CREAT | O_TRUNC | O_BINARY # "a", O_WRONLY | O_CREAT | O_APPEND # "ab", O_WRONLY | O_CREAT | O_APPEND | O_BINARY # "r+", O_RDWR # "rb+", "r+b", O_RDWR | O_BINARY # "w+", O_RDWR | O_CREAT | O_TRUNC # "wb+", "w+b", O_RDWR | O_CREAT | O_TRUNC | O_BINARY # "a+", O_RDWR | O_CREAT | O_APPEND # "ab+", "a+b", O_RDWR | O_CREAT | O_APPEND | O_BINARY # # Open the file specified at path/mode (on the HOST), and return a "handle" to be used in # subsequent function calls. def file_open(path, mode, &blk) fd = File.new self, path, mode return fd if blk.nil? blk.call fd fd.close end end module_function # Find the socket from the list of QEMU argument commandline; confirm with entry in # /proc/net/unix. def find_socket # ps axf | grep qemu-system | sed 's|.*qemu-system-x86_64 \(.*\)$|g' end end
true
f3a58d34da26f0893e8160556d95b5b5c78bdb5f
Ruby
ceclinux/rubyeveryDAMNday
/53.MaximumSubarray.rb
UTF-8
294
3.328125
3
[]
no_license
# @param {Integer[]} nums # @return {Integer} def max_sub_array(nums) min = 0 final = nums[0] curr = 0 nums.each_with_index do |a, index| curr += a final = [curr - min, final].max if index != 0 min = [curr, min].min end final end
true
a82593538b73bfd22da785c97c0c301386cc50d0
Ruby
AaronJHarvey/ruby-objects-has-many-through-readme-onl01-seng-pt-032320
/lib/waiter.rb
UTF-8
536
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#customer to meal, waiter to meal, so customer to waiter class Waiter attr_accessor :name, :yrs_experience @@all = [] def initialize(name, yrs_experience) @name = name @yrs_experience = yrs_experience @@all << self end def self.all @@all end def new_meal(customer,total,tip=0) Meal.new(self, customer, total,tip) end def meals Meal.all.select{|meal| meal.waiter == self} end def best_tipper best_tipped_meal = meals.max do |meal_a, meal_b| meal_a.tip <=> meal_b.tip end best_tipped_meal.customer end end
true
6b3bb33c2a07973ca024843e05e7dac24e8d153c
Ruby
thebravoman/software_engineering_2013
/class23_homework/B-Georgi-Ivanov-09/Ruby/Plane.rb
UTF-8
3,095
4.15625
4
[]
no_license
require_relative "Group" class Plane def initialize rows, seats_per_row, after_which_seat_is_the_walkway @seats = Array.new(rows+1) { Array.new(seats_per_row+1, 0) } # Creating array and filling it with 0. 0 means a seat is empty @num_of_rows = rows @num_of_seats_per_row = seats_per_row @after_which_seat_is_the_walkway = after_which_seat_is_the_walkway @empty_seats = rows * seats_per_row end def fly_plane puts "Flying away..." end def fill_plane while @empty_seats > 0 add_group_to_plane end puts "Plane is full!" end def add_group_to_plane new_group = Group.new puts "Ceated group of #{new_group.get_people_in_group}" find_seats new_group end def find_seats new_group if new_group.get_people_in_group == 1 add_one_person elsif new_group.get_people_in_group == 2 && @empty_seats >= 2 add_two_people elsif new_group.get_people_in_group == 3 && @empty_seats >= 3 add_three_people else puts "Not enough seats!" end end def add_one_person @seats.each_index do |row| next if row == 0 # Skiping the 0 row @seats[row].each_index do |seat| next if seat == 0 # Skiping the 0 seat if @seats[row][seat] == 0 puts "New passenger on row = #{row}, seat = #{seat}" @seats[row][seat] = 1 @empty_seats -= 1 return end end end end def add_two_people @seats.each_index do |row| next if row == 0 # Skiping the 0 row @seats[row].each_index do |seat| next if seat == 0 # Skiping the 0 seat if @seats[row][seat] == 0 && @seats[row][seat+1] == 0 if seat != @after_which_seat_is_the_walkway && seat+1 != @after_which_seat_is_the_walkway+1 @seats[row][seat] = 2 @seats[row][seat+1] = 2 puts "Passenger 2 seat is row = #{row}, seat = #{seat}" puts "Passenger 2's friend's seat is row = #{row}, seat = #{seat+1}" @empty_seats -= 2 return end end end end end def add_three_people @seats.each_index do |row| next if row == 0 # Skiping the 0 row @seats[row].each_index do |seat| next if seat == 0 # Skiping the 0 seat if @seats[row][seat] == 0 && @seats[row][seat+1] == 0 && @seats[row][seat+2] == 0 if seat != @after_which_seat_is_the_walkway && seat+1 != @after_which_seat_is_the_walkway+1 && seat+2 != @after_which_seat_is_the_walkway+2 # checks if: 3 | 3 3 if seat+1 != @after_which_seat_is_the_walkway && seat+2 != @after_which_seat_is_the_walkway+1 # checks if: 3 3 | 3 @seats[row][seat] = 3 @seats[row][seat+1] = 3 @seats[row][seat+2] = 3 puts "Passenger 3 seat is row = #{row}, seat = #{seat}" puts "Passenger 3's friend's seat is row = #{row}, seat = #{seat+1}" puts "Passenger 3's other friend's seat is row = #{row}, seat = #{seat+2}" @empty_seats -= 3 return end end end end end end def print_all_seats @seats.each_index do |row| next if row == 0 # Skiping the 0 row @seats[row].each_index do |seat| next if seat == 0 # Skiping the 0 seat print " #{@seats[row][seat]}" end puts end end end
true
cd0e5e9f10876fe3ae521d6a14c080e855ca31f5
Ruby
mmabraham/Chess
/lib/pieces/slidable.rb
UTF-8
493
2.71875
3
[]
no_license
module Slidable def moves moves = [] move_dirs.each do |diff| new_pos = pos while true new_pos = next_after(new_pos, diff) break unless new_pos.all? { |idx| idx < 8 && idx > -1 } if board[new_pos].symbol moves << new_pos unless board[new_pos].color == color break end moves << new_pos end end moves end private def next_after(pos, diff) [pos[0] + diff[0], pos[1] + diff[1]] end end
true
fe21b1add92dd5f22794f290b3ac661fa4214d65
Ruby
zerothabhishek/talk-rspec-and-testing
/samples-proper/lib/1.rb
UTF-8
61
2.6875
3
[]
no_license
class MyCalculator def self.add(x,y) x + y end end
true
7f23de6da344cdac34eba8562de0e60b30faf5e2
Ruby
budmc29/ruby_sandbox
/exercism/raindrops/raindrops.rb
UTF-8
539
3.734375
4
[]
no_license
# Convert a number to a string, the contents of which depend on the number's factors. class Raindrops FACTORS = [3, 5, 7] SOUNDS = { 3 => 'Pling', 5 => 'Plang', 7 => 'Plong' } def self.convert(number) string = '' FACTORS.each do |factor| string << SOUNDS[factor] if has_factor?(number, factor) end string << number.to_s if string.empty? string end private def self.has_factor?(number, factor) return true if number % factor == 0 end end module BookKeeping VERSION = 3 end
true
c062b70fe7740b249ee68f0aeb95c67479466051
Ruby
pp3n/ruby
/calculator.rb
UTF-8
930
4.28125
4
[]
no_license
def multiply(first_number, second_number) first_number.to_f * second_number.to_f end def add(first_number, second_number) first_number.to_f + second_number.to_f end def divide(first_number, second_number) first_number.to_f / second_number.to_f end def sub(first_number, second_number) first_number.to_f - second_number.to_f end puts "Select your operation 1) Multiply, 2) Add, 3) Divide, 4) Subtract" choice = gets.chomp.to_i puts "Please enter the first number" first_number = gets.chomp puts "Please enter the second number" second_number = gets.chomp if choice == 1 puts "Your output is #{multiply(first_number, second_number)}" elsif choice == 2 puts "Your output is #{add(first_number, second_number)}" elsif choice == 3 puts "Your output is #{divide(first_number, second_number)}" elsif choice ==4 puts "Your output is #{sub(first_number, second_number)}" else puts "Select a valid choice again! "end
true
ad5bd08ecee47499fe8328ba292053167003b09c
Ruby
meisyal/sastrawi-ruby
/lib/sastrawi/stemmer/context/visitor/remove_derivational_suffix.rb
UTF-8
1,042
2.8125
3
[ "MIT", "CC-BY-NC-SA-3.0" ]
permissive
require 'sastrawi/stemmer/context/removal' ## # Remove derivational suffix # Asian J. (2007) "Effective Techniques for Indonesian Text Retrieval" page 61 # http://researchbank.rmit.edu.au/eserv/rmit:6312/Asian.pdf module Sastrawi module Stemmer module Context module Visitor class RemoveDerivationalSuffix def visit(context) result = remove_suffix(context.current_word) if result != context.current_word removed_part = context.current_word.sub(/#{Regexp.quote(result)}/, '') removal = Sastrawi::Stemmer::Context::Removal.new(self, context.current_word, result, removed_part, 'DS') context.add_removal(removal) context.current_word = result end end ## # Original rule: i|kan|an # Added the adopted foreign suffix rule: is|isme|isasi def remove_suffix(word) word.sub(/(is|isme|isasi|i|kan|an)$/, '') end end end end end end
true
9e4138c3bcba179e43d04b8f25dcbc83dbcc093d
Ruby
yana-gi/atcoder
/abc191/a/main.rb
UTF-8
123
3.109375
3
[]
no_license
#!/usr/bin/env ruby v, t, s, d = gets.split.map(&:to_i) second = d / v.to_f puts second >= t && second <= s ? 'No' : 'Yes'
true
f767aedd82feba664800d83073777b1a60214fcb
Ruby
mattiasbergbom/gcovtools
/lib/file.rb
UTF-8
3,512
3.109375
3
[ "MIT" ]
permissive
require_relative './line' require 'pathname' class TrueClass def to_i return 1 end end class FalseClass def to_i return 0 end end module GCOVTOOLS class File attr_reader :name, :lines, :meta, :stats def initialize name fail "name required" unless name and name.is_a? String @name = name @lines = {} @meta = {} @stats = {} _update_stats end # return lines as array, in order by number def lines @lines.sort.map{|key,val|val} end def add_lines &block fail "add_lines requires a block" unless block_given? @adding = true yield @adding = false _update_stats end def _update_stats @stats = { :missed_lines => 0, :exec_lines => 0, :empty_lines => 0, :total_exec => 0, :total_lines => 0, :lines => 0, :coverage => 0.0, :hits_per_line => 0.0 } @lines.each do |index,line| @stats[:missed_lines] += (line.state == :missed).to_i @stats[:exec_lines] += (line.state == :exec).to_i @stats[:total_exec] += (line.count.is_a?(Integer) ? line.count : 0 ) @stats[:empty_lines] += (line.state == :none).to_i end @stats[:lines] = @stats[:exec_lines] + @stats[:missed_lines] @stats[:total_lines] = @stats[:lines] + @stats[:empty_lines] if @stats[:lines] > 0 @stats[:coverage] = @stats[:exec_lines].to_f / @stats[:lines].to_f @stats[:hits_per_line] = @stats[:total_exec].to_f / @stats[:lines] else @stats[:coverage] = 1 @stats[:hits_per_line] = 0 end @stats[:coverage_s] = sprintf("%0.01f%",100.0*@stats[:coverage]) @stats[:hits_per_line_s] = sprintf("%0.02f",@stats[:hits_per_line]) end def _add_line line if line.number == 0 key,val = /([^:]+):(.*)$/.match(line.text).to_a[1..2] @meta[key] = val else @lines[line.number] = line end end def <<(line) fail "need to be in add_lines block" unless @adding _add_line line end def self.load filename files = [] file = nil ::File.open(filename, "r") do |file_handle| file_handle.each_line do |line_| line = GCOVTOOLS::Line.parse(line_) if line.number == 0 key,val = /([^:]+):(.*)$/.match(line.text).to_a[1..2] if key == 'Source' if !file.nil? file._update_stats files << file end # if file = GCOVTOOLS::File.new val end # if source end # if line == 0 file._add_line line end # each line end# file_handle if file file._update_stats files << file end # if file files end def self.demangle filename result = filename.dup if start = result.index(/###/) result = result[start..-1] end result.gsub!( /(###|#|\^|\.gcov$)/, {"###"=>"/","#"=>"/","^"=>"..",".gcov"=>""} ) result = ::Pathname.new(result).cleanpath.to_s result end def merge! other other.lines.each do |line| if @lines.has_key? line.number @lines[line.number].merge! line else @lines[line.number] = line end end _update_stats end def merge other result = self.dup result.merge! other result end end # class File end
true
0e24bfb07ce5f9595abbecdf2c5b0352643e6693
Ruby
lindig/ring3tools
/size.rb
UTF-8
3,601
2.765625
3
[ "MIT" ]
permissive
#! /usr/bin/env ruby # # Report code size by OCaml module in a native binary # require 'set' require 'getoptlong' class OCamlModule include Comparable attr_reader :name, :start, :stop def initialize(name, start) @name = name @start = start @stop = nil end def <=>(other) return self.name <=> other.name end def to_s @name end def size (@stop-@start).to_f/1024.0 end def stop(addr) @stop = addr end end class OCamlBinary @@start = %r{(^[a-f0-9]{16}) ([a-zA-Z]) _?caml(.*)__code_begin$} @@stop = %r{(^[a-f0-9]{16}) ([a-zA-Z]) _?caml(.*)__code_end$} attr_reader :name, :modules def initialize(name) @name = name @modules = Hash.new self.read end def to_s @name end def keys @modules.keys end def read cmd = ["/usr/bin/nm", "-n", @name] IO.popen(cmd) do |io| io.each do |line| match = @@start.match(line) if match then name = match[3] addr = match[1].to_i(16) @modules[name] = OCamlModule.new(name, addr) end match = @@stop.match(line) if match then name = match[3] addr = match[1].to_i(16) @modules[name].stop(addr) end end end end def dump @modules.each do |name, m| printf "%6.1f %s\n", m.size, name end end end def report1(left) left = OCamlBinary.new(left) puts "# modules in #{left.name} (size in Kb)" left.modules.sort.each do |_,m| printf("%-50s %6.1f\n", m.name, m.size) end end def report2(left,right) left = OCamlBinary.new(left) right = OCamlBinary.new(right) l = Set.new(left.modules.keys) r = Set.new(right.modules.keys) puts "# modules in #{left.name} #{right.name} (size in Kb)" left_total = 0 right_total = 0 (l & r).sort.each do |m| printf("%-50s %6.1f %6.1f\n", m, left.modules[m].size, right.modules[m].size) left_total += left.modules[m].size right_total += right.modules[m].size end printf("# totals: %6.1f %6.1f\n",left_total,right_total) left_total = 0 puts puts "# modules only in #{left.name} (size in Kb)" (l - r).sort.each do |m| printf("%-50s %6.1f\n", m, left.modules[m].size) left_total += left.modules[m].size end printf("# total: %6.1f\n",left_total) right_total = 0 puts puts "# modules only in #{right.name} (size in Kb)" (r - l).sort.each do |m| printf("%-50s %6.1f\n", m, right.modules[m].size) right_total += right.modules[m].size end printf("# total: %6.1f\n",right_total) end opts = GetoptLong.new( [ '--help' , '-h', GetoptLong::NO_ARGUMENT ], ) opts.each do |opt, arg| case opt when '--help' puts <<~EOF #{$0} ocaml.exe [ocaml.exe] Report the code size per OCaml module found in the binary provided as argument. When two binaries are provided, report modules found in both and only either of the binaries. EOF exit 0 else raise ArgumentError, "#{opt} not recognized" end end case ARGV.length when 0 STDERR.puts "At least one binary needs to be provided" exit 1 when 1 file = ARGV[0] if not File.exists?(file) then STDERR.puts "Does not exist: #{file}" exit 1 end report1(ARGV[0]) when 2 left = ARGV[0] right = ARGV[1] if not File.exists?(left) then STDERR.puts "File does not exist: #{left}" exit 1 end if not File.exists?(right) then STDERR.puts "File does not exist: #{right}" exit 1 end report2(left, right) else STDERR.puts "More than two binaries provided." exit 1 end
true
9188afe68bcf94c1359a9cc9ea853af9b89fc1d7
Ruby
sarthak19-qait/Ruby
/Ruby/27).Modules.rb
UTF-8
179
3.203125
3
[]
no_license
module Tools def sayHii(name) puts "hello #{name}" end def sayBie(name) puts "hello #{name}" end end include Tools Tools.sayHii("Somil")
true
1b21815fcc9089dc5bad11c90b37485457bc0be5
Ruby
mwagner19446/wdi_work
/w01/d05/Kirsten/rental.rb
UTF-8
5,264
3.65625
4
[]
no_license
class Apartment def initialize end def apartment_name=(apartment_name) @apartment_name = apartment_name end def apartment_name return @apartment_name end def price=(price) @price = price end def price return @price end def sqft=(sqft) @sqft = sqft end def sqft return @sqft end def num_beds=(num_beds) @num_beds = num_beds end def num_beds return @num_beds end def num_baths=(num_baths) @num_baths = num_baths end def num_baths return @num_baths end def renter=(renter) @renter = renter end def renter return @person end end class Building def initialize @apartment = [] end def apartment return @apartment end def building_name=(building_name) @building_name = building_name end def building_name return @building_name end def address=(address) @address = address end def address return @address end def num_floors=(num_floors) @num_floors = num_floors end def num_floors return @num_floors end def apartments=(apartments) @apartments = apartments end def apartments @apartments end def add_apartment(apartment) self.apartment().push(apartment) end end class Person def initialize end def person_name=(person_name) @person_name = person_name end def person_name return @person_name end def age=(age) @age = age end def age return @age end def gender=(gender) @gender = gender end def gender return @gender end def apartment_name=(apartment_name) @apartment_name = apartment_name end def apartment_name return @apartment_name end end def menu puts "Welcome to the rental index!" puts "What would you like to do?" puts "1. View building details" puts "2. Add an apartment to the building" puts "3. Add a tenant" puts "4. List the apartment directory for the building" puts "Quit" end madison = Building.new madison.building_name=("The Madison") madison.address=("25 Madison Ave") madison.num_floors=(5) menu response = gets.chomp.downcase while response != "quit" case response when "1" puts "The name of this building is #{madison.building_name}." puts "It is located at #{madison.address}." puts "It has #{madison.num_floors} floors and #{madison.apartment.size} apartments." #show name, address, number of floors, number of apartments when "2" puts "What's the name of the apartment?" name_apartment = gets.chomp puts "What is the square footage?" user_sqft = gets.chomp.to_i puts "What is the cost per month?" user_price = gets.chomp.to_i puts "How many bedrooms?" user_beds = gets.chomp.to_i puts "How many bathrooms?" user_bath = gets.chomp.to_i puts "Who is renting? If there is no occupant put 'none'." user_renter = gets.chomp new_apartment = Apartment.new new_apartment.apartment_name = name_apartment new_apartment.sqft = user_sqft new_apartment.price = user_price new_apartment.num_beds = user_beds new_apartment.num_baths = user_bath new_apartment.renter = user_renter if user_renter != "none" puts "You have created #{name_apartment} with #{user_sqft} square feet, #{user_beds} beds, #{user_bath} baths, that #{user_renter} is renting." else puts "You have created #{name_apartment} with #{user_sqft} square feet, #{user_beds} beds, and #{user_bath} baths that costs $#{user_price} per month and is currently unoccupied." end madison.add_apartment(new_apartment) when "3" puts "What is the tenant's name?" input_name = gets.chomp puts "What is their age?" input_age = gets.chomp puts "What gender are they?" input_gender = gets.chomp puts "What apartment do they live in?" input_apartment = gets.chomp new_tenant = Person.new new_tenant.person_name = input_name new_tenant.age = input_age new_tenant.gender = input_gender new_tenant.apartment_name = input_apartment puts "You have created a new tenant #{input_name} who is #{input_age} and #{input_gender} and lives in #{input_apartment}" madison.add_apartment(input_apartment) when "4" if user_renter == "none" list_name = madison.apartment().each {|obj| print obj.apartment_name } list_sqft = madison.apartment().each {|obj| print obj.sqft } list_beds = madison.apartment().each {|obj| print obj.num_beds } list_bath = madison.apartment().each {|obj| print obj.num_baths } list_cost = madison.apartment().each {|obj| print obj.price } list_renter = madison.apartment().each {|obj| print obj.renter } puts "#{list_name[1]} is #{list_sqft} with #{list_beds} beds and #{list_bath} baths. It costs $#{list_cost} per month." else puts "#{list_renter} is renting #{list_name}." end # cannot get this to return the correct information. Either returns the entire array for the apartment or returns nil. # if just the method is listed, it will put the right info, but otherwise it will not, even if you try to + other strings in between. # the information is going in to the array, but cannot figure out how to call information back out. # dir_name = madison.apartment().each {|obj| puts obj.apartment_name } # puts "all this #{dir_name}" end menu response = gets.chomp.downcase end
true
1d3fec3a5900e57a045c1bc05560aab5afc5817b
Ruby
justonemorecommit/puppet
/spec/unit/util/windows/api_types_spec.rb
UTF-8
7,267
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# encoding: UTF-8 require 'spec_helper' describe "FFI::MemoryPointer", :if => Puppet::Util::Platform.windows? do # use 2 bad bytes at end so we have even number of bytes / characters let(:bad_string) { "hello invalid world".encode(Encoding::UTF_16LE) + "\xDD\xDD".force_encoding(Encoding::UTF_16LE) } let(:bad_string_bytes) { bad_string.bytes.to_a } let(:a_wide_bytes) { "A".encode(Encoding::UTF_16LE).bytes.to_a } let(:b_wide_bytes) { "B".encode(Encoding::UTF_16LE).bytes.to_a } context "read_wide_string" do let (:string) { "foo_bar" } it "should properly roundtrip a given string" do FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr| expect(ptr.read_wide_string(string.length)).to eq(string) end end it "should return a given string in UTF-8" do FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr| read_string = ptr.read_wide_string(string.length) expect(read_string.encoding).to eq(Encoding::UTF_8) end end it "should raise an error and emit a debug message when receiving a string containing invalid bytes in the destination encoding" do Puppet[:log_level] = 'debug' expect { FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, bad_string_bytes) ptr.read_wide_string(bad_string.length) end }.to raise_error(Encoding::InvalidByteSequenceError) expect(@logs.last.message).to eq("Unable to convert value #{bad_string.dump} to encoding UTF-8 due to #<Encoding::InvalidByteSequenceError: \"\\xDD\\xDD\" on UTF-16LE>") end it "should not raise an error when receiving a string containing invalid bytes in the destination encoding, when specifying :invalid => :replace" do FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, bad_string_bytes) read_string = ptr.read_wide_string(bad_string.length, Encoding::UTF_8, false, :invalid => :replace) expect(read_string).to eq("hello invalid world\uFFFD") end end it "raises an IndexError if asked to read more characters than there are bytes allocated" do expect { FFI::MemoryPointer.new(:byte, 1) do |ptr| ptr.read_wide_string(1) # 1 wchar = 2 bytes end }.to raise_error(IndexError, /out of bounds/) end it "raises an IndexError if asked to read a negative number of characters" do expect { FFI::MemoryPointer.new(:byte, 1) do |ptr| ptr.read_wide_string(-1) end }.to raise_error(IndexError, /out of bounds/) end it "returns an empty string if asked to read 0 characters" do FFI::MemoryPointer.new(:byte, 1) do |ptr| expect(ptr.read_wide_string(0)).to eq("") end end it "returns a substring if asked to read fewer characters than are in the byte array" do FFI::MemoryPointer.new(:byte, 4) do |ptr| ptr.write_array_of_uint8("AB".encode('UTF-16LE').bytes.to_a) expect(ptr.read_wide_string(1)).to eq("A") end end it "preserves wide null characters in the string" do FFI::MemoryPointer.new(:byte, 6) do |ptr| ptr.write_array_of_uint8(a_wide_bytes + [0, 0] + b_wide_bytes) expect(ptr.read_wide_string(3)).to eq("A\x00B") end end end context "read_arbitrary_wide_string_up_to" do let (:string) { "foo_bar" } let (:single_null_string) { string + "\x00" } let (:double_null_string) { string + "\x00\x00" } it "should read a short single null terminated string" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to).to eq(string) end end it "should read a short double null terminated string" do FFI::MemoryPointer.from_string_to_wide_string(double_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to(512, :double_null)).to eq(string) end end it "detects trailing single null wchar" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr).to receive(:read_wide_string).with(string.length, anything, anything, anything).and_call_original expect(ptr.read_arbitrary_wide_string_up_to).to eq(string) end end it "detects trailing double null wchar" do FFI::MemoryPointer.from_string_to_wide_string(double_null_string) do |ptr| expect(ptr).to receive(:read_wide_string).with(string.length, anything, anything, anything).and_call_original expect(ptr.read_arbitrary_wide_string_up_to(512, :double_null)).to eq(string) end end it "should raises an IndexError if max_length is negative" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect { ptr.read_arbitrary_wide_string_up_to(-1) }.to raise_error(IndexError, /out of bounds/) end end it "should return an empty string when the max_length is 0" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to(0)).to eq("") end end it "should return a string of max_length characters when specified" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to(3)).to eq(string[0..2]) end end it "should return wide strings in UTF-8" do FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr| read_string = ptr.read_arbitrary_wide_string_up_to expect(read_string.encoding).to eq(Encoding::UTF_8) end end it "should not raise an error when receiving a string containing invalid bytes in the destination encoding, when specifying :invalid => :replace" do FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, bad_string_bytes) read_string = ptr.read_arbitrary_wide_string_up_to(ptr.size / 2, :single_null, :invalid => :replace) expect(read_string).to eq("hello invalid world\uFFFD") end end it "should raise an IndexError if there isn't a null terminator" do # This only works when using a memory pointer with a known number of cells # and size per cell, but not arbitrary Pointers FFI::MemoryPointer.new(:wchar, 1) do |ptr| ptr.write_array_of_uint8(a_wide_bytes) expect { ptr.read_arbitrary_wide_string_up_to(42) }.to raise_error(IndexError, /out of bounds/) end end it "should raise an IndexError if there isn't a double null terminator" do # This only works when using a memory pointer with a known number of cells # and size per cell, but not arbitrary Pointers FFI::MemoryPointer.new(:wchar, 1) do |ptr| ptr.write_array_of_uint8(a_wide_bytes) expect { ptr.read_arbitrary_wide_string_up_to(42, :double_null) }.to raise_error(IndexError, /out of bounds/) end end end end
true
8319dc4d3d36ea507d1b68235eedba2c998fc86d
Ruby
Muhidin123/ruby-oo-complex-objects-school-domain
/lib/school.rb
UTF-8
621
3.625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class School attr_accessor :school_name, :name, :grade def initialize(school_name, hash={}, *grade) @school_name = school_name @name = name @grade = grade @hash = hash end def roster @hash end def add_student(name, grade) if roster.length == 0 || !@hash.key?(grade) @hash[grade] = [name] elsif roster.length > 0 && @hash.key?(grade) @hash[grade] << name end end def grade(grade) @hash[grade] end def sort @hash[9] = @hash[9].sort @hash.sort.to_h end end
true
34ad7a30dc809a12412566a7fe37da3aa5962a98
Ruby
Segrelove/ruby-friday
/exo_07_c.rb
UTF-8
169
3.046875
3
[]
no_license
user_name = gets.chomp puts user_name # la différence entre trois programmes est l'affichage alors que la fonctionnalité est la même, qui est d'afficher l'user input
true
fd180d5c59362a237f52cfba1d14eadc9227bb63
Ruby
bright-spark/mobilize-base
/lib/mobilize-base/extensions/google_drive/worksheet.rb
UTF-8
8,852
2.640625
3
[ "Apache-2.0" ]
permissive
module GoogleDrive class Worksheet def to_tsv(gsub_line_breaks=" ") sheet = self rows = sheet.rows header = rows.first return nil unless header and header.first.to_s.length>0 #look for blank cols to indicate end of row col_last_i = (header.index("") || header.length)-1 #ignore user-entered line breaks for purposes of tsv reads out_tsv = rows.map do |r| row = r[0..col_last_i].join("\t") row.gsub!(/[\n\r]/,gsub_line_breaks) row = row + "\n" row end.join + "\n" out_tsv.tsv_convert_dates(Mobilize::Gsheet.config['sheet_date_format'], Mobilize::Gsheet.config['read_date_format']) end def add_headers(headers) headers.each_with_index do |h,h_i| self[1,h_i+1] = h end self.save end def delete_sheet1 sheet = self #delete sheet1 sheet1 = sheet.spreadsheet.worksheet_by_title("Sheet1") || sheet.spreadsheet.worksheet_by_title("Sheet 1") if sheet1 sheet1.delete return true end end def add_or_update_rows(upd_rows) sheet = self curr_rows = sheet.to_tsv.tsv_to_hash_array headers = curr_rows.first.keys curr_rows = [] if curr_rows.length==1 and curr_rows.first['name'].nil? curr_row_names = curr_rows.map{|r| r['name']} upd_rows.each_with_index do |row,urow_i| crow_i = curr_row_names.index(row['name']) if crow_i.nil? curr_row_names << row['name'] crow_i = curr_row_names.length-1 end row.each do |col_n,col_v| col_v_i = headers.index(col_n) sheet[crow_i+2,col_v_i+1] = col_v end end sheet.save end def merge(merge_sheet,user_name,crop) #write the top left of sheet #with the contents of merge_sheet sheet = self sheet.reload entry = sheet.spreadsheet.acl_entry("#{user_name}@#{Mobilize::Gdrive.domain}") unless entry and ['writer','owner'].include?(entry.role) raise "User #{user_name} is not allowed to write to #{sheet.spreadsheet.title}" end merge_sheet.reload curr_rows = sheet.num_rows curr_cols = sheet.num_cols merge_rows = merge_sheet.num_rows merge_cols = merge_sheet.num_cols raise "zero sized merge sheet" if merge_rows == 0 or merge_cols == 0 #make sure sheet is at least as big as necessary #or as small as necessary if crop is specified if merge_rows > curr_rows or (merge_rows < curr_rows and crop==true) sheet.max_rows = merge_rows sheet.save end if merge_cols > curr_cols or (merge_cols < curr_cols and crop==true) sheet.max_cols = merge_cols sheet.save end batch_start = 0 batch_length = 80 merge_sheet.rows.each_with_index do |row,row_i| row.each_with_index do |val,col_i| sheet[row_i+1,col_i+1] = val end if row_i > batch_start + batch_length sheet.save batch_start += (batch_length+1) end end sheet.save end def read(user) sheet = self entry = sheet.spreadsheet.acl_entry("#{user}@#{Mobilize::Gdrive.domain}") if entry and ['reader','writer','owner'].include?(entry.role) sheet.to_tsv else raise "User #{user} is not allowed to read #{sheet.spreadsheet.title}" end end def write(tsv,user,crop=true) sheet = self entry = sheet.spreadsheet.acl_entry("#{user}@#{Mobilize::Gdrive.domain}") unless entry and ['writer','owner'].include?(entry.role) raise "User #{user} is not allowed to write to #{sheet.spreadsheet.title}" end tsvrows = tsv.split("\n") #no rows, no write return true if tsvrows.length==0 headers = tsvrows.first.split("\t") batch_start = 0 batch_length = 80 rows_written = 0 curr_rows = sheet.num_rows curr_cols = sheet.num_cols #make sure sheet is at least as big as necessary #or small as necessary if crop if tsvrows.length > curr_rows or (tsvrows.length < curr_rows and crop==true) sheet.max_rows = tsvrows.length sheet.save end if headers.length > curr_cols or (tsvrows.length < curr_rows and crop==true) sheet.max_cols = headers.length sheet.save end #write to sheet in batches of batch_length while batch_start < tsvrows.length batch_end = batch_start + batch_length tsvrows[batch_start..batch_end].each_with_index do |row,row_i| rowcols = row.split("\t") rowcols.each_with_index do |col_v,col_i| sheet[row_i + batch_start + 1, col_i + 1]= %{#{col_v}} end end sheet.save batch_start += (batch_length + 1) rows_written += batch_length if batch_start>tsvrows.length + 1 break end end true end def check_and_fix(tsv) sheet = self sheet.reload #loading remote data for checksum rem_tsv = sheet.to_tsv return true if rem_tsv.to_s.length==0 rem_table = rem_tsv.split("\n").map{|r| r.split("\t").map{|v| v.googlesafe}} loc_table = tsv.split("\n").map{|r| r.split("\t").map{|v| v.googlesafe}} re_col_vs = [] errcnt = 0 #checking cells loc_table.each_with_index do |loc_row,row_i| loc_row.each_with_index do |loc_v,col_i| rem_row = rem_table[row_i] if rem_row.nil? errcnt+=1 "No Row #{row_i} for Write Dst".oputs break else rem_v = rem_table[row_i][col_i] if loc_v != rem_v if ['true','false'].include?(loc_v.to_s.downcase) #google sheet upcases true and false. ignore elsif loc_v.to_s.downcase.gsub("-","").gsub(" ","")==rem_v.to_s.downcase.gsub("-","").gsub(" ","") #supported currency, silently converted whether it's an actual currency or not #put a backtick on it. sheet[row_i+1,col_i+1] = %{'#{loc_v}} re_col_vs << {'row_i'=>row_i+1,'col_i'=>col_i+1,'col_v'=>%{'#{loc_v}}} elsif (loc_v.to_s.count('e')==1 or loc_v.to_s.count('e')==0) and loc_v.to_s.sub('e','').to_i.to_s==loc_v.to_s.sub('e','').gsub(/\A0+/,"") #trim leading zeroes #this is a string in scentific notation, or a numerical string with a leading zero #GDocs handles this poorly, need to rewrite write_dst cells by hand with a leading apostrophe for text sheet[row_i+1,col_i+1] = %{'#{loc_v}} re_col_vs << {'row_i'=>row_i+1,'col_i'=>col_i+1,'col_v'=>%{'#{loc_v}}} elsif loc_v.class==Float or loc_v.class==Fixnum if (loc_v - rem_v.to_f).abs>0.0001 "row #{row_i.to_s} col #{col_i.to_s}: Local=>#{loc_v.to_s} , Remote=>#{rem_v.to_s}".oputs errcnt+=1 end elsif rem_v.class==Float or rem_v.class==Fixnum if (rem_v - loc_v.to_f).abs>0.0001 "row #{row_i.to_s} col #{col_i.to_s}: Local=>#{loc_v.to_s} , Remote=>#{rem_v.to_s}".oputs errcnt+=1 end elsif loc_v.to_s.is_time? rem_time = begin Time.parse(rem_v.to_s) rescue nil end if rem_time.nil? || ((loc_v - rem_time).abs>1) "row #{row_i.to_s} col #{col_i.to_s}: Local=>#{loc_v} , Remote=>#{rem_v}".oputs errcnt+=1 end else #"loc_v=>#{loc_v.to_s},rem_v=>#{rem_v.to_s}".oputs begin if loc_v.force_encoding("UTF-8") != rem_v.force_encoding("UTF-8") #make sure it's not an ecoding issue "row #{row_i.to_s} col #{col_i.to_s}: Local=>#{loc_v} , Remote=>#{rem_v}".oputs errcnt+=1 end rescue => exc "#{exc.to_s}".oputs "row #{row_i.to_s} col #{col_i.to_s}: Local=>#{loc_v} , Remote=>#{rem_v}".oputs errcnt+=1 end end end end end end if errcnt==0 if re_col_vs.length>0 sheet.save "rewrote:#{re_col_vs.to_s}".oputs else true end else sheet.save "#{errcnt} errors found in checksum".oputs end end end end
true