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
036fdea67f5022a5535fd5e690838b1eb5fbe9fd
Ruby
ext/hink
/spec/lib/plugins/feed_spec.rb
UTF-8
2,516
2.546875
3
[]
no_license
require 'spec_helper' require 'liquid' require "formatters/feed" require 'plugins/feed' describe Feed do let(:feed_url) { "http://news.example.com" } let(:feed_template) { %( <rss version="2.0"> <channel> <title>News feed</title> <link>http://news.example.com</link> <description>All news</description> <item> <title>News post</title> <link>http://news.example.com/posts/4711</link> <description>&lt;p&gt;Lorem ipsum dolor sit amet&lt;/p&gt;&lt;p&gt;Foo bar baz&lt;/p&gt;</description> <author>Embraquel D. Tuta</author> <pubDate>{{date}}</pubDate> <guid>http://news.example.com/posts/4711</guid> </item> </channel> </rss> ) } let(:item_output) { "[News] News post | http://news.example.com/posts/4711" } subject { Feed.new } before(:all) do Formatters::Feed.stub(:parse_response!) Formatters::Feed.stub(:to_s) end describe "interval" do before(:each) do Hink.stub(:config).and_return( { feed: { uri: "http://news.example.com", interval: 5, template: "[{{ type }}] {{ title }} | {{ link }}" } } ) Feed.instance_variable_set(:@last_update, {}) end context "a new post exists" do before(:each) do date = Time.now + 3600 feed = Liquid::Template.parse(feed_template).render('date' => date.strftime("%a, %d %b %Y %H:%M:%S UTC")) stub_request(:get, feed_url).to_return( status: 200, body: feed ) end it "tries to parse that post" do Formatters::Feed.any_instance.should_receive(:'parse_response!') Feed.check_news(feed_url) end it "renders correct output" do Formatters::Feed.any_instance.should_receive(:'parse_response!') Formatters::Feed.any_instance.should_receive(:to_s).and_return(item_output) Feed.check_news(feed_url).should == [item_output] end end context "no new posts" do before(:each) do date = Time.now - 3600 feed = Liquid::Template.parse(feed_template).render('date' => date.strftime("%a, %d %b %Y %H:%M:%S GMT+1")) stub_request(:get, "http://news.example.com").to_return( status: 200, body: feed ) end it "returns nothing" do Feed.check_news(feed_url).should == [] end end end end
true
ad4e3a926d497a71083f299d30a52a54fd8b45f4
Ruby
chethan/ProjectEuler
/Ruby/ProblemSixteen.rb
UTF-8
288
3.6875
4
[]
no_license
#2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. #What is the sum of the digits of the number 2^(1000)? require "Utils" class Problem_Sixteen def self.mine p (2 ** 1000).to_digits.inject{|sum,i| sum +=i} end end Problem_Sixteen.mine
true
3528d6d45c02561ec9c5142bfdb52bb052dcb393
Ruby
danwhitston/2017-learn-to-program
/chap07/ex2.rb
UTF-8
282
3.375
3
[ "MIT" ]
permissive
# Deaf grandma your_sentence = "" puts "AFTERNOON SONNY!" until your_sentence == "BYE" your_sentence = gets.chomp if your_sentence == your_sentence.upcase puts "NO, NOT SINCE " + (rand(99) + 1910).to_s + "!" else puts "HUH?! SPEAK UP, SONNY!" end end
true
aab77d8ac7f0b305a7983965faa4caa65bf4b5f1
Ruby
bstiber/launch_school_exercises
/loops2/five.rb
UTF-8
921
4.71875
5
[]
no_license
# The following code increments number_a and number_b by either 0 or 1. loop is used # so that the variables can be incremented more than once, however, break stops the # loop after the first iteration. Use next to modify the code so that the loop # iterates until either number_a or number_b equals 5. Print "5 was reached!" before # breaking out of the loop. # Use next to skip the rest of the current iteration and start executing the next iteration. # We'll use the same example as before to demonstrate. This time we'll skip 4. # use next with unless number_a = 0 number_b = 0 loop do p number_a += rand(2) p number_b += rand(2) next unless number_a == 5 || number_b == 5 break end puts "number 5 was reached!" number_a = 0 number_b = 0 # using if/else instead loop do p number_a += rand(2) p number_b += rand(2) break if number_a == 5 || number_b == 5 end puts "number 5 was reached!"
true
3c7ea1bc491d213a918b94a93ee55e91260e8ce8
Ruby
HCoban/Training
/algorithms/random_subarray.rb
UTF-8
726
3.65625
4
[]
no_license
def random_subarray(arr, n) dup = arr.dup r = rand(dup.length) dup[0], dup[r] = dup[r], dup[0] i = 1 while i < n r = rand(dup.length-i) + i dup[i], dup[r] = dup[r], dup[i] i += 1 end dup[0...n] end arr = [3, 7, 5, 11, 12] freq = { 3 => 0, 7 => 0, 5 => 0, 11 => 0, 12 => 0 } 10000000.times do r = random_subarray(arr, 3) r.each { |el| freq[el] += 1 } end indexes = {0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0} 10000000.times do r = random_subarray(arr, arr.length) indexes[r.index(3)] += 1 end def frequency(hash) total = hash.values.inject(&:+).to_f freq = {} hash.each do |k, v| freq[k] = (v.to_f / total) * 100.0 end freq end puts frequency(freq) puts frequency(indexes)
true
c26dafd0184f0b8acd9a40b3cef3673835237352
Ruby
tjarratt/transmogrifier
/lib/transmogrifier/nodes/value_node.rb
UTF-8
603
2.984375
3
[ "MIT" ]
permissive
require_relative "node" module Transmogrifier class ValueNode < Node attr_reader :parent_node def initialize(value, parent_node=nil) @value = value @parent_node = parent_node end def find_all(keys) return [self] if keys.empty? raise "cannot find children of ValueNode satisfying non-empty selector #{keys}" end def modify(pattern, replacement) raise "Value is not modifiable using pattern matching" unless @value.respond_to?(:gsub) return @value.gsub!(Regexp.new(pattern), replacement) end def raw @value end end end
true
73356a6669812040deb8e8d3a7d3f5ac14af58b5
Ruby
billuyadavg/ruby_code
/check_number_occurrence.rb
UTF-8
2,012
3.53125
4
[]
no_license
#------------------------------------------------------------ # Checking occurrence of give number in give range of numbers #------------------------------------------------------------ def is_validated if $start_num > $end_num re_enter_number else return false end end def re_enter_number puts " Please Enter Correct Range End Number : " end_num = gets end_num = end_num.to_i $end_num = end_num is_validated end puts "==================================================================== " puts " \t Most welcome to Ruby " + RUBY_VERSION + " language development \n" puts "==================================================================== " puts " Please Enter Range Starting Number : " start_num = gets # enter any value start_num = start_num.to_i $start_num = start_num start_num_temp = start_num puts " Please Enter Range End Number : " end_num = gets end_num = end_num.to_i $end_num = end_num is_validated puts " Please Enter For Which Occurrences Number : " ornc_chk_num = gets ornc_chk_num = ornc_chk_num.strip ornc_num_arr = [] while(start_num <= end_num ) ornc_num_arr << start_num if start_num.to_s.index(ornc_chk_num) if start_num.to_s.index(ornc_chk_num) please_skip = true start_num.to_s.split("").each do |num| ornc_num_arr << start_num if (num.to_s.index(ornc_chk_num) && !please_skip ) if please_skip && ornc_chk_num == num please_skip = false end end end start_num +=1 end puts "====================================================================\n" puts " ======== Occurence Checking For #{ornc_chk_num.to_s } Number is #{ ornc_num_arr.size } Times Occured in #{ start_num_temp.to_s } to #{ end_num.to_s } =======" puts ornc_num_arr.join(", ").to_s puts "====================================================================\n" puts "\n==================================================================== " puts "== This code is written by : Billu Yadav (billuyadav208@gmail.com) ==" puts "==================================================================== "
true
16bd380c61381e2be1911d1ed2eeae5ac112d992
Ruby
yonjinkoh/assignment5
/Parser.rb
UTF-8
234
3.34375
3
[]
no_license
#Parses tweet lines class Parser def initialize(text) @line = text end def receiver receivers = @line.scan(/\@\w+/) return receivers.map!{ |element| element.gsub(/@/, '') } end def sender return @line[/\w+/] end end
true
05a12a91ead76258fbbf8d21860e037eae341fac
Ruby
Saicheg/bsuir-courses
/2016/InnaKorotkova/hw-0/reverse.rb
UTF-8
1,035
3.546875
4
[]
no_license
# 1/usr/bin/env ruby operators = ["*", "/", "+", "-", "!"] flag = true count = 0 values = [] stack = [] def bitoperation(value, count) code = value.to_s(2).reverse if code.length > count && count.positive? code.each_char do |i| if count.nonzero? && code[i] == "1" code[i] = "0" count -= 1 end end end count < code.length ? code.reverse.to_i(2) : 0 end def operation!(symbol, stack) var = stack.pop arg = stack.pop case symbol when "*" then stack.push(arg * var) when "-" then stack.push(arg - var) when "+" then stack.push(arg + var) when "/" then stack.push(arg.to_f / var.to_f) when "!" then stack.push(bitoperation(arg, var)) end end while flag value = gets.chomp if /^\d+$/ =~ value values.push(value = value.to_i) count += 1 elsif operators.include?(value) count -= 1 values.push(value) flag = false if count == 1 || count <= 0 end end values.each { |x| operators.include?(x) ? operation!(x, stack) : stack.push(x) } print stack[0], "\n"
true
9039155b1c0309a73dacbea1d50145bb9ba8331b
Ruby
SettRaziel/wrf_forecast
/lib/wrf_forecast/forecast/wind_text.rb
UTF-8
3,068
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'wrf_forecast/data/directions' module WrfForecast module Text # This class generates the forecast text for the wind speed # and direction of the forecast # warnings: all lesser warnings are a subset of the highest warning, that means # only the worst warning needs to be shown, that can be done during text creation class WindText < MeasurandText # initialization # @param [ExtremeValues] extreme_values the wind extreme values # @param [Symbol] prevalent_direction the prevalent wind direction # @param [WindThreshold] thresholds the wind threshold def initialize(extreme_values, prevalent_direction, thresholds) @prevalent_direction = prevalent_direction super(extreme_values, thresholds) end private # @return [Symbol] the prevalent wind direction attr_reader :prevalent_direction # method to generate the forecast text for the wind def generate_forecast_text @text = I18n.t("forecast_text.wind.text_start") @text.concat(create_strength_text) @text.concat(create_wind_text) nil end # method to generate the warning text for the measurand # @return [String] the warning text def generate_warning_text @warnings end # method to generate the text about the day def create_strength_text wind_strength = I18n.t("forecast_text.wind.strength_normal") if (is_threshold_active?(:hurricane_day)) wind_strength = I18n.t("forecast_text.wind.strength_extremly_stormy") elsif (is_threshold_active?(:storm_day)) wind_strength = I18n.t("forecast_text.wind.strength_very_stormy") elsif (is_threshold_active?(:storm_squall_day)) wind_strength = I18n.t("forecast_text.wind.strength_stormy") elsif (is_threshold_active?(:squall_day)) wind_strength = I18n.t("forecast_text.wind.strength_squall") elsif (is_threshold_active?(:windy_day)) wind_strength = I18n.t("forecast_text.wind.strength_windy") end return wind_strength end # method to generate the text with wind values def create_wind_text text = I18n.t("forecast_text.wind.text_maximum") text.concat((@extreme_values.maximum * 3.6).ceil.to_s) text.concat(I18n.t("forecast_text.wind.text_maximum_unit")) text.concat(create_prevalent_direction_text) text.concat(I18n.t("forecast_text.wind.text_mean")) mean = (@extreme_values.maximum + @extreme_values.minimum) / 2.0 text.concat((mean * 3.6).ceil.to_s) text.concat(I18n.t("forecast_text.wind.text_finish")) return text end # method to create the text for the prevalent wind direction def create_prevalent_direction_text if (@prevalent_direction == nil) return I18n.t("forecast_text.wind.direction_circular") end return WrfForecast::Directions.new().get_direction_string(@prevalent_direction) end end end end
true
0f00bc74b1070b0158fc79287b40fb4c882bb964
Ruby
tamarlehmann/lrthw
/ex38.rb
UTF-8
1,176
3.921875
4
[]
no_license
ten_things = "Apples Oranges Crows Telephone Light Sugar" puts "Wait there are not 10 things in that list. Lets fix that" stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] # using math make sure there's 10 times while stuff.length != 10 next_one = more_stuff.pop puts "Adding #{next_one}" stuff.push(next_one) puts "There are #{stuff.length} items now." end puts "There we go: #{stuff}" puts "Let's do some things with stuff." puts stuff[1] puts stuff[-1] puts stuff.pop() puts stuff.join(' ') puts stuff[3..5].join("#") # can use an array when you have something that matches the array data stductures # useful features: # 1. If you need to maintain order. Remember, this is listed order, not sorted order. Arrays do not sort for you. # 2. If you need to access the contents randomly by a number. Remember, this is using cardinal numbers starting at 0. # 3. If you need to go through the contents linearly (first to last). Remember, thats what for loops are for. # Note: more_stuff.pop() is call pop on more_stuff and is the same as pop(more_stuff) which is call pop # with argument more_stuff.
true
2f202037a04e3525bac1abc1e0836e67df7b52a4
Ruby
MattTennison/advent-of-code-2020
/lib/day_sixteen.rb
UTF-8
3,293
3.28125
3
[]
no_license
class TicketRule attr_reader :name def initialize(valid_ranges, name) @ranges = valid_ranges @name = name end def valid?(number) @ranges.any? { |range| range.include?(number) } end end class Ticket def initialize(values) @values = values end def invalid_values(rules) @values.select { |value| rules.none? { |r| r.valid?(value) } } end def valid?(rules) if (rules.count != @values.count) return false end result = true @values.each_with_index { |value, index| result = result && rules[index].valid?(value) } result end def value_at(index) @values[index] end end class TicketScanner def initialize(rule_list) @rule_list = rule_list end def invalid_values(tickets) tickets .map { |ticket| ticket.invalid_values(@rule_list) } .flatten end def valid_tickets(tickets) tickets .select { |ticket| ticket.invalid_values(@rule_list).empty? } end end class TicketRuleOrderAlgorithm def find_correct_order(tickets, rule_set) valid_tickets = tickets.select { |ticket| ticket.invalid_values(rule_set).empty? } order_options = starting_order_options(tickets, rule_set) valid_tickets.each do |ticket| order_options = valid_order_options_for_ticket(ticket, order_options) end order_options # rules = order_options.flatten # rules.map { |r| r.name } end private def starting_order_options(tickets, rule_set) rule_options = [] (0..rule_set.count - 1).each do |index| max = tickets.max { |ticket| ticket.value_at(index) }.value_at(index) min = tickets.min { |ticket| ticket.value_at(index) }.value_at(index) rule_options.push(rule_set.select { |rule| rule.valid?(max) && rule.valid?(min) }) end rule_options end def valid_order_options_for_ticket(ticket, order_options) options = order_options.map.with_index do |rule_list, index| rule_list.select { |rule| rule.valid?(ticket.value_at(index)) } end identified_rule = options.select { |o| o.count == 1 }.flatten options.map do |option| option.count == 1 ? option : option.reject { |o| identified_rule.include?(o) } end end end class DaySixteen def initialize(puzzle_input) @input = puzzle_input end def ticket_scanning_error_rate TicketScanner.new(rules).invalid_values(tickets).sum end def rule_order TicketRuleOrderAlgorithm.new.find_correct_order(tickets, rules.to_set).map do |rules| rules[0].name end end private def rules rule_regex = Regexp.new(/(\w+): (\d+)-(\d+) or (\d+)-(\d+)/) ranges = @input.scan(rule_regex).map do |matchdata| name = matchdata[0] first_rule_start, first_rule_end = matchdata.values_at(1, 2) second_rule_start, second_rule_end = matchdata.values_at(3, 4) TicketRule.new([ Range.new(first_rule_start.to_i, first_rule_end.to_i), Range.new(second_rule_start.to_i, second_rule_end.to_i) ], name) end end def tickets lines = @input.split("\n").map{ |line| line.strip } nearby_ticket_lines = lines[(lines.index("nearby tickets:") + 1..)] nearby_ticket_lines.map do |str| values = str.split(",").map { |s| s.to_i } Ticket.new(values) end end end
true
298222c73f46a7b7a5501a79c0e4098de1326c62
Ruby
keigori/marubatugame
/Output.rb
UTF-8
382
3.734375
4
[]
no_license
#盤面を出力するクラス class Output def ban (*banmen) 3.times do |i| 3.times do |n| print banmen[i][n] print " " end puts '' end end def win(k) case when k == 1 puts "先攻の勝利です" when k == 2 puts "後攻の勝利です" else k == 0 puts "引き分けです" end end end
true
3c7957690f708a5b084d2028a054ea2a385fff02
Ruby
diegofontecilla/BookMarkManager
/app.rb
UTF-8
639
2.578125
3
[]
no_license
require 'sinatra/base' require './lib/bookmark' require 'uri' require 'sinatra' require 'sinatra/flash' class BookmarkManager < Sinatra::Base enable :sessions register Sinatra::Flash get '/' do 'Hello world' end get '/bookmark' do @bookmarks = Bookmark.all erb :index end post '/bookmark' do puts params['url'] redirect('/bookmark') end get '/bookmark/new' do erb :"bookmark/new" end post '/bookmark/new' do flash[:notice] = 'You must submit a real url' unless Bookmark.create(url: params['url']) redirect '/bookmark' end # Start the server if ruby file executed directly run! if app_file == $0 end
true
fd88691ca995dcbced9947a203b0830cd1849d9e
Ruby
estein1988/backend_module_0_capstone
/day_6/ex_3_exercise.rb
UTF-8
1,068
4.03125
4
[]
no_license
class MyCar attr_accessor :color, :model attr_reader :year def initialize(year, color, model) @year = year @color = color @model = model @current_speed = 0 end def info puts "The #{year} #{color} #{model} is the car you will be driving today." end def speed_up(number) @current_speed += number puts "You push the gas and the acclerate #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake and decclerate #{number} mph." end def current_speed puts "You are now going #{@current_speed} mph." end def shut_down @current_speed = 0 puts "Please park your #{year} #{color} #{model}." end def spray_paint(color) self.color = color puts "Your new car color of #{color} looks great!" end end ford = MyCar.new('1989', 'Red', 'Mustang') ford.info ford.speed_up(20) ford.current_speed ford.brake(14) ford.current_speed ford.shut_down ford.current_speed puts "-" * 20 puts ford.color = 'Yellow' puts ford.year puts "-" * 20 ford.spray_paint('Yellow')
true
e91850a3bcbee3ec2cbf79005f8a00953089a0c3
Ruby
ManuelAgustinLucero/ruby
/eje4.rb
UTF-8
280
3.40625
3
[]
no_license
print "Porfavor ingrese un numero: " numero= gets numero=numero.to_i resultado=0 i=0 while resultado <= numero i+=1 resultado =resultado+i end # for i in(0..numero.to_i) # puts i # # result+=i # end puts "El resultado es #{resultado}" # puts "El resultado es #{result}"
true
68cccb10ab58c8133ea35e7d5e2733632fca3ea9
Ruby
arkency/zombiaki
/lib/zombie.rb
UTF-8
508
3.421875
3
[]
no_license
class Zombie def initialize(lives=1, name="zombie", moves_back_after_shoot=true) @original_lives = lives @lives = lives @name = name @moves_back_after_shoot = moves_back_after_shoot end def name @name end def one_life_left? @lives == 1 end def hit @lives -= 1 end def dead? @lives == 0 end def can_move_back? not dead? and @moves_back_after_shoot end def lives @lives end def restore_health @lives = @original_lives end end
true
85375be699a6193f8fd64a28142b8b34a6754733
Ruby
bezrukavyi/design_patterns
/behavioral/interpreter/parser.rb
UTF-8
889
3.4375
3
[]
no_license
class Parser attr_accessor :token OPERATIONS = %w(plus equal).freeze def initialize(text) @text = text @tokens = text.scan(/\(|\)|[\w\.\*]+/) end def next_token token = ParseSymbol.new(@tokens.shift).execute parsed_tokens << token token end def last_token token = parsed_tokens[-2] token == ')' ? results.last : token end def parsed_tokens @parsed_tokens ||= [] end def results @results ||= [] end def expression @token = next_token if @token.nil? results.last elsif @token == '(' results << expression expression elsif @token == ')' last_token else OPERATIONS.include?(token) ? operation_execute(@token) : expression end end private def operation_execute(class_name) Object.const_get(class_name.capitalize).new(last_token, expression).execute end end
true
0285f7fbc39be098e23e1673fa81d52ef2dde8b7
Ruby
rodrigocezzar/programacaoorientadaaobjetos
/computer.rb
UTF-8
169
2.953125
3
[]
no_license
class Computer def turn_on "turn on the computer kkkkk" end def shut_down "shutdown the computer" end end computer = Computer.new puts computer.turn_on
true
c6cfc4a77302d30641199464b681a7cfaf6efb62
Ruby
Koda-thp/Morpion
/lib/app/board_case.rb
UTF-8
334
3.03125
3
[]
no_license
# frozen_string_literal: true class BoardCase attr_accessor :case_id, :sign # TO DO : la classe a 2 attr_accessor, sa valeur en string (X, O, ou vide), ainsi que son identifiant de case def initialize(case_id, sign = " ") # règle sa valeur, ainsi que son numéro de case @case_id = case_id @sign = sign end end
true
b3975e3638895b3dfc3000c5a71f25bb6ff543d8
Ruby
arches/favorites
/lib/favorites.rb
UTF-8
339
2.703125
3
[ "MIT" ]
permissive
module Favorites def self.included(base) base.extend(ClassMethods) end module ClassMethods def favorite(finder, shortcuts) singleton = (class << self; self; end) shortcuts.each do |name, value| singleton.send(:define_method, name, lambda{ send("find_by_#{finder}", value) }) end end end end
true
d466cd26895f5f157d7d635d9090f04785ff6be1
Ruby
jfield44/TropoSparkIntegration
/app/controllers/tropo_actions_controller.rb
UTF-8
2,140
2.515625
3
[ "MIT" ]
permissive
require "net/http" require "uri" require 'open-uri' class TropoActionsController < ApplicationController skip_before_filter :verify_authenticity_token, :only => [:create] def create message_id = params[:data][:id] sender = params[:data][:personEmail] room_id = params[:data][:roomId] recieved_message = CiscoSpark::Message.fetch(message_id) parsed_messsage = recieved_message.text puts parsed_messsage if parsed_messsage.start_with?("/sms") || parsed_messsage.start_with?("/Sms") || parsed_messsage.start_with?("/phone") || parsed_messsage.start_with?("/Phone") self.slash_tropo_request(parsed_messsage, room_id) end render :nothing => true, :status => 200, :content_type => 'text/html' end def slash_tropo_request(parsed_message, room_id) request_values = parsed_message.split() puts request_values delivery_type = request_values[0].tr('/', '') recipient = request_values[1] message = "" for index in 2 ... request_values.size message = message + " " + request_values[index] puts "request_values[#{index}] = #{request_values[index]}" end puts message TropoAction.create(:recipient => recipient, :delivery_type => delivery_type, :message => message) url = "https://api.tropo.com/1.0/sessions?action=create&token=" if delivery_type == "phone" url = url + "YOUR_VOICE_API_TOKEN" + "&delivery_type=phone" elsif delivery_type == "sms" url = url + "YOUR_VOICE_SMS_TOKEN" + "&delivery_type=sms" end url = url + "&recipient=" + recipient + "&message=" + message.lstrip response = open(URI.encode(url)).read tropo_message = delivery_type == "phone" ? "Tropo: Phone Call Request Recieved" : "Tropo: SMS Request Recieved" CiscoSpark::Message.create(roomId: room_id, text: tropo_message) if delivery_type == "sms" SmsRetrieval.where(phone_number: recipient).destroy_all @persist = SmsRetrieval.create(phone_number: recipient, room_id: room_id) end end private def create_params params.require(:tropo_action).permit(:recipient, :delivery_type, :message) end end
true
304eb5d6e90252904f5bf48d4dd053a185bb63fe
Ruby
dsteed112/programming-univbasics-4-square-array-denver-web-033020
/lib/square_array.rb
UTF-8
184
3.734375
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(numbers) counter = 0 sqr_numbers=[] while numbers[counter] do sqr_numbers<<numbers[counter]*numbers[counter] counter += 1 end sqr_numbers end
true
2160db391c74e6db1ce4d6a1e87a37d8f8609de3
Ruby
parryjos1/sei35-homework
/warmups/week4/day_05_nucleotide_count/nucleotide_count.rb
UTF-8
499
3.390625
3
[]
no_license
def count_nucleotides dna bases_count = { 'A' => 0, 'C' => 0, 'T' => 0, 'G' => 0 } dna.each_char do |base| if bases_count.key? base bases_count[ base ] += 1 else puts " #{base} is not a valid nucleotide " end end bases_count.each do |key, val| puts "#{key}: #{val}" end end count_nucleotides "AGCTTTTXCATTCTGACTGCAACMGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
true
252282bd16ff3ce91d4560a15bc4f38e9e22c6d2
Ruby
StarPerfect/flash_cards
/test/round_test.rb
UTF-8
2,125
3.640625
4
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/card' require './lib/deck' require './lib/turn' require './lib/round' class RoundTest < Minitest::Test def setup @card_1 = Card.new("What is the capital of Italy?", "Rome", :Geography) @card_2 = Card.new("What is the capital of England?", "London", :Geography) @card_3 = Card.new("What is Japan's form of currency?", "Yen", :Finance) @cards = [@card_1, @card_2, @card_3] @deck = Deck.new(@cards) @round = Round.new(@deck) end def test_existance assert_instance_of Round, @round end def test_attributes assert_equal @deck, @round.deck end def test_turns_adds_turn assert_equal [], @round.turns @round.take_turn("Rome") assert_equal "Rome", @round.turns.first.guess end def test_current_card assert_equal @card_1, @round.current_card end def test_take_turn new_turn = Turn.new("Rome", @card_1) assert_equal new_turn.guess, @round.take_turn("Rome").guess end def test_if_new_turn_is_class new_turn = Turn.new("Rome", @card_1) assert_equal Turn, new_turn.class end def test_if_turn_correct new_turn = Turn.new("Rome", @card_1) assert new_turn.correct? end def test_if_turn_incorrect new_turn_2 = Turn.new("Denver", @card_1) refute new_turn_2.correct? end def test_number_correct @round.take_turn("Rome") assert_equal 1, @round.number_correct end def test_number_correct_by_category @round.take_turn("Rome") @round.number_correct_by_category(:Geography) assert_equal 1, @round.number_correct_by_category(:Geography) assert_equal 0, @round.number_correct_by_category(:STEM) end def test_percent_correct @round.take_turn("Rome") @round.take_turn("Denver") assert_equal 50.0, @round.percent_correct end def test_percent_correct_by_category @round.take_turn("Rome") @round.take_turn("Denver") @round.take_turn("Yen") assert_equal 50.0, @round.percent_correct_by_category(:Geography) assert_equal 100.0, @round.percent_correct_by_category(:Finance) end end
true
9f8fcc196aa2524d45d59aaedeeac83a7c1ae3ce
Ruby
djllap/crackin-the-code-interview
/Ch 1 - Strings/1.5.rb
UTF-8
721
4.03125
4
[]
no_license
# Implement a method to perform basic string compression # using the counts of repeated characters. For instance, # the string 'aabcccccaaa' would become 'a2b1c5a3'. If the # compressed string would not become smaller than the original # string, return the original string. You can assume the string # only has upper and lowercase letters a-z. def compress str comp = '' currChar = str[0] i = 1 count = 1 while i < str.length if str[i] == currChar i += 1 count += 1 else comp += "#{currChar}#{count}" count = 0 currChar = str[i] i += 1 end end comp += "#{currChar}#{count+1}" str.length > comp.length ? comp : str end p compress('aaaabbbbbbbbcca')
true
b9193011571c0db298dc6c9be005dba16cf6b22f
Ruby
efueger/donation-system
/lib/payment.rb
UTF-8
1,095
2.578125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'net/http' require 'net/https' require 'thank_you_mailer' class Payment attr_accessor :request def initialize(request) @request = request end def attempt response = post('https://api.stripe.com/v1/charges') if response.code == '200' ThankYouMailer.send_email(request.email, request.name) [] elsif response.code == '402' [:card_error] else [:invalid_request] end end private def post(url) uri = URI.parse(url) https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true http_request = Net::HTTP::Post.new(uri.path) http_request.basic_auth(ENV['STRIPE_API_KEY'], '') http_request.set_form_data(form_data) https.request(http_request) end def form_data { 'amount' => request.amount, 'currency' => request.currency, 'source[object]' => 'card', 'source[number]' => request.card_number, 'source[exp_month]' => request.exp_month, 'source[exp_year]' => request.exp_year, 'source[cvc]' => request.cvc } end end
true
99d740bf87b2bbd47068ab0d9a0ec07be2497a89
Ruby
nkoehring/towerdefence
/classes/global_event_handler.rb
UTF-8
862
2.765625
3
[ "ISC" ]
permissive
module TowerDefence class GlobalEventHandler include EventHandler::HasEventHandler def initialize clock, handle_sdl_events=true @clock = clock @clock.enable_tick_events @handle_sdl = handle_sdl_events # Create an EventQueue to take events from the keyboard, etc. # The events are taken from the queue and passed to objects # as part of the main loop. @queue = EventQueue.new() @queue.enable_new_style_events end def fire event @queue << event end def update # Fetch input events, etc. from SDL, and add them to the queue. @queue.fetch_sdl_events if @handle_sdl # Tick the clock and add the TickEvent to the queue. @queue << @clock.tick # Process all the events on the queue. @queue.each do |e| handle(e) end end end end
true
6dd1b7172a39bdc4a1000a81781e48e12ed93542
Ruby
kmhaines/renewable_energy_forecasting
/lib/repf/generic_data.rb
UTF-8
2,572
3.046875
3
[ "MIT" ]
permissive
require 'repf' require 'repf/predictor/solar' require 'csv' require 'date' module REPF class GenericData attr_accessor :data def initialize( csv ) @data = to_array_of_hashes( clean( csv ) ) @data_by_date = {} end def dates @data.collect {|dx| dx[:date]}.sort.uniq end def by_date(d) dd = Date === d ? d : Date.parse(d) if @data_by_date.has_key? dd @data_by_date[dd] else @data_by_date[dd] = @data.select {|dx| dx[:date] == dd} end end def clean( csv ) csv.reject do |row| row.first =~ /^\s*\#/ end.reject do |row| row.empty? end.collect do |row| row.collect {|item| String === item ? item.strip : item} end end def to_array_of_hashes( information ) @fields = decode_field_abbreviations information.first new_fields = [] information[1..-1].each do |row| next if row.length != @fields.length structure = { :date => date_from_data( row ) }.merge( data_as_hash( row ) ) { |key, oldval, newval| oldval } new_fields << structure end new_fields end private def date_from_data row if @fields.index( :date ) date_representation = row[@fields.index :date] else year = row[@fields.index :year] month = row[@fields.index :month] day = row[@fields.index :day] date_representation = "#{year}-#{month}-#{day}" end Date.parse( date_representation ) end def data_as_hash row h = {} @fields.each do |f| case f when :year, :month, :day next else h[f] = row[ @fields.index f ] end end h end def decode_field_abbreviations(fields) fields.collect {|f| field_abbreviation_to_symbol f.downcase} end def field_abbreviation_to_symbol(field) case field.to_s when 'mon' :month when 'hr' :hour when 'min' :minute when 'tmzn' :timezone when 'tmpf' :temperature when 'relh' :relative_humidity when 'sknt' :wind_speed when 'gust' :wind_gust when 'drct' :wind_direction when 'solr' :insolation when 'peak' :wind_peak_speed when 'prec' :precipitation when 'dwpf' :dewpoint else field.to_sym end end end class PowerData < GenericData end class WeatherData < GenericData end end
true
c64817b97d52d41043dc15db9c452d3a64898785
Ruby
uk-gov-mirror/ministryofjustice.specialist-publisher
/app/importers/cma_import/missing_body_generator.rb
UTF-8
1,117
2.546875
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
class CmaImportMissingBodyGenerator def initialize(create_document_service:, document_repository:) @create_document_service = create_document_service @document_repository = document_repository end def call(data) document = create_document_service.call(data) if needs_body_generating?(document) generate_body(document) document_repository.store(document) Presenter.new(document) else document end end private attr_reader :create_document_service, :document_repository def needs_body_generating?(document) document.body.empty? && document.attachments.size == 1 end def default_body "Full text of the decision" end def generate_body(document) attachment = document.attachments.first.snippet document.update(body: "#{default_body} #{attachment}") end class Presenter < SimpleDelegator def import_notes super.concat(messages) end private def messages [ body_missing_message, ] end def body_missing_message "missing `body` field replaced with default" end end end
true
80443348240d9192f38d7738b9c632459ae5664a
Ruby
epang1/my-select-001
/lib/my_select.rb
UTF-8
267
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_select(collection) # your code here! newlist = [] counter = 0 while counter < collection.count if yield(collection[counter]) == true newlist << collection[counter] counter += 1 else counter += 1 end end return newlist end
true
e5de4c3047148227682afe0180ddc0a9a11d7a64
Ruby
virajs/aws-sdk-core-ruby
/lib/aws/api/doc_example.rb
UTF-8
2,932
2.734375
3
[ "Apache-2.0" ]
permissive
module Aws module Api class DocExample include Seahorse::Model::Shapes def initialize(obj_name, method_name, operation) @obj_name = obj_name @method_name = method_name @operation = operation end def to_str "resp = #{@obj_name}.#{@method_name}(#{params[1...-1]})" end alias to_s to_str alias inspect to_str private def params return '' if @operation.input.members.empty? structure(@operation.input, '') end def structure(shape, i) lines = ['{'] shape.members.each do |member_name, member_shape| if member_shape.required lines << "#{i} # required" end lines << "#{i} #{member_name}: #{member(member_shape, i + ' ')}," end lines << "#{i}}" lines.join("\n") end def map(shape, i) if multiline?(shape.members) multiline_map(shape, i) else "{ #{key_name(shape)} => #{value(shape.members)} }" end end def multiline_map(shape, i) lines = ["{"] lines << "#{i} #{key_name(shape)} => #{member(shape.members, i + ' ')}," lines << "#{i} # repeated ..." lines << "#{i}}" lines.join("\n") end def list(shape, i) if multiline?(shape.members) multiline_list(shape, i) else "[#{value(shape.members)}, '...']" end end def multiline_list(shape, i) lines = ["["] lines << "#{i} #{member(shape.members, i + ' ')}," lines << "#{i} # repeated ... " lines << "#{i}]" lines.join("\n") end def member(shape, i) case shape when StructureShape then structure(shape, i) when MapShape then map(shape, i) when ListShape then list(shape, i) else value(shape) end end def value(shape) case shape when StringShape then string_value(shape) when IntegerShape then 'Integer' when FloatShape then 'Float' when BooleanShape then 'true || false' when TimestampShape then '<Time,DateTime,Date,Integer,String>'.inspect when BlobShape then "#{shape_name(shape, false)}<String,IO>".inspect else raise "unhandled shape type `#{shape.type}'" end end def string_value(shape) if shape.enum shape.enum.join('|').inspect else shape_name(shape) end end def multiline?(shape) shape.is_a?(StructureShape) or shape.is_a?(MapShape) or shape.is_a?(ListShape) end def shape_name(shape, inspect = true) value = shape.metadata['shape_name'] inspect ? value.inspect : value end def key_name(shape, inspect = true) shape_name(shape.keys) end end end end
true
9d8dcbc31c3fa4c2cc9fc1f831c8691e07c2776d
Ruby
clburns107/web-app__todo-list
/app/models/assignee.rb
UTF-8
736
2.828125
3
[]
no_license
class Assignee < ActiveRecord::Base #Class Method for collection of an assignee's assignments # #takes an argument of a collection of assignments # #Returns all todo items assigned to an assignee def self.todo_items(assignments) all_tasks = [] assignments.each do |assignment| all_tasks= Todo.where(id: assignment.todo_id) end return all_tasks end # returns a todo object for an assignee def todo_object task = Todo.find_by_id(self.todo_id) return task end # returns a category object for a todo for an assignee def category_object task = Todo.find_by_id(self.todo_id) category = Categories.find_by_id(task.category_id) return category end end
true
49ae37506816424795aa0ef831e648cd913e3cca
Ruby
postmodern/raingrams
/spec/probability_table_spec.rb
UTF-8
2,155
3
3
[ "MIT" ]
permissive
require 'raingrams/probability_table' require 'spec_helper' describe ProbabilityTable do before(:all) do @grams = [:a, :b, :a, :a, :b, :c, :d, 2, 3, :a] @table = ProbabilityTable.new @grams.each { |g| @table.count(g) } end describe "empty table" do before(:all) do @empty_table = ProbabilityTable.new end it "should not be dirty" do expect(@empty_table).not_to be_dirty end it "should be empty" do expect(@empty_table).to be_empty end it "should not have any frequencies" do expect(@empty_table.frequencies).to be_empty end it "should have no probabilities" do expect(@empty_table.probabilities).to be_empty end it "should have no grams" do expect(@empty_table.grams).to be_empty end end describe "un-built table" do it "should be dirty" do expect(@table).to be_dirty end it "should have the observed grams" do expect(@table.grams - @grams.uniq).to be_empty end it "should have non-zero frequencies" do @table.frequencies.each_value do |freq| expect(freq).to be > 0 end end it "should have non-zero frequencies for grams it has observed" do @grams.uniq.each do |g| expect(@table.frequency_of(g)).to be > 0 end end it "should return a zero frequency for unknown grams" do expect(@table.frequency_of(:x)).to eq(0) end it "should not have any probabilities yet" do expect(@table.probabilities).to be_empty end end describe "built table" do before(:all) do @table.build end it "should not be dirty" do expect(@table).not_to be_dirty end it "should return a zero probability for unknown grams" do expect(@table.probability_of(:x)).to eq(0.0) end it "should have non-zero probabilities" do @table.probabilities.each_value do |prob| expect(prob).to be > 0.0 end end it "should have non-zero probabilities for grams it has observed" do @grams.uniq.each do |g| expect(@table.probability_of(g)).to be > 0.0 end end end end
true
8cb8331a64185e591103617a6499d068e00d3077
Ruby
dhalai/hashids.rb
/lib/hashids.rb
UTF-8
6,081
3.046875
3
[ "MIT" ]
permissive
# encoding: utf-8 class Hashids VERSION = "0.0.5" DEFAULT_ALPHABET = "xcS4F6h89aUbideAI7tkynuopqrXCgTE5GBKHLMjfRsz" PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43] SaltError = Class.new(ArgumentError) MinLengthError = Class.new(ArgumentError) AlphabetError = Class.new(ArgumentError) def initialize(salt = "", min_length = 0, alphabet = DEFAULT_ALPHABET) @salt = salt @min_length = min_length @alphabet = alphabet @chars_regex = /./ validate_attributes setup_alphabet end def encrypt(*numbers) numbers.flatten! if numbers.length == 1 if numbers.empty? || numbers.reject { |n| Integer(n) && n > 0 }.any? "" else encode(numbers, @alphabet, @salt, @min_length) end end def decrypt(hash) hash.empty? ? [] : decode(hash) end private def validate_attributes unless @salt.kind_of?(String) raise Hashids::SaltError, "The salt must be a String" end unless @min_length.kind_of?(Fixnum) raise Hashids::MinLengthError, "The min length must be a Fixnum" end unless @min_length >= 0 raise Hashids::MinLengthError, "The min length must be 0 or more" end unless @alphabet.kind_of?(String) raise Hashids::AlphabetError, "The alphabet must be a String" end end def setup_alphabet @seps = [] @guards = [] @alphabet = @alphabet.scan(@chars_regex).uniq.join('') if @alphabet.length < 4 raise AlphabetError, "Alphabet must contain at least 4 unique characters." end PRIMES.each do |prime| char = @alphabet[prime - 1] break if char.nil? @seps << char @alphabet.tr!(char, ' ') end [0, 4, 8, 12].each do |index| separator = @seps[index] unless separator.nil? @guards << separator @seps.delete_at(index) end end @alphabet.delete!(' ') @alphabet = consistent_shuffle(@alphabet, @salt) end def encode(numbers, alphabet, salt, min_length = 0) ret = "" seps = consistent_shuffle(@seps, numbers).scan(@chars_regex) lottery_char = "" numbers.each_with_index do |number, i| if i == 0 lottery_salt = numbers.join('-') numbers.each { |n| lottery_salt += "-#{(n + 1) * 2}" } lottery = consistent_shuffle(alphabet, lottery_salt) ret += lottery_char = lottery[0] alphabet = "#{lottery_char}#{alphabet.delete(lottery_char)}" end alphabet = consistent_shuffle(alphabet, "#{lottery_char.ord & 12345}#{salt}") ret += hash(number, alphabet) if (i + 1) < numbers.length seps_index = (number + i) % seps.length ret += seps[seps_index] end end if ret.length < min_length first_index = 0 numbers.each_with_index do |number, i| first_index += (i + 1) * number end guard_index = first_index % @guards.length guard = @guards[guard_index] ret = guard + ret if ret.length < min_length guard_index = (guard_index + ret.length) % @guards.length guard = @guards[guard_index] ret += guard end end while ret.length < min_length pad_array = [alphabet[1].ord, alphabet[0].ord] pad_left = encode(pad_array, alphabet, salt) pad_right = encode(pad_array, alphabet, pad_array.join('')) ret = "#{pad_left}#{ret}#{pad_right}" excess = ret.length - min_length ret = ret[(excess.div(2)), min_length] if excess > 0 alphabet = consistent_shuffle(alphabet, salt + ret) end ret end def decode(hash) ret = [] if hash.length > 0 original_hash = hash alphabet = "" lottery_char = "" hash_split = hash.tr(@guards.join(''), ' ').split(' ') hash = hash_split[[3,2].include?(hash_split.length) ? 1 : 0] hash.tr!(@seps.join(''), ' ') hash_array = hash.split(' ') hash_array.each_with_index do |sub_hash, i| if sub_hash.length > 0 if i == 0 lottery_char = hash[0] sub_hash = sub_hash[1..-1] alphabet = lottery_char + @alphabet.delete(lottery_char) end if alphabet.length > 0 && lottery_char.length > 0 alphabet = consistent_shuffle(alphabet, (lottery_char.ord & 12345).to_s + @salt) ret << unhash(sub_hash, alphabet) end end end ret = [] if encrypt(*ret) != original_hash end ret end def consistent_shuffle(alphabet, salt) ret = "" alphabet = alphabet.join("") if alphabet.respond_to? :join salt = salt.join("") if salt.respond_to? :join alphabet_array = alphabet.scan(@chars_regex) salt_array = salt.scan(@chars_regex) sorting_array = [] salt_array << 0 if salt_array.empty? salt_array.each { |char| sorting_array << char.ord } sorting_array.each_with_index do |int,i| add = true k = i while k != sorting_array.length + i - 1 next_index = (k + 1) % sorting_array.length if add sorting_array[i] += sorting_array[next_index] + (k * i) else sorting_array[i] -= sorting_array[next_index] end add = !add k += 1 end sorting_array[i] = sorting_array[i].abs end i = 0 while alphabet_array.length > 0 pos = sorting_array[i] pos %= alphabet_array.length if pos >= alphabet_array.length ret += alphabet_array[pos] alphabet_array.delete_at(pos) i = (i+1) % sorting_array.length end ret end def hash(number, alphabet) hash = "" while number > 0 hash = "#{alphabet[number % alphabet.length]}#{hash}" number = number.div(alphabet.length) end hash end def unhash(hash, alphabet) number = 0 hash.scan(@chars_regex).each_with_index do |char, i| if pos = alphabet.index(char) number += pos * alphabet.length ** (hash.length - i - 1) end end number end end
true
2e6587c03cb1b72360c053bc843fc1a7acad0ad1
Ruby
Terryben/LoLStatsApp
/test/concTest.rb
UTF-8
340
3.421875
3
[]
no_license
def get_running_thread_count #borrowed from used Kashyap on Stack Overflow Thread.list.select {|thread| thread.status == "run"}.count end x = Thread.new { sleep 1 puts "Hello" sleep 1 puts "Father" } y = Thread.new { puts "My" sleep 1 puts "good" sleep 1 } puts "Thread count is #{get_running_thread_count}" x.join y.join
true
1dac94de2b64436c0dd88e74c14002883515ea69
Ruby
Sahej-Sandhu/W1D5
/skeleton/lib/00_tree_node.rb
UTF-8
1,233
3.46875
3
[]
no_license
require "byebug" class PolyTreeNode attr_reader :children def initialize(value) @value = value @children = [] end def parent @parent end def children @children end def value @value end def inspect if @children.empty? @value.inspect else @children.inspect end end def add_child(child) child.parent = self unless @children.include?(child) end def remove_child(child) if @children.include?(child) @children.delete(child) child.parent = nil else raise "this is not my child" end end def parent= (new_parent) old_parent = @parent return if new_parent == old_parent old_parent.children.delete(self) unless old_parent.nil? new_parent.children << self unless new_parent.nil? @parent = new_parent end def dfs(target_value) return self if self.value == target_value @children.each do |child| found = child.dfs(target_value) return found unless found.nil? end nil end def bfs(target_value) queue = [self] until queue.empty? node = queue.shift return node if node.value == target_value queue.concat(node.children) end nil end end
true
edbf53f2134631152456ecc4c872dc594f49e3d8
Ruby
cin9247/MealMonster
/spec/models/order_spec.rb
UTF-8
1,638
2.84375
3
[]
no_license
require_relative "../../app/models/order" describe Order do describe "#valid?" do context "given no offerings" do it "is not valid" do subject.offerings = [] expect(subject.valid?).to eq false end end context "given one offering" do it "is valid" do subject.offerings = [double] expect(subject.valid?).to eq true end end end describe "#deliver!" do it "sets the state to delivered" do subject.deliver! expect(subject.delivered?).to eq true expect(subject.loaded?).to eq false end end describe "#load!" do it "sets the state to loaded" do subject.load! expect(subject.loaded?).to eq true expect(subject.delivered?).to eq false end end describe "after initialization" do it "is not delivered" do expect(subject.delivered?).to eq false end it "is not canceled" do expect(subject.canceled?).to eq false end end describe "#cancel!" do before do subject.cancel! end it "is canceled afterwards" do expect(subject.canceled?).to eq true end end describe "#price" do let(:result) { Order.new(offerings: offerings).price } context "no offerings for this order" do let(:offerings) { [] } it "returns zero" do expect(result).to eq Money.zero end end context "two offerings given" do let(:offerings) { [double(:offering, price: Money.new(12)), double(:offering, price: Money.new(2))] } it "sums up the price" do expect(result).to eq Money.new(14) end end end end
true
4a5c6a459ec34d62cac055788e7d0a34969af07f
Ruby
JoseVteVento/koan
/about_modules.rb
UTF-8
3,512
3.609375
4
[]
no_license
require File.expand_path(File.dirname(__FILE__) + '/neo') class AboutModules < Neo::Koan module Nameable def set_name(new_name) @name = new_name end def here :in_module end end def test_cant_instantiate_modules assert_raise(___(NoMethodError)) do Nameable.new end end # ------------------------------------------------------------------ class Dog include Nameable attr_reader :name def initialize @name = "Fido" end def bark "WOOF" end def here :in_object end end def test_normal_methods_are_available_in_the_object fido = Dog.new assert_equal __("WOOF"), fido.bark end def test_module_methods_are_also_available_in_the_object fido = Dog.new assert_nothing_raised do # __ fido.set_name("Rover") end end def test_module_methods_can_affect_instance_variables_in_the_object fido = Dog.new assert_equal __("Fido"), fido.name fido.set_name("Rover") assert_equal __("Rover"), fido.name end def test_classes_can_override_module_methods fido = Dog.new assert_equal __(:in_object), fido.here end end #----------------------------------------------------------------------- #When creating complex objects, we use inheritance #You should create a complex chair using simple components class Chair_Components module Back attr_reader :back_height def back_set_height(new_heigth) @back_height = new_heigth end end module Seat attr_reader :seat_width def seat_set_width(new_width) @seat_width = new_width end end module Leg attr_reader :leg_height def leg_set_height(new_heigth) @leg_height = new_heigth end end class Chair include Back, Seat, Leg def build_chair(leg_h, seat_w, back_h) leg_set_height(leg_h) seat_set_width(seat_w) back_set_height(back_h) end def tell_me_your_tall @back_height + @leg_height + 1 end def tell_me_your_width @seat_width end def paint_the_chair paint_back paint_seat paint_legs end def paint_back @back_height.times {puts "*"} end def paint_seat puts "*" * @seat_width end def paint_legs #build a line @leg_height.times {puts ('*'.ljust @seat_width-1) << "*"} end end class Testing_Chair #this new chair's measure are back = 5, seat = 9, leg = 6 #and its tall = 12 my_chair = Chair.new my_chair.build_chair(6,9,5) my_chair.paint_the_chair my_chair.tell_me_your_tall def test_total_height_is_the_sum_of_the_height_of_the_objects assert_equal __(12), my_chair.tell_me_your_tall end def test_total_width_equals_the_width_of_the_seat assert_equal __(9), my_chair.tell_me_your_width end #create your chair which total heigth = 10 and total width = 7 def test_creating_your_own_chair your_chair = Chair.new your_chair.build_chair(__, __, __) your_chair.paint_the_chair assert_equal 10, your_chair.tell_me_your_tall assert_equal 7, your_chair.tell_me_your_width end def test_creating_other_chair #create a new chair which total height and total width are the same other_chair = Chair.new #write here your code assert_equal other_chair.tell_me_your_width = other_chair.tell_me_your_tall end def test_should_use_all_arguments assert_raise (__(ArgumenError)) do error_chair = Chair.new error_chair (5,5) end end end end
true
11e00b65a40963538fbe4a9747df48b50a85538f
Ruby
hannakalinowska/project-euler
/spec/problem037_spec.rb
UTF-8
632
3.15625
3
[]
no_license
require 'spec_helper' require 'problem037' RSpec.describe "Truncatable primes" do describe '#left_to_right_primes' do it 'returns true' do number = 3797 expect(left_to_right_primes(number.to_s)).to eq(true) end it 'returns false' do number = 333 expect(left_to_right_primes(number.to_s)).to eq(false) end end describe '#right_to_left_primes' do it 'returns true' do number = 3797 expect(right_to_left_primes(number.to_s)).to eq(true) end it 'returns false' do number = 333 expect(right_to_left_primes(number.to_s)).to eq(false) end end end
true
e5683367d1030b6596017e3c83f62c601707b04d
Ruby
trizen/sidef
/scripts/Tests/bitonic_sorter.sf
UTF-8
804
3.703125
4
[ "Artistic-2.0" ]
permissive
#!/usr/bin/ruby # Bitonic sorter # https://en.wikipedia.org/wiki/Bitonic_sorter func bitonic_compare(x, bool) { var dist = (x.len/2 -> int) for i in ^dist { if ((x[i] > x[i + dist]) == bool) { x.swap(i, i+dist) } } } func bitonic_merge(x, bool) { return(x) if (x.len == 1) bitonic_compare(x, bool) var parts = x/2 var first = bitonic_merge(parts[0], bool) var second = bitonic_merge(parts[1], bool) first + second } func bitonic_sort(x, bool=true) { return(x) if (x.len <= 1) var parts = x/2 var first = bitonic_sort(parts[0], true) var second = bitonic_sort(parts[1], false) bitonic_merge(first + second, bool) } var a = 16.of { 100.irand } var s = bitonic_sort(a) assert_eq(a.sort, s) say "** Test passed!"
true
f1113716f9814d664cf4f472fd2af13138649c29
Ruby
purchease/goose_project
/app/mutations/space/rule.rb
UTF-8
560
2.515625
3
[]
no_license
class Space::Rule < Mutations::Command optional do integer :space_id end def validate @space = Space.find space_id end def execute if @space.space_skill = two_times two_times elsif [5,9,14,18,23,27,32,36,41,45,50,54,59].include?(space_id) rip elsif [5,9,14,18,23,27,32,36,41,45,50,54,59].include?(space_id) hole elsif [5,9].include?(space_id) else end end # On va créer chaque méthode pour mettre les règles des cases # def two_times end def rip end def hole end end
true
a8aa403b7a3bca27a8ce37e145e5f6ffc9459f3f
Ruby
karlstav/fusuma
/lib/fusuma/device.rb
UTF-8
3,155
2.71875
3
[ "MIT" ]
permissive
module Fusuma # detect input device class Device attr_accessor :id attr_accessor :name attr_accessor :available def initialize(id: nil, name: nil, available: nil) @id = id @name = name @available = available end # @param [Hash] def assign_attributes(attributes) attributes.each do |k, v| case k when :id self.id = v when :name self.name = v when :available self.available = v end end end class << self # @return [Array] def ids available.map(&:id) end # @return [Array] def names available.map(&:name) end # @raise [SystemExit] # @return [Array] def available @available ||= fetch_available.tap do |d| MultiLogger.debug(available_devices: d) raise 'Touchpad is not found' if d.empty? end rescue RuntimeError => ex MultiLogger.error(ex.message) exit 1 end def reset @available = nil end # @param [String] def given_device=(name) return if name.nil? @available = available.select { |d| d.name == name } return unless names.empty? MultiLogger.error("Device #{name} is not found.\n Check available device with: $ fusuma --list-devices\n") exit 1 end private # @return [Array] def fetch_available line_parser = LineParser.new LibinputCommands.new.list_devices do |line| line_parser.push(line) end line_parser.generate_devices end # parse line and generate devices class LineParser attr_reader :lines def initialize @lines = [] end # @param line [String] def push(line) lines.push(line) end # @return [Array] def generate_devices device = nil lines.each_with_object([]) do |line, devices| device ||= Device.new device.assign_attributes extract_attribute(line: line) if device.available devices << device device = nil end end end # @param [String] # @return [Hash] def extract_attribute(line:) if (id = id_from(line)) { id: id } elsif (name = name_from(line)) { name: name } elsif (available = available?(line)) { available: available } else {} end end def id_from(line) line.match('^Kernel:[[:space:]]*') do |m| m.post_match.match(/event[0-9]+/).to_s end end def name_from(line) line.match('^Device:[[:space:]]*') do |m| m.post_match.strip end end def available?(line) # NOTE: natural scroll is available? return false unless line =~ /^Nat.scrolling: / return false if line =~ %r{n/a} true end end end end end
true
8d4dab39f24f9b37e756dc0cfdae32bca1276bcf
Ruby
hashimoton/spelling_alphabet
/spec/converter_spec.rb
UTF-8
1,059
2.71875
3
[ "MIT" ]
permissive
# coding: utf-8 require 'spec_helper' describe SpellingAlphabet do describe 'Converter' do context 'when generated without arguments' do before do @c = SpellingAlphabet::Converter.new end it 'converts letters to the corresponding words with the default word set' do expect(@c.spellout("A1")).to eq("Alfa Unaone") end it 'converts words to the original letters with the default word set' do expect(@c.interpret("Zulu Nadazero")).to eq("Z0") end end context 'when generated with a word set' do before do @c = SpellingAlphabet::Converter.new(SpellingAlphabet::Japanese) end it 'converts letters to the corresponding words with the given word set' do expect(@c.spellout("A1")).to eq("Alfa 数字のひと") end it 'converts words to the original letters with the given word set' do expect(@c.interpret("Zulu 数字のまる")).to eq("Z0") end end end end # EOF
true
d4b7a3f7bc304cfeca63a45d6da14156fe6feb0b
Ruby
trizen/sidef
/scripts/Tests/hash_concat.sf
UTF-8
338
3.171875
3
[ "Artistic-2.0" ]
permissive
#!/usr/bin/ruby # ## Hash.concat on various things, including non-hashes # var hash = Hash() hash += 1 assert_eq(hash{"1"}, nil) hash += Hash(:a => :b) assert_eq(hash{:a}, :b) hash += %w(c d) # 2-item array assert_eq(hash{:c}, :d) hash += "2":3 # an actual Pair assert_eq(hash{"2"}, 3) say "** Test passed!"
true
9f159738dd98fee239d1f2001051f50c2590a7bb
Ruby
nhutwkm/bai_tap_ruby
/Baitap/diadiem.rb
UTF-8
361
3.46875
3
[]
no_license
class Database def initialize end end x=[2,4,5,6,8,12,7,12,15] y=[4,5,2,9,6,14,78,9,2] puts "Nhap toa do diem o:" puts "nhap x:" $xx= gets.chomp.to_i puts "nhap y:" $yy= gets.chomp.to_i i=x.length-1 for i in (0..i) r=Math.sqrt(($xx-x[i])*($xx-x[i])+($yy-y[i])*($yy-y[i])) if r<=5 puts "[#{x[i]},#{y[i]}]" end puts r end # puts x.length # puts y.length
true
bfc42531a96af33bce0607d51843da32bf797ddc
Ruby
jmmastey/theatre-calendars
/lib/parsers/auditorium.rb
UTF-8
993
2.59375
3
[]
no_license
require_relative 'generic_parser' class Auditorium < GenericParser title 'Auditorium Theater' location '50 East Congress Parkway, Chicago, IL' uri 'http://auditoriumtheatre.org/wb/pages/home/performances-events/calendar.php?date=%Y-%m-01' date_xpath "//table[@class='calendar']//td[@class='linkedweekendday' or @class='linkedweekday']" def parse_date(date) url_base = "http://auditoriumtheatre.org" self.day = date.xpath("./div[@class='dayTxt']").text date.xpath(".//div[@class='eventItem']").map do |event| time = event.xpath(".//div[@class='eventItemTxt']").inner_html .gsub(/.*<br>/, '').gsub(/[\(\)]/, '') start_time = make_time(time) { :title => event.xpath(".//div[@class='eventItemTxt']/a").attr('title').to_s, :location => location, :start => start_time, :end => start_time + 7200, :url => url_base + event.xpath(".//div[@class='eventItemTxt']/a").attr('href').to_s } end end end
true
11c5b1895a3f5b449b09e2facfd6798ea85e7f29
Ruby
saga1/double_write_cache_stores
/lib/double_write_cache_stores/client.rb
UTF-8
7,306
2.546875
3
[ "MIT" ]
permissive
module DoubleWriteCacheStores class Client # rubocop:disable Metrics/ClassLength attr_accessor :read_and_write_store, :write_only_store def initialize(read_and_write_store_servers, write_only_store_servers = nil) @read_and_write_store = read_and_write_store_servers if write_only_store_servers if read_and_write_store_servers.class != write_only_store_servers.class raise "different cache store instance. #{read_and_write_store_servers.class} != #{write_only_store_servers.class}" end @write_only_store = write_only_store_servers end end def [](key) get key end def get_cas(key) if @read_and_write_store.respond_to? :get_cas @read_and_write_store.get_cas key elsif @read_and_write_store.respond_to? :read_cas @read_and_write_store.read_cas key elsif @read_and_write_store.respond_to? :dalli @read_and_write_store.dalli.get_cas key end end def set_cas(key, value, cas = 0, options = nil) cas_unique = if @read_and_write_store.respond_to? :set_cas @read_and_write_store.set_cas key, value, cas, options elsif @read_and_write_store.respond_to? :read_cas options ||= {} options[:cas] = cas @read_and_write_store.write_cas key, value, options elsif @read_and_write_store.respond_to? :dalli @read_and_write_store.dalli.set_cas key, value, cas, options end if @write_only_store && cas_unique set_or_write_method_call @write_only_store, key, value, options end cas_unique end def delete(key) result = @read_and_write_store.delete key @write_only_store.delete key if @write_only_store result end def []=(key, value) set key, value end def touch(key, ttl = nil) result = if @read_and_write_store.respond_to? :touch @read_and_write_store.touch key, ttl elsif @read_and_write_store.respond_to? :dalli @read_and_write_store.dalli.touch key, ttl end if @write_only_store if @write_only_store.respond_to? :touch @write_only_store.touch key, ttl elsif @write_only_store.respond_to? :dalli @write_only_store.dalli.touch key, ttl end end result end def flush if flush_cache_store || flush_cache_store(:clear) true else false end end def fetch(name, options = {}, &_block) raise UnSupportException "Unsupported #fetch from client object." unless @read_and_write_store.respond_to?(:fetch) delete name if options[:force] if options[:race_condition_ttl] fetch_race_condition name, options { yield } else unless value = get_or_read_method_call(name) value = yield write_cache_store name, value, options end value end end def increment(key, amount = 1, options = {}) increment_cache_store key, amount, options end alias_method :incr, :increment def decrement(key, amount = 1, options = {}) decrement_cache_store key, amount, options end alias_method :decr, :decrement def write_cache_store(key, value, options = nil) set_or_write_method_call @read_and_write_store, key, value, options set_or_write_method_call @write_only_store, key, value, options if @write_only_store end alias_method :set, :write_cache_store alias_method :write, :write_cache_store def get_or_read_method_call(key) if @read_and_write_store.respond_to? :get @read_and_write_store.get key elsif @read_and_write_store.respond_to? :read @read_and_write_store.read key end end alias_method :get, :get_or_read_method_call alias_method :read, :get_or_read_method_call def get_multi_or_read_multi_method_call(*keys) if @read_and_write_store.respond_to? :get_multi @read_and_write_store.get_multi(*keys) elsif @read_and_write_store.respond_to? :read_multi @read_and_write_store.read_multi(*keys) else raise UnSupportException "Unsupported multi keys get or read from client object." end end alias_method :get_multi, :get_multi_or_read_multi_method_call alias_method :read_multi, :get_multi_or_read_multi_method_call private def fetch_race_condition(key, options, &_block) result = fetch_to_cache_store(@read_and_write_store, key, options) { yield } fetch_to_cache_store(@write_only_store, key, options) { result } if @write_only_store && @write_only_store.respond_to?(:fetch) result end def fetch_to_cache_store(cache_store, key, options, &_block) if cache_store.is_a? Dalli::Client ttl = options[:expires_in] cache_store.fetch key, ttl, options { yield } else cache_store.fetch key, options { yield } end end def set_or_write_method_call(cache_store, key, value, options) if cache_store.respond_to? :set ttl = options[:expires_in] if options cache_store.set key, value, ttl, options elsif cache_store.respond_to? :write cache_store.write key, value, options end end def increment_cache_store(key, amount, options) rw_store_value = incr_or_increment_method_call @read_and_write_store, key, amount, options return rw_store_value unless @write_only_store incr_or_increment_method_call @write_only_store, key, amount, options end def decrement_cache_store(key, amount, options) rw_store_value = decr_or_decrement_method_call @read_and_write_store, key, amount, options return rw_store_value unless @write_only_store decr_or_decrement_method_call @write_only_store, key, amount, options end def incr_or_increment_method_call(cache_store, key, amount, options) ttl = options[:expires_in] if options default = options.key?(:initial) ? options[:initial] : amount if cache_store.is_a? Dalli::Client cache_store.incr key, amount, ttl, default elsif cache_store.respond_to? :increment options[:initial] = amount unless options.key?(:initial) cache_store.increment key, amount, options end end def decr_or_decrement_method_call(cache_store, key, amount, options) if cache_store.is_a?(Dalli::Client) ttl = options[:expires_in] if options default = options.key?(:initial) ? options[:initial] : 0 cache_store.decr key, amount, ttl, default elsif cache_store.respond_to? :decrement options[:initial] = 0 unless options.key?(:initial) cache_store.decrement key, amount, options end end def flush_cache_store(method = :flush) if @read_and_write_store.respond_to? method if @write_only_store && @write_only_store.respond_to?(method) @write_only_store.send method end @read_and_write_store.send method else false end end end end
true
2bf9be674159d35442b45c9802b1d583cbad8e63
Ruby
pantry/pantry
/lib/pantry/communication/reading_socket.rb
UTF-8
1,963
2.765625
3
[ "MIT" ]
permissive
module Pantry module Communication # Base class of all sockets that read messages from ZMQ. # Not meant for direct use, please use one of the subclasses for specific # functionality. class ReadingSocket include Celluloid::ZMQ finalizer :shutdown attr_reader :host, :port def initialize(host, port, security) @host = host @port = port @listener = nil @security = security end def add_listener(listener) @listener = listener end def open @socket = build_socket Communication.configure_socket(@socket) @security.configure_socket(@socket) open_socket(@socket) @running = true self.async.process_messages end def build_socket raise "Implement the socket setup." end def open_socket(socket) raise "Connect / Bind the socket built in #build_socket" end def shutdown @running = false end # Some ZMQ socket types include the source as the first packet of a message. # We need to know if the socket in question does this so we can properly # build the Message coming in. def has_source_header? false end protected def process_messages while @running process_next_message end @socket.close end def process_next_message next_message = [] # Drop the ZMQ given source packet, it's extraneous for our purposes if has_source_header? @socket.read end next_message << @socket.read while @socket.more_parts? next_message << @socket.read end async.handle_message( SerializeMessage.from_zeromq(next_message) ) end def handle_message(message) @listener.handle_message(message) if @listener end end end end
true
aff593572efe0d37940793228e45e1a276662b4d
Ruby
voxpupuli/modulesync
/lib/modulesync/cli/thor.rb
UTF-8
1,048
2.609375
3
[ "Apache-2.0" ]
permissive
require 'thor' require 'modulesync/cli' module ModuleSync module CLI # Workaround some, still unfixed, Thor behaviors # # This class extends ::Thor class to # - exit with status code sets to `1` on Thor failure (e.g. missing required option) # - exit with status code sets to `1` when user calls `msync` (or a subcommand) without required arguments # - show subcommands help using `msync subcommand --help` class Thor < ::Thor def self.start(*args) if (Thor::HELP_MAPPINGS & ARGV).any? && subcommands.none? { |command| command.start_with?(ARGV[0]) } Thor::HELP_MAPPINGS.each do |cmd| if (match = ARGV.delete(cmd)) ARGV.unshift match end end end super end desc '_invalid_command_call', 'Invalid command', hide: true def _invalid_command_call self.class.new.help exit 1 end default_task :_invalid_command_call def self.exit_on_failure? true end end end end
true
206ccf675a22e1144564f8b139c7793980127a4a
Ruby
mthorry/programming_languages-web-071717
/programming_languages.rb
UTF-8
1,005
3.09375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reformat_languages(languages) new_hash = {} languages.each do |language_class, values| # language_class = :oo; values = {:ruby=>{...}} values.each do |language, info| # language = :ruby; info = {:type=>"interpreted"} info.each do |type, spec| # type = :type; spec = "interpreted" if new_hash[language].nil? new_hash[language] = {} end new_hash[language][:style] ||= [] #creates new :style key new_hash[language][:style] << language_class #adding :language_class into new style array which is located HERE in bottom level of hash. if new_hash[language][type].nil? new_hash[language][type] = spec end end end end new_hash end # new_hash = {} # languages.each do |language_class, values| # new_hash[language_class] = values # values.each do |language,type| # language # type.each do |type, types| # type # types # end # end # end
true
6f510473668148ab61bb82b1df27a50cda6da563
Ruby
pithyless/lego
/lib/lego/model.rb
UTF-8
3,258
2.6875
3
[ "MIT" ]
permissive
require 'active_support/core_ext/hash/deep_merge' module Lego class Model class ParseError < StandardError def initialize(errors={}) @errors = errors super(errors.inspect) end attr_reader :errors end private_class_method :new class << self def attribute(attr, type, *args) parsers[attr.to_sym] = Lego.value_parser(type, *args) end def parsers @_parsers ||= {} end def validations @_validations ||= Hash.new { |h,k| h[k] = [] } end def attribute_names parsers.keys end def validates(attr, callable=nil, &block) attr = attr.to_sym if callable && callable.is_a?(Symbol) validations[attr] << callable else validations[attr] << block end end def coerce(hash) res = parse(hash) res.value? ? res.value : fail(ParseError.new(res.error)) end def parse(hash) return Lego.just(hash) if hash.instance_of?(self) fail ArgumentError, "attrs must be hash: '#{hash.inspect}'" unless hash.respond_to?(:key?) result = _parse(hash) if result.value? model = new(result.value) _validate(model) else result end end def _validate(obj) attrs = {} validations.each do |name, attr_validations| attrs[name] = Lego.just(obj) attr_validations.each do |validation| if validation.is_a?(Symbol) callable_method_name = validation.to_sym validation = ->(o){ o.method(callable_method_name).call } end attrs[name] = attrs[name].next(validation) end end if attrs.all?{ |k,v| v.value? } Lego.just(obj) else Lego.fail(Hash[*attrs.map{ |k,v| [k, v.error] if v.error? }.compact.flatten(1)]) end end def _parse(data) data = data.dup attrs = {} parsers.each do |name, parser| name = name.to_sym value = data.key?(name) ? data.delete(name) : data.delete(name.to_s) attrs[name] = parser.parse(value) end fail ArgumentError, "Unknown attributes: #{data}" unless data.empty? if attrs.all?{ |k,v| v.value? } Lego.just(Hash[*attrs.map{ |k,v| [k, v.value] }.flatten(1)]) else Lego.fail(Hash[*attrs.map{ |k,v| [k, v.error] if v.error? }.compact.flatten(1)]) end end end def initialize(attrs={}) @attributes = attrs.freeze end attr_reader :attributes def merge(other) self.class.coerce(as_json.deep_merge(other)) end def method_missing(name, *args, &block) attributes.fetch(name.to_sym) { super } end # Equality def ==(o) o.class == self.class && o.attributes == attributes end alias_method :eql?, :== def hash attributes.hash end # Serialize def as_json(opts={}) raise NotImplementedError, 'as_json with arguments' unless opts.empty? {}.tap do |h| attributes.each do |attr, val| h[attr] = val.as_json end end end end end
true
efb9b4bac3638d00b9b45cf7554d5c23da43a3f3
Ruby
janvmusic/RubyRubyRubyRuby
/HardWay/ex20.rb
UTF-8
673
3.84375
4
[]
no_license
input_file = ARGV[0] def print_all(f) puts f.read() end def rewind(f) f.seek(0,IO::SEEK_SET) end def print_line(line_count,f) puts "#{line_count} #{f.readline()}" end current_file = File.open(input_file) puts "First let's print the whole file" puts #a blank space print_all(current_file) puts "Now let's rewind, kind of like a tape." rewind(current_file) puts "Let's three lines:" current_line = 1 print_line(current_line,current_file) puts "current_line = #{current_line}" current_line += 1 print_line(current_line,current_file) puts "current_line = #{current_line}" current_line += 1 print_line(current_line,current_file) puts "current_line = #{current_line}"
true
04d1ec325f5b57fdf716b3915ea3136c9cad0caa
Ruby
MerStara/poseidon
/test/connection_test.rb
UTF-8
1,286
2.59375
3
[ "MIT" ]
permissive
require 'test_helper' class ConnectionTest < MiniTest::Test def setup @client = StringIO.new @connection = ::Poseidon::Connection.new(@client) end def ready_to_read_test # 默认可读 @connection.reset assert(@connection.ready_to_read?) @connection.send(:instance_variable_set, "@remain_body_size", 0) # 如果剩余字节为0,则不可读 refute(@connection.ready_to_read?) end def ready_to_write_test # 有rack提供的response对象存在,则可写,默认无response,不可写 @connection.reset refute(@connection.ready_to_write?) @connection.response = [200, {"Content-Length": "200"}, ["hello", "world"]] assert(@connection.ready_to_write?) end def ready_to_handle_test # 可读数据长度为0,且无response对象,表示应该进行逻辑处理 @connection.reset refute(@connection.ready_to_handle?) @connection.send(:instance_variable_set, "@remain_body_size", 0) assert(@connection.ready_to_handle?) end def _read_data_test @connection.reset @client.write "hello\r\n" assert_equal "hello\r\n", @connection._read_data(@client, :gets, "\r\n") @client.write "world" assert_equal "world", @connection._read_data(@client, :read_nonblock, 5) end end
true
771f58422f512353401b19cbf0d0f5a0d3cf8657
Ruby
cbituin/oo-student-scraper-v-000
/lib/scraper.rb
UTF-8
1,676
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'open-uri' require 'pry' require 'nokogiri' class Scraper def self.scrape_index_page(index_url) html = File.read(index_url) roster = Nokogiri::HTML(html) students = [] roster.css(".student-card").each do |student_card| students << { :name => student_card.css(".student-name").text, :location => student_card.css(".student-location").text, :profile_url => student_card.css("a").attribute("href").value } end students end def self.scrape_profile_page(profile_url) html = File.read(profile_url) profile_page = Nokogiri::HTML(html) student_profile = {} profile_page.css(".profile").each do |div| div.css(".social-icon-container a").each do |a| # a.at_css("a[href*='rss']") #=> returns nil OR returns matching element if a.attribute("href").value.include?("twitter") student_profile[:twitter] = a.attribute("href").value # end elsif a.attribute("href").value.include?("linkedin") student_profile[:linkedin] = a.attribute("href").value # end elsif a.attribute("href").value.include?("github") student_profile[:github] = a.attribute("href").value # end else # a.at_css("a img[src*='rss-icon']") != nil # binding.pry student_profile[:blog] = a.attribute("href").value end end student_profile[:profile_quote] = div.css(".profile-quote").text student_profile[:bio] = div.css(".bio-content .description-holder p").text end student_profile end end
true
41511afbe2cd594211e3636fd1b54f8b2744307e
Ruby
kenichi/h2
/lib/h2/server/stream/request.rb
UTF-8
2,085
2.859375
3
[ "MIT" ]
permissive
module H2 class Server class Stream class Request # a case-insensitive hash that also handles symbol translation i.e. s/_/-/ # HEADER_HASH = Hash.new do |hash, key| k = key.to_s.upcase k.gsub! '_', '-' if Symbol === key _, value = hash.find {|header_key,v| header_key.upcase == k} hash[key] = value if value end attr_reader :body, :headers, :stream def initialize stream @stream = stream @headers = HEADER_HASH.dup @body = '' end # retreive the IP address of the connection # def addr @addr ||= @stream.connection.socket.peeraddr[3] rescue nil end # retreive the authority from the stream request headers # def authority @authority ||= headers[AUTHORITY_KEY] end # retreive the HTTP method as a lowercase +Symbol+ # def method return @method if defined? @method @method = headers[METHOD_KEY] @method = @method.downcase.to_sym if @method @method end # retreive the path from the stream request headers # def path return @path if defined?(@path) @path = headers[PATH_KEY] @path = @path.split('?').first if @path end # retreive the query string from the stream request headers # def query_string return @query_string if defined?(@query_string) @query_string = headers[PATH_KEY].index '?' return if @query_string.nil? @query_string = headers[PATH_KEY][(@query_string + 1)..-1] end # retreive the scheme from the stream request headers # def scheme @scheme ||= headers[SCHEME_KEY] end # respond to this request on its stream # def respond status:, headers: {}, body: '' @stream.respond status: status, headers: headers, body: body end end end end end
true
5ad1a8ba833d97715ead84f383f0f8d76e2ecf84
Ruby
moacirguedes/ZSSN-api
/app/controllers/concerns/reportable.rb
UTF-8
1,575
2.515625
3
[]
no_license
module Reportable extend ActiveSupport::Concern def infection_status if @survivor.infected render json: { error: 'This survivor is flagged as infected' }, status: :forbiden end end def percentage_infected ((Survivor.total_infected / Survivor.total_survivors) * 100).round(2) end def percentage_non_infected ((Survivor.total_non_infected / Survivor.total_survivors) * 100).round(2) end def items_average total_survivors = Survivor.total_survivors water_average = (Item.total_water / total_survivors).round(2) food_average = (Item.total_food / total_survivors).round(2) medication_average = (Item.total_medication / total_survivors).round(2) ammunition_average = (Item.total_ammunition / total_survivors).round(2) { water_per_survivor: water_average, food_per_survivor: food_average, medication_per_survivor: medication_average, ammunition_per_survivor: ammunition_average } end def check_reporter @reporter = Survivor.find(report_params[:reporter_survivor_id]) if @reporter.infected render json: { error: 'This reporter is infected' }, status: :forbiden end end def check_survivors if @first_survivor.infected || @second_survivor.infected render json: { error: 'Can\'t trade, one or both survivors are infected' }, status: :forbiden elsif @first_survivor == @second_survivor render json: { error: 'Can\'t trade, need to be two differents survivors' }, status: :unprocessable_entity end end end
true
73dc3644a7eadd1071240b3182d5e523cf9a326a
Ruby
CodeZeus-dev/leap-years
/lib/leap_years.rb
UTF-8
171
3.203125
3
[]
no_license
def leap_year?(year) return true if (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) return false if (year % 100 == 0 && year % 400 != 0) || (year % 4 != 0) end
true
22f41d3c54701960786dd5104e1d345b39821b19
Ruby
arslanyousaf77/coeus-ruby-basic-practice
/arrays.rb
UTF-8
659
3.6875
4
[]
no_license
arr = Array.new arr1 = Array.new(10) #specifiying size names = Array.new(3, "coeus") puts "#{names}" nums = Array.new(10) { |e| e = e +1 } puts "#{nums}" nums1 = Array.[](1,2,3,4) puts "#{nums1}" nums2 = Array[10,20,30,"Arslan"] puts "#{nums2}" nums3 = Array(0..10) puts "#{nums3}" puts "#{nums3[2]}" puts "#{nums1 & nums3}" puts "#{nums1-nums3}" puts "#{nums1|nums3}" nums1.delete_at(3) puts "#{nums1}" nums3.delete_if{|e| e%2==0} puts "#{nums3}" puts "#{nums3.empty?}" a = [ "a", "b", "c" ] n = [ 65, 66, 67 ] puts a.pack("A3A3A3") #=> "a b c " puts a.pack("a3a3a3") #=> "a\000\000b\000\000c\000\000" puts n.pack("ccc") #=> "ABC"
true
ebad1da65c8691bd409dd824b11634145ce28200
Ruby
foaf/foaftown
/2008/foafnews/news.bbc-linker.rb
UTF-8
4,329
2.765625
3
[]
no_license
#!/usr/bin/ruby # # This is a quick hack utility to summarise the link structure of # news.bbc.co.uk, and operates over a local crawled copy of the site # (I used curlmirror), by default in the dest/ subdirectory. # # See below for a 'find' script that evokes this program on each file. # Ultimately the ruby script should handle this logic. # # The idea here: links are metadata. BBC News articles have hardcoded # "see also" links to other (*previous*) BBC stories, plus to key Web URLs. # So we can build an index of this linking structure to determine some # implicit similarity data about the articles. This includes their topics, # and should allow us to suggest relevant *future* URLs for older articles. # TODO: # Think about computing a score for topical closeness that takes into account # the fact that only previous pages are allowed to be added at authorship time. # So the presence of page-A as a see-also topic for page-B is more impressive # if lots of other pages existed as 'competition', at the moment B was tagged. # # dc:creator [ :openid <http://danbri.org/>; :mbox <mailto:danbri@danbri.org> ]. # Run it on a subset with: # find dest/1/hi/world/ -name \*.html -exec ruby ./arr.rb {} \; # Notes: # clean these defaults out: # BBC, News, BBC News, news online, world, uk, international, foreign, british, online, service # Todo: crawl everything # get titles # normalise URIs # extract special keywords # generate rdf/a files # language? welsh etc # skosify categories # offsite vs internal crossrefs # other link metadata? # page types? # special case sport? def path2url(file) a=('http://news.bbc.co.uk' + file.gsub(/^(\.\/)*dest/,"") ) a.gsub!(/\/\//,"/") return(a) end def normal(file, rel) # puts "norming: \t\tfile: #{file} url: #{rel}" if (rel =~ /^http:/) return(rel) end file = "#{file}" current=path2url(file) current.gsub!( /([^\/]+)$/,"") a=current+rel a.gsub!(/\/\/$/,"/") return(a) end def dotfix(url) # puts "#Fixing: #{url}" if (! url =~ /\.\./) # puts "# its ok already, returning. " return(url) else # at least one .. new='' found_pair=false url.scan(/(.*)\/(\w+)\/\.\.\/(.*)$/) do # puts "# Found a pair. #{$1} - #{$2} - #{$3}" new = $1 + '/' + $3 found_pair=true end # puts "# Found pair is: #{found_pair}" if (found_pair==true) url = new if (url =~ /\.\./) # puts "# new url has dots, retrying. " return(dotfix(url)) else return(url) end end # puts "# Got dots but no pair. returning." return(url) end post = dedot(url) if (post =~ /\.\./) url = dotfix(post) else return(post) end end # we want a local file path, and the real Web URL def extract(file,myurl) STDERR.puts "# Scanning: #{myurl} via file:#{file}" doc="" dct='http://purl.org/dc/terms/' # rdf = "<dc:Document rdf:about='#{myurl}' xmlns:dc='http://purl.org/dc/terms/' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n" nt = '' File.read(file).each do |x| doc += x end doc.gsub!(/\n/, "") doc.gsub!(/\s+/, " ") if (doc =~ /<title>\s*([^<]*)\s*<\/title>/) # puts "title: #{$1}" t = $1 t.gsub!(/\s*$/,"") nt += "<#{myurl}> <#{dct}title> \"#{t}\" . \n" end doc.scan(/<meta name="([^"]*)" con∫tent="([^"]*)"\s*\/>/) do p=$1 v=$2 p.downcase! puts "#{p}: #{v}" end doc.scan(/<div\s+class="arr">\s*<a\s+href="([^"]*)">\s*([^<]*)\s*<\/a>\s*<\/div>/) do rt = $2 rl = $1 n = normal(file,rl) # puts "# Starting dotfix with #{n}" n = dotfix(n) n.chomp! nt += "<#{myurl}> <#{dct}relation> <#{n}> .\n" rt.chomp! rt.gsub!(/\s*$/,"") nt += "<#{n}> <#{dct}title> \"#{rt}\" .\n" end puts "\n" puts nt end ### main script: file = ARGV.shift if (file != nil) STDERR.puts "# Found argv #{file} - running in single doc mode." url=path2url(file) extract(file, url) else STDERR.puts "# Running in huge list of files mode (sampler)." # todo = `find . -name \*.html -exec ruby ./arr.rb {} \\; ` todo = `find dest/1/hi/world/ -name \*.html -exec ruby ./arr.rb {} \\; ` todo.each do |file| file.chomp! STDERR.puts "# Using: #{file}" url=path2url(file) extract(file, url) end end
true
5802de54f6554e900d62bd5716892be308a01822
Ruby
Salsa-Dude/review-flatiron
/Mod-1/Object-Oriented/mass-assignment.rb
UTF-8
847
3.71875
4
[]
no_license
# Create a Person class that accepts a hash upon initialization. The keys of the hash should conform to the attributes below: # allowable properties: class Person attr_accessor :name, :birthday, :hair_color, :eye_color, :height, :weight, :handed, :complexion, :t_shirt_size, :wrist_size, :glove_size, :pant_length, :pant_width def initialize(attributes=nil) if attributes attributes.each do |key, value| self.send("#{key}=", value) end end end end info = { :name => "Avi", :birthday => "01/29/1984", :hair_color => "brown", :eye_color => "brown", :height => "short", :weight => "good", :handed => "lefty", :complexion => "decent", :t_shirt_size => "medium", :wrist_size => "small", :glove_size => "normal", :pant_length => "32", :pant_width => "32" } lizz = Person.new(info) p lizz
true
fc2b5db75715b29f1851532ef1199b31bd5e3fbe
Ruby
jfhinchcliffe/advent_of_code_2020
/day_1/day_1.rb
UTF-8
803
3.359375
3
[]
no_license
require_relative "../file_loader.rb" lines = FileLoader.new("./day_1/input.txt").lines(->(x) { x.to_i }) # test_lines = [ # 1721, # 979, # 366, # 299, # 675, # 1456, # ] TARGET_NUMBER = 2020 part_one_result = lines.reduce({}) do |acc, num| complement = TARGET_NUMBER - num break num * complement if acc[num] acc[complement] = num acc end puts "Part One Result: #{part_one_result}" # I feel dirty... lines.each_with_index do |outer_val, outer_index| lines.each_with_index do |middle_val, middle_index| lines.each_with_index do |inner_val, inner_index| if outer_val + middle_val + inner_val == TARGET_NUMBER puts "Part Two Result: #{outer_val} * #{middle_val} * #{inner_val} = #{outer_val * middle_val * inner_val}" raise end end end end
true
caf67b5d41681be15ea577acf03a4c28e1b116e7
Ruby
rodrigets/logica-de-programacao
/5 - Funções/funcoes04.rb
UTF-8
315
4.09375
4
[ "MIT" ]
permissive
#Escreva uma função chamada fat que retorna o fatorial de um número. A função #deve verificar se o parâmetro passado é inteiro e maior do que zero, caso contrário #deve retornar -1. def fat(x) if x >= 0 fatorial = 1 for i in 1..x do fatorial *= i end return fatorial else return -1 end end
true
f12ac90176f5fc0631b6643cef20aed9eb94fb84
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/src/3143.rb
UTF-8
192
3.484375
3
[]
no_license
def compute(a, b) hamming = 0 if (a == b) then return hamming # Optimisation end a.each_char.zip(b.each_char) do |l, r| (l.nil? || r.nil?) || (l == r) || hamming += 1 end hamming end
true
072973b2095f43e4a90523d0b8990614180f7cc1
Ruby
olci34/MoDay
/lib/api.rb
UTF-8
1,151
2.859375
3
[ "MIT" ]
permissive
class Api @@api_key = "8f1dd76b" def self.get_movie_by_id(id) movie = Movie.find_by_imdbID(id) if !movie #Avoids requesting API on already existed movies. url = "https://www.omdbapi.com/?i=#{id}&apikey=#{@@api_key}" response = HTTParty.get(url) if response["Error"] # API ERROR HANDLING abort("Something went wrong: #{response["Error"]}") else genre_array = response["Genre"].split(", ").collect {|genre_name| Genre.find_by_name(genre_name)} stars = response["Actors"].split(", ").collect {|star_name| Star.find_or_create_by_name(star_name)} director = response["Director"].split(", ").collect {|star_name| Director.find_or_create_by_name(star_name)} movie_hash = {title: response["Title"], year: response["Year"], runtime: response["Runtime"], genre_array: genre_array, director: director, stars: stars, plot: response["Plot"], imdbRating: response["imdbRating"], imdbID: response["imdbID"]} new_movie = Movie.new(movie_hash) end else movie end end end
true
91d96849903eb6a83b3c3c06b3addc03e351f9dc
Ruby
cmb84scd/oo_relationships1
/polymorphism.rb
UTF-8
914
3.453125
3
[]
no_license
class ScrambledDiary def initialize(contents) @contents = contents end def read @contents end def scramble(scrambler) @contents = scrambler.scramble(@contents) end end class ScrambleAdvanceChars def initialize(steps) @steps = steps end def scramble(contents) plain_chars = contents.chars scrambled_chars = plain_chars.map do |char| (char.ord + @steps).chr end contents = scrambled_chars.join end end class UnscrambleAdvanceChars def initialize(steps) @steps = steps end def scramble(contents) scrambled_chars = contents.chars plain_chars = scrambled_chars.map do |char| (char.ord - @steps).chr end contents = plain_chars.join end end class ScrambleReverse def scramble(contents) contents = contents.reverse end end class UnscrambleReverse def scramble(contents) contents = contents.reverse end end
true
8899c5c2e44662b88bfeb4982d7d87c137697282
Ruby
blacktm/tello
/bin/telloedu
UTF-8
751
2.515625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'tello/colorize' require 'tello/version' # Check Command-line Arguments ################################################# $edu = 'EDU' usage = "Fly the Tello#{$edu} drone with Ruby!".bold + "\n Usage: tello#{$edu.to_s.downcase} <command> <options> [-v|--version] Summary of commands and options: console Open an interactive Tello console --test Start the console in test mode server Start the test server -v|--version Prints the installed version\n\n" if ARGV.delete '--test' then $tello_testing = true end case ARGV[0] when 'console' require 'tello/cli/console' when 'server' require 'tello/cli/server' when '-v', '--version' puts Tello::VERSION else puts usage end
true
17adb4511d60042e1b2b491b27e9b695b72f7d3a
Ruby
olook/chaordic-packr
/lib/chaordic-packr/buy_order.rb
UTF-8
1,181
2.875
3
[]
no_license
require "chaordic-packr/packable_with_info" require "chaordic-packr/cart" module Chaordic module Packr class BuyOrder < PackableWithInfo # @param [Cart] cart Shopping cart. # @return [BuyOrder] def initialize(cart) @cart = cart if cart.instance_of? Cart @tags = [] super() end # @param [String] id Order identification. # @return [String] Set order identification. def oid=(id) @oid = id end # @return [String] Order identification. def oid @oid end # @param [Array<String>] ts Product tags. # @return [Array<String>] Set product tags, overwriting the existing Array of strings. def tags=(ts) @tags = ts.map{|t| t.to_s } if t.kind_of? Array end # @return [Array<String>] Product tags. def tags; @tags; end # @return [Hash] Information hash, using package's prefix. If there's a user, also include user's information hash. def to_hash h = super h.merge! @cart.to_hash h['oid'] = @oid h['buyOrderTags'] = Oj.dump(@tags.uniq) if @tags.any? h end end end end
true
c44f3fcbbf3a59ee0fe05fd19bb5c1ab8e821c1c
Ruby
jaredianmills/sql-crowdfunding-lab-nyc-web-062518
/lib/sql_queries.rb
UTF-8
1,628
3.125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your sql queries in this file in the appropriate method like the example below: # # def select_category_from_projects # "SELECT category FROM projects;" # end # Make sure each ruby method returns a string containing a valid SQL statement. def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name "SELECT title, SUM(amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY title ORDER BY title ASC" end def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name "SELECT name, age, SUM(amount) FROM users JOIN pledges ON users.id = pledges.user_id GROUP BY name ORDER BY name ASC" end def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal "SELECT title, SUM(amount) - projects.funding_goal FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY title HAVING SUM(amount) >= projects.funding_goal" end def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_amount_and_users_name "SELECT name, SUM(amount) FROM users JOIN pledges ON users.id = pledges.user_id GROUP BY name ORDER BY SUM(amount)" end def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category "SELECT category, amount FROM projects JOIN pledges ON projects.id = pledges.project_id WHERE projects.category = 'music'" end def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category "SELECT category, SUM(amount) FROM projects JOIN pledges on projects.id = pledges.project_id WHERE projects.category = 'books'" end
true
11e44b257ebd42c73f2f88d90b749bc6b8f5cdbd
Ruby
Junaidshah/ruby_programming
/objects_variables_classes.rb
UTF-8
630
3.6875
4
[]
no_license
#!/usr/bin/ruby -w class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id =id @cust_name =name @cust_addr =addr end def display_details() puts "Customer Id :#@cust_id" puts "Customer Name:#@cust_name" puts "Customer addr:#@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "The total number of customers are :#@@no_of_customers" end end cust1=Customer.new("1","Junaid","Bangalore") cust2=Customer.new("2","Barrow","San fransisco") cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers()
true
59142cc098ac20a16fbb219363a3bb30b9e761a5
Ruby
code-builders/curriculum
/playground/chair.rb
UTF-8
424
2.734375
3
[]
no_license
class Chair attr_accessor :name, :weight, :color, :height, :rolls, :created_at def initialize(attrs={}) # attrs is a hash # {height: 30, name: "Vilgot", rolls: true} @name = attrs[:name] @weight = attrs[:weight] @color = attrs[:color] @height = attrs[:height] @rolls = attrs[:rolls] @created_at = attrs[:created_at] # @name = n # @weight = w end end
true
111cf6b054d7d57a76a964a907d52b4831831b1b
Ruby
KoreanFoodComics/glimmer
/lib/command_handlers/models/widget_observer.rb
UTF-8
664
2.84375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class WidgetObserver attr_reader :widget, :property @@property_type_converters = { :text => Proc.new { |value| value.to_s }, :items => Proc.new { |value| value.to_java :string} } def initialize model, property @widget = model @property = property end def update(value) converted_value = value converter = @@property_type_converters[@property.to_sym] converted_value = converter.call(value) if converter @widget.widget.send("set#{@property.camelcase(:upper)}", converted_value) unless evaluate_property == converted_value end def evaluate_property @widget.widget.send(@property) end end
true
03a8b88c6aeb54cc3ec577157a6aa3dd3b46de29
Ruby
chrisotto/phase-0-tracks
/ruby/santa.rb
UTF-8
1,602
3.625
4
[]
no_license
class Santa attr_reader :age, :ethnicity attr_accessor :gender def initialize(gender, ethnicity) puts "Initializing Santa instance ..." @gender = gender puts "Gender: #{@gender}" @ethnicity = ethnicity puts "Ethnicity: #{@ethnicity}" @reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"] puts "Reindeer Ranking: #{@reindeer_ranking.join(', ')}" @age = 0 puts "Age: #{@age}" end def speak puts "Ho, ho, ho! Haaaappy holidays!" end def eat_milk_and_cookies(cookie_type) puts "That was a good #{cookie_type}!" end def celebrate_birthday @age += 1 puts "I turned #{@age} years old today!" end def get_mad_at(reindeer) @reindeer_ranking << @reindeer_ranking.delete(reindeer) puts "#{@reindeer_ranking.last}, you just got on my naughty list." puts "Reindeer Ranking: #{@reindeer_ranking.join(', ')}" end end # santa = Santa.new("agender", "black") # puts "Santa is #{santa.ethnicity}." # santa.speak # santa.eat_milk_and_cookies("snickerdoodle") # santa.celebrate_birthday # puts "Santa is #{santa.age} years old." # santa.get_mad_at("Vixen") # santa.gender = 'bigender' # puts "I now identify as #{santa.gender}." genders = ["agender", "bigender", "female", "gender fluid", "male", "N/A"] ethnicities = ["black", "Japanese-African", "Latino", "Mystical Creature (unicorn)", "prefer not to say", "white", "N/A"] santas = [] 100.times do santas << Santa.new(genders.sample,ethnicities.sample) rand(140).times {santas.last.celebrate_birthday} end
true
0f7af4e8ff392c25df20d84898f1dac183bc230a
Ruby
Alohata/Alohata.github.io
/ruby/hash_to_yaml.rb
UTF-8
3,981
2.75
3
[]
no_license
# encoding: utf-8 require 'yaml' languages = { :bg => { name: '', image_title: 'Щастливи моменти', title_1:'Безценни дни. Те всичките ухаят на море', subtitle_1: 'Прозрачна вода. Лъскави вълни', subtitle_2: 'Северния бряг на Оаху, Хавай', block_1: '<p>Прозрачна вода, лъскави вълни, тръбни или бавни езди, риф или пясъчни дъна. Можете да сърфирате на всички видове вълни в Хавай, толкова дълго, колкото успеете да се задържите на борда. Щатът Хавай (САЩ) има осем основни острова: <b>Хавай, Мауи, Оаху, Кахоолаве, Ланай, Молокай, Кауаи</b> и <b>Niihau.</b> </p> <p>Най-популярните хавайски сърф места са разположени в The Big Island (Хавай), The Valley остров (Maui), The Garden остров (Kauai) и на мястото Gathering (Oahu). </p> <p>Начинаещи и напреднали могат да сърфират през почти всички 365 дни на годината. </p>', block_2: '<p>Хавай е безспорно дома на сърфа, домакин на множество състезания от световна класа всяка година. Плажовете постоянно са посещавани от фанатизирани местни или всеотдайни сърфисти, които предприемат дълго пътуване до Хавай в желанието си да яхнат най-известните вълни в света. </p> <p>Древните хавайски хора не смятат сърфирането просто за занимание, хоби или екстремен спорт. По-скоро Хавайските хора са интегрирали сърфирането в тяхната култура и сърфирането е повече изкуство, отколкото нещо друго. Те наричат това изкуство <em>heʻe nalu</em> - плъзгане по вълна. </p>', more: 'Продължава →', }, :en => { name:'Aloha Desi', image_title: 'Happy moments', title_1:'The precious days. They all smell like a sea.', subtitle_1: 'Transparent water. Glassy waves', subtitle_2: 'North shore of Oahu, Hawaii', block_1: '<p>Transparent water, glassy waves, tubular or slower rides, reef or sandy bottoms. You can surf all types of waves in Hawaii, as long as you"ve got a board. The US State of Hawaii has eight main islands: <b>Hawaii, Maui, Oahu, Kahoolawe, Lanai, Molokai, Kauai</b> and <b>Niihau</b>. </p> <p>The most popular Hawaiian surf spots are located in <em>The Big Island (Hawaii), The Valley Isle (Maui), The Garden Isle (Kauai) and in The Gathering Place (Oahu).</em> </p> <p>Beginners and advanced might get surf in almost all 365 days of the year. </p>', block_2: '<p> Hawaii is undisputedly the home of surfing, hosting numerous world class competitions every year. The beaches are frequented by fanatic locals and dedicated surfers who make the pilgrimage to Hawaii wanting to surf the world"s most famous waves. </p> <p>The Ancient Hawaiian people did not consider surfing a mere recreational activity, hobby, extreme sport. Rather, the Hawaiian people integrated surfing into their culture and made surfing more of an art than anything else. They referred to this art as <em>heʻe nalu</em> - “wave sliding.” </p>', more: 'Continue reading →', }, } File.write("..\\libraries\\translations_test.yml", languages.to_yaml)
true
6727db76e391c2f114e434202a7520e17ebd2dd5
Ruby
translunar/boolean
/lib/boolean/plot.rb
UTF-8
2,943
3.046875
3
[]
no_license
require 'pry' require 'rubyvis' class Float def exponent return nil if self == Float::INFINITY || self == -Float::INFINITY return 0 if self == 0 Math.log10(self).floor end end module Boolean module Plot class << self # Bin by order of magnitude. # Pairs should consist of a p-value and a number of items with that p-value. # # Returns fractions def rebin_by_exponent n, pairs bins = Array.new(n+1, 0) # 0.1-1, 0.01-0.1, 0.001-0.01 denom = 0 pairs.each do |pair| denom += pair[1] ((-n-1)..0).each do |i| if pair[0] <= 10**i bins[n+i-1] += pair[1] break elsif i == 0 && pair[0] >= 1 STDERR.puts "Warning: item fell out of bin range (>1): #{pair[0]}" end end end bins.map { |bin| bin / denom.to_f } end def fig_2b(real, ran) min_exp = [real.keys.min.exponent, ran.keys.min.exponent].min real_bins = rebin_by_exponent(min_exp.abs, real) ran_bins = rebin_by_exponent(min_exp.abs, ran) log_min = 10**([(real_bins - [0.0]).min, (ran_bins - [0.0]).min].min.exponent-1) w = 500 h = 400 x = pv.Scale.linear(0, real_bins.size).range(0, w) y = pv.Scale.log(log_min, 1.0).range(0, h) vis = Rubyvis::Panel.new do width w height h bottom 80 left 60 right 20 top 5 rule do line_width 2 data y.ticks bottom y visible(lambda { |d| d.to_s =~ /^1/ } ) end.anchor('left').add(pv.Label).visible(lambda { |d| d<1 && d.to_s =~ /^1/ }). text(y.tick_format) rule do line_width 2 data( (0..(real_bins.size)).to_a) left x stroke_style(lambda { |d| d != 0 ? "#eee" : "#000" }) visible(lambda { |d| d.to_i == d && d.to_i % 5 == 1 }) end.anchor('bottom').add(pv.Label).visible(lambda { |d| d.to_i == d && d.to_i % 5 == 1 }). text(lambda { |d| d == 1 ? "[1,0.1)" : "[10^-#{d-1},10^-#{d})" }).text_angle(-Math::PI/2).text_align('right') line do data real_bins.reverse line_width 3 left(lambda { x.scale(self.index) }) bottom(lambda { |d| d == 0 ? 0 : y.scale(d) }) stroke_style 'blue' end line do data ran_bins.reverse line_width 3 left(lambda { x.scale(self.index) }) bottom(lambda { |d| d == 0 ? 0 : y.scale(d) }) stroke_style 'red' stroke_dasharray(3) #if self.respond_to?(:stroke_dasharray) end end vis.render File.open("2b.svg", "w") do |f| f.write(vis.to_svg) end [real_bins, ran_bins] end end end end
true
51a1ed9312eabd9bb819fa996dfc928a623a3eb6
Ruby
skipsuva/advanced-hashes-hashketball-001-prework-web
/hashketball.rb
UTF-8
8,880
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def game_hash { :home => { :team_name => "Brooklyn Nets", :colors => ["Black","White"], :players => [ {:player_name => "Alan Anderson", :number => 0, :shoe => 16, :points => 22, :rebounds => 12, :assists => 12, :steals => 3, :blocks => 1, :slam_dunks => 1 }, {:player_name => "Reggie Evans", :number => 30, :shoe => 14, :points => 12, :rebounds => 12, :assists => 12, :steals => 12, :blocks => 12, :slam_dunks => 7}, {:player_name => "Brook Lopez", :number => 11, :shoe => 17, :points => 17, :rebounds => 19, :assists => 10, :steals => 3, :blocks => 1, :slam_dunks => 15}, {:player_name => "Mason Plumlee", :number => 1, :shoe => 19, :points => 26, :rebounds => 12, :assists => 6, :steals => 3, :blocks => 8, :slam_dunks => 5}, {:player_name => "Jason Terry", :number => 31, :shoe => 15, :points => 19, :rebounds => 2, :assists => 2, :steals => 4, :blocks => 11, :slam_dunks => 1}] }, :away => { :team_name => "Charlotte Hornets", :colors => ["Turquoise","Purple"], :players => [ {:player_name => "Jeff Adrien", :number => 4, :shoe => 18, :points => 10, :rebounds => 1, :assists => 1, :steals => 2, :blocks => 7, :slam_dunks => 2}, {:player_name => "Bismak Biyombo", :number => 0, :shoe => 16, :points => 12, :rebounds => 4, :assists => 7, :steals => 7, :blocks => 15, :slam_dunks => 10}, {:player_name => "DeSagna Diop", :number => 2, :shoe => 14, :points => 24, :rebounds => 12, :assists => 12, :steals => 4, :blocks => 5, :slam_dunks => 5}, {:player_name => "Ben Gordon", :number => 8, :shoe => 15, :points => 33, :rebounds => 3, :assists => 2, :steals => 1, :blocks => 1, :slam_dunks => 0 }, {:player_name => "Brendan Haywood", :number => 33, :shoe => 15, :points => 6, :rebounds => 12, :assists => 12, :steals => 22, :blocks => 5, :slam_dunks => 12}] } } end def num_points_scored(player) # points_scored = nil # # game_hash.collect do |team, team_data| # team_data.collect do |attributes, data| # if attributes == :players # data.each do |player_hash| # if player_hash[:player_name] == player # points_scored = player_hash[:points] # end # end # end # end # end # points_scored result = nil all_players.find do |player_data| if player_data[:player_name] == player result = player_data[:points] end end result end #new method def all_players home_players = game_hash[:home][:players] away_players = game_hash[:away][:players] home_players.concat(away_players) end def shoe_size(player) shoe_man = nil game_hash.collect do |team, team_data| team_data.collect do |attributes, data| if attributes == :players data.each do |player_hash| if player_hash[:player_name] == player shoe_man = player_hash[:shoe] end end end end end shoe_man end def team_colors(team_name) #colors = [] # games_hash.collect do |team, team_data| # team_data.collect do |attributes, data| # if attributes == :colors # data.each do |team_color| # if games_hash[team][:team_name] == team_name # colors << team_color # end # end # end # end # end # colors result = game_hash.find do |location, team_data| team_data[:team_name] == team_name end _location, data = result data[:colors] end def team_names # team_name_array = [] # # game_hash.collect do |team, team_data| # team_data.collect do |attributes, data| # if attributes == :team_name # team_name_array << data # end # end # end # team_name_array all_teams.map do |team| team[:team_name] end end #new method def all_teams # home_team = game_hash[:home] # away_team = game_hash[:away] # [home_team, away_team] game_hash.values end def player_numbers(team_name) # team_jerseys = [] # # game_hash.each do |team, team_data| # team_data.each do |attributes, data| # if attributes == :players # data.each do |player_hash| # player_hash.each do |att, val| # if games_hash[team][:team_name] == team_name # team_jerseys << player_hash[:number] # end # end # end # end # end # end # team_jerseys = team_jerseys.uniq team = find_team_by_name(team_name) team[:players].map do |stats| stats[:number] end end #new method def find_team_by_name(team_name) all_teams.find do |team| team.has_value?(team_name) end end def player_stats(player) stats = {} game_hash.collect do |team, team_data| team_data.collect do |attributes, data| if attributes == :players data.collect do |player_hash| if player_hash[:player_name] == player stats = player_hash end end end end end stats.delete_if do |x, y| x == :player_name end stats end def big_shoe_rebounds # big_shoe_size = 0 # big_shoe_name = "" # rebound = nil # # game_hash.collect do |team, team_data| # team_data.collect do |attributes, data| # if attributes == :players # data.each do |player_hash| # player_hash.each do |att, val| # if att == :shoe # if player_hash[:shoe] > big_shoe_size # big_shoe_size = player_hash[:shoe] # big_shoe_name = player_hash[:player_name] # end # end # end # end # end # end # end # game_hash.collect do |team, team_data| # team_data.collect do |attributes, data| # if attributes == :players # data.each do |player_hash| # if player_hash[:player_name] == big_shoe_name # rebound = player_hash[:rebounds] # end # end # end # end # end # rebound sorted = all_players.sort_by do |stats| stats[:shoe] end _name, stats = sorted.first _name[:rebounds] end
true
e6a6ab712e75a9270009987d8abe5a42a8c096bb
Ruby
benhutchinson/FAAST-Tube
/lib/train.rb
UTF-8
925
3.171875
3
[]
no_license
class Train MINIMUM_COACHES = 1 attr_reader :capacity, :passengers_in_train def initialize(define_coaches = {}) @coach_count = define_coaches.fetch(:coaches, MINIMUM_COACHES) @capacity = @coach_count * 40 @passengers_in_train = [] @at_a_station = false end def full? @passengers_in_train.count == @capacity end def arrives_at_station(station) raise TrainStillAtAnotherStation if @at_a_station == true raise StationIsFullOfTrains if station.full_of_trains? station.train_arrives_at_station(self) @at_a_station = true end def departs_from_station(station) raise TrainNotHere if @at_a_station == false station.train_departs_from_station(self) @at_a_station = false end def passenger_alights_train(passenger) @passengers_in_train.delete(passenger) end def passenger_boards_train(passenger) @passengers_in_train.push(passenger) end end
true
b42de41db4deac230fbe268d359eb8c9c70de9ea
Ruby
VAGAScom/protoboard
/lib/protoboard/circuit_proxy_factory.rb
UTF-8
1,836
2.75
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Protoboard ## # This module is responsible to manage a proxy module that executes the circuit. module CircuitProxyFactory class << self using Protoboard::Refinements::StringExtensions ## # Creates the module that executes the circuit def create_module(circuits, class_name) module_name = infer_module_name(class_name, circuits.map(&:method_name)) proxy_module = Module.new # Encapsulates instance methods in a module to be used later instance_methods = Module.new do circuits.each do |circuit| unless circuit.singleton_method? define_method(circuit.method_name) do |*args| Protoboard.config.adapter.run_circuit(circuit) { super(*args) } end end end end proxy_module.const_set('InstanceMethods', instance_methods) # Encapsulates singleton methods in a module to be used later class_methods = Module.new do circuits.each do |circuit| if circuit.singleton_method? define_method(circuit.method_name) do |*args| Protoboard.config.adapter.run_circuit(circuit) { super(*args) } end end end end proxy_module.const_set('ClassMethods', class_methods) Protoboard.const_set(module_name, proxy_module) end private ## # Formats the module name def infer_module_name(class_name, methods) methods = methods.map(&:to_s).map do |method| method.convert_special_chars_to_ordinals end methods_joined = methods.map { |method| method.camelize }.join "#{methods_joined}#{class_name.split('::').join('')}CircuitProxy" end end end end
true
d351c428fafd506b157b98f11883b1e0a5ee07cb
Ruby
luther07/aws-sdk-for-ruby
/lib/aws/record/attribute_macros.rb
UTF-8
10,029
3
3
[ "Apache-2.0" ]
permissive
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. require 'aws/record/attributes/string' require 'aws/record/attributes/integer' require 'aws/record/attributes/sortable_integer' require 'aws/record/attributes/float' require 'aws/record/attributes/sortable_float' require 'aws/record/attributes/boolean' require 'aws/record/attributes/datetime' require 'aws/record/attributes/date' module AWS module Record module AttributeMacros # Adds a string attribute to this class. # # @example A standard string attribute # # class Recipe < AWS::Record::Base # string_attr :name # end # # recipe = Recipe.new(:name => "Buttermilk Pancakes") # recipe.name #=> 'Buttermilk Pancakes' # # @example A string attribute with +:set+ set to true # # class Recipe < AWS::Record::Base # string_attr :tags, :set => true # end # # recipe = Recipe.new(:tags => %w(popular dessert)) # recipe.tags #=> #<Set: {"popular", "desert"}> # # @param [Symbol] name The name of the attribute. # @param [Hash] options # @option options [Boolean] :set (false) When true this attribute # can have multiple values. def string_attr name, options = {} add_attribute(StringAttribute.new(name, options)) end # Adds an integer attribute to this class. # # class Recipe < AWS::Record::Base # integer_attr :servings # end # # recipe = Recipe.new(:servings => '10') # recipe.servings #=> 10 # # @param [Symbol] name The name of the attribute. # @param [Hash] options # @option options [Boolean] :set (false) When true this attribute # can have multiple values. def integer_attr name, options = {} add_attribute(IntegerAttribute.new(name, options)) end # Adds a sortable integer attribute to this class. # # class Person < AWS::Record::Base # sortable_integer_attr :age, :range => 0..150 # end # # person = Person.new(:age => 10) # person.age #=> 10 # # === Validations # # It is recomended to apply a validates_numericality_of with # minimum and maximum value constraints. If a value is assigned # to a sortable integer that falls outside of the +:range: it will # raise a runtime error when the record is saved. # # === Difference Between Sortable an Regular Integer Attributes # # Because SimpleDB does not support numeric types, all values must # be converted to strings. This complicates sorting by numeric values. # To accomplish sorting numeric attributes the values must be # zero padded and have an offset applied to eliminate negative values. # # @param [Symbol] name The name of the attribute. # @param [Hash] options # @option options [Range] :range A numeric range the represents the # minimum and maximum values this attribute should accept. # @option options [Boolean] :set (false) When true this attribute # can have multiple values. def sortable_integer_attr name, options = {} add_attribute(SortableIntegerAttribute.new(name, options)) end # Adds a float attribute to this class. # # class Listing < AWS::Record::Base # float_attr :score # end # # listing = Listing.new(:score => '123.456') # listing.score # => 123.456 # # @param [Symbol] name The name of the attribute. # @param [Hash] options # @option options [Boolean] :set (false) When true this attribute # can have multiple values. def float_attr name, options = {} add_attribute(FloatAttribute.new(name, options)) end # Adds sortable float attribute to this class. # # Persisted values are stored (and sorted) as strings. This makes it # more difficult to sort numbers because they don't sort # lexicographically unless they have been offset to be positive and # then zero padded. # # === Postive Floats # # To store floats in a sort-friendly manor: # # sortable_float_attr :score, :range => (0..10) # # This will cause values like 5.5 to persist as a string like '05.5' so # that they can be sorted lexicographically. # # === Negative Floats # # If you need to store negative sortable floats, increase your +:range+ # to include a negative value. # # sortable_float_attr :position, :range => (-10..10) # # AWS::Record will add 10 to all values and zero pad them # (e.g. -10.0 will be represented as '00.0' and 10 will be represented as # '20.0'). This will allow the values to be compared lexicographically. # # @note If you change the +:range+ after some values have been persisted # you must also manually migrate all of the old values to have the # correct padding & offset or they will be interpreted differently. # # @param [Symbol] name The name of the attribute. # @param [Hash] options # @option options [Range] :range The range of numbers this attribute # should represent. The min and max values of this range will determine # how many digits of precision are required and how much of an offset # is required to make the numbers sort lexicographically. # @option options [Boolean] :set (false) When true this attribute # can have multiple values. def sortable_float_attr name, options = {} add_attribute(SortableFloatAttribute.new(name, options)) end # Adds a boolean attribute to this class. # # @example # # class Book < AWS::Record::Base # boolean_attr :read # end # # b = Book.new # b.read? # => false # b.read = true # b.read? # => true # # listing = Listing.new(:score => '123.456' # listing.score # => 123.456 # # @param [Symbol] name The name of the attribute. def boolean_attr name, options = {} attr = add_attribute(BooleanAttribute.new(name, options)) # add the boolean question mark method define_method("#{attr.name}?") do !!__send__(attr.name) end end # Adds a datetime attribute to this class. # # @example A standard datetime attribute # # class Recipe < AWS::Record::Base # datetime_attr :invented # end # # recipe = Recipe.new(:invented => Time.now) # recipe.invented #=> <DateTime ...> # # If you add a datetime_attr for +:created_at+ and/or +:updated_at+ those # will be automanaged. # # @param [Symbol] name The name of the attribute. # # @param [Hash] options # # @option options [Boolean] :set (false) When true this attribute # can have multiple date times. # def datetime_attr name, options = {} add_attribute(DateTimeAttribute.new(name, options)) end # Adds a date attribute to this class. # # @example A standard date attribute # # class Person < AWS::Record::Base # date_attr :birthdate # end # # baby = Person.new # baby.birthdate = Time.now # baby.birthdate #=> <Date: ....> # # @param [Symbol] name The name of the attribute. # # @param [Hash] options # # @option options [Boolean] :set (false) When true this attribute # can have multiple dates. # def date_attr name, options = {} add_attribute(DateAttribute.new(name, options)) end # A convenience method for adding the standard two datetime attributes # +:created_at+ and +:updated_at+. # # @example # # class Recipe < AWS::Record::Base # timestamps # end # # recipe = Recipe.new # recipe.save # recipe.created_at #=> <DateTime ...> # recipe.updated_at #=> <DateTime ...> # def timestamps c = datetime_attr :created_at u = datetime_attr :updated_at [c, u] end # @private private def add_attribute attribute attr_name = attribute.name attributes[attr_name] = attribute # setter define_method("#{attr_name}=") do |value| self[attr_name] = value end # getter define_method(attr_name) do self[attr_name] end # before type-cast getter define_method("#{attr_name}_before_type_cast") do @_data[attr_name] end ## dirty tracking methods define_method("#{attr_name}_changed?") do attribute_changed?(attr_name) end define_method("#{attr_name}_change") do attribute_change(attr_name) end define_method("#{attr_name}_was") do attribute_was(attr_name) end define_method("#{attr_name}_will_change!") do attribute_will_change!(attr_name) end define_method("reset_#{attr_name}!") do reset_attribute!(attr_name) end attribute end end end end
true
8863f2964658dd0f6ce779af465c51e9ec95b115
Ruby
dsulfaro/Algorithms-Projects
/heaps_and_heapsort/lib/heap_sort.rb
UTF-8
290
3.34375
3
[]
no_license
require_relative "heap" class Array def heap_sort! heap = BinaryMinHeap.new # heapify array while self.length > 0 heap.push(self.shift) end sorted = [] # pop off heap elements into array while heap.count > 0 self << heap.extract end end end
true
36c68c0939d442927fa4715959bc519ea4100f8e
Ruby
zfbtianya/code
/ruby/decate.rb
UTF-8
263
3.203125
3
[]
no_license
#!/usr/bin/ruby require "./Week.rb" class Decade include Week no_of_yrs = 10 def no_of_months puts Week::FIRST_DAY number = 10*12 puts number end end d1 = Decade.new puts Week::FIRST_DAY Week.weeks_in_month Week.weeks_in_year d1.no_of_months
true
787ad4ef0c2f91c0a024a456a92c30df91266c6e
Ruby
yR-DEV/MOD-1-PROJ-SW
/bin/run.rb
UTF-8
1,716
3.515625
4
[ "Unlicense" ]
permissive
require_relative '../config/environment' require 'pry' require 'colored' #binding.pry class CLI def self.return_or_quit puts "\nType 'return' to return to the main menu. Type 'quit' to exit.\n\n".green.bold response = gets.chomp if response == "return" self.main_menu elsif response == "quit" puts "Goodbye!".green.bold self.quit else self.return_or_quit end end def self.quit exit end def self.main_menu puts "\nEnter 'artists' to see upcoming shows they are in,\nEnter 'venues' to see venues with upcoming shows,\nEnter 'hottest show' to see the most popular artist and show location/information:".bold.green puts "Enter 'quit' to exit application.\n".bold.green @@response = gets.chomp if @@response == "artists" Artist.get_all_artists puts "\nEnter specific artist(s) to see the show information:\n".bold.green artist_prompt = gets.chomp Artist.get_one_artist(artist_prompt) self.return_or_quit elsif @@response == "venues" Venue.get_all_venues puts "\nEnter venue to view specific show and artist:\n".bold.green venue_prompt = gets.chomp Venue.get_one_venue(venue_prompt) self.return_or_quit elsif @@response == "hottest show" most_popular = Artist.all.map do |artist| artist["popularity"] end most_popular = most_popular.sort!.reverse.first Artist.get_most_popular_artist(most_popular) self.return_or_quit elsif @@response == "quit" self.quit else puts "\nInput not recognized. Please try typing 'artists', 'venues', or 'shows'\n".red.bold self.main_menu end end self.main_menu end
true
6cb9d9eedc77b46cfc40037b4930dc94487ca978
Ruby
Becojo/adventofcode
/2022/6.rb
UTF-8
193
3.203125
3
[]
no_license
input = ARGF.read.strip def find(input, n) input.size.times do |i| if input[i...i+n].chars.uniq.size == n return i + n end end end puts find(input, 4) puts find(input, 14)
true
d7123ce921258361feefe89dea3d444d4d4d6d80
Ruby
shinwang1/phase-0
/week-5/calculate-mode/my_solution.rb
UTF-8
3,093
3.734375
4
[ "MIT" ]
permissive
# Calculate the mode Pairing Challenge # I worked on this challenge [by with: Scoot Southard] # I spent [1.5] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. ########## 0. Pseudocode # What is the input? An array of number or integers # What is the output? Return an array that occurs most frequent. # Evalueceptions: return everything if they all occur at the same frequency. # What are the steps needed to solve the problem? # 1. Make a method called mode and takes an array # 2. Tally up the numbers that repeat in the array and set it to a place holder # 3. Iterate over the array again to find which occurance equal the place holder, then # 4. Append this number to a new array. # 5. Print out the unique numbers in each array. ########### 1. Initial Solution # def mode (array) # high = 0 # array.each do |x| # if array.count(x) > high # high = array.count(x) # end # end # new_array = [] # array.each do |x| # if array.count(x) == high # new_array << x # end # end # return new_array.uniq # end # 3. Refactored Solution def mode (array) number_count = 0 array.each do |value| if array.count(value) > number_count number_count = array.count(value) end end new_array = [] array.each do |value| if array.count(value) == number_count new_array << value end end return new_array.uniq end # 4. Reflection #Which data structure did you and your pair decide to implement and why? # We first started off with trying to use a hash; however, we could not figure out a way # to count the repeating values and still have the keys attached to it. After about an hour # of both of us researching, we decided to move to arrays. With arrays, we were able to count # the repeated values with non-destructive methods. Once we tallied up those repeated values, # we created used the unique method to get rid of repeated numbers in the array. #Were you more successful breaking this problem down into implementable pseudocode than the last with a pair? # I'm not sure what this question is asking. If we're comparing to 5.2, then I think it was just as challenging. # I think pseudocode works to a certain point. If we're unable to find the method or algorithm to achieve # what we want from a data structure, then we're going to have to go a different way. #What issues/successes did you run into when translating your pseudocode to code? # We first formed a hash with a method .group_by. This method makes key/value pairs of values that # are alike. However, once we had the hash, we could not extract a count to see which values repeated # the most. #What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? # Were they difficult to implement? # We used the .each method to iterate and the .count method to tally matching values. We did not find # others during the refactor because .count was specific to the function that we needed.
true
4a5858f72b186e6e2b37d0000fa5bec426c9375a
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/bf779a88fd014ea697d84450aa72e7f3.rb
UTF-8
1,636
4.21875
4
[]
no_license
# Pseudocode # Need to make a program that can calculate the difference between two DNA strand # Only going to worry about sequences of equal length # If a user inputs 2 strings of letters - a sequence # Return an integer that is the amount of differences between the two strings # New algorithm idea: Compare at each index up to a certain distance. # Checks up to the index of the shortest strand assuming they aren't equal length. # For loop or each? class Hamming def self.compute(string1, string2) strand_one = string1.split("") strand_two = string2.split("") @hamming_distance = 0 if strand_one.length == strand_two.length measure_length(strand_one, strand_two) iterate_through_strands(strand_one, strand_two) @hamming_distance elsif strand_two.length > strand_one.length measure_length(strand_one, strand_two) iterate_through_strands(strand_one, strand_two) @hamming_distance elsif strand_one.length > strand_two.length measure_length(strand_one, strand_two) iterate_through_strands(strand_one, strand_two) @hamming_distance end end def self.iterate_through_strands(strand_one, strand_two) for i in 0..measure_length(strand_one, strand_two) if strand_one[i] != strand_two[i] @hamming_distance += 1 end end end def self.measure_length(strand_one, strand_two) if strand_one.length > strand_two.length strand_two.length - 1 elsif strand_two.length > strand_one.length strand_one.length - 1 elsif strand_one.length == strand_two.length strand_one.length - 1 end end end
true
6620e07fe50c21752cc4e2f91c318065af3e562b
Ruby
Lantoniaina/mercredi
/pyramide.rb
UTF-8
209
3.375
3
[]
no_license
def num puts "Combien d'étages voulez-vous pour votre pyramide,qui varie de 5 à 25: " num =gets.chomp.to_i diez = 1 while num > 0 puts " "*num << "#" *diez num -= 1 diez += 2 end end puts num
true
91d61cf28fbba1bd53d665f2abb668e54b67b066
Ruby
danielkza/bolsa-capital
/lib/tasks/simulate.rake
UTF-8
1,057
2.578125
3
[]
no_license
require 'simplify' namespace :simulate do desc 'TODO' task :payment do Simplify::public_key = "sbpb_N2YyMWMwNmMtNGRiOS00MjBhLTk1NzAtNTQ4NGEzZGUwNDUy" Simplify::private_key = "ERInD4vAyClXX8LVfMVRBqAKpj5teXHGsfWzcNRT0b15YFFQL0ODSXAOkNtXTToq" new_payment("5105105105105100", 2756) end task :populate do Simplify::public_key = "sbpb_N2YyMWMwNmMtNGRiOS00MjBhLTk1NzAtNTQ4NGEzZGUwNDUy" Simplify::private_key = "ERInD4vAyClXX8LVfMVRBqAKpj5teXHGsfWzcNRT0b15YFFQL0ODSXAOkNtXTToq" cards = ["5105105105105100", "5555555555554444", "5185540810000019", "4012888888881881", "371449635398431"] (1..200).each do |i| card = cards[rand(4)] amount = 5000 + rand(20000) p card p amount new_payment( card, amount) end end def new_payment card, amount payment = Simplify::Payment.create({ "card" => { "number" => card, "expMonth" => 11, "expYear" => 15, "cvc" => "123" }, "reference" => (Time.new(2015, 4, 10, 2, 2, 2, "+02:00").utc.to_i * 1000), "amount" => amount, "currency" => "BRL", "description" => "New payment to the merchant" }) if payment['paymentStatus'] == 'APPROVED' puts "Payment approved" end end end
true
6f949e257f09331ba9a1d9a05ce77970b3c753fd
Ruby
szagar/pyzts
/daemons/ibgw2filed/lib/setup_queue/message.rb
UTF-8
750
2.8125
3
[]
no_license
require "json" require_relative "../log_helper" module SetupQueue class Message include LogHelper def initialize(params) @command = params[:command] @data = params[:data] end def to_json {command: @command, data: @data}.to_json end def self.decode(json_msg) warn "SMZ: decode(#{json_msg})" msg = from_json(json_msg) warn "SMZ: msg = #{msg}" [msg[:command],msg[:data]] rescue warn "SetupQueue::Message cannot be decoded, message: #{json_msg}" ["nop",""] end private def self.from_json(json_msg) JSON.parse(json_msg, symbolize_names: true) rescue warn "SetupQueue::Message cannot parse json message: #{json_msg}" end end end
true
7b43c707e18a7fbe13869ac852555190f8cf23dd
Ruby
kurt-friedrich/Blackjack-
/card.rb
UTF-8
551
3.328125
3
[]
no_license
class Card attr_accessor :face, :suit, :value def initialize(face, suit) self.face = face self.suit = suit self.value = infer_value end def self.suits %w(Clubs Spades Hearts Diamonds) end def self.faces %w(2 3 4 5 6 7 8 9 10 J Q K A) end def infer_value if face.to_i > 0 face.to_i else face_values[face.to_sym] end end def >(card) self.value > card.value end def face_values { :J => 10, :Q => 10, :K => 10, :A => 11 } end end # deck = Card.new
true
8f1d0258b903eb4e349e56ee2b22d81ceff081c2
Ruby
miochung7/Ruby_Challenges
/6kyu Array-Diff.rb
UTF-8
954
4
4
[]
no_license
=begin Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list a, which are present in list b. array_diff([1,2],[1]) == [2] If a value is present in b, all of its occurrences must be removed from the other: array_diff([1,2],[1]) == [2] =end =begin Test.describe("Basic Tests") do Test.assert_equals(array_diff([1,2], [1]), [2], "a was [1,2], b was [1], expected [2]") Test.assert_equals(array_diff([1,2,2], [1]), [2,2], "a was [1,2,2], b was [1], expected [2,2]") Test.assert_equals(array_diff([1,2,2], [2]), [1], "a was [1,2,2], b was [2], expected [1]") Test.assert_equals(array_diff([1,2,2], []), [1,2,2], "a was [1,2,2], b was [], expected [1,2,2]") Test.assert_equals(array_diff([], [1,2]), [], "a was [], b was [1,2], expected []") end =end def array_diff(a, b) a.each do |x| if b.include?(x) a.delete(x) end end end
true
e8cf2d36380cfa00bff0533f4345a2bdf8373cf0
Ruby
Schofield88/Smart_Pension_test
/spec/printer_spec.rb
UTF-8
697
2.65625
3
[]
no_license
require './lib/printer' describe Printer do let (:printer) { Printer.new } let (:total) { [ {:url=>"/about", :visits=>1}, {:url=>"/help", :visits=>6}, {:url=>"/about/2", :visits=>3} ] } let (:unique) { [ {:url=>"/about", :ips=>["451.106.204.921"]}, {:url=>"/about/2", :ips=>["382.335.626.855", "316.433.849.805"]} ] } context "#render" do it "sorts and renders the data" do expect{ printer.render(total: total, unique: unique) }.to output("Pages sorted by total visits:\n/help: 6 visit(s)\n/about/2: 3 visit(s)\n/about: 1 visit(s)\n\nPages sorted by unique visits:\n/about/2: 2 visit(s)\n/about: 1 visit(s)\n").to_stdout end end end
true
bb4c079903c9283bddbd5d9a573465a48588f5c6
Ruby
self20/broad
/spec/support/fake_servers/fake_omdb.rb
UTF-8
543
2.546875
3
[ "MIT" ]
permissive
require 'sinatra/base' class FakeOmdb < Sinatra::Base get '/' do imdb_id = params["i"] data = omdb_data(imdb_id) content_type :json [200, data] end get '/*' do raise NotImplementedError, "'#{self.url}' is not implemented in this fake" end private def omdb_data(imdb_id) file_path = "spec/fixtures/omdb/#{imdb_id}.json" if File.file?(file_path) File.read(file_path) else File.read("spec/fixtures/omdb/default.json") end end class NotImplementedError < StandardError; end end
true
07d87faebbf10c4af5a3287789f0faec089cfc17
Ruby
e-g-r-ellis/ruby-native-pallendrome
/lib/mygem/pallendromelib.rb
UTF-8
165
2.90625
3
[]
no_license
require 'mygem/pallendrome' def first_ruby_call puts "Calling ruby pallendrome with 'hello'" result = pallendrome "hello" puts "Ruby result: "+result.to_s end
true
f80494a767796f29a36f5db4d66ffaf7fd15b156
Ruby
arturocedilloh/LS_101
/lesson_4/selection_transformation.rb
UTF-8
3,231
4.09375
4
[]
no_license
=begin produce = { 'apple' => 'Fruit', 'carrot' => 'Vegetable', 'pear' => 'Fruit', 'broccoli' => 'Vegetable' } def select_fruit(fruit_list) hsh = {} fruit_list.each do |k,v| if v == 'Fruit' hsh[k] = v end end hsh end puts select_fruit(produce) # => {"apple"=>"Fruit", "pear"=>"Fruit"} puts produce #---------------------------------------------------------------------- def double_numbers(numbers) doubled_numbers = [] counter = 0 loop do break if counter == numbers.size current_number = numbers[counter] doubled_numbers << current_number * 2 counter += 1 end doubled_numbers end def double_numbers!(numbers) counter = 0 loop do break if counter == numbers.size current_number = numbers[counter] numbers[counter] = current_number * 2 counter += 1 end numbers end puts my_numbers = [1, 4, 3, 7, 2, 6] puts double_numbers(my_numbers) puts my_numbers puts double_numbers!(my_numbers) puts my_numbers #----------------------------------------------------------------------- def double_odd_numbers(numbers) doubled_numbers = [] counter = 0 loop do break if counter == numbers.size current_number = numbers[counter] current_number *= 2 if counter.odd? doubled_numbers << current_number counter += 1 end doubled_numbers end puts my_numbers = [1, 4, 3, 7, 2, 6] puts double_odd_numbers(my_numbers) puts my_numbers #----------------------------------------------------------------------- def general_select(produce_list, selection_criteria) produce_keys = produce_list.keys counter = 0 selected_fruits = {} loop do break if counter == produce_keys.size current_key = produce_keys[counter] current_value = produce_list[current_key] # used to be current_value == 'Fruit' if current_value == selection_criteria selected_fruits[current_key] = current_value end counter += 1 end selected_fruits end produce = { 'apple' => 'Fruit', 'carrot' => 'Vegetable', 'pear' => 'Fruit', 'broccoli' => 'Vegetable' } general_select(produce, 'Fruit') # => {"apple"=>"Fruit", "pear"=>"Fruit"} general_select(produce, 'Vegetable') # => {"carrot"=>"Vegetable", "broccoli"=>"Vegetable"} general_select(produce, 'Meat') #----------------------------------------------------------------------- def multiply(number_list, choice) counter = 0 loop do break if counter == number_list.size number_list[counter] = number_list[counter] * choice counter += 1 end number_list end puts my_numbers = [1, 4, 3, 7, 2, 6] puts multiply(my_numbers, 3) # => [3, 12, 9, 21, 6, 18] #----------------------------------------------------------------------- =end def select_letter(sentence, character) selected_chars = '' counter = 0 loop do break if counter == sentence.size current_char = sentence[counter] if current_char == character selected_chars << current_char end counter += 1 end selected_chars end question = 'How many times does a particular character appear in this sentence?' select_letter(question, 'a') # => "aaaaaaaa" select_letter(question, 't') # => "ttttt" select_letter(question, 'z') # => ""
true
e84ad79e2a30867db2449c4cddd43c1bf7898394
Ruby
MDes41/class_exercises
/refactoring/pattern_refactor/pattern_refactor.rb
UTF-8
399
3.234375
3
[]
no_license
class Engine def core_weight 250 end def propeller_weight 50 end def weight core_weight + propeller_weight end end class Plane attr_reader :engine def initialize @engine = Engine.new end def body_weight 1000 end def engine_count 2 end def weight body_weight + engine_count * engine.weight end end dusty = Plane.new dusty.weight
true
2040b612d7cf00e1e83ef2033866a413b1833469
Ruby
nbriar/snapapp_api
/test/models/hyperlink_test.rb
UTF-8
999
2.578125
3
[]
no_license
# == Schema Information # # Table name: hyperlinks # # id :bigint(8) not null, primary key # url :string # text :string # target :string # action :string # created_at :datetime not null # updated_at :datetime not null # require 'test_helper' class HyperlinkTest < ActiveSupport::TestCase test "requires a url to be created" do link = Hyperlink.create() assert_equal ["can't be blank"], link.errors.messages[:url] end test "url must start with / or http:// or https://" do link = Hyperlink.create(url: "invalid_url") assert link.errors.messages[:url].include? "must be a valid link starting with `/`, `http://` or `https://`" end test "url must not have spaces" do link = Hyperlink.create(url: "/invalid url") assert link.errors.messages[:url].include? "must not have spaces" end test "can create a hyperlink" do link = Hyperlink.create(url: "/valid_url") assert link.id.present? end end
true
5b8804ab00bd883e3b51bef5db6d444015901a3a
Ruby
thinkerbot/tap
/tap-server/lib/tap/controller/extname.rb
UTF-8
790
2.53125
3
[ "MIT" ]
permissive
module Tap class Controller # Add handling of extnames to controller paths. The extname of a request # is chomped and stored in the extname attribute for use wherever. module Extname # Returns the extname for the current request, or nil if no extname # was specified in the paths_info. def extname @extname ||= nil end # Overrides route to chomp of the extname from the request path info. # If no extname is specified, extname will be remain nil. def route @extname = File.extname(request.path_info) @extname = nil if @extname.empty? args = super unless args.empty? || extname == nil args.last.chomp!(extname) end args end end end end
true
6de86c689354c1ae41d634f151660901a7751e7c
Ruby
snakeyworm/mulparse
/test/ruby_comments_test.rb
UTF-8
170
2.578125
3
[ "MIT" ]
permissive
=begin =end # Hi # Hello world! # foo # oof # Hi =end # # quark # Not a # Block comment # Hello world! # foo # blather # bar =begin #
true
f918ee485472ae93d16817c773d0e506c94cbc76
Ruby
avdgaag/laze
/lib/laze/plugins.rb
UTF-8
1,524
2.890625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
module Laze # Plugins provides access to all Laze plugins. # # A plugin is a simple decorator that can wrap an Item object. Every plugin # itself can tell you to what objects it applies, and an Item includes # all available plugins by using the +include_plugins+ macro: # # class MyItem < Item # include_plugins :my_item # end # # == Example # # A plugin is a simple module that usually replaces methods on Item objects. # Here's a simple example: # # class MyItem < Item # include_plugins :my_item # def foo # 'bar' # end # end # # module Plugins # module MyPlugin # def applies_to?(kind) # kind == :my_item # end # # def foo # super + '!' # end # end # end # # MyItem.new.foo # => 'bar!' # # == Working with plugins # # Usually, each plugin should have its own file, require any third-party # libraries and be responsible for when things go wrong. # # A plugin should be stored in /plugins, where it is automatically loaded. module Plugins # Loop over all available plugins, yielding each. def self.each(for_kind = nil) # :yields: module constants.each do |c| const = Laze::Plugins.const_get(c) yield const if const.is_a?(Module) && (for_kind.nil? || const.applies_to?(for_kind)) end end end end # Load all plugins from /plugins Dir[File.join(File.dirname(__FILE__), 'plugins', '*.rb')].each { |f| require f }
true
8655e2847ba4ca97a4598e29e3e293e90e9d4d46
Ruby
williamkennedy/Euler-Solutions
/EulerProblem3.rb
UTF-8
315
3.71875
4
[]
no_license
#The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143 ? require 'prime' def prime_factors(n) return [n] if Prime.prime?(n) Prime.prime_division(n) end puts prime_factors(600851475143).inspect #refactor to only return the largest Prime factor
true