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
bfed4377d9d355f8e8b3f3fc1e9ca3e85e2dbc26
Ruby
FiXato/ubuntu-machine
/lib/capistrano/ext/ubuntu-machine/helpers.rb
UTF-8
2,628
2.828125
3
[ "MIT" ]
permissive
require 'erb' # render a template def render(file, binding) template = File.read("#{File.dirname(__FILE__)}/templates/#{file}.erb") result = ERB.new(template).result(binding) end # allows to sudo a command which require the user input via the prompt def sudo_and_watch_prompt(cmd, regex_to_watch) sudo cmd, :pty => true do |ch, stream, data| watch_prompt(ch, stream, data, regex_to_watch) end end # allows to run a command which require the user input via the prompt def run_and_watch_prompt(cmd, regex_to_watch) run cmd, :pty => true do |ch, stream, data| watch_prompt(ch, stream, data, regex_to_watch) end end # utility method called by sudo_and_watch_prompt and run_and_watch_prompt def watch_prompt(ch, stream, data, regex_to_watch) # the regex can be an array or a single regex -> we force it to always be an array with [*xx] if [*regex_to_watch].find { |regex| data =~ regex} # prompt, and then send the response to the remote process ch.send_data(Capistrano::CLI.password_prompt(data) + "\n") else # use the default handler for all other text Capistrano::Configuration.default_io_proc.call(ch, stream, data) end end def add_to_file(file,lines) [*lines].each do |line| run 'echo "%s" >> %s' % [line.gsub('"','\"'),file] end end def sudo_add_to_file(file,lines) tmpfile = "#{File.basename(file)}.tmp" sudo "cp #{file} #{tmpfile}" # Temporarily make world read/writable so it can be appended to. sudo "chmod 0777 #{tmpfile} && sudo chown #{user}:#{user} #{tmpfile}" add_to_file(tmpfile,lines) # Use cp + rm instead mv so the destination file will keep its owner/modes. sudo "cp #{tmpfile} #{file} && rm #{tmpfile}" end # Re-activate sudo session if it has expired. def sudo_keepalive sudo "ls > /dev/null" end # Adds 1 or more commands to the cron tab # - commands can be a string or an array # - period should be a valid crontab period # - use_sudo can be set to true if you want to edit the root crontab. def add_to_crontab(commands,period,use_sudo=false) send_cmd = use_sudo ? :sudo : :run tmp_cron="/tmp/cron.tmp" self.send(send_cmd, "rm -f #{tmp_cron} && touch #{tmp_cron}") run "(#{use_sudo ? 'sudo ' : ''}crontab -l || true) > #{tmp_cron}" cron_lines = [*commands].map{|cmd| "#{period} #{cmd}"} add_to_file(tmp_cron, cron_lines) self.send(send_cmd, "crontab #{tmp_cron}") sudo "rm -f #{tmp_cron}" end # Adds 1 or more commands to the cron tab of root # - commands can be a string or an array # - period should be a valid crontab period def sudo_add_to_crontab(commands,period) add_to_crontab(commands, period, true) end
true
38efcf7ed3a7da755fc7145c62f3aa8f233e7bc2
Ruby
Moutalib/humpass
/lib/humpass/database.rb
UTF-8
1,403
2.90625
3
[ "MIT" ]
permissive
require "base64" require "json" module Humpass class << self attr_accessor :database end def self.set_database(file_path = nil) self.database ||= Database.new(file_path) end class Database attr_accessor :file_path def initialize(file_path = __dir__ + '/humpass.dat') raise 'Configuration not sat!' if Humpass.configuration.nil? @file_path = file_path end def write(data) File.open(file_path, 'w+') { |file| file.write(encrypt(database_password, Base64.encode64(data))) } end def read begin Base64.decode64(decrypt(database_password, File.open(file_path, 'r').read)) rescue '' end end def database_password Humpass.configuration.master_password = gets.chomp if Humpass.configuration.master_password.nil? Humpass.configuration.master_password end def encrypt(key, data) cipher = OpenSSL::Cipher::AES.new(128, :CBC).encrypt cipher.key = Digest::SHA2.hexdigest(key)[0..15] cipher.update(data) + cipher.final end def decrypt(key, data) cipher = OpenSSL::Cipher::AES.new(128, :CBC).decrypt cipher.key = Digest::SHA2.hexdigest(key)[0..15] s = data.unpack("C*").pack("c*") begin s.empty? ? "" : cipher.update(s) + cipher.final rescue abort("Wrong Master Password!") end end end end
true
6915f2719dc57efc7aed891c07855a97375b96d2
Ruby
neelabhgupta/Geometry
/lib/length.rb
UTF-8
683
3.859375
4
[]
no_license
#Length in metres class Length M_UNIT = 'm' CM_UNIT = 'cm' MM_UNIT = 'mm' attr_reader :length_m def initialize(length, unit) @length_m = convert_to_m(length.to_f, unit) end def convert_to_m(side, unit) if unit == CM_UNIT side = side / 100 elsif unit == MM_UNIT side = side / 1000 end side end def +(other_length) Length.new(length_m + other_length.length_m, M_UNIT) end def *(scalar) Length.new(length_m * scalar, M_UNIT) end def ==(other_object) return false if self.class != other_object.class length_m == other_object.length_m end def hash length_m.hash end alias_method :eql?, :== end
true
23104bd0c197b13212566200a4214230b61b6ed1
Ruby
testdouble/suture
/test/suture/adapter/log_test.rb
UTF-8
1,771
2.515625
3
[ "MIT" ]
permissive
require "suture/adapter/log" module Suture::Adapter class LogTest < UnitTest class FakeThing include Suture::Adapter::Log def stuff log_debug("an debug") log_info("an info") log_warn("an warn") log_error("an error") end end def setup super @log_io = StringIO.new config_log(:log_io => @log_io) end def test_debug_level config_log(:log_level => "DEBUG") FakeThing.new.stuff assert_match "Suture: an debug", read_log assert_match "Suture: an info", read_log assert_match "Suture: an warn", read_log assert_match "Suture: an error", read_log end def test_warn_level config_log(:log_level => "WARN") FakeThing.new.stuff assert_not_match "Suture: an debug", read_log assert_not_match "Suture: an info", read_log assert_match "Suture: an warn", read_log assert_match "Suture: an error", read_log end def test_error_level config_log(:log_level => "ERROR", :log_file => nil) FakeThing.new.stuff assert_not_match "Suture: an debug", read_log assert_not_match "Suture: an info", read_log assert_not_match "Suture: an warn", read_log assert_match "Suture: an error", read_log end def test_default_level config_log(:log_level => nil) FakeThing.new.stuff assert_not_match "Suture: an debug", read_log assert_match "Suture: an info", read_log assert_match "Suture: an warn", read_log assert_match "Suture: an error", read_log end private def config_log(attrs) Suture.config(attrs) Suture::Adapter::Log.reset! end def read_log @log_io.tap(&:rewind).read end end end
true
d1e9cc18d4b9da1f8e5c393fe8ecea1d6753ccf2
Ruby
mattapayne/jambase4r
/lib/models/event.rb
UTF-8
741
2.734375
3
[ "MIT" ]
permissive
module JamBase4R class Event include Model attr_reader :id, :artists, :venue, :ticket_url, :event_url, :date def initialize(element) return if element.blank? build(element) end private def build(element) @artists = [] @id = get_value(element, EVENT_ID) @ticket_url = get_value(element, TICKET_URL) @event_url = get_value(element, EVENT_URL) @date = get_value(element, EVENT_DATE) v = element.get_elements(VENUE) unless v.blank? @venue = Venue.new(v.first) end artists = element.get_elements(ARTISTS) unless artists.blank? artists.each {|a| @artists << Artist.new(a) } end end end end
true
13b0298e335b856b28adbea02d6dd0ad0e3bdfa5
Ruby
DUSAEN052/green_grocer-dumbo-web-career-010719
/grocer.rb
UTF-8
1,466
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def consolidate_cart(cart) # code here output = {} cart.each do |item| item.each do |key, value| if output.key?(key) output[key][:count] += 1 else output[key] = value output[key].merge!({:count => 1}) end end end return output end def apply_coupons(cart, coupons) # code here if coupons.length == 0 return cart end output = {} cart.each do |item, info| coupons.each do |coupon| if coupon[:item] == item and coupon[:num] <= info[:count] if output[coupon[:item] + " W/COUPON"] == nil output[coupon[:item] + " W/COUPON"] = { :price => coupon[:cost], :clearance => info[:clearance], :count => 1 } else output[coupon[:item] + " W/COUPON"][:count] += 1 end cart[item][:count] -= coupon[:num] end output[item] = info end end output end def apply_clearance(cart) # code here cart.each do |item, info| if info[:clearance] info[:price] = (info[:price] * 0.8).round(2) end end cart end def checkout(cart, coupons) # code here total = 0 consolidated = consolidate_cart(cart) couponned = apply_coupons(consolidated, coupons) cleared = apply_clearance(couponned) cleared.each do |item, info| total += info[:price] * info[:count] end if total > 100 return total * 0.9 end return total end
true
64997a57b06b4197f2cbbcd56cd5be57a4c081b0
Ruby
vivianafb/Actividad17
/Ejercicio6.rb
UTF-8
492
3.234375
3
[]
no_license
class Product attr_accessor :name, *:medidas def initialize(name, *medidas) @name = name @medidas = medidas.map(&:to_i) end def promedio @medidas.inject(&:+) / @medidas.size.to_f end end products_list = [] data = [] File.open('catalogo.txt', 'r') { |file| data = file.readlines.map(&:chomp)} data.each do |prod| ls = prod.split(', ') products_list << Product.new(*ls) end p products_list products_list.each do |product| p product.name p product.promedio end
true
5f959a9b37edfb308fc23810a95af8be040a0125
Ruby
cernandes/curso-ruby
/missoes_especiais/compras/app.rb
UTF-8
449
3.53125
4
[]
no_license
# 3 - No arquivo app.rb crie uma instância da classe Produto e adicione valores aos atributos nome e preco. # Depois, inicie uma instância da classe Mercado passsando como atributo a instância da classe Produto e para finalizar execute o método comprar. require_relative 'produto' require_relative 'mercado' produto = Produto.new produto.nome = 'Notebook' produto.preco = 5.500 mercado = Mercado.new(produto.nome, produto.preco) mercado.comprar
true
bbfcd041e079b7de2605b9f9585a8a1476be9f53
Ruby
zacholauson/tictactoe.rb
/spec/gamestate_spec.rb
UTF-8
6,241
3.296875
3
[]
no_license
describe Gamestate do describe "#initialize" do let(:gamestate) { Gamestate.new } it "should create a new board" do expect(gamestate.board).to eq(['-', '-', '-', '-', '-', '-', '-', '-', '-']) end it "should set the first move to 'x' for the computer" do expect(gamestate.turn).to eq("x") end it "should create a empty movelist to hold moves" do expect(gamestate.send(:movelist)).to eq([]) end end describe "#move" do let(:gamestate) { create_gamestate_from_string("xo-o--x-x", turn: "o") } before do gamestate.stub(:movelist) {[0, 1, 8, 3, 6]} end it "should put an 'o' in the 4th index" do expect(gamestate.move(4).board).to eq(["x", "o", "-", "o", "o", "-", "x", "-", "x"]) end end describe "#unmove" do let(:gamestate) { create_gamestate_from_string("xo-o--x-x", turn: "o") } before do gamestate.stub(:movelist) {[0, 1, 8, 3, 6, 4]} end it "should reset the last move on the board to '-'" do expect(gamestate.unmove.board).to eq(["x", "o", "-", "o", "-", "-", "x", "-", "x"]) end end describe "#other_turn" do context "computers first" do let(:gamestate) { Gamestate.new } it "should return return 'o' if its computers turn" do expect(gamestate.other_turn).to eq("o") end end context "humans first" do let(:gamestate) { Gamestate.new(nil, "o") } it "should return return 'x' if its the humans turn" do expect(gamestate.other_turn).to eq("x") end end end describe "#possible_moves" do context "new game" do let(:gamestate) { Gamestate.new } it "should return the index of every available possition" do expect(gamestate.possible_moves).to eq([0,1, 2, 3, 4, 5, 6, 7, 8]) end end context "game in progress" do let(:gamestate) { create_gamestate_from_string("xo-o--x-x") } it "should return the index of available positions in an array" do expect(gamestate.possible_moves).to eq([2, 4, 5, 7]) end end end describe "#winning_positions" do let(:gamestate) { Gamestate.new } it "should return the indexes of every winning line ( horizontal, vertical, diagonal )" do expect(gamestate.winning_positions).to eq([[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]) end end describe "#winning_lines" do context "new game" do let(:gamestate) { Gamestate.new } it "should return winnable line status' (horizontals, verticals, and diagonals)" do expect(gamestate.winning_lines).to eq([["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]) end end context "game in progress" do let(:gamestate) { create_gamestate_from_string("xo-o--x-x") } it "should return winnable lines status' (horizontals, verticals, and diagonals)" do expect(gamestate.winning_lines).to eq([["x", "o", "-"], ["o", "-", "-"], ["x", "-", "x"], ["x", "o", "x"], ["o", "-", "-"], ["-", "-", "x"], ["x", "-", "x"], ["-", "-", "x"]]) end end end describe "#win?" do context "computer has won" do let(:gamestate) { create_gamestate_from_string("xo-ox-xox") } it "should return true if the computer ('x') has won" do expect(gamestate.win?("x")).to be_true end end context "no one has won" do let(:gamestate) { create_gamestate_from_string("xo-o--xox") } it "should return false if no one has won yet or tied" do expect(gamestate.win?("x")).to be_false expect(gamestate.win?("o")).to be_false end end end describe "#tied?" do let(:gamestate) { create_gamestate_from_string("xoxxoooxo") } it "should return true if the game is tied" do expect(gamestate.tied?).to be_true end end describe "#first_move?" do context "new game" do let(:gamestate) { Gamestate.new } it "should return true if no one has made a move" do expect(gamestate.first_move?).to be_true end end context "game in progress" do let(:gamestate) { create_gamestate_from_string("x-o-x-oxo") } before do gamestate.stub(:movelist) { [0, 2, 4, 6, 7, 8] } end it "should return false if previous moves have taken place" do expect(gamestate.first_move?).to be_false end end end describe "#game_over?" do let(:gamestate) { create_gamestate_from_string("xx-oxxoxo") } it "should return true if the game is over (winner / tie)" do expect(gamestate.game_over?).to be_true end end describe "#players_turn?" do let(:gamestate) { Gamestate.new(nil, "o") } it "should return true if it's the players turn" do expect(gamestate.players_turn?).to be_true end end describe "#computers_turn?" do let(:gamestate) { Gamestate.new } it "should return true if its the computers turn" do expect(gamestate.computers_turn?).to be_true end end describe "#set_players_turn" do let(:gamestate) { Gamestate.new } it "should set the gamestates turn to 'x' // the players turn" do gamestate.set_players_turn expect(gamestate.players_turn?).to be_true end end describe "#set_computers_turn" do let(:gamestate) { Gamestate.new(nil, "o") } it "should set the gamestates turn to 'o' // the computers turn" do gamestate.set_computers_turn expect(gamestate.computers_turn?).to be_true end end describe "#space_available?" do let(:gamestate) { create_gamestate_from_string("x-x-o-o-o") } it "should return true when the given index is an available position on the board" do expect(gamestate.space_available?(1)).to be_true end end end
true
6bd159a66f2e353d2150246cafcdff1b828dad73
Ruby
acevedo93/EXERCISM
/ruby/rna-transcription/rna_transcription.rb
UTF-8
650
2.71875
3
[]
no_license
class Complement def self.of_dna complement_string='' # Best solution complement_strng.tr('CGTA', 'GCAU') # Manual solution # final_complement = '' # complement_string.split('').each do |c| # case c # when 'G' # final_complement += 'C' # when 'C' # final_complement += 'G' # when 'T' # final_complement += 'A' # when 'A' # final_complement += 'U' # else # final_complement # end # end # final_complement end end
true
73a5e796510ddbc36b6e479194f9922628f89864
Ruby
yasmineezequiel/Vanilla_Ruby
/Section_19_Modules_and_Mixins/Introduction_to_Modules.rb
UTF-8
566
3.296875
3
[]
no_license
# What is a module? # A module is a toolbox or container of methods and constants # Module methods and constants can be used as needed # Modules create namespaces for methods with the same name # Modules cannot be used to create instances # Modules can be mixed into classes to add behavior # Syntax and Style: # Module names are written in UpperCamelCase. # Contants in modules should be written in ALL CAPS # Access modules methods with the dot operator (.) # Access module constants with the :: symbol. # The :: symbol is called the scope resolution operator.
true
c5bca7078bcf4eced6ea74ca96c31e82a2a1ba97
Ruby
cbrenner04/advent_of_code
/2019/05/solution.rb
UTF-8
168
2.796875
3
[]
no_license
# frozen_string_literal: true require_relative("../intcode") part_one, = Intcode.new(INPUT, 1).run part_two, = Intcode.new(INPUT, 5).run puts part_one puts part_two
true
93e1df23bf36fe5124bd03fffaa2c5d08af89923
Ruby
BhargaviAA/ruby_assignments
/assignment1/simple_calculator.rb
UTF-8
474
3.921875
4
[]
no_license
#!/urs/bin/ruby -w puts('Enter two numbers') num1=gets num2=gets number1=num1.to_i number2=num2.to_i puts "[add], [subtract], [multiply] or [divide]" answer=gets.chomp case answer when 'add' sum=number1+number2 print sum.to_s when 'subtract' difference=number1-number2 print difference.to_s when 'multiply' product=number1*number2 print product.to_s when 'divide' quotient=number1/number2 print quotient.to_s end
true
31ac8dae653d9172769f2b8a418e8196353e9b3e
Ruby
archive-for-processing/JRubyArt
/test/color_group_test.rb
UTF-8
790
2.5625
3
[ "GPL-3.0-only", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.0-or-later" ]
permissive
# frozen_string_literal: true require_relative 'test_helper' require_relative '../library/color_group/color_group' Java::Monkstone::JRLibrary.load(JRuby.runtime) java_import Java::Monkstone::ColorUtil PALETTE = %w[#FFFFFF #FF0000 #0000FF].freeze COLORS = [16_777_215, 16_711_680, 255].to_java(:int) # ColorGroup Tests class ColorGroupTest < Minitest::Test def test_new group = ColorGroup.new(COLORS) assert group.is_a? ColorGroup end def test_web_array group = ColorGroup.from_web_array(PALETTE) assert group.is_a? ColorGroup end def test_ruby_string p5array = [16_777_215, 16_711_680, 255] group = ColorGroup.new(COLORS) ruby_string = "%w[#FFFFFF #FF0000 #0000FF]\n" result = group.ruby_string assert_equal(result, ruby_string) end end
true
3d569eb5ed40ebf0996fe3832b0446c7f52a8234
Ruby
southpawgeek/perlweeklychallenge-club
/challenge-141/roger-bell-west/ruby/ch-2.rb
UTF-8
501
3.3125
3
[]
no_license
#! /usr/bin/ruby def likenumber(source,factor) s=source.to_s.split('').map {|i| i.to_i} m=s.length n=0 1.upto((1<<m)-2) do |mask| c=0 0.upto(m-1) do |di| if (mask & 1<<di)>0 then c=c*10+s[di] end end if c % factor == 0 then n+=1 end end return n end require 'test/unit' class TestLikenumber < Test::Unit::TestCase def test_ex1 assert_equal(9,likenumber(1234,2)) end def test_ex2 assert_equal(3,likenumber(768,4)) end end
true
cfc718c6883dcc5de2b0c60577a6f07e7313edc5
Ruby
nmbits/rbe
/gen/lib/rbe/cpp/type.rb
UTF-8
708
2.578125
3
[ "MIT" ]
permissive
module RBe module Cpp class Type < String def initialize(string) self.replace normalize_common(string) end def void? self == "void" end def normalize normalize_common self.dup end def normalize! normalize_common self end def dereferenced if /\*$/ =~ self return Type.new($`.strip) end raise "#{type} is not a pointer" end private def normalize_common(target) target.gsub!(/\s+/, ' ') target.gsub!(/\*\s*/, '*') target.gsub!(/([a-zA-Z0-9_])\s*\*/, "\\1 *") target.strip! target end end end end
true
2341346699138ff8a6abfbb0debbca2d363d26cd
Ruby
NicholasBaraldi/Ruby
/Rock_Paper_Scissors.rb
UTF-8
1,746
4.03125
4
[]
no_license
class Player MOVES = [:rock, :paper, :scissors] attr_reader :score, :move def initialize @score = 0 @move = nil end def get_move loop do puts "Pick a move." print "> " @move = gets.chomp.strip.downcase.to_sym if @move == :quit return false elsif MOVES.include?(@move) return @move else puts "Invalid move." end end end def win @score += 1 end end class PC_Player < Player def get_move @move = MOVES.sample end end class Game WIN_SCENARIOS = [ [:rock, :scissors], [:paper, :rock], [:scissors, :paper] ] def initialize @tie = 0 @p1 = Player.new @p2 = PC_Player.new play end def winner if @p1.move == @p2.move puts "It's a tie!" @tie += 1 elsif WIN_SCENARIOS.include?([@p1.move, @p2.move]) puts "You win!" @p1.win else puts "PC wins!" @p2.win end end def round return false unless @p1.get_move return false unless @p2.get_move result puts scores puts puts "Let's play again." true end def play loop do break unless round end puts puts "Goodbye!" end def result puts puts "You played #{@p1.move} and PC played #{@p2.move}." winner end def scores puts "Scores:" puts "Player: #{@p1.score}" puts "PC: #{@p2.score}" puts "Ties: #{@tie}" end end Game.new
true
dd24dd36593f6b288656f0e2d195b96c2b97085d
Ruby
CarterNelms/amateur_sports_league
/app/controllers/session_controller.rb
UTF-8
1,292
2.765625
3
[ "MIT" ]
permissive
class SessionController TERMINATE_COMMANDS = ['end','exit','quit','q'] def begin @controller = SportsController.new() @command = "list" sign_in apply_user_input end def sign_in puts "Hello. Please enter your username" username = clean_gets.capitalize # Player.create(username: username, first_name: 'Carter', last_name: "Nelms", age: 24, is_male: true) @user = Player.where("username = '#{username}'").first if @user puts "Welcome #{@user.username}" else puts "Hello #{username}. Would you like to create a new account? (y/N)" input = clean_gets.downcase if input == 'y' || input == 'yes' @user = PlayersController.new().add(username) @command = "exit" unless @user else puts "Now exiting..." @command = "exit" end end end def apply_user_input while @controller && !TERMINATE_COMMANDS.include?(@command) possible_new_controller = Router.navigate_session(@command) if possible_new_controller @controller = possible_new_controller else @controller = @controller.navigate_menu(@command, @user) # unless Router.navigate_session(self, @command) end @command = clean_gets.downcase if @controller end end end
true
91d8e3a7ae5d78f77ee6e4c27bee7a38a598231f
Ruby
isabella232/java_service
/libraries/option.rb
UTF-8
608
3.4375
3
[ "MIT" ]
permissive
class Option attr_reader :name attr_reader :value attr_reader :prefix def initialize(name, value, prefix, separator) @name = name @value = value @prefix = prefix @separator = separator end def apply_quotes(value) if /\s/ =~ value.to_s and not /^(["']).*\1$/ =~ value value = "\"#{value}\"" end value end def to_s if value "#{prefix}#{name}#{separator}#{apply_quotes(value)}" else "#{prefix}#{name}" end end def separator if @separator.kind_of? Proc @separator.call(@name) else @separator end end end
true
d031ebb693d7b26b480904a01b7e0a7b410af685
Ruby
mellowcoder/myflix
/spec/features/user_manages_their_queue_spec.rb
UTF-8
2,531
2.578125
3
[]
no_license
require 'spec_helper' feature "A User Manages Their Queue" do given(:steve) {Fabricate(:user, email: "smartin@example.com", password: "king-tut", full_name: "Steve Martin")} scenario "adding videos to queue and reordering queue" do comedy = Fabricate(:category, name: 'Comedy') monk1 = Fabricate(:video, title: "Monk 1", category: comedy) monk2 = Fabricate(:video, title: "Monk 2", category: comedy) futurama1 = Fabricate(:video, title: "Futurama 1", category: comedy) futurama2 = Fabricate(:video, title: "Futurama 2", category: comedy) feature_sign_in(steve) # After sign in they should be redirected to the home page after sign in expect(current_path).to eq(home_path) # View a video click_link "video_#{monk1.id}" expect_current_to_be_the_path_for_video(monk1) # Add the video to your queue click_link("+ My Queue") expect(current_path).to eq(my_queue_path) expect(page).to have_content(monk1.title) # Return to the video from the link in the queue and verify that you can not add the video to the queue a second time click_link(monk1.title) expect_current_to_be_the_path_for_video(monk1) expect(current_path).to eq(video_path(monk1)) expect_to_not_see_add_to_queue_link # Add additional videos and verify that they appear in the queue add_video(monk2) add_video(futurama1) expect_video_to_be_in_queue(monk1) expect_video_to_be_in_queue(monk2) expect_video_to_be_in_queue(futurama1) # Reorder the queue and verify that it updates set_video_postion(monk1, 5) set_video_postion(monk2, 7) set_video_postion(futurama1, 6) click_button 'Update Instant Queue' expect_video_postion(monk1, 1) expect_video_postion(monk2, 3) expect_video_postion(futurama1, 2) end end def add_video(video) click_link("Videos") click_link "video_#{video.id}" click_link("+ My Queue") end def set_video_postion(video, position) find("input[data-video-id='#{video.id}']").set(position) end def expect_to_not_see_add_to_queue_link expect(page).to_not have_content("+ My Queue") expect(page).to have_content("In Your Queue") end def expect_current_to_be_the_path_for_video(video) expect(current_path).to eq(video_path(video)) end def expect_video_to_be_in_queue(video) expect(page).to have_content(video.title) end def expect_video_postion(video, position) expect(find("input[data-video-id='#{video.id}']").value).to eq(position.to_s) end
true
62dff053924d5e3f345ff1964cf5dc3ca1a3fa81
Ruby
zackads/mumble
/spec/mumble_spec.rb
UTF-8
882
3.453125
3
[]
no_license
require('mumble') describe Mumble do describe '.mumble_letters' do context 'given an empty string' do it 'returns an empty string' do expect(Mumble.new.mumble_letters('')).to eq '' end end context 'given a single upper case character string' do it 'returns the given string' do expect(Mumble.new.mumble_letters('A')).to eq 'A' end end context 'given another uppercase character string' do it 'returns the given string' do expect(Mumble.new.mumble_letters('B')).to eq 'B' end end context 'given a string of two upper case characters' do it 'returns the string mumbled' do expect(Mumble.new.mumble_letters('AB')).to eq 'A-Bb' expect(Mumble.new.mumble_letters('BC')).to eq 'B-Cc' expect(Mumble.new.mumble_letters('CD')).to eq 'C-Dd' end end end end
true
b710b1fda2f13e59e14bb9c7d3f0e7a027eb459c
Ruby
alexauff/THP
/Week_3/Week_3_Thu/tictactoe/tic_tac.rb
UTF-8
3,065
3.984375
4
[]
no_license
require "pry" class BoardCase #TO DO : la classe a 2 attr_accessor, sa valeur (X, O, ou vide), ainsi que son numéro de case) attr_accessor :value, :number def initialize(value, number) #TO DO doit régler sa valeur, ainsi que son numéro de case @value = value @number= number end def to_s #TO DO : doit renvoyer la valeur au format string return @value = value.to_s return @number = number.to_s end end binding.pry class Board include Enumerable #TO DO : la classe a 1 attr_accessor, une array qui contient les BoardCases attr_accessor :array def initialize #TO DO : #Quand la classe s'initialize, elle doit créer 9 instances BoardCases #Ces instances sont rangées dans une array qui est l'attr_accessor de la classe @array = [] (1..9).each do |i| @array << BoardCase.new("", i) end end def to_s #TO DO : afficher le plateau print " 1 | 2 | 3 ", " 4 | 5 | 6 ", " 7 | 8 | 9 " print "\n" return @array.to_s end def play #TO DO : une méthode qui change la BoardCase jouée en fonction de la valeur du joueur (X, ou O) if @value == "X" puts BoardCase "X" elsif @value == "O" puts BoardCase "O" else puts BoardCase end end # def victory? # #TO DO : qui gagne ? # @winning = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 5, 7], [1, 5, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9]] # if player1.value == winning # puts "#{name1} gagne la partie !" # elsif player2.value.include?.winning # puts "#{name2} gagne la partie !" # else # puts "Match nul !" # end # end end class Player #TO DO : la classe a 2 attr_accessor, son nom, sa valeur (X ou O). Elle a un attr_writer : il a gagné ? attr_accessor :name, :value attr_writer :state def initialize(name, value, state) #TO DO : doit régler son nom, sa valeur, son état de victoire @name = name @value = value @state = state end end class Game def initialize #TO DO : créé 2 joueurs, créé un board puts "Quel est ton nom?" name1 = gets.chomp puts "Et celui de ton adversaire?" name2 = gets.chomp player1 = Player.new(name1, "X", "") player2 = Player.new(name2, "O", "") end def go # TO DO : lance la partie puts "Bienvenue au Morpion. Appuie n'importe où pour commencer." puts "" @@input = gets.chomp start = Board.new end def turn #TO DO : affiche le plateau, demande au joueur il joue quoi, vérifie si un joueur a gagné, passe au joueur suivant si la partie n'est pas finie puts " 1 | 2 | 3 ", " 4 | 5 | 6 ", " 7 | 8 | 9 " print "\n" puts "choisis une case" @number = gets.chomp if player1.value == winning puts "#{name1} gagne la partie !" elsif player2.value.include?.winning puts "#{name2} gagne la partie !" else puts "Match nul !" end end end Game.new.go
true
8cf1d83fafe5b5f049fc0f2d9e1c55a71cd9eea6
Ruby
charlottebrf/57-shades-of-ruby
/09_paint_calculator/spec/checks_validity_spec.rb
UTF-8
649
3.078125
3
[ "MIT" ]
permissive
require_relative "../checks_validity" describe "checks validity of user input" do it "returns false if given 0" do checker = ChecksValidity.new("0") expect(checker.is_valid?()).to eq (false) end it "returns true if a digit between 1-9 is given" do checker = ChecksValidity.new("6") expect(checker.is_valid?()).to eq (true) end it "returns true if a digit between 10-99 is given" do checker = ChecksValidity.new("99") expect(checker.is_valid?()).to eq (true) end it "returns true if a digit over 100+ is given" do checker = ChecksValidity.new("10000") expect(checker.is_valid?()).to eq (true) end end
true
0baa8240eca8b5c2ad8bd75d416eac1aae6c87d3
Ruby
charlescui/oauth-clients
/lib/oauth_clients/core.rb
UTF-8
1,474
2.53125
3
[ "MIT" ]
permissive
require 'oauth_clients/oauth_upload.rb' module OAuthClients::Core class Base attr_accessor :provider, :credentials delegate :get, :post, :to => :http_client def initialize(provider,credentials,options={}) @provider = provider @credentials = credentials end def http_client HttpClient.new end end class OAuthBase < Base attr_accessor :consumer_options # delegate :oauth_get, :oauth_post, :oauth_put, :oauth_delete, :to => :access_token include OAuthClients::OAuthUpload def initialize(provider,credentials,options={}) super @consumer_options ||= {} end def access_token @access_token ||= ::OAuth::AccessToken.new(consumer, credentials[:token], credentials[:secret]) end def consumer @consumer ||= ::OAuth::Consumer.new(provider.key, provider.secret, consumer_options) end end class HttpClient def post(url,params) puts "#{url} => #{params}" url = URI(url) req = Net::HTTP::Post.new(url.path) req.form_data = params OAuthClients.new_http(url).request(req) end end class StringIOWrapper def initialize(url, stringio) @url = url @stringio = stringio end def path File.basename(@url) end def read @stringio.read end def method_missing(name,*args) @stringio.send(name, *args) end end end
true
15c5d2445fd63d517aa49e7c45fbeb65f642fe8d
Ruby
michaelpmattson/substrings
/substrings.rb
UTF-8
864
4.46875
4
[]
no_license
dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"] def substrings(my_string, dictionary) #first, convert my_string to an array. my_array = my_string.downcase.split #make an output hash. output = Hash.new #make an each loop that looks at all items in the substring/dictionary array. dictionary.each do |substring| #check if the substring is in each item of my_array (using .include? method) my_array.each do |item| if item.include?(substring) #add to the Hash if output[substring] output[substring] += 1 else output[substring] = 1 end end end end #return the output hash return output end puts substrings("below", dictionary) puts substrings("Howdy partner, sit down! How's it going?", dictionary)
true
de0f65d2290db8cd23d799380f1638d6f7c8181a
Ruby
robfors/ruby-sumac
/lib/sumac/calls/remote_calls.rb
UTF-8
2,032
3.046875
3
[ "Apache-2.0" ]
permissive
module Sumac class Calls # Manages calls originating from the remote endpoint. # Keeps track of ongoing calls such that: # * a killed connection can wait for them to finish # * the connection can be set to the correct state when it knows all calls have completed # @api private class RemoteCalls # Build a new {RemoteCalls} manager. # @param connection [Connection] calls are to be made from # @return [RemoteCalls] def initialize(connection) @connection = connection @calls = {} end # Check if any ongoing calls exist. # @return [Boolean] def any? @calls.any? end # Processes a {Messages::CallRequest} message. # Called when a relevant message has been received by the messenger. # @param message [Messages::CallRequest] # @raise [ProtocolError] if an ongoing call aready exists with the id received # @return [void] def process_request_message(message) raise ProtocolError if @calls[message.id] call = RemoteCall.new(@connection) call.process_request_message(message) @calls[message.id] = call end # Processes a the response of a remote call that has returned. # @param call [RemoteCall] # @param quiet [Boolean] suppress any message to the remote endpoint # @return [void] def process_response(call, quiet: ) call.process_response unless quiet finished(call) end # Validate the received method and arguments for the call. # @param call [RemoteCall] # @return [Boolean] if request is valid (a response has not been sent) def validate_request(call) call.validate_request end private # Cleans up a call that has finished. # Removes it from the list of calls so a future call can use the same id. # @param call [RemoteCall] # @return [void] def finished(call) @calls.delete(call.id) end end end end
true
eae7252ba040bbeadf1ad26f4653a272010d1757
Ruby
marckm/firsthandonruby
/ruby_lang/5-enums.rb
UTF-8
417
3.40625
3
[ "MIT" ]
permissive
# symbols in ruby are quite like enums in C# # a symbol is declared with : # symbols are a representation to a unique location in memory # symbols are also very performant because they are precalculated def display_shape_name(shapeType) case shapeType when :square then puts "I am a square" when :circle then puts "I am a circle" when :rectangle then puts "I am a rectangle" end end display_shape_name(:circle)
true
f216cb00f63656521586d8ce2427520100d6d481
Ruby
BadzoProgra/rails-yelp-mvp
/db/seeds.rb
UTF-8
1,732
2.5625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts "Creating restaurants" la_comiti = {name: "La comitiva", address: "16 rue de la tour d'auvergne", phone_number: "0645268590", category: "french"} le_cond = {name: "Le condor", address: "4 rue mayran", phone_number: "0445268590", category: "french"} le_Syph = {name: "Le Siphonneur", address: "18 rue mayran", phone_number: "0445268590", category: "belgian"} ly = {name: "Chez Ly", address: "18 rue de rechechouard", phone_number: "0445265790", category: "chinese"} big_mama = {name: "Big mama", address: "4 rue de iéna", phone_number: "0645265790", category: "italian"} [la_comiti, le_cond, le_Syph, ly, big_mama].each do |attributes| restaurant = Restaurant.create!(attributes) puts "Created #{restaurant.name}" end puts "Finished" #Restaurant.create([{name: "La comitiva"}, {address: "16 rue de la tour d'auvergne", {phone_number: "0645268590"}, {category: "french"}]) #Restaurant.create({name: "Le condor"}, {address: "4 rue mayran", {phone_number: "0445268590"}, {category: "french"}]) #Restaurant.create({name: "Le condor"}, {address: "4 rue mayran", {phone_number: "0445268590"}, {category: "belgian"}]) #Restaurant.create({name: "Chez Ly"}, {address: "18 rue de rechechouard", {phone_number: "0445265790"}, {category: "chinese"}]) #Restaurant.create({name: "Big mama"}, {address: "4 rue de iéna"}, {phone_number: "0645265790"}, {category: "italian"}])
true
8d057ad0a5ab9ba49a37ed489292bb3237b06a17
Ruby
timkellogg/autoFB
/updateFB.rb
UTF-8
791
2.671875
3
[]
no_license
require 'rubygems' require 'selenium-webdriver' # Get user email print 'email:' email = gets.chomp! # Get user password print 'password:' password = gets.chomp! # Get user status print 'Status Update to Make' status = gets.chomp! # Set driver to Selenium for firefox & get address driver = Selenium::WebDriver.for :firefox driver.get "https://facebook.com" # Input email email_field = driver.find_element :name => "email" email_field.send_keys "#{email}" # Input password password_field = driver.find_element :name => "pass" password_field.send_keys "#{password}" password_field.submit() # Input status status_box = driver.find_element :name => "xhpc_message" status_box.send_keys "#{status}" status_box.submit() wait = Selenium::WebDriver::Wait.new(:timeout => 10) driver.quit
true
1301f6251c1d9bce570424848cb757235f3c013a
Ruby
kArTeL/Natty
/Dangerfile
UTF-8
2,175
2.65625
3
[]
no_license
# Sometimes it's a README fix, or something like that - which isn't relevant for # including in a project's CHANGELOG for example declared_trivial = github.pr_title.include? "#trivial" # Make it more obvious that a PR is a work in progress and shouldn't be merged yet warn("PR is classed as Work in Progress") if github.pr_title.include? "[WIP]" # Warn when there is a big PR warn("Big PR") if git.lines_of_code > 500 # Don't let testing shortcuts get into master by accident fail("fdescribe left in tests") if `grep -r fdescribe specs/ `.length > 1 fail("fit left in tests") if `grep -r fit specs/ `.length > 1 # Warn when library files has been updated but not tests. has_app_changes = !git.modified_files.grep(/Natty/).empty? tests_updated = !git.modified_files.grep(/NattyTest/).empty? ui_tests_updated = !git.modified_files.grep(/NattyUITest/).empty? if has_app_changes message "Project has app changes." end if tests_updated message "Project test were updated." end if ui_tests_updated message "Project UI test were changes." end if has_app_changes && (!tests_updated && !ui_tests_updated) warn("The Project files were changed, but the tests remained unmodified. Consider updating or adding to the tests to match the Project changes.") end # Mainly to encourage writing up some reasoning about the PR, rather than just leaving a title. if github.pr_body.length < 50 warn("Please provide a more detailed summary in the Pull Request description") end # Request a CHANGELOG entry, and give an example if !git.modified_files.include?('CHANGELOG.md') && has_app_changes fail("Please include a CHANGELOG entry to credit yourself! \nYou can find it at [CHANGELOG.md](https://github.com/kArteL/Natty/blob/master/CHANGELOG.md).", :sticky => false) markdown <<-MARKDOWN Here's an example of your CHANGELOG entry: ```markdown * #{github.pr_title}\s\s [#{github.pr_author}](https://github.com/#{github.pr_author}) [#issue_number or task] Link:(https://github.com/CocoaPods/CocoaPods/issues/issue_number) [#Description] Lorem ipsum lorem ipsum ``` *note*: There are two invisible spaces after the entry's text. MARKDOWN end # lint swiftlint.lint_files
true
10d65b96360d9c7994cd0aab73c914565e550882
Ruby
Mauricepwong/robotbay_T2A2
/app/controllers/robots_controller.rb
UTF-8
2,651
2.640625
3
[]
no_license
class RobotsController < ApplicationController # pull the specific robot from the database and sets it before a method is run. before_action :set_robot, only: %i[show edit update destroy] # prompts for login if user not signed in before_action :authenticate_user!, except: %i[index] # ensure user has permission to change that robot. before_action :access_robot, :sold_robots, only: %i[edit update destroy] rescue_from RuntimeError, with: :unauthorised # Unathorised method to only allow users to edit their own robots def unauthorised flash[:notice] = 'Unauthorised operation. Please try another option ' redirect_to robots_path end # Index page to list all robots that have not been sold yet. def index @robots = Robot.where.missing(:sale).order(params[:sort]) end # Initialise a new robot def new @robot = Robot.new end # Method to create robot def create @robot = Robot.new(robot_params) if @robot.save flash[:notice] = 'Robot was successfully created' redirect_to robots_path else redirect_to new_robot_path, flash[:alert] = 'Error saving robot. Please try again' end end def show end def edit end # Method to update a specific robot def update if @robot.update(robot_params) flash[:notice] = 'Robot was successfully updated' redirect_to @robot else redirect_to @robot, flash[:alert] = 'Error updating robot. Please try again' end end # Destroys a specific def destroy @robot.destroy flash[:notice] = 'Robot was successfully deleted' redirect_to robots_path end # Retrieves from database for a specific user the robots that they listed, have sold and purchased. def manage @current_robots = current_user.robots.where.missing(:sale) @sold_robots = current_user.sold_robots @purchased_robots = current_user.purchased_robots end private # Calls the database based on the params to find a specifc robot. def set_robot begin @robot = Robot.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:alert] = 'That robot does not exist' redirect_to robots_path end end # Prevent any user besides the owner to edit a robot def access_robot raise 'unauthorised' if current_user != @robot.user end def sold_robots if @robot.sold == true flash[:alert] = 'Robot has been sold and can no longer be updated' redirect_to robot_path(@robot) end end def robot_params params.require(:robot).permit(:name, :description, :price, :image, :user_id, category_ids: []) end end
true
81678185d89197b475bc77e59a4b14155e144f6a
Ruby
ecarlisle/nfg-fundraiser
/app/models/fundraiser.rb
UTF-8
247
2.609375
3
[]
no_license
class Fundraiser < ActiveRecord::Base def full_name [first_name, last_name].join(' ') end def percent_to_goal ((current_amount/goal_amount)*100).round end def image_file ([first_name, last_name].join('_') + ".jpg").downcase end end
true
ec1fa8b46b4ab9c8cd56d67970507cbc7c96dc76
Ruby
chrisvire/export-bsv-script
/export-bsv-script.rb
UTF-8
1,401
2.9375
3
[ "MIT" ]
permissive
require 'docx' require 'optparse' class String def is_integer? self.to_i.to_s == self end end ARGV << "-h" if ARGV.empty? $options = { :title => 'Title', :passage => '' } OptionParser.new do |opts| opts.banner = 'Usage: export_bsv_script.rb [options] FILENAME' opts.on('-t', '--title TITLE', 'Title of script') do |title| $options[:title] = title end opts.on('-p', '--passage PASSAGE', 'Passage of script') do |title| $options[:title] = title end opts.on_tail("-h", "--help", "Show this message") do puts opts exit end end.parse! if ARGV.empty? puts opts.help puts "At least one parameter required!" exit end filepath = ARGV[0] Dir.chdir(File.dirname(filepath)) file = File.basename(filepath) title = $options[:title] passage = $options[:passage] doc = Docx::Document.open(file) table = doc.tables[0] table.rows.each do |row| page = row.cells[0].nil? ? "" : row.cells[0].to_s if page == "T" title = row.cells[2].nil? ? title : row.cells[2].to_s passage = row.cells[3].nil? ? passage : row.cells[3].to_s elsif page.is_integer? Dir.mkdir(title) unless File.exists?(title) text = row.cells[2].nil? ? "" : row.cells[2].to_s ref = row.cells[3].nil? ? "" : row.cells[3].to_s File.open(File.join(title, page + ".txt"), "w+") do |f| f.write("#{title.strip}~#{passage.strip}~#{ref.strip}~#{text.strip}") end end end
true
264d25e7d467dad8d094f6e895be3daf8669c324
Ruby
tybenz/project-euler
/problem06.rb
UTF-8
114
2.859375
3
[]
no_license
list = *(1..100) sosq = list.inject(0) do |s, n| s += n * n end sqos = list.inject(:+) ** 2 puts sqos - sosq
true
7365756365a2111faeefc312834ed40171a0f90d
Ruby
zhusan/mower
/spec/models/mower_spec.rb
UTF-8
862
2.96875
3
[]
no_license
require 'spec_helper' require './models/lawn' require './models/mower' describe Mower do it "is valid with a direction" do mower = Mower.new(1, 2, "N") expect(mower).to be_valid end it "is valid with an invalid direction" do mower = Mower.new(1, 2, "A") expect(mower).not_to be_valid end it "move to a right direction" do mower = Mower.new(1, 2, "N") mower.set_direction_by_step('W') expect(mower.x).to eq 1 expect(mower.y).to eq 3 expect(mower.direction).to eq "N" end it "update direction only when step is L or R" do mower = Mower.new(1, 2, "N") mower.set_direction_by_step('L') expect(mower.x).to eq 1 expect(mower.y).to eq 2 expect(mower.direction).to eq "W" end it "is move out of lawn" do mower = Mower.new(0, 2, "W") expect(mower.move('M')).to eq false end end
true
3a1c6a1207e403433829327f2f698b988478992c
Ruby
rgilbert82/Data-Structures
/heap.rb
UTF-8
1,300
3.71875
4
[]
no_license
class Heap attr_reader :data def initialize(*values) @data = values max_heapify! end def sort! max_heapify! last = size - 1 while last > 0 @data[0], @data[last] = @data[last], @data[0] last -= 1 sift!(0, last) end @data end def sort Heap.new(*@data).sort! end def max_heapify! last_parent_idx = size / 2 - 1 last_parent_idx.downto(0) do |idx| self.sift!(idx, size - 1) end @data end def sift!(first, last) while first * 2 + 1 <= last swap = first child1 = first * 2 + 1 child2 = child1 + 1 if @data[swap] < @data[child1] swap = child1 end if child2 <= last && @data[swap] < @data[child2] swap = child2 end if first == swap return else @data[first], @data[swap] = @data[swap], @data[first] first = swap end end end def insert(value) @data.push(value) max_heapify! end def delete_at(idx) @data.delete_at(idx) max_heapify! end def delete(value) @data.delete(value) max_heapify! end alias :push :insert alias :<< :insert def size @data.size end alias :length :size def clear @data.clear end def to_s @data.to_s end end
true
82a9453134a602e0a14f2d802993bb0cd49fa1b0
Ruby
malev/freeling-client
/lib/freeling_client/token.rb
UTF-8
324
2.671875
3
[ "MIT" ]
permissive
module FreelingClient class Token attr_accessor :form, :lemma, :tag, :prob, :pos def initialize(opt = {}) @form = opt[:form] @lemma = opt[:lemma] @tag = opt[:tag] @prob = opt[:tag] end def [](key) key = key.to_sym if key.is_a? String self.send(key) end end end
true
21f78b5f9f60c4b87475ddcd22b3f47d9edca819
Ruby
yumayo14/character_game
/character_checker.rb
UTF-8
744
3.3125
3
[]
no_license
# frozen_string_literal: true class CharacterChecker attr_reader :characters def initialize(characters) @characters = characters end def best_characters characters.select { |character| character.attack + character.defence == highest_parameter } end def best_attackers characters.select { |character| character.attack == highest_attack_point } end def best_defenders characters.select { |character| character.defence == highest_defence_point } end private def highest_parameter characters.map { |character| character.attack + character.defence }.max end def highest_attack_point characters.map(&:attack).max end def highest_defence_point characters.map(&:defence).max end end
true
3b48dccba066453e983ad41ec773fe933e649995
Ruby
jeremiahkellick/terminal-chess
/pawn.rb
UTF-8
1,625
3.09375
3
[]
no_license
require_relative "add_pos" class Pawn < Piece def initialize(pos, board, color) super @vertical = color == :white ? -1 : 1 @promotion_row = color == :white ? 0 : 7 @first_time_pos_set = true @starting_row = nil end def pos=(value) super if @first_time_pos_set @starting_row = value[0] @first_time_pos_set = false end end def moves result = [] straight_positions.each do |pos| if @board.valid_pos?(pos) && @board[pos].null? result << pos else break end end diagonal_diffs.each do |diff| new_pos = add_pos(@pos, diff) if @board.valid_pos?(new_pos) piece = @board[new_pos] if (!piece.null? && piece.color != @color) || (piece.is_a?(EnPassantPiece) && piece.piece_to_destroy.color != @color) result << new_pos end end end result end def on_move(start_pos, end_pos) super if (start_pos[0] - end_pos[0]).abs > 1 @board[behind_pos] = EnPassantPiece.new(behind_pos, self) end @board.promote(self) if promotion_due? end def diagonal_diffs [[@vertical, -1], [@vertical, 1]] end def straight_diff [@vertical, 0] end def straight_positions if @pos[0] == @starting_row [add_pos(@pos, straight_diff), add_pos(@pos, [@vertical * 2, 0])] else [add_pos(@pos, straight_diff)] end end def letter "P" end def unicode "\u265F" end private def promotion_due? @pos[0] == @promotion_row end def behind_pos [pos[0] - @vertical, pos[1]] end end
true
e9e6e5c928fe67b8e9e7d020fd62a9e8fb0c9081
Ruby
kavinderd/todo
/lib/todo.rb
UTF-8
1,193
2.625
3
[ "MIT" ]
permissive
#TODO: Read PR article about require and require relative require_relative "todo/version" require_relative "todo/version" require_relative "todo/list" require_relative 'todo/presenter' module Todo class Application def initialize(persistent: false) @list = init_list(persistent) @presenter = Todo::Presenter.new end def add(name:, **options) @list.add(name: name, priority: options[:priority], list: options[:list]) end def finish(task_name, **options) if options[:list] access_list(options[:list]).finish(task_name) else @list.finish(task_name) end end def remove(task_name) @list.remove(task_name) end def tasks(options={}) item = options[:list] ? access_list(options[:list]) : @list return "no such list" unless item @presenter.present(item: item, info: :tasks, level: options[:level]) end def lists @presenter.present(item: @list, info: :lists) end def access_list(list_name) @list.access_list(list_name) end private def init_list(persistent) if persistent Todo::List.load else Todo::List.new end end end end
true
65171af1e6c761875710398124d272259f8c7b01
Ruby
fred84/calabash-extras
/test/walker_test.rb
UTF-8
3,427
2.953125
3
[]
no_license
require 'test/unit' require 'calabash-extras/walker' require 'calabash-extras/page_object_comparator' class WalkerTest < Test::Unit::TestCase class BaseDummyPage include Calabash::Extras::PageObjectComparator attr_accessor :will_match, :called, :back_called def initialize @called = false @back_called = false end def all_elements 'list of all elements in string' end def match(all_elements) @will_match end def go @called = true end def back @back_called = true end end class EulaDummyPage < BaseDummyPage; end class LoginDummyPage < BaseDummyPage; end class MainMenuDummyPage < BaseDummyPage; end class UnreachablePage < BaseDummyPage; end class DeadEndPage < BaseDummyPage; end class NonExistentPage < BaseDummyPage; end class RefundDummyPage < BaseDummyPage; end class OrderHistoryDummyPage < BaseDummyPage; end class OrderInfoDummyPage < BaseDummyPage; end def setup @eula = EulaDummyPage.new @login = LoginDummyPage.new @main_menu = MainMenuDummyPage.new @unreachable = UnreachablePage.new @not_existent = NonExistentPage.new @order_history = OrderHistoryDummyPage.new @order_info = OrderInfoDummyPage.new @refund = RefundDummyPage.new @matrix = { @eula => { @login => lambda { @eula.go }, }, @login => { @main_menu => lambda { @login.go }, @eula => lambda { @main_menu.back } }, @main_menu => { @login => lambda { @main_menu.back }, @order_history => lambda { @main_menu.go } }, @order_history => { @main_menu => lambda { @order_history.back }, @order_info => lambda { @order_history.go } }, @order_info => { @order_history => lambda { @order_info.back }, @refund => lambda { @order_info.go } }, @refund => { @order_info => lambda { @refund.back } }, @unreachable => { # unreachable } } @walker = Calabash::Extras::Walker.new(0, @matrix, lambda { |str| } ) end def test_refund_to_main_menu @refund.will_match = true @walker.go @main_menu assert_back_called @refund assert_back_called @order_info assert_back_called @order_history end def test_eula_to_refund_page @eula.will_match = true @walker.go @refund assert_called @eula assert_called @login assert_called @main_menu assert_called @order_history assert_called @order_info assert_called @order_info end def test_unreachable @eula.will_match = true err = assert_raise RuntimeError do @walker.go @unreachable end assert_equal 'Unable to find path from "%s" to "%s"' % [@eula, @unreachable.name], err.message end def test_not_found @eula.will_match = true err = assert_raise RuntimeError do @walker.go @not_existent end assert_equal 'Page "%s" does not exist' % [@not_existent], err.message end def test_unable_to_determine_current_page end private def assert_called (page, method = :go) assert page.called, 'Call to method "%s" of page %s was expected' % [method, page.name] end def assert_back_called (page) assert page.back_called, 'Call to method "back" of page %s was expected' % [page.name] end end
true
4a7b73e1f8218109508ea4f0aba40625680b8ed1
Ruby
Zimbra/zm-genesis
/src/ruby/reportResult.rb
UTF-8
2,366
2.578125
3
[]
no_license
#!/bin/env ruby # # $File$ # $DateTime$ # # $Revision$ # $Author$ # # 2006 Zimbra # # Test Summary Processing require "yaml" (resultFilePattern, suite, os, build, branch, type, url) = ARGV #resultFilePattern = "testsummary.txt" #suite = "SOAP" #os = "FC5" #branch = "main" #type = "SMOKE" #build = "20061107020101_FOSS" #h1 = { "a" => 100, "c" => 70} #h2 = { "a" => 250 } # #h3 = h1.merge(h2) do |key, oldval, newval| # oldval + newval #end #puts YAML.dump(h3) #Logging open('/tmp/report.txt','w') do |mfile| mfile.puts `pwd` mfile.puts resultFilePattern mfile.puts suite mfile.puts os mfile.puts branch mfile.puts type mfile.puts build end exit if [resultFilePattern, build].any? { |x| x.nil? } #Get statistic from a file and generate a Hash def getStat(fileName) result = Hash.new(0) counter = 0 while((File.size(fileName) == 0) && (counter < 60)) #wait for sixty seconds; ran into situation where file is open but zero sized sleep 1 counter = counter + 1 end File.open(fileName).each do |line| next if (line =~/^#/) mArray = line.chomp.split(/=|:/).map {|x| x.upcase} result[mArray.first] = result[mArray.first] + mArray[-1].to_i end return result end # Generate result file pattern base on input file name def getFilePattern(filePattern) return if filePattern.nil? File.split(filePattern).inject do |memo, obj| File.join(memo, obj.split(/\./).join('*.')) end end begin # Tally up the results result = Dir.glob(getFilePattern(resultFilePattern)).inject(Hash.new) do |memo, obj| memo.merge(getStat(obj)) do |key, oldval, newval| oldval.to_i + newval.to_i end end if(result.size > 0) mBuild, mBit = build.split('_') mCommand = "STAF zqa-tms-stax RESULT RECORD SUITE #{suite} OS #{os} BRANCH #{branch} BITS #{mBit} TYPE #{type} BUILD #{mBuild} "+ "PASSED #{result['PASSED']} FAILED #{result['FAILED']} ERRORS #{result['ERRORS']}" mCommand = mCommand + " URL #{url}" unless url.nil? open('/tmp/report.txt','a') do |mfile| mfile.puts mCommand mfile.puts `#{mCommand}` end else open('/tmp/report.txt','a') do |mfile| mfile.puts "No result" mfile.puts mCommand mfile.puts YAML.dump(result) end end rescue => e open('/tmp/report.txt','a') do |mfile| mfile.puts e.backtrace.join("\n") end end
true
936a558852b0cc36fbaec42482644141e2ad5ae2
Ruby
potatocommune/Ruby-Learn-to-program-Exercises
/chapter8/method.rb
UTF-8
348
3.59375
4
[]
no_license
def do_you_like_mexican_food(food) goodAnswer = false while (not goodAnswer) puts "Do you like eating #{food.to_s}?" answer = gets.chomp.downcase if (answer == 'yes' or answer == 'no') goodAnswer = true else puts 'Please answer "yes" or "no".' end end puts answer end do_you_like_mexican_food("quesadilla")
true
25f5ee503500d9293f3e46af6c47806da7e90806
Ruby
lethan/Advent-of-Code
/2018/day10.rb
UTF-8
1,162
3.03125
3
[]
no_license
file = File.open('input_day10.txt', 'r') points = [] while (line = file.gets) points << /position=<\s*(-?\d+),\s*(-?\d+)> velocity=<\s*(-?\d+),\s*(-?\d+)>/.match(line)[1..4].map(&:to_i) end file.close x_minmax = points.map(&:first).minmax area = (x_minmax[1] - x_minmax[0]).abs y_minmax = points.map { |a| a[1] }.minmax area += (y_minmax[1] - y_minmax[0]).abs new_area = area time = 0 until new_area > area area = new_area points.each do |point| point[0] += point[2] point[1] += point[3] end x_minmax = points.map(&:first).minmax new_area = (x_minmax[1] - x_minmax[0]).abs y_minmax = points.map { |a| a[1] }.minmax new_area += (y_minmax[1] - y_minmax[0]).abs time += 1 end points.each do |point| point[0] -= point[2] point[1] -= point[3] end x_minmax = points.map(&:first).minmax y_minmax = points.map { |a| a[1] }.minmax display = Array.new( (y_minmax[1] - y_minmax[0]).abs + 1){ Array.new( (x_minmax[1] - x_minmax[0]).abs + 1, false) } points.each do |point| display[ point[1] - y_minmax.first ][ point[0] - x_minmax.first ] = true end display.each do |out| puts out.map { |b| b ? '#' : ' ' }.join end puts time - 1
true
c9becc3ebb6d8c6838f60647045235085f6d56f9
Ruby
Lupeman/WDI_10_homework
/Jaime/WEEK4/d1/calculator-class.rb
UTF-8
587
3.4375
3
[]
no_license
require "pry" require "./calculator.rb" calculator = Calculator.new def get_info(calculator) puts "Enter the numbers you want to work with:" calculator.value1 = gets.chomp.to_i calculator.value2 = gets.chomp.to_i puts "Would you like to add, subtract, multiply, divide or quit?" calculator.operator_info = gets.chomp end get_info(calculator) calculator.perform_task def try_again puts "Anything else you want to work on? (y/n)" try_again_answer = gets.chomp if try_again_answer == "y" get_info elsif try_again_answer == "n" quit end end # binding.pry
true
5902a1002d02e7cab7a80f69e289da9957b9843d
Ruby
kyrasteen/sales_engine
/test/invoice_items_repository_test.rb
UTF-8
1,701
2.59375
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require_relative '../lib/invoice_item_repository' class InvoiceItemRepoTest < Minitest::Test def setup filename = './test/support/invoice_items_test_data.csv' @invoice_items = InvoiceItemRepo.new(filename, nil) end def test_it_finds_all assert_equal 19, @invoice_items.all.length end def test_it_can_find_by_id assert_equal "1", @invoice_items.find_by_id(1).id.to_s end def test_it_can_find_all_by_id assert_equal 2, @invoice_items.find_all_by_id(5).count end def test_it_can_find_by_invoice_id assert_equal "1", @invoice_items.find_by_invoice_id(1).invoice_id.to_s end def test_it_can_find_all_by_invoice_id assert_equal 8, @invoice_items.find_all_by_invoice_id(1).count end def test_it_can_find_by_created_at date = Date.parse('2012-03-27 14:54:09 UTC') assert @invoice_items.find_by_created_at(date).is_a?(InvoiceItem) end def test_it_can_find_all_by_created_at date = Date.parse('2012-03-27 14:54:09 UTC') assert_equal 19, @invoice_items.find_all_by_created_at(date).count end def test_it_can_find_by_updated_at date = Date.parse('2012-03-27 14:54:09 UTC') assert @invoice_items.find_by_updated_at(date).is_a?(InvoiceItem) end def test_it_can_find_all_by_updated_at date = Date.parse('2012-03-27 14:54:09 UTC') assert_equal 19, @invoice_items.find_all_by_updated_at(date).count end def test_it_can_find_by_quantity assert_equal 9, @invoice_items.find_by_quantity(9).quantity.to_i end def test_it_can_find_by_all_by_unit_price assert_equal 2, @invoice_items.find_all_by_unit_price(BigDecimal('72018')).count end end
true
b5ac5c6fc242f83eb21a9054adc1b4fe2f1d0a93
Ruby
hayduke19us/forgot_tmux
/lib/trail_head/setup.rb
UTF-8
1,480
2.953125
3
[]
no_license
require "course/simple_walk" require "course/auto_simple" require "course/complex_walk" require "course/auto_complex" require "trail_head/start" module Setup def self.initial_setup Start.find_bash puts %{We reccomend you remap your CAPS LOCK key to CTRL. In OS X this option is within your System Preferences/Keyboard options. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Linux takes a little more work but you can find out how to remap keys at http://www.emacswiki.org/emacs/MovingTheCtrlKey} puts puts %{We offer four kinds of setups: =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 1. Simple = .tmux.conf in HOME dir. inludes walk thru. 2. AutoSimple = .tmux.conf in HOME dir. No walk thru. 3. Complex = dotfiles dir setup with git repo and .tmux.conf. Walk thru. 4. AutoComplex = " ". No walk thru. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-= Choose a setup. (1|2|3|4)} setup_choice = gets.chomp.to_i unless setup_choice =~ (/\Aex|it\z/) setup_choice = setup_choice.to_i if setup_choice == 1 SimpleWalk.start elsif setup_choice == 2 AutoSimple.start elsif setup_choice == 3 ComplexWalk.start elsif setup_choice == 4 AutoComplex.start else puts "please make a selection of 1-4 or type 'exit' to quit." end else return end end end
true
48d4f6d01aed81b73759da4e0fe88eccc382c2db
Ruby
AmeliaFannin/euler
/euler-027.rb
UTF-8
1,570
4
4
[]
no_license
# Quadratic primes # Problem 27 # Euler discovered the remarkable quadratic formula: # n² + n + 41 # It turns out that the formula will produce 40 primes for the consecutive values # n = 0 to 39. # However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, # and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41. # The incredible formula n² − 79n + 1601 was discovered, # which produces 80 primes for the consecutive values n = 0 to 79. # The product of the coefficients, −79 and 1601, is −126479. # Considering quadratics of the form: # n² + an + b, where |a| < 1000 and |b| < 1000 # where |n| is the modulus/absolute value of n # e.g. |11| = 11 and |−4| = 4 # Find the product of the coefficients, a and b, for the quadratic expression # that produces the maximum number of primes for consecutive values of n, # starting with n = 0. # answer = -59231 # time = 6.686s require 'prime' def quads primes = 0 product = 0 -1000.upto(1000) do |a| Prime.each(1000) do |b| n = 0 last_prime = 0 until n == b num = (n * n) + (a * n) + b if num.prime? n += 1 last_prime = num else break end end # saves if number of primes is greater if n > primes product = a * b primes = n puts "Coefficients #{a},#{b}, #{primes} primes, last prime = #{last_prime}" end end end puts "#{primes} primes, product of coefficients is #{product}" end quads
true
71483932f3be432821c6b219519e6ed7231df74a
Ruby
woahdae/rush
/lib/rush/service.rb
UTF-8
7,157
3.375
3
[ "MIT" ]
permissive
## # === Creating new services # To create new services, you need to create two subclasses, one from this # (Rush::Service), and another from Rush::ServiceInstance. They must # be named Rush::Service::[ServiceName] and # Rush::Service::[ServiceName]Instance, respectively. # # Your Rush::Service subclass needs to define an +instances+ method # that checks the box to see what is already running (probably via bash's +ps+), # and creates an array of ServiceInstance subclasses representing what is running # on the server (see +instances+ documentation for more information). # # Your Rush::ServiceInstance subclass needs to define +start+, +stop+, # +status+, and possibly +restart+ (by default restart just calls +stop+ and # +start+). Also, to_s should be a form of semi-verbose status. For examlpe, # a Mongrel service instance would report "port - status" in to_s, and a Clusterip # instance would report "ip - status". class Rush::Service attr_accessor :name, :box ## # For creating new Rush::Service *subclass* instances. # # You can call new on a subclass to initialize a Service object # (e.g. Rush::Service::Mongrel.new(box)), or use # Rush::Service.factory. One is almost always cleaner than the other. # === Behaviors # * Stores all +*option+ values in their own instance variable # * stores the box, name, and options in instance variables # === Parameters # [+box+] A Rush::Box subclass instance, ex. Rush::RemoteBox # [+*options+] Options for creation on initializing the particular Service, # and that will be passed to the ServiceInstance objects it # initializes (via +instance+). # Ex, all mongrel service instances might need to know what # environment to run in. Thus, you could pass in :environment => # "development" to have all instances created by the service # run in development mode (via passing that option in at instance # creation). # # It is interesting to note that +*options+ can take unix-like # flags that will automatically be set to true in the options # hash. For example, # Service.new(box, :debug_mode, :environment => "development") # would produce an options hash of # {:debug_mode => true, :environment => "development"}. # Caveat: flags MUST come before key-value options. See # +Enumerable#to_options_hash+ for more info. # === Returns # Nothing in particular # === Raises # * RuntimeError if new is called from Rush::Service def initialize(box, *options) if self.class == Rush::Service raise "Cannot call new from Rush::Service - use factory instead" end @name = self.class.service_name @box = box initialize_options(self.class.final_options(*options)) end ## # Creates a new Rush::Service subclass instance based on the +name+ # parameter like "Rush::Service::Name" # # Ex. self.factory(:test, box) would call Rush::Service::Test.new(box) # === Parameters # [+name+] a symbol representing the service name, ex: +:mongrel+. # Note that it is not case sensitive (i.e. it capitalizes it # for you) # [+box+] a Rush::Box subclass instance (ex. Rush::RemoteBox) # [+*options+] Options to be passed to [Service].new # === Returns # Newly instantiated Rush::Service::[Name] object # === Raises # nothing def self.factory(name, box, *options) klass = "Rush::Service::#{name.to_s.capitalize}" Kernel.qualified_const_get(klass).new(box, *options) end ##### Instance Methods ##### ## # Creates an instance of the service using both the options set on this # service (which are usually defaults form a config file) as well as # +*options+ given. Anything in +*options+ will override this services # options. # # Note that this does not 'start' the instance on the box. Usage would be: # # mongrel_instance = box[:mongrel].instance(:port => 3000) # mongrel_instance.status => "not running" # mongrel_instance.start => true # mongrel_instance.status => "running" # # (note that box[:mongrel] is shorthand for Rush::Service.factory(:mongrel, box)) # === Parameters # [+*options+] Options for Rush::Service::[Service]Instance.new, e.g. :port or :ip # === Returns # A newly instantiated Rush::Service::[Service]Instance object # === Raises # nothing def instance(*options) all_options = @options.merge(options.to_options_hash) Rush::ServiceInstance.factory(@name, @box, all_options) end ## # Calls status on all of the ServiceInstances configured to be running # === Parameters # [+*options+] Passes these on to def status(*options) # TODO: this is *not* how it's supposed to work. This will only give the # status of all *running* instances. There is no way to define what is # /supposed/ to be running ATM, though. statuses = [] self.instances.each {|instance| statuses << instance.to_s} return statuses end ## # Migrates all of the services from the services' box to another # === Behaviors # * calls Rush::ServiceInstance#migrate on all instances of the service # on the box, passing +*options+ to each. # === Parameters # [+dst+] A Rush::Box subclass object (ex. Rush::RemoteBox) # [+*options+] Rush::ServiceInstance migrate options # === Returns # Nothing in partucular # === Raises # Nothing def migrate(dst, *options) self.instances.each { |instance| instance.migrate(dst, *options) } end # Needs to be defined in subclasses. Must return an array # of Rush::ServiceInstance subclass objects. def instances; end ##### Class Methods ##### def self.status(*boxes) statuses = {} $boxes.each {|box| statuses[box.host] = box[self.to_sym].status } return statuses end ##### Misc ##### def to_s puts status end def to_sym self.name.underscore.to_sym end def self.service_name self.to_s.split("::").last end def self.to_sym self.service_name.underscore.to_sym end ## # Merges author-defined default options from # Rush::Service::[Service]::DEFAULTS, config file options (usually from # ~/.rush/config.yml), and +*options+ into one options hash. # Author-defined defaults are loaded first and will be overwritten by any # options in the config file, which in turn will be overwritten by anything # passed into +*options+ # === Parameters # [+*options+] An array of options to be turned into an options hash. See # Enumerable#to_options_hash. # === Returns # A Hash containing the merging of options as described above. # === Raises # Nothing def self.final_options(*options) begin defaults = self::DEFAULTS rescue NameError defaults = {} end config_options = Rush::Config.load_yaml(:section => self.to_sym) these_options = options.to_options_hash final_options = defaults.merge(config_options).merge(these_options) end end
true
f2e3217c5cee9542d2f8031ecf76fc2ca8a4c720
Ruby
leetie/learn_ruby
/04_pig_latin/pig_latin.rb
UTF-8
1,343
3.9375
4
[]
no_license
#write your code here #def translate word # vowelArray = ["a", "e", "i", "o", "u", "y"] # wordArray = word.split("") # output = "" # vowelArray.each do |vowel| # if wordArray[0] == vowel # output = word + "ay" # return output # end # break # end # firstLetter = wordArray.slice!(0, 1) # puts firstLetter # wordArray.push(firstLetter) # puts wordArray # wordArray.join() + "ay" # end #square def translate_word(word) first_letter = word[0].downcase if word[0..1] == "qu" return word[2..-1] + word[0..1] + "ay" end if word[0] == "s" && word[1..2] == "qu" return word[3..-1] + word[0] + word[1..2] + "ay" end if ["a", "e", "i", "o", "u"].include?(first_letter) #translate word that starts with vowel "#{word}ay" else #translate word that starts with consonant(s) consonants = [] consonants << word[0] if["a", "e", "i", "o", "u"].include?(word[1]) == false consonants << word[1] if["a", "e", "i", "o", "u"].include?(word[2]) == false consonants << word[2] end end "#{word[consonants.length..-1] + consonants.join + "ay"}" end end def translate(string) a = string.split(" ") b = a.map {|word| translate_word(word)} b.join(" ") end puts translate_word("square")
true
b38bab0be354cf86b32e845a0296e4289f0f2cce
Ruby
emadb/playground
/ruby/fibo.rb
UTF-8
475
3.765625
4
[]
no_license
#!/usr/bin/ruby # def fibo(x) # f1 = 1 # f2 = 1 # fn = 1 # [2..x].each do |n| # fn = f1 + f2 # f2 = f1 # f1 = fn # puts "f1=#{f1} f2=#{f2} fn=#{fn}" # end # fn # end def fibo(x) @sq5 = Math.sqrt(5) @gm = (1 + @sq5) / 2 @gn = (1 - @sq5) / 2 return ((@gm**x - @gn**x) / @sq5).to_i end def run test_cases = STDIN.gets.to_i test_cases.times do |n| puts fibo(n) end end STDIN.gets.to_i.times { run }
true
b6ff82cd944c84d681bc30a028f8f8f5d6bca028
Ruby
zayneio/ghostchat
/app/models/group.rb
UTF-8
1,780
2.875
3
[]
no_license
require 'digest/md5' require 'encrypt_text' class Group < ApplicationRecord attr_accessor :expires_in has_secure_password validations: false has_many :users, dependent: :destroy # has_one :creator, class_name: "User", dependent: :destroy # accepts_nested_attributes_for :creator # accepts_nested_attributes_for :users # validates_associated :creator, on: :create has_many :messages, dependent: :destroy validates :title, presence: true, uniqueness: {case_sensitive: false} validates :expires_in, numericality: {:greater_than => 0, :less_than_or_equal_to => 1440} before_validation :sanitize, :slugify before_create :set_expiration #takes input of group's password (after authentication) and creates a key def self.set_group_key(password) # EncryptText.encrypt_key(Digest::MD5.hexdigest(password + ENV["message_key"])) ENV["message_key"] end #gets the encryption key based off what's stored in the user's session def self.get_group_key(session) # EncryptText.decrypt_key(session) session end def to_param self.slug end def slugify self.slug = self.title.downcase.gsub(" ", "-") end def sanitize self.title = self.title.strip end def set_expiration self.expiration = Time.now + self.expires_in.to_i.minutes end def self.check_expired Group.where('expiration < ?', Time.now).destroy_all end def random_title randtitle = RandomNouns.sample until !Group.pluck(:title).include? randtitle do randtitle = RandomNouns.sample end self.title=randtitle end def self.checkvalid(g) #check if exist if g.nil? return false #expired? elsif g.expiration < Time.now g.destroy return false else return true end end end
true
cd0ac7c1cce1fb3b811bcf0af81fb4b1d344394e
Ruby
victor-am/ruby_detective
/lib/ruby_detective/ast/nodes/query.rb
UTF-8
2,565
2.71875
3
[ "MIT" ]
permissive
module RubyDetective module AST module Nodes class Query attr_reader :node def initialize(node) @node = node end # TODO: accept multiple criteria def where(criteria = {}) case when criteria.key?(:type) type_validation_function = ->(node) { node.type == criteria[:type] } deep_search(node, [type_validation_function]) else deep_search(node) end end # TODO: ignore constant definitions, only return constant references def constant_references(where: {}) constants = deep_search(node, [:constant_reference_node?]) case when where.key?(:namespace) constants.select { |c| c.namespace.include?(where[:namespace].to_sym) } else constants end end # TODO: ignore constant definitions, only return constant references # This finds all constants, ignoring the nested ones. # For example: # The "Foo::Bar" code contain two constants, but this method will only bring # up one (the Bar one), with access to it's full path. def top_level_constant_references(where: {}) constants = deep_search(node, [:constant_reference_node?, :top_level_constant?]) case when where.key?(:namespace) constants.select { |c| c.namespace.include?(where[:namespace].to_sym) } else constants end end def class_declarations deep_search(node, [:class_declaration_node?]) end private def deep_search(node, validation_methods = [], acc: []) return if node.value_node? validation_result = validation_methods.map do |validation_method| if validation_method.is_a?(Symbol) node.respond_to?(validation_method) && node.public_send(validation_method) elsif validation_method.is_a?(Proc) begin validation_method.call(node) rescue NoMethodError false end else raise ArgumentError, "Unexpected validation method data type" end end # Only appends the node to the results if all validations passed acc << node if validation_result.all? node.children.each { |child| send(__method__, child, validation_methods, acc: acc) } acc.uniq end end end end end
true
412e9b5b8fa077a7a4e7f9d60dfa52a786e99728
Ruby
mjburgess/public-notes
/ruby-notes/00.Overview/01.Overview-Course.rb
UTF-8
1,340
3.125
3
[]
no_license
puts "PURPOSE: To Learn Ruby Programming " puts "OBJECTIVE: To complete 14 modules in ruby, as below. " puts "INTRODUCTIONS: Hello! " puts "EXPERIENCE: What relevant experience do you have?" puts "APPLICATIONS: How will you use ruby? " puts puts "SCHEDULE" puts puts "QA RUBY PROGRAMMING -- FOUR DAY" puts %w{ 08.00-17.00 8.00-09.30 BREAK 09.45-11.15 BREAK 11.30-12.45 BREAK 13.30-15.00 } # 9.30am - 4pm: 9.30-11.00 B 11.15-12.30am B 13.15-14.30 B 14.45-16.00 # TO DO: REVISE -- TOO MANY MODULES FOR 4D puts puts puts " D T Ch Title " puts puts " 1 AM 1 Introduction " puts " 1 AP 2 Fundamentals " puts " 1 PM 3 Flow" puts " 2 AM 4 Strings ~11.00" puts " 2 AM 5 Collections ~12.30" puts " 2 PM 6 Iteration ~14.30" puts " 2 PM 8 Regex* ~16.15" puts " 3 AM 9 Def " puts " 3 AM 10 Class " puts " 3 PM 11 Include " puts " 3 PM 12 Errors " puts puts " 4 AM 7 Persistence ~11" puts " 4 AM 13 Multitasking ~12.30" puts " 4 AP 15 REVIEW ~13.30" puts "EXTRA: Libraries" puts puts "PROCESS: ~1h 30m / module" puts "1. demonstration 1 h " puts "2. review notes: pptx, .rb 5 m " puts "3. independent exercise 20 m " puts "4. review exercise 5 m "
true
37ca9b93497aba449468d37942a7c0f6e2bec8f1
Ruby
liyunlunaomi123/conference_plan
/lib/conference_plan/track.rb
UTF-8
2,458
2.984375
3
[]
no_license
# frozen_string_literal: true module ConferencePlan class Track attr_reader :date attr_accessor :morning, :lunch, :afternoon, :networking_event def initialize(date) @date = date end def arrange_talks(talks_per_track) @total_time = talks_per_track.map(&:talk_length).inject do |sum, talk_length| sum + talk_length end raise 'Do not have enough talks for one day plan' if @total_time < 6 * 60 get_morning_plan(talks_per_track) get_lunch_plan get_afternoon_plan(talks_per_track) get_networking_event_plan end def get_morning_plan(talks_per_track) # get morning plan from 9am morning_talks = get_morning_talks(talks_per_track, 3 * 60) morning_talks.first.time = Time.new(date.year, date.month, date.day, 9, 0) @morning = morning_talks.each_with_index.inject([]) do |arr, (talk, i)| unless i == 0 pre_talk = morning_talks[i - 1] talk.time = pre_talk.time + pre_talk.talk_length * 60 end arr << talk end end def get_lunch_plan @lunch = Talk.new('Lunch 60min') lunch.time = Time.new(date.year, date.month, date.day, 12, 0) end def get_afternoon_plan(talks_per_track) # get afternoon plan from 1pm afternoon_talks = talks_per_track.reject { |talk| morning.include?(talk) } afternoon_talks.first.time = Time.new(date.year, date.month, date.day, 13, 0) @afternoon = afternoon_talks.each_with_index.inject([]) do |arr, (talk, i)| unless i == 0 pre_talk = afternoon_talks[i - 1] talk.time = pre_talk.time + pre_talk.talk_length * 60 end arr << talk end end def get_networking_event_plan @networking_event = Talk.new('Networking Event 60min') networking_event.time = afternoon.last.time + afternoon.last.talk_length * 60 end def get_morning_talks(talks_per_track, morning_session_time) (1..talks_per_track.size).each do |combination_size| talks_per_track.combination(combination_size).each do |combination| if combination.map(&:talk_length) .inject { |sum, talk_length| sum + talk_length } == morning_session_time return combination end end end raise 'Can not fill in morning session' end end end
true
95ee2d7fd2d09a65f5f4c147675bde2521d8585c
Ruby
jeanlazarou/swiby
/demo/word_puzzle/puzzle_server.rb
UTF-8
10,427
2.78125
3
[]
no_license
#-- # Copyright (C) Swiby Committers. All rights reserved. # # The software in this package is published under the terms of the BSD # style license a copy of which has been included with this distribution in # the LICENSE.txt file. # #++ require 'thread' require 'mongrel' require 'cgi/session' require 'puzzle/grid_factory' class Collaborator EVENT_BATCH_SIZE = 10 attr_accessor :other, :grid, :lang def initialize @events = [] @lock = Mutex.new end def push_event ev @lock.synchronize do @events << ev end end def dequeue_events message = "" @lock.synchronize do EVENT_BATCH_SIZE.times do ev = @events.shift break unless ev message += "\n" if message.length > 0 message += ev end end return message if message.length > 0 nil end def clear_queue @lock.synchronize do @events.clear @events << 'broken' end end def disconnect @lock.synchronize do if @other @other.other = nil @other.clear_queue end @events.clear @other = nil end end end # Enhance Mongrel's wrapper to make it more uniform with the HttpResponse class class Mongrel::CGIWrapper def write data self.out { data } end def start head = {} yield head, self header(head['Content-Type']) end end class PuzzleBaseHandler < Mongrel::HttpHandler DEFAULT_TIMEOUT = 120 # 120 sec = 2 minutes @@available = [] @@lock_collab = Mutex.new @@lock_builder = Mutex.new def initialize config @config = config end def process(request, response) cgi = Mongrel::CGIWrapper.new(request, response) session = CGI::Session.new(cgi, 'database_manager' => CGI::Session::MemoryStore) process_for_session session, request, cgi end def parameters request request.body.rewind s = request.body.readlines.join Mongrel::HttpRequest.query_parse(s) end def language request, out params = parameters(request) lang = params["lang"] lang = 'en' unless lang unless lang == 'en' or lang == 'fr' out.write 'unsupported' return nil end lang end def heartbeat session session[:registered] = Time.now + @config.connection_timeout end def next_available lang @@lock_collab.synchronize do index = nil i = 0 @@available.each do |collab| if collab.lang == lang index = i break end i += 1 end @@available.delete_at(index) if index end end def add_available collab @@lock_collab.synchronize { @@available << collab } end def delete_available collab @@lock_collab.synchronize { @@available.delete collab } end def send text, session, response heartbeat session response.start do |head, out| head["Content-Type"] = "text/plain" out.write text end end def send_grid request, response response.start do |head, out| lang = language(request, out) return unless lang head["Content-Type"] = "text/plain" out.write grid_message(lang) end end def grid_message lang @@lock_builder.synchronize do unless @en_factory @en_factory = GridFactory.new @fr_factory = GridFactory.new @fr_factory.change_language :fr end if lang == 'fr' grid = @fr_factory.create else grid = @en_factory.create end msg = "#{grid.cols};#{grid.rows};" grid.each_line do |line| line.each do |row, col| msg += grid[row, col] end end msg += ';' grid.each_word do |word| msg += "#{word.text};#{word.reverse?};#{word.slot.join(';')};" end msg end end end class NewPuzzleHandler < PuzzleBaseHandler def process(request, response) @config.log_basic "Processing new grid request" send_grid request, response end end class RegisterHandler < PuzzleBaseHandler def process_for_session session, request, response @config.log_basic "Processing register request" response.start do |head, out| head["Content-Type"] = "text/plain" if session[:registered] and Time.now > session[:registered] delete_available session[:collab] session[:registered] = nil end if session[:registered] out.write 'love' else out.write 'welcome' session[:collab] = Collaborator.new add_available session[:collab] end end heartbeat session end end class UnregisterHandler < PuzzleBaseHandler def process_for_session session, request, response @config.log_basic "Processing unregister request" response.start do |head, out| head["Content-Type"] = "text/plain" if session[:registered] collab = session[:collab] collab.disconnect delete_available collab # in case no collaboration was happening out.write 'bye' session.delete else out.write 'error' end end end end class CollaborateHandler < PuzzleBaseHandler def process_for_session session, request, response @config.log_detail "Processing collaborate request" response.start do |head, out| head["Content-Type"] = "text/plain" lang = language(request, out) return unless lang collab = session[:collab] return collab unless collab # the client unregistered while asking for a collaboration... if collab.other out.write collab.other.grid else collab.lang = lang delete_available collab other = next_available(lang) if other grid = grid_message(lang) collab.grid = grid other.grid = grid collab.other = other other.other = collab out.write grid else add_available collab out.write 'none' end end end heartbeat session end end class EventHandler < PuzzleBaseHandler def process_for_session session, request, response @config.log_detail "Processing event request" other = session[:collab].other if other ev = parameters(request)['event'] other.push_event(ev) if ev and ev.length > 0 @config.log_detail " event -> #{ev}" send 'ok', session, response else send 'error', session, response end end end class ConsumeHandler < PuzzleBaseHandler def process_for_session session, request, response @config.log_detail "Processing consume request" collab = session[:collab] ev = collab.dequeue_events if ev send ev, session, response else send 'none', session, response end end end class PuzzleServer def initialize timeout = PuzzleBaseHandler::DEFAULT_TIMEOUT, host = '127.0.0.1', port = 3000, log_level = :basic @timeout = timeout @host = host @port = port @log_level = log_level end def start silent = false port = @port host = @host timeout_duration = @timeout @config = Mongrel::Configurator.new(:host => @host) do @timeout_duration = timeout_duration if silent def self.log msg end end def self.log_basic msg log msg end def self.log_detail msg log msg if @log_level == :detail end log "Starting server (#{host}:#{port})" listener :port => port do uri "/puzzle/new", :handler => NewPuzzleHandler.new(self) uri "/puzzle/register", :handler => RegisterHandler.new(self) uri "/puzzle/unregister", :handler => UnregisterHandler.new(self) uri "/puzzle/collaborate", :handler => CollaborateHandler.new(self) uri "/puzzle/event", :handler => EventHandler.new(self) uri "/puzzle/consume", :handler => ConsumeHandler.new(self) end trap("INT") do log "Shutting down..." stop end def self.connection_timeout @timeout_duration end run end end def stop @config.log "Shutting down..." @config.stop end end if $0 == __FILE__ require 'optparse' options = {:host => '127.0.0.1', :port => 3000, :timeout => PuzzleBaseHandler::DEFAULT_TIMEOUT, :log_level => :basic} parser = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.on("-h", "--host name", "HTTP host name/ip for the server") do |h| options[:host] = h end opts.on("-p", "--port num", "HTTP port for the server") do |p| options[:port] = p.to_i end opts.on("-t", "--timeout duration", "Timeout for client session (in sec)") do |t| options[:timeout] = t.to_i end opts.on("-l", "--log level", [:basic, :detail], "Level of logging is basic or detail") do |level| options[:log_level] = level end end parser.parse! server = PuzzleServer.new(options[:timeout], options[:host], options[:port], options[:log_level]) server.start.join end
true
45d045b097d87a22ffd2b3714344f2cb8352ae92
Ruby
alejandro-mr/data-structures-practice
/ruby/linked_list/singly_linked_list/SinglyLinkedList.rb
UTF-8
2,087
3.65625
4
[]
no_license
class LinkedList def initialize(head = nil) @head = head if head @count = 1; else @count = 0; end end def getCount @count end def print_list _current = @head unless _current puts "List is empty!" else while _current do puts "Node: #{_current.getValue}" _current = _current.getNext end end end def insert(node) unless @head @head = node @count += 1 else _current = @head while _current.getNext do _current = _current.getNext end _current.setNext(node) @count += 1 end end def insert_beginning(node) unless @head @head = node @count += 1 else node.setNext(@head) @head = node @count += 1 end end def insert_after(node, afterNode) _current = @head if _current.getValue == afterNode.getValue node.setNext(_current.getNext) _current.setNext(node) @count += 1 else while _current && _current.getNext do if _current.getNext.getValue == afterNode.getValue node.setNext(_current.getNext.getNext) _current.getNext.setNext(node) @count += 1 return else _current = _current.getNext end end end end def remove(node) if @head && @head.getValue == node.getValue @head = @head.getNext @count -= 1 else _current = @head while _current && _current.getNext do if _current.getNext.getValue == node.getValue _current.setNext(_current.getNext.getNext) @count -= 1 else _current = _current.getNext end end end end def pop _current = @head if _current && !_current.getNext @head = nil @count = 0 else while _current && _current.getNext do unless _current.getNext.getNext _current.setNext(nil) @count -= 1 return else _current = _current.getNext end end end end end
true
35753a712ac29ead6db85c848148bdd78f70929d
Ruby
ihsaneddin/ripple-lib-rpc-ruby
/lib/ripple/methods/transaction.rb
UTF-8
6,693
2.5625
3
[ "ISC" ]
permissive
module Ripple module Methods module Transaction # # TODO # The book_offers method retrieves a list of offers, also known as the order book, between two currencies # options are: # ledger_hash String (Optional) A 20-byte hex string for the ledger version to use. (See Specifying a Ledger) # ledger_index String or Unsigned Integer (Optional) The sequence number of the ledger to use, or a shortcut string to choose a ledger automatically. (See Specifying a Ledger) # limit Unsigned Integer (Optional) If provided, the server does not provide more than this many offers in the results. The total number of results returned may be fewer than the limit, because the server omits unfunded offers. # taker String (Optional) The Address of an account to use as a perspective. Unfunded offers placed by this account are always included in the response. (You can use this to look up your own orders to cancel them.) # taker_gets Object Specification of which currency the account taking the offer would receive, as an object with currency and issuer fields (omit issuer for XRP), like currency amounts. # taker_pays Object Specification of which currency the account taking the offer would pay, as an object with currency and issuer fields (omit issuer for XRP), like currency amounts. # def book_offers opts=[] end def prepare_sign(opts={}) params = { secret: client_secret, offline: opts[:offline] || false, tx_json: { 'TransactionType' => opts[:transaction_type] || 'Payment', 'Account' => client_account, 'Destination' => opts[:destination], 'Amount' => opts[:amount], } } if opts.key?(:SendMax) and opts.key?(:Paths) # Complex IOU send params[:tx_json]['SendMax'] = opts[:SendMax] params[:tx_json]['Paths'] = opts[:Paths] end if opts.key?(:DestinationTag) params[:tx_json]['DestinationTag'] = opts[:DestinationTag] end if opts.key?(:InvoiceID) params[:tx_json]['InvoiceID'] = opts[:InvoiceID] end params end # Parameters for opts # tx_json Object Transaction definition in JSON format # secret String (Optional) Secret key of the account supplying the transaction, used to sign it. Do not send your secret to untrusted servers or through unsecured network connections. Cannot be used with key_type, seed, seed_hex, or passphrase. # seed String (Optional) Secret key of the account supplying the transaction, used to sign it. Must be in base58 format. If provided, you must also specify the key_type. Cannot be used with secret, seed_hex, or passphrase. # seed_hex String (Optional) Secret key of the account supplying the transaction, used to sign it. Must be in hexadecimal format. If provided, you must also specify the key_type. Cannot be used with secret, seed, or passphrase. # passphrase String (Optional) Secret key of the account supplying the transaction, used to sign it, as a string passphrase. If provided, you must also specify the key_type. Cannot be used with secret, seed, or seed_hex. # key_type String (Optional) Type of cryptographic key provided in this request. Valid types are secp256k1 or ed25519. Defaults to secp256k1. Cannot be used with secret. Caution: Ed25519 support is experimental. # offline Boolean (Optional, defaults to false) If true, when constructing the transaction, do not try to automatically fill in or validate values. # build_path Boolean (Optional) If provided for a Payment-type transaction, automatically fill in the Paths field before signing. Caution: The server looks for the presence or absence of this field, not its value. This behavior may change. # fee_mult_max Integer (Optional, defaults to 10; recommended value 1000) Limits how high the automatically-provided Fee field can be. Signing fails with the error rpcHIGH_FEE if the current load multiplier on the transaction cost is greater than (fee_mult_max ÷ fee_div_max). Ignored if you specify the Fee field of the transaction (transaction cost). # fee_div_max Integer (Optional, defaults to 1) Signing fails with the error rpcHIGH_FEE if the current load multiplier on the transaction cost is greater than (fee_mult_max ÷ fee_div_max). Ignored if you specify the Fee field of the transaction (transaction cost). New in: rippled 0.30.1 # # :tx_blob // Optional. Replaces all other parameters. Raw transaction # :transaction_type // Optional. Default: 'Payment' # :destination // Destination account # :amount // Ammount to send # :SendMax // Optional. Complex IOU send # :Paths // Optional. Complex IOU send def sign(opts = {}) post(:sign, prepare_sign(opts)) end # Parameters for opts # :tx_blob // Optional. Replaces all other parameters. Raw transaction # :transaction_type // Optional. Default: 'Payment' # :destination // Destination account # :amount // Ammount to send # :SendMax // Optional. Complex IOU send # :Paths // Optional. Complex IOU send def submit(opts = {}) params = { secret: client_secret, } if opts.key?(:tx_blob) params.merge!(opts) else params.merge!({tx_json: { 'TransactionType' => opts[:transaction_type] || 'Payment', 'Account' => client_account, 'Destination' => opts[:destination], 'Amount' => opts[:amount] }}) if opts.key?(:SendMax) and opts.key?(:Paths) # Complex IOU send params[:tx_json]['SendMax'] = opts[:SendMax] params[:tx_json]['Paths'] = opts[:Paths] end if opts.key?(:DestinationTag) params[:tx_json]['DestinationTag'] = opts[:DestinationTag] end if opts.key?(:InvoiceID) params[:tx_json]['InvoiceID'] = opts[:InvoiceID] end end # puts "Submit: " + params.inspect post(:submit, params) end def transaction_entry(opts={}) params = { tx_hash: tx_hash, ledger_index: ledger_index } post(:transaction_entry, params) end def tx(tx_hash) post(:tx, {transaction: tx_hash}) end def tx_history(start = 0) post(:tx_history, {start: start}) end end end end
true
3cd579848dd5f91a6b0d7b638713878d3801880f
Ruby
tactppp/intern_training_algorithm
/poker_step4.rb
UTF-8
2,619
3.8125
4
[]
no_license
require './draw_hand.rb' tehuda_card = draw_hand def card_suite(card) case card[0] when "S" kono_suite = "スペード" when "H" kono_suite = "ハート" when "D" kono_suite = "ダイヤ" when "C" kono_suite = "クラブ" end return kono_suite end def card_num(card) if card[1,2].to_i > 0 kono_num = card[1,2] else case card[1,1] when "A" kono_num = "エース" when "K" kono_num = "キング" when "Q" kono_num = "クイーン" when "J" kono_num = "ジャック" end end return kono_num end def draw_card(a) suite = card_suite(a) num = card_num(a) card_string = suite + num return card_string end def pair(card) pair_count = 0 for i in 0..card.length-2 do for j in i+1..card.length-1 do if card[i][1,2]==card[j][1,2] pair_count += 1 end end end return pair_count end def straight(card) a = [] for i in 0..4 do a[i] = num_hantei(card[i]).to_i end a.sort! if a[0]==1&&a[1]==10&&a[2]==11&&a[3]==12&&a[4]==13 return true end for i in 0..a.length-2 do if a[i]+1 != a[i+1] return false end end return true end def num_hantei(num) case num[1,2] when "A" return 1 when "K" return 13 when "Q" return 12 when "J" return 11 else return num[1,2] end end def flash(card) for i in 1..card.length-1 do if card[0][0]!=card[i][0] return false end end return true end def straight_flash(card) if straight(card) && flash(card) return true else return false end end def royal_straight_flash(card) royal = [] for i in 0..4 do royal[i] = num_hantei(card[i]).to_i end royal.sort! if royal[0]==1&&royal[1]==10&&royal[2]==11&&royal[3]==12&&royal[4]==13&&flash(hand) return true end return false end def hand_hantei(hand) kaburi = pair(hand) if royal_straight_flash(hand) poker_hand = "ロイヤルストレートフラッシュ" elsif straight_flash(hand) poker_hand = "ストレートフラッシュ" elsif kaburi == 6 poker_hand = "フォーカード" elsif kaburi == 4 poker_hand = "フルハウス" elsif flash(hand) poker_hand = "フラッシュ" elsif straight(hand) poker_hand = "ストレート" else case kaburi when 1 poker_hand = "ワンペア" when 2 poker_hand = "ツーペア" when 3 poker_hand = "スリーカード" else poker_hand = "ブタ" end end return poker_hand end puts hand_hantei(tehuda_card) tehuda_card.each do |card| puts draw_card(card) end
true
9f54d2d052b108ec4c70608250e380108e28194d
Ruby
remiodufuye/oo-relationships-practice-dc-web-102819
/app/models/guest.rb
UTF-8
919
3.359375
3
[]
no_license
class Guest @@all = [] attr_reader :name def initialize (name) @name = name @@all = self end def self.all @@all end def trips Trip.all.select do |trip| trip.guest == self end end def listings self.trips.map do |trip| trip.listing end.uniq end def trip_count self.trips.length end def self.find_all_by_name(new_name) self.all.select do |guest| guest.name == new_name end end def self.pro_traveller_help Trip.all.map do |trips| trips.guest.name end end def self.pro_traveller pro_travel_hash = self.pro_traveller_help.reduce(Hash.new(0)) { |a, b| a[b] += 1; a } pro_travel_hash.select {|k,v| v > 1} pro_travel_hash.keys end end
true
bb9b128a562ae2cb35d3a0f502de1390d73921d0
Ruby
mshkdm/wikipedia-scrapper
/hello-world.rb
UTF-8
298
2.65625
3
[ "MIT" ]
permissive
require "open-uri" # puts open("https://en.wikipedia.org/wiki/Ada_Lovelace").read # puts open("http://nytimes.com").read remote_base_url = "https://en.wikipedia.org/wiki" remote_page_name = "Ada_Lovelace" remote_full_url = remote_base_url + "/" + remote_page_name puts open(remote_full_url).read
true
5b710ccfc5a9b226138f087621a2a7eabd6bcdd6
Ruby
sds/scss-lint
/lib/scss_lint/linter/placeholder_in_extend.rb
UTF-8
976
2.71875
3
[ "MIT" ]
permissive
module SCSSLint # Checks that `@extend` is always used with a placeholder selector. class Linter::PlaceholderInExtend < Linter include LinterRegistry def visit_extend(node) # Ignore if it cannot be statically determined that this selector is a # placeholder since its prefix is dynamically generated return if node.selector.first.is_a?(Sass::Script::Tree::Node) # The array returned by the parser is a bit awkward in that it splits on # every word boundary (so %placeholder becomes ['%', 'placeholder']). selector = node.selector.join if selector.include?(',') add_lint(node, 'Avoid comma sequences in `@extend` directives; ' \ 'prefer single placeholder selectors (e.g. `%some-placeholder`)') elsif !selector.start_with?('%') add_lint(node, 'Prefer using placeholder selectors (e.g. ' \ '%some-placeholder) with @extend') end end end end
true
83b77d3dc5be01bd8c7ed061eab3886cf57af01d
Ruby
troygnichols/zark-billing-api
/app/commands/authenticate_user.rb
UTF-8
794
2.6875
3
[]
no_license
class AuthenticateUser prepend SimpleCommand def initialize(email, password) @email = email @password = password end def call if user = find_user AuthenticateUser.response_content(user) else nil end end def AuthenticateUser.response_content(user) { token: create_token(user), profile: user.attributes.slice( 'id', 'name', 'email', 'address', 'created_at', 'updated_at') } end def AuthenticateUser.create_token(user) JSONWebToken.encode(user_id: user.id) end private attr_accessor :email, :password def find_user user = User.find_by(email: email, active: true) return user if user && user.authenticate(password) errors.add :user_authentication, 'invalid credentials' nil end end
true
a2e1394a01b028d1f8305b463b7fd709b89e0382
Ruby
hangmanandhide/aA-Pair-Programming-Projects
/W2D1/Chess/NullPiece.rb
UTF-8
149
2.609375
3
[]
no_license
class NullPiece < Piece attr_reader :color, :symbol include Singleton def initialize @color = "rainbow" @symbol = :sunshine end end
true
a9a1a6d40746809f46e95ee19d0cfb407a093338
Ruby
MrMicrowaveOven/AlgorithmsCurriculum
/Heap.rb
UTF-8
738
3.6875
4
[]
no_license
class MinHeap def initialize(&prc) @values = [] prc ||= Proc.new {|x,y| x <=> y} @comparator = prc end def min @values.first end def pop popped = @values.shift heapify_up! popped end def swap(key1, key2) @values[key1], @values[key2] = @values[key2], @values[key1] end def parent(child_index) parent_index = (child_index - 1)/2 @values(parent_index) end def children(parent_index) child_index1 = 2*parent_index + 1 child_index2 = 2*parent_index + 2 child1, child2 = @values[child_index1], @values[child_index2] [child1, child2] end def insert @values.push heapify_up! end private def heapify_up! end def heapify_down! end end
true
8614c6d4fbaca43deaa4c15fd82f97cd3252281a
Ruby
susanev/advent-of-code
/2016/day03/part1.rb
UTF-8
440
3.625
4
[]
no_license
class Part1 def initialize(file_name) @count = 0 processFile(file_name) output end def processFile(file_name) File.open(file_name, "r") do |f| f.each_line do |line| validTriangle(line.chomp.split(" ").map(& :to_i)) end end end def validTriangle(sides) max = sides.max if sides.reduce(:+) - max > max @count += 1 end end def output puts "#{@count} possible triangles" end end Part1.new("input.txt")
true
ca8cbb52f6f44080e9210414e916e5d0109768f6
Ruby
antonhalim/green_grocer-bk-002-public
/grocer.rb
UTF-8
1,974
3.234375
3
[]
no_license
require 'pry' require 'pry-nav' def consolidate_cart(cart:[]) foodhash = {} ## cart.each_with_objec({}) do |carthash, new_cart_hash| cart.each do |food| #cart is the array food = each index in array {"tempeh"=>} food.each do |food_name, attribute_hash| #food_name = "TEMPEH" attribute_hash = ":price" foodhash[food_name] ||= attribute_hash foodhash[food_name][:count] ||= 0 foodhash[food_name][:count] +=1 end end foodhash end def apply_coupons(cart:[], coupons:[]) coupons.each do |coupon_hash| # coupon [{:item => "AVOCADO", :num => 2, :cost => 5.0}] coupon_hash.each do |coupon_keys, coupon_values| # :item, :num, :cost ---- #"AVOCADO", 2, 5.0 if cart.keys.include?(coupon_values) && coupon_hash[:num] <= cart[coupon_values][:count] cart[coupon_values][:count] -= coupon_hash[:num] cart[coupon_values + " W/COUPON"] ||= {} cart[coupon_values + " W/COUPON"][:price] = coupon_hash[:cost] cart[coupon_values + " W/COUPON"][:clearance] = cart[coupon_values][:clearance] cart[coupon_values + " W/COUPON"][:count]||= 0 cart[coupon_values + " W/COUPON"][:count] += 1 end end end cart end def apply_clearance(cart:[]) cart.each do |item, value| #"TEMPEH" ---- #{:price => 3.0} if value[:clearance] value[:price] = (value[:price] * 0.8).round(2) end end end def checkout(cart: [], coupons: []) total = 0 each = 0 consolidated = consolidate_cart(cart: cart) couponed = apply_coupons(cart: consolidated, coupons: coupons) clearanced = apply_clearance(cart: couponed) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ clearanced.each do |item_array| total += item_array[1][:price]*item_array[1][:count] # binding.pry end if total > 100 (total*0.9).round(2) else total.round(2) end end
true
3c6e96092457cfe9cc9c3b51ba1dfbb73a783047
Ruby
hosiawak/rubinius_macros
/spec/andand_spec.rb
UTF-8
1,422
3.140625
3
[]
no_license
describe "Andand macro" do it "returns the left hand argument if the right is missing" do :foo.andand.should == :foo end it "rewrites foo.andand.bar into __x__ = foo; x && x.bar" do [1,2,3].andand.to_s.should == "123" nil.andand.to_s.should == nil end it "rewrites sends with 1 argument" do [1,2,3].andand.inject(:+).should == 6 # end it "rewrites sends with many arguments" do [1,2,3].andand.inject(0, :+).should == 6 end it "rewrites sends with block" do [1,2,3].andand.inject { |sum,n| sum + n}.should == 6 end it "rewrites sends with passed block" do sum = proc { |sum,n| sum + n} [1,2,3].andand.inject(&sum).should == 6 end it "rewrites sends with passed block and argument" do sum = proc { |sum,n| sum + n} [1,2,3].andand.inject(0, &sum).should == 6 end it "rewrites sends with block and argument" do [1,2,3].andand.inject(0) { |sum,n| sum + n}.should == 6 end describe "with a block on the right side" do it "passes left argument as a block parameter" do 'foo'.andand { |fu| fu + 'bar'}.should == 'foobar' # fu = 'foo' and fu + 'bar' # end it "degenerates block with no parameter and one statement" do # 'foo' and :bar 'foo'.andand { :bar }.should == :bar end it "accepts a passed block" do b = proc { :bar } 'foo'.andand(&b).should == :bar end end end
true
e1f360abeabbb5462c3f57ccb452dae62b42b356
Ruby
brooksquil/back-end-class-demos
/modules_mixins/main.rb
UTF-8
371
3.140625
3
[]
no_license
require_relative "student_type_error" require_relative "cars" require_relative "student" #creates instance of student jordan = Student.new("Jordan") puts jordan #following works with extend: # puts Student.description #following works with include: puts jordan.description puts Student.has_car? #if below changed to string triggers rescue block jordan.student_age(28)
true
5cf71fc78763b9cb8a52fb5a922bbe82458f3009
Ruby
dannehdan/birthday
/lib/birthday_calc.rb
UTF-8
291
3.328125
3
[]
no_license
require 'date' class BirthdayCalc def initialize(date) @date = Date.parse(date) end def birthday @date end def days_until_birthday year = Date.today.year next_bday = "#{@date.day}-#{@date.month}-#{year}" (Date.today - Date.parse(next_bday)).to_i end end
true
e3cd1f468bfa956184e42963792a8b8248752b5a
Ruby
cgilroy/chess
/piece.rb
UTF-8
4,586
3.40625
3
[]
no_license
require 'singleton' require_relative 'slideable' require_relative 'stepable' require_relative 'board' class Piece attr_accessor :pos attr_reader :color, :board def initialize(color,board,pos) @color = color @board = board @pos = pos end def destination_square_type(end_pos) return :out_of_bounds if !end_pos[0].between?(0,7) || !end_pos[1].between?(0,7) end_object = @board[end_pos] return :empty if end_object.is_a?(NullPiece) return :enemyFilled if end_object.color != @color return :friendlyFilled if end_object.color == @color end def move_into_check?(end_pos) # debugger duped_board = board_dup duped_board.move_piece!(@pos,end_pos) return true if duped_board.in_check?(@color) false end def board_dup # debugger test_board = Board.new (0..7).each do |row| (0..7).each do |col| copy_piece = @board[[row,col]] if !copy_piece.is_a?(NullPiece) new_piece = copy_piece.class.new(copy_piece.color,test_board,copy_piece.pos) new_piece.board = test_board else new_piece = NullPiece.instance end test_board[[row,col]] = new_piece end end test_board end def valid_moves # debugger moves.select do |end_pos| move_into_check?(end_pos) == false end end def board=(board) @board = board end end class Knight < Piece include Stepable def initialize(color,board,pos) super(color,board,pos) end def symbol if color == :black "#{"\u265E".encode('utf-8')}" else "#{"\u2658".encode('utf-8')}" end end def move_diffs [[1,-2],[1,2],[-1,-2],[-1,2],[2,-1],[2,1],[-2,-1],[-2,1]] end end class Bishop < Piece include Slideable def initialize(color,board,pos) super(color,board,pos) end def symbol if color == :black "#{"\u265D".encode('utf-8')}" else "#{"\u2657".encode('utf-8')}" end end def move_dirs diagonal_dirs end end class Rook < Piece include Slideable def initialize(color,board,pos) super(color,board,pos) end def symbol if color == :black "#{"\u265C".encode('utf-8')}" else "#{"\u2656".encode('utf-8')}" end end def move_dirs horizontal_dirs end end class Queen < Piece include Slideable def initialize(color,board,pos) super(color,board,pos) end def symbol if color == :black "#{"\u265B".encode('utf-8')}" else "#{"\u2655".encode('utf-8')}" end end def move_dirs horizontal_dirs + diagonal_dirs end end class King < Piece include Stepable def initialize(color,board,pos) super(color,board,pos) end def symbol if color == :black "#{"\u265A".encode('utf-8')}" else "#{"\u2654".encode('utf-8')}" end end def move_diffs [[1,1],[1,-1],[-1,1],[-1,-1],[1,0],[0,1],[-1,0],[0,-1]] end end class Pawn < Piece def initialize(color,board,pos) super(color,board,pos) end def symbol if color == :black "#{"\u265F".encode('utf-8')}" else "#{"\u2659".encode('utf-8')}" end end def moves step = forward_dir dirs = [] dirs = [[pos[0]+step,pos[1]]] if destination_square_type([pos[0]+step,pos[1]]) == :empty dirs << [pos[0]+step*2,pos[1]] if at_start_row? && destination_square_type([pos[0]+step*2,pos[1]]) == :empty dirs.concat(side_attacks) dirs end def at_start_row? current_row = pos[0] return true if (current_row == 1 && color == :black) || (current_row == 6 && color == :white) false end def forward_dir color == :black ? 1 : -1 end def side_attacks attacks = [] step = forward_dir [[step,1],[step,-1]].each do |h,v| check_pos = [pos[0]+h,pos[1]+v] attacks << check_pos if destination_square_type(check_pos) == :enemyFilled end attacks end end class NullPiece < Piece include Singleton def initialize end def symbol " " end end
true
4f5cf758116da1e9e8fe94595eba94e189d05b40
Ruby
challyed/EdsDailyProgrammerRUBY
/spaces.rb
UTF-8
998
3.578125
4
[]
no_license
"I am 6'2\" tall" # escape double-qoute inside a string 'I am 6\'2" tall.' # escape single-qoute inside a sting tabby_cat = "\tI'm tabbed in." #\t puts a tab persian_cat = "I'm split\non a line." # \n means new line blackslash_cat = "I'm \\a\\ cat." #shows what a double \\\\ does fat_cat = <<MY_HEREDOC I'll to do list: \t* Cat food. \t* Fishes. \t* Catnip.\n\t* Grass. MY_HEREDOC puts tabby_cat #added tabby_cat puts persian_cat #added persian_cat puts blackslash_cat #added blackslash_cat puts fat_cat #added fat_cat puts "Hello\t\tworld" #\t puts a tab puts "Hello\b\b\b\b\bGoodbye world" #\b is backspace puts "Hello\rStart over world" # \r is is a carriage return, a control character or mechanism # used to reset a device's position to the beginning of a line of text. puts "1. Hello\n2. World" # \n means new line puts "\a Hello \a" #\a is a bell puts "\a Todolist \a" puts "1. Learn Ruby\n\ta. Get Notepad++\n\tb. Use Learn Ruby the hardway\n\tc. check mistakes and dont copy and paste"
true
3d5a9763af5c8f2688d88a24fa49b70fb3e2ddc2
Ruby
Cosmin-Croitoriu/bank_tech_kata
/spec/transaction_spec.rb
UTF-8
926
2.59375
3
[]
no_license
# frozen_string_literal: true require 'transaction' describe Transaction do describe '#initialize' do it 'initializes a new transaction' do transaction = Transaction.new expect(transaction).to be_an_instance_of(Transaction) end end describe '#deposit_transaction' do it 'creates a log for a deposit' do log = Transaction.new log.deposit_transaction('02/07/2019', 500, 600) expect(log.transaction_log).to eq( credit: 500.00, debit: ' ', balance: 600.00, date: '02/07/2019' ) end end describe '#withdraw_transaction' do it 'creates a log for a withdraw from the account' do log = Transaction.new log.withdraw_transaction('02/07/2019', 500, 600) expect(log.transaction_log).to eq( credit: ' ', debit: 500.00, balance: 600.00, date: '02/07/2019' ) end end end
true
514221359c9ae3d28fe6f153389c8227fdc87bd6
Ruby
ThomasPedersen/Plant
/plant.rb
UTF-8
441
2.640625
3
[ "MIT" ]
permissive
require 'rubygems' require 'serialport' serialport = SerialPort.new("/dev/tty.usbmodemfd121", 9600, 8, 1, SerialPort::NONE) file = File.open("samples.csv", 'a') trap("INT") { file.close(); exit } while true do while (line = serialport.gets.chomp) do a = line.split(',') a.unshift (Time.now.utc.to_f * 1000).to_i.to_s a.unshift Time.now.to_s if (a.count == 4) then puts a.join(',') file.puts a.join(',') end end end
true
bae2b56c39df83651e34cdc889474f1e9c106002
Ruby
bryanmillstein/Chess
/Sliding_Piece.rb
UTF-8
780
3.125
3
[]
no_license
require 'byebug' class SlidingPiece < Piece DELTA_DIAGONOL = [ [-1, -1], [1, 1], [1, -1], [-1, 1] ] DELTA_HORZ_VERT = [ [1, 0], [-1, 0], [0, 1], [0, -1] ] def moves moves = [] self.class::DELTA.each do |delta| moves += each_delta(delta) end #validation moves end def each_delta(delta) moves = [] current_position = [position[0] + delta[0], position[1] + delta[1]] while on_board?(current_position) && board.empty?(current_position) moves << current_position current_position = [current_position[0] + delta[0], current_position[1] + delta[1]] end if on_board?(current_position) && enemy?(current_position) moves << current_position end moves end end
true
b66bab057493871b8af013a59939497d3036b5a1
Ruby
JoyJing1/app_academy
/emoji_chess/pieces/pawn.rb
UTF-8
1,160
3.328125
3
[]
no_license
require_relative 'piece' class Pawn < Piece attr_accessor :moved PAWN_DIR = { :white => [[-1,-1], [-1, 0], [-1,1]], :black => [[1,-1], [1,0], [1,1]] } def initialize(color, start_pos, board) @value = (color == :black ? ' 💩 ' : ' 🌊 ') @moved = false super end def build_moves moves = [] left_diff, forward_diff, right_diff = PAWN_DIR[@color] [left_diff, right_diff].each do |diff| capture_pos = new_position(@pos, diff) unless (capture_pos.nil? || @board[capture_pos].is_a?(NullPiece)) moves << capture_pos if @board[capture_pos].color != color end end forward_one = new_position(@pos, forward_diff) moves << forward_one if empty?(forward_one) unless moved? forward_two = new_position(forward_one, PAWN_DIR[@color][1]) moves << forward_two if empty?(forward_two) end moves end def moved? @moved end private def new_position(orig_pos, diff) new_pos = [orig_pos[0] + diff[0], orig_pos[1] + diff[1]] Board.in_bounds?(new_pos) ? new_pos : nil end def empty?(pos) (!pos.nil? && @board[pos].is_a?(NullPiece)) end end
true
295454f2d111ec1fa6331b96a0357410c5ad2e54
Ruby
wordtreefoundation/archdown
/lib/archdown/download.rb
UTF-8
920
2.671875
3
[ "MIT" ]
permissive
require 'archivist/client' require 'retriable' require 'archdown/librarian' require 'archdown/library' module Archdown class Download attr_reader :library_root, :search_terms def initialize(library_root, search_terms) @library = Library.new(library_root) @search_terms = search_terms @client = Archivist::Client::Base.new end def go!(&each_book) page = 1 loop do books = ::Retriable.retriable :on => Faraday::Error::TimeoutError do terms = @search_terms.merge(:page => page) begin @client.search(terms) rescue => e $stderr.puts "Search Terms: #{JSON.pretty_generate(terms)}" raise e end end break if books.empty? books.each do |book| Librarian.new(@library, book).store_book(&each_book) end page += 1 end end end end
true
b8b6c178d662bfe1a17095987ec0e34ee347a178
Ruby
pmanko/slice
/app/models/engine/expressions/unary.rb
UTF-8
252
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Engine module Expressions class Unary < Expression attr_accessor :operator, :right def initialize(operator, right) @operator = operator @right = right end end end end
true
014ca55d1b4892f2435049657123de9559ef2622
Ruby
carriewalsh/module_3_diagnostic
/spec/features/user_can_search_by_zip_spec.rb
UTF-8
1,229
2.71875
3
[]
no_license
require "rails_helper" describe "User can search by zip code" do it "returns a list of stations that match query" do visit "/" fill_in "zip", with: 80206 click_on "Locate" expect(current_path).to eq('/search') expect(page).to have_content("Total Results: 93") expect(page).to have_css(".station", count: 15) within first ".station" do expect(page).to have_content("Name: ") expect(page).to have_content("Address: ") expect(page).to have_content("Fuel Types: ") expect(page).to have_content("Distance: ") expect(page).to have_content("Access Times: ") end end end # As a user # When I visit "/" # And I fill in the search form with 80206 (Note: Use the existing search form) # And I click "Locate" # Then I should be on page "/search" # Then I should see the total results of the stations that match my query, 90. # Then I should see a list of the 15 closest stations within 5 miles sorted by distance # And the stations should be limited to Electric and Propane # And the stations should only be public, and not private, planned or temporarily unavailable. # And for each of the stations I should see Name, Address, Fuel Types, Distance, and Access Times
true
fa9219c7012878174bb73e5959c2eb2037244cd7
Ruby
bodrovis-learning/Ruby-SOLID-video
/dip/before.rb
UTF-8
538
3.171875
3
[]
no_license
class TerminalPrinter def write(msg) $stdout.write "#{@prefix} #{message}" end end class FilePrinter def write(msg) File.open('log.txt', 'a+:UTF-8') do |f| f.write msg f.write "\n" end end end class Logger def initialize @prefix = "#{Time.now.strftime('%d-%b-%Y %H:%M:%S')} -->" end def log_stdout(message) TerminalPrinter.new.write "#{@prefix} #{message}" end def log_file(message) FilePrinter.new.write "#{@prefix} #{message}" end end logger = Logger.new logger.log_file 'hi'
true
c8908784741397dd022b695d5e4f7382c3809b2d
Ruby
KED-2020/app-mind-map
/app/presentation/view_objects/subscriptions_list.rb
UTF-8
419
2.59375
3
[]
no_license
# frozen_string_literal: true require_relative 'subscription' module Views # View for a a list of project entities class SubscriptionsList def initialize(subscriptions) @subscriptions = subscriptions.map.with_index { |sub, i| Subscription.new(sub, i) } end def each @subscriptions.each do |sub| yield sub end end def any? @subscriptions.any? end end end
true
9270c2805f5b30fe42f079a1af988bff600a558d
Ruby
atpons/lect-satlib
/network_sat/server.rb
UTF-8
833
2.90625
3
[]
no_license
require "../satrb.rb" require "socket" require "logger" @log = Logger.new(STDOUT) @port = 20000 @log.info("[*] Listening on #{@port} for initialize information") s0 = TCPServer.open(@port) sock = s0.accept while buf = sock.gets buf = eval(buf) @c_begin = buf[0] @c_end = buf[1] end sock.close s0.close @log.info("[*] Listening on #{@port} for booleans") s0 = TCPServer.open(@port) sock = s0.accept while buf = sock.gets @var = eval(buf) end sock.close s0.close @c = 0 #c_begin = @var.count / 2 + 1 #c_end = @var.count @log.info("[*] Calculation on 01 (#{@c_begin} to #{@c_end})") @var.each do |bool| a = Passat::Boolean.new a.input(bool) a.file_load("20.cnf") @c += 1 # @log.debug("[-] Solving SAT on 02 (times: #{@c})") if a.check @log.info("[*] Solved and SAT on 02 (times: #{@c})") break end end
true
5b54b42c90312f4b0bcef7be9ee3267daa720d28
Ruby
triposorbust/digraph
/lib/arc.rb
UTF-8
380
3.296875
3
[]
no_license
require 'node' class Arc # Arcs always originate in the parent Node. attr_reader :destination attr_accessor :weight def initialize destination, weight raise TypeError, "arcs must link to node" unless destination.is_a? Node raise TypeError, "weight must be numeric" unless weight.is_a? Numeric @destination = destination @weight = weight end end
true
cf94b9dd71bd3584691ea7a3d1a084811e4c1f54
Ruby
irenemoreno/InBetweenJobs
/WeArePeople/pruebaWAp/gom_jabbar/cart.rb
UTF-8
552
3.03125
3
[]
no_license
class Cart def initialize(pricing_rules = nil) @items = [] @kr = 3.14 @me = 42 @un = 999 end def add item @items << item end def total kr = @items.count "KR" if kr % 2 == 0 then total_kr = (kr.to_i / 2) * @kr else total_kr = (kr.to_i / 2 + 1) * @kr end me = @items.count "ME" if me >= 3 then @me = 33.33 end total_me = me * @me un = @items.count "UN" total_un = un * @un @price = total_kr + total_me + total_un end end
true
605fe9807a3b250e23816a8aebb16ee72ab82abc
Ruby
33marvil/CodeaCamp
/semana_2/Martes 3_02/adivina_numero.rb
UTF-8
418
3.984375
4
[]
no_license
class NumberGuessingGame def initialize end def guess(num_usuario) num = rand(1..10) if num_usuario < num puts "Too low" elsif num_usuario > num puts "Too high" else "You got it!" end p num end end # Pruebas game = NumberGuessingGame.new p game.guess(5) == "Too low" p game.guess(8) == "Too high" p game.guess(7) == "Too high" p game.guess(6) == "You got it!"
true
b864fa9120d95b18a9f16d7f36336dd51645ee79
Ruby
pocke/mighty_json
/lib/mighty_json/errors.rb
UTF-8
914
2.765625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# frozen_string_literal: true module MightyJSON class Error < StandardError attr_reader :path, :type, :value def initialize(path:, type:, value:) @path = path @type = type @value = value end def to_s position = path.empty? ? "" : " at .#{path.join('.')}" "Expected type of value #{value}#{position} is #{type}" end alias message to_s end class IllegalTypeError < StandardError attr_reader :type def initialize(type:) @type = type end def to_s "#{type} can not be put on toplevel" end alias message to_s end class UnexpectedFieldError < StandardError attr_reader :path, :value def initialize(path: , value:) @path = path @value = value end def to_s position = "#{path.join('.')}" "Unexpected field of #{position} (#{value})" end alias message to_s end end
true
2901a6642d358f161d7d435d0cc38132c84558eb
Ruby
christinamcmahon/programming-univbasics-4-square-array-seattle-web-120919
/lib/square_array.rb
UTF-8
180
3.4375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(array) # your code here counter = 0 result = [] while array[counter] do result[counter] = array[counter]**2 counter += 1 end return result end
true
412ed6ecc61be966947a244e3bf7b59295cf561e
Ruby
maddymthompson/kwk-t1-say-hello-ruby-teachers-l1
/colors.rb
UTF-8
89
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
colors = ["Red", "Yellow", "Blue"] puts "First: #{colors[0]}" puts "Last: #{colors[2]}"
true
c1de2f52cae6a621df6da3b9cee994f94824b156
Ruby
itatchi3/bootcamp
/ruby/test.rb
UTF-8
306
3.328125
3
[]
no_license
class Foo def initialize(arg) @foo = arg end def foo puts @foo end def bar puts @foo end end foo = Foo.new("foo") foo.foo #=> foo foo.bar #=> foo bar = Foo.new("bar") bar.foo #=> bar foo.bar #=> bar # 異なる値をインスタンス変数に代入している foo.foo #=> foo
true
454d0e6ab0d403e8298a27f8aaa32b7c28bcb53e
Ruby
thomascpan/exercises
/sorting_agorithms/SelectionSort.rb
UTF-8
424
3.4375
3
[]
no_license
# Selection Sort unsorted_list1 = 10.times.map{rand(100)} unsorted_list2 = 10.times.map{rand(100)} def selection_sort(list) i = 0 while i < list.length-1 min_index = i j = i+1 while j < list.length min_index = j if list[j] < list[min_index] j+=1 end list[i],list[min_index] = list[min_index],list[i] i+=1 end return list end p unsorted_list1 p selection_sort(unsorted_list1)
true
bb204b237a4bee7507f088d770aee168fea68825
Ruby
anthonylebrun/rpn_calculator
/lib/abstract_factory.rb
UTF-8
803
3.203125
3
[]
no_license
# This class returns a module that when included defines the # concrete_factories method on its class which in turn returns # an array of classes belonging to the argument module. # Usage: # # class Foo # include AbstractFactory.new(FactoryWrapperModule) # # concrete_factories.each do |factory| # ... # end # end class AbstractFactory < Module def initialize(mod) @mod = mod define_methods end private def define_methods define_concrete_factories_method end def define_concrete_factories_method mod = @mod define_method(:concrete_factories) do mod.constants.reduce([]) do |classes, constant| const = mod.const_get(constant) if const.is_a? Class classes.push(const) end classes end end end end
true
bae353326550e7c5f26fdf5ce1384e010be9f72e
Ruby
necmigunduz/hackerrank-solutions
/manas_and_stones.rb
UTF-8
539
3.28125
3
[]
no_license
#!/bin/ruby require 'json' require 'stringio' # Complete the stones function below. def stones(n, a, b) ar=[0] (n-1).times do |val| tmp=[] ar.each do |v| tmp << v+a if !tmp.include?(v+a) tmp << v+b if !tmp.include?(v+b) end ar=tmp end ar.sort end fptr = File.open(ENV['OUTPUT_PATH'], 'w') t = gets.to_i t.times do n = gets.to_i a = gets.to_i b = gets.to_i result = stones n, a, b fptr.write result.join " " fptr.write "\n" end fptr.close()
true
4df5bc41601edb77d7f3bec85917670281af95dc
Ruby
adamjmurray/mtk
/spec/mtk/patterns/sequence_spec.rb
UTF-8
6,033
2.875
3
[ "BSD-3-Clause" ]
permissive
require 'spec_helper' describe MTK::Patterns::Sequence do SEQUENCE = MTK::Patterns::Sequence let(:elements) { [1,2,3] } let(:sequence) { SEQUENCE.new(elements) } it "is a MTK::Collection" do sequence.should be_a MTK::Groups::Collection # and now we won't test any other collection features here... see collection_spec end describe ".from_a" do it "acts like .new" do SEQUENCE.from_a(elements).should == sequence end end describe "#elements" do it "is the array the sequence was constructed with" do sequence.elements.should == elements end end describe "#next" do it "enumerates the elements" do nexts = [] elements.length.times do nexts << sequence.next end nexts.should == elements end it "raises StopIteration when the end of the Sequence is reached" do elements.length.times{ sequence.next } lambda{ sequence.next }.should raise_error(StopIteration) end it "should automatically break out of Kernel#loop" do nexts = [] loop do # loop rescues StopIteration and exits the loop nexts << sequence.next end nexts.should == elements end it "enumerates the elements in sub-sequences" do sub_sequence = SEQUENCE.new [2,3] sequence = SEQUENCE.new [1,sub_sequence,4] nexts = [] loop { nexts << sequence.next } nexts.should == [1,2,3,4] end it "skips over empty sub-sequences" do sub_sequence = SEQUENCE.new [] sequence = SEQUENCE.new [1,sub_sequence,4] nexts = [] loop { nexts << sequence.next } nexts.should == [1,4] end end describe "@min_elements" do it "prevents a StopIteration error until min_elements have been emitted" do pattern = SEQUENCE.new([1,2,3], cycle_count: 1, min_elements: 5) 5.times{ pattern.next } lambda{ pattern.next }.should raise_error StopIteration end end describe "@max_cycles" do it "is the :max_cycles option the pattern was constructed with" do SEQUENCE.new( [], max_cycles: 2 ).max_cycles.should == 2 end it "is 1 by default" do SEQUENCE.new( [] ).max_cycles.should == 1 end it "loops indefinitely when it's nil" do sequence = SEQUENCE.new( [1], max_cycles: nil ) lambda { 100.times { sequence.next } }.should_not raise_error end it "causes a StopIteration exception after the number of cycles has completed" do sequence = SEQUENCE.new( elements, max_cycles: 2 ) 2.times do elements.length.times { sequence.next } # one full cycle end lambda { sequence.next }.should raise_error StopIteration end end describe "#max_cycles_exceeded?" do it "is false until max_elements have been emitted" do sequence = SEQUENCE.new( elements, max_cycles: 2 ) 2.times do sequence.max_cycles_exceeded?.should be_false elements.length.times { sequence.next } # one full cycle end # unlike with element_count and max_elements_exceeded?, cycle_count doesn't get bumped until # you ask for the next element and a StopIteration is thrown lambda { sequence.next }.should raise_error StopIteration sequence.max_cycles_exceeded?.should be_true end it "is always false when max_cycles is not set" do pattern = PATTERN.new([:anything], max_cycles: nil) 15.times { pattern.max_cycles_exceeded?.should be_false and pattern.next } end end it "has max_elements_exceeded once max_elements have been emitted (edge case, has same number of elements)" do sequence = SEQUENCE.new([1,2,3,4,5], :max_elements => 5) 5.times { sequence.max_elements_exceeded?.should(be_false) and sequence.next } sequence.max_elements_exceeded?.should be_true lambda { sequence.next }.should raise_error StopIteration end it "raises a StopIteration error when a nested pattern has emitted more than max_elements" do sequence = SEQUENCE.new([Patterns.Cycle(1,2)], :max_elements => 5) 5.times { sequence.next } lambda{ sequence.next }.should raise_error StopIteration end describe "#rewind" do it "restarts at the beginning of the sequence" do loop { sequence.next } sequence.rewind sequence.next.should == elements.first end it "returns self, so it can be chained to #next" do first = sequence.next sequence.rewind.next.should == first end it "causes sub-sequences to start from the beginning when encountered again after #rewind" do sub_sequence = SEQUENCE.new [2,3] sequence = SEQUENCE.new [1,sub_sequence,4] loop { sequence.next } sequence.rewind nexts = [] loop { nexts << sequence.next } nexts.should == [1,2,3,4] end end end describe MTK::Patterns do describe "#Sequence" do it "creates a Sequence" do MTK::Patterns.Sequence(1,2,3).should be_a MTK::Patterns::Sequence end it "sets #elements from the varargs" do MTK::Patterns.Sequence(1,2,3).elements.should == [1,2,3] end end describe "#PitchSequence" do it "creates a Sequence" do MTK::Patterns.PitchSequence(1,2,3).should be_a MTK::Patterns::Sequence end it "sets #elements from the varargs" do MTK::Patterns.PitchSequence(1,2,3).elements.should == [Pitch(1),Pitch(2),Pitch(3)] end end describe "#IntensitySequence" do it "creates a Sequence" do MTK::Patterns.IntensitySequence(1,2,3).should be_a MTK::Patterns::Sequence end it "sets #elements from the varargs" do MTK::Patterns.IntensitySequence(1,2,3).elements.should == [Intensity(1),Intensity(2),Intensity(3)] end end describe "#DurationSequence" do it "creates a Sequence" do MTK::Patterns.DurationSequence(1,2,3).should be_a MTK::Patterns::Sequence end it "sets #elements from the varargs" do MTK::Patterns.DurationSequence(1,2,3).elements.should == [Duration(1),Duration(2),Duration(3)] end end end
true
b64391c2df461099f4daffefb83475e1f0c23198
Ruby
uswitch/ontology
/lib/ontology/cli.rb
UTF-8
815
2.703125
3
[ "Apache-2.0" ]
permissive
require_relative './source.rb' require_relative './store.rb' module Ontology module CLI def self.store_from_paths(paths, options) store = Store.new paths.each { |path| if File.directory?(path) $stderr.puts "Loading directory '#{path}'" directory = Ontology::Source::Directory.new(path) things = directory.sync elsif File.file?(path) $stderr.puts "Loading file '#{path}'" things = File.readlines(path).map { |thing| JSON.parse(thing, symbolize_names: true) } else $stderr.puts "Unknown path type: #{path}" next end $stderr.puts "Adding #{things.count} things to store" things.each { |thing| store.add!(thing) } } store end end end
true
d752f67e6522281df924fcf0db8e79238e6b5ee3
Ruby
hilkeros/raudio-test
/app/models/midi.rb
UTF-8
1,672
3.03125
3
[]
no_license
class Midi attr_accessor :script def initialize(instrument) @instrument = instrument.identifier @script = ("<script id='MidiCode'> window.onload = function() { var midi_converter = " + self.midi_converter_array.to_s + "; if (navigator.requestMIDIAccess) { console.log('Browser supports MIDI!'); } if (navigator.requestMIDIAccess) { navigator.requestMIDIAccess() .then(success, failure); } function success (midi) { console.log('Got midi!'); var inputs = midi.inputs.values(); for (var input = inputs.next(); input && !input.done; input = inputs.next()) { input.value.onmidimessage = onMIDIMessage; function onMIDIMessage (message) { console.log(message.data); if (message.data[0] === 144) { playNote(message.data[1]); } if (message.data[0] === 128) { stopNote(message.data[1]); } } } } function failure () { console.error('No access to midi devices') } function playNote(note) {" + @instrument + ".triggerAttack(midi_converter[note]); } function stopNote(note) {" + @instrument + ".triggerRelease(); } }</script>").html_safe end def midi_note_to_note_name(note) midi_converter_array[note] end def midi_converter_array array = [] note_names = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] 10.times do |i| note_names.each do |n| array.push( n + (i-2).to_s) end end return array end end
true
74555d185777741fc202ddcda9139db9ee93b03a
Ruby
tckmn/oldstuffs
/ruby/num-coder.rb
UTF-8
1,407
3.59375
4
[]
no_license
$chrs = %w[0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z . , ? ! ( ) ' / \ @ # $ % ^ & * : + - =] $len = $chrs.length def encode i, iterations code = '' while i != 0 code = String($chrs[i % $len]) + code i /= $len end if iterations > 0 puts "#{iterations} iterations left" word = '' code.bytes.each do |thing| word += ("%03d" % thing).to_s end code = encode word.to_i, iterations - 1 end code end def decode code, iterations code.upcase! i2 = '' for x in 0...code.size i2 += code[x] unless ($chrs.index code[x]).nil? end code = i2 i = 0 for x in 0...code.size i += ($chrs.index code[x]) * ($len ** ((code.size - 1) - x)) end original = '' i2 = i.to_s i2 = '0' + i2 if i2.size % 3 != 0 for num in i2.scan(/.{3}/) original += num.to_i.chr end if iterations > 0 puts "#{iterations} iterations left" original = decode original, iterations - 1 end original end while true begin word = '' print 'Encode: ' gets.chomp.bytes.each do |thing| word += ("%03d" % thing).to_s end print 'Iterations: ' puts encode word.to_i, gets.chomp.to_i - 1 print 'Decode: ' tmp = gets.chomp print 'Iterations: ' puts decode tmp, gets.chomp.to_i - 1 rescue Exception => e puts 'Error' end end
true
12bd1b71feac26d6702da0c5a0d3103fbf0f7bf0
Ruby
netosober/ruby-project-euler
/02-fib.rb
UTF-8
161
3.296875
3
[]
no_license
a = 1 b = 2 sum = 0 while a < 4000000 && b <4000000 do if (b%2 == 0) sum += b puts "#{b} - #{sum}" end c = a + b a = b b = c end puts sum
true
124168bd7db906786fb68513f96fdfd45fecbd87
Ruby
genya0407/boxboxbox-cli
/mrblib/box.rb
UTF-8
265
2.875
3
[ "MIT" ]
permissive
class Box # @dynamic image_name, top_left, bottom_right attr_reader :image_name, :top_left, :bottom_right def initialize(image_name:, top_left:, bottom_right:) @image_name = image_name @top_left = top_left @bottom_right = bottom_right end end
true
226d1a1bd0ab3d3d6ff034687f34e154b951f597
Ruby
gd875/ruby-collaborating-objects-lab-v-000
/lib/mp3_importer.rb
UTF-8
435
3
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class MP3Importer attr_accessor :path def initialize(path) @path = path end def files all_file_paths = Dir["#{path}/**/*.mp3"] normalized_files = [] all_file_paths.each do |file_path| normalized_files << file_path.split("/")[4] end normalized_files #binding.pry end def import files.each do |file| Song.new_by_filename(file) end #binding.pry end end
true
c452239ffcf571987144844d56bfd217a01cb0a4
Ruby
SamuSan/ballin_spice
/cards/diamond.rb
UTF-8
106
2.671875
3
[]
no_license
require_relative 'card.rb' class Diamond < Card def initialize value super @suit = :d end end
true