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
e47075a11eb8949d0c55997157888f84db256ea8
Ruby
maca/scruby
/lib/scruby/sclang.rb
UTF-8
1,181
2.65625
3
[ "MIT", "GPL-3.0-or-later" ]
permissive
require "concurrent-edge" module Scruby class SclangError < StandardError; end class Sclang include Concurrent def initialize @process = Process.new("sclang", "-i scruby") end def spawn spawn_async.value! end def spawn_async return Promises.fulfilled_future(self) if process.alive? process.spawn Promises.future(Cancellation.timeout(3)) do |cancelation| loop { case process.read when /Welcome/ then break when /Error/ then raise(SclangError, "failed to spawn sclang") else cancelation.check! end } self end end def kill process.kill end def eval(code) unless process.alive? raise SclangError, "sclang process not running, try `sclang.spawn`" end eval_async(code).value! end def eval_async(code) Promises.future do process.puts_gets("(#{code}).postcs \e")&.strip end end private attr_reader :process class << self def spawn new.spawn end def main @main ||= new end end end end
true
9ca7b151a7f68e2603813877d5252b98e6dedd8d
Ruby
dreikanter/feeder
/app/services/push.rb
UTF-8
1,400
2.5625
3
[ "MIT" ]
permissive
# TODO: Drop this class # :reek:TooManyStatements class Push include Logging include Callee param :post def call publish_post_content # TODO: Use better way to limit API calls rate sleep 1 end private def publish_post_content attachment_ids = create_attachments post_id = create_post(attachment_ids) post.update(freefeed_post_id: post_id) create_comments(post_id) # TODO: post.success! log_info("---> new post URL: #{post.permalink}") # rescue StandardError # post.fail! # raise end def create_post(attachment_ids) response = freefeed.create_post( post: { body: post.text, attachments: attachment_ids }, meta: { feeds: [post.feed.name] } ) response.parse.dig("posts", "id") end def create_comments(post_id) post.comments.each do |comment| freefeed.create_comment( comment: { body: comment, postId: post_id } ) end end def create_attachments post.attachments.map { |url| create_attachment(url) } end def create_attachment(url) Downloader.call(url) do |io, content_type| response = freefeed.create_attachment(io, content_type: content_type) response.parse.fetch("attachments").fetch("id") end end def freefeed @freefeed ||= FreefeedClientBuilder.call end end
true
4c03360143d7404285c3f70642c099a479de1dd0
Ruby
microsoftgraph/msgraph-sdk-ruby
/lib/models/column_validation.rb
UTF-8
6,461
2.734375
3
[ "MIT" ]
permissive
require 'microsoft_kiota_abstractions' require_relative '../microsoft_graph' require_relative './models' module MicrosoftGraph module Models class ColumnValidation include MicrosoftKiotaAbstractions::AdditionalDataHolder, MicrosoftKiotaAbstractions::Parsable ## # Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. @additional_data ## # Default BCP 47 language tag for the description. @default_language ## # Localized messages that explain what is needed for this column's value to be considered valid. User will be prompted with this message if validation fails. @descriptions ## # The formula to validate column value. For examples, see Examples of common formulas in lists. @formula ## # The OdataType property @odata_type ## ## Gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. ## @return a i_dictionary ## def additional_data return @additional_data end ## ## Sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. ## @param value Value to set for the additionalData property. ## @return a void ## def additional_data=(value) @additional_data = value end ## ## Instantiates a new columnValidation and sets the default values. ## @return a void ## def initialize() @additional_data = Hash.new end ## ## Creates a new instance of the appropriate class based on discriminator value ## @param parse_node The parse node to use to read the discriminator value and create the object ## @return a column_validation ## def self.create_from_discriminator_value(parse_node) raise StandardError, 'parse_node cannot be null' if parse_node.nil? return ColumnValidation.new end ## ## Gets the defaultLanguage property value. Default BCP 47 language tag for the description. ## @return a string ## def default_language return @default_language end ## ## Sets the defaultLanguage property value. Default BCP 47 language tag for the description. ## @param value Value to set for the defaultLanguage property. ## @return a void ## def default_language=(value) @default_language = value end ## ## Gets the descriptions property value. Localized messages that explain what is needed for this column's value to be considered valid. User will be prompted with this message if validation fails. ## @return a display_name_localization ## def descriptions return @descriptions end ## ## Sets the descriptions property value. Localized messages that explain what is needed for this column's value to be considered valid. User will be prompted with this message if validation fails. ## @param value Value to set for the descriptions property. ## @return a void ## def descriptions=(value) @descriptions = value end ## ## Gets the formula property value. The formula to validate column value. For examples, see Examples of common formulas in lists. ## @return a string ## def formula return @formula end ## ## Sets the formula property value. The formula to validate column value. For examples, see Examples of common formulas in lists. ## @param value Value to set for the formula property. ## @return a void ## def formula=(value) @formula = value end ## ## The deserialization information for the current model ## @return a i_dictionary ## def get_field_deserializers() return { "defaultLanguage" => lambda {|n| @default_language = n.get_string_value() }, "descriptions" => lambda {|n| @descriptions = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::DisplayNameLocalization.create_from_discriminator_value(pn) }) }, "formula" => lambda {|n| @formula = n.get_string_value() }, "@odata.type" => lambda {|n| @odata_type = n.get_string_value() }, } end ## ## Gets the @odata.type property value. The OdataType property ## @return a string ## def odata_type return @odata_type end ## ## Sets the @odata.type property value. The OdataType property ## @param value Value to set for the @odata.type property. ## @return a void ## def odata_type=(value) @odata_type = value end ## ## Serializes information the current object ## @param writer Serialization writer to use to serialize this model ## @return a void ## def serialize(writer) raise StandardError, 'writer cannot be null' if writer.nil? writer.write_string_value("defaultLanguage", @default_language) writer.write_collection_of_object_values("descriptions", @descriptions) writer.write_string_value("formula", @formula) writer.write_string_value("@odata.type", @odata_type) writer.write_additional_data(@additional_data) end end end end
true
da536462e7c27de22fada711be6bd720d49ab5cb
Ruby
benwah/test-concurrency
/runners.rb
UTF-8
1,689
2.796875
3
[]
no_license
require_relative './thread_pool.rb' require 'ruby-prof' class BaseRunner def initialize(job, number_of_times) @job = job @number_of_times = number_of_times end def run puts "[#{self.class}] Doing #{@job} #{@number_of_times} times." start_time = Time.now.utc perform puts "Total time: #{Time.now.utc - start_time}s" end def profile yield RubyProf.measure_mode = RubyProf::PROCESS_TIME # profiler = RubyProf::Profile.new # profiler.exclude_methods!(BaseRunner, :profile) # profiler.exclude_common_methods! # profiler.start # yield # print_result(profiler.stop) end def print_result(result) # printer = RubyProf::GraphPrinter.new(result) # printer.print(STDOUT, {}) printer = RubyProf::GraphHtmlPrinter.new(result) # printer = RubyProf::FlatPrinter.new(result) f = File.open("#{self.class}.html", 'w') printer.print(f, {}) # printer = RubyProf::MultiPrinter.new(result) # printer.print(:path => ".", :profile => "profile") end end class SingleThreaded < BaseRunner def perform profile do @number_of_times.times.map do |job_number| @job.new(job_number).do_work end end end end class MultiThreaded < BaseRunner def perform profile do threads = @number_of_times.times.map do |job_number| Thread.new do @job.new(job_number).do_work end end threads.each(&:join) end end end class MultiProcessed < BaseRunner def perform @number_of_times.times.map do |job_number| fork do profile do @job.new(job_number).do_work end end end Process.wait end end
true
38fbfe51b5f7859bbff82de253b927f849128e99
Ruby
RubyMoney/money
/spec/money/constructors_spec.rb
UTF-8
2,474
3.203125
3
[ "MIT" ]
permissive
# encoding: utf-8 describe Money::Constructors do describe "::empty" do it "creates a new Money object of 0 cents" do expect(Money.empty).to eq Money.new(0) end it "instantiates a subclass when inheritance is used" do special_money_class = Class.new(Money) expect(special_money_class.empty).to be_a special_money_class end end describe "::zero" do subject { Money.zero } it { is_expected.to eq Money.empty } it "instantiates a subclass when inheritance is used" do special_money_class = Class.new(Money) expect(special_money_class.zero).to be_a special_money_class end end describe "::ca_dollar" do it "creates a new Money object of the given value in CAD" do expect(Money.ca_dollar(50)).to eq Money.new(50, "CAD") end it "is aliased to ::cad" do expect(Money.cad(50)).to eq Money.ca_dollar(50) end it "instantiates a subclass when inheritance is used" do special_money_class = Class.new(Money) expect(special_money_class.ca_dollar(0)).to be_a special_money_class end end describe "::us_dollar" do it "creates a new Money object of the given value in USD" do expect(Money.us_dollar(50)).to eq Money.new(50, "USD") end it "is aliased to ::usd" do expect(Money.usd(50)).to eq Money.us_dollar(50) end it "instantiates a subclass when inheritance is used" do special_money_class = Class.new(Money) expect(special_money_class.us_dollar(0)).to be_a special_money_class end end describe "::euro" do it "creates a new Money object of the given value in EUR" do expect(Money.euro(50)).to eq Money.new(50, "EUR") end it "is aliased to ::eur" do expect(Money.eur(50)).to eq Money.euro(50) end it "instantiates a subclass when inheritance is used" do special_money_class = Class.new(Money) expect(special_money_class.euro(0)).to be_a special_money_class end end describe "::pound_sterling" do it "creates a new Money object of the given value in GBP" do expect(Money.pound_sterling(50)).to eq Money.new(50, "GBP") end it "is aliased to ::gbp" do expect(Money.gbp(50)).to eq Money.pound_sterling(50) end it "instantiates a subclass when inheritance is used" do special_money_class = Class.new(Money) expect(special_money_class.pound_sterling(0)).to be_a special_money_class end end end
true
e9a5f08883f544584d0c40bd4e21dc8a88f24abe
Ruby
fredrik/resize.fakedew.net
/receive/app.rb
UTF-8
1,095
2.53125
3
[]
no_license
require 'sinatra' require 'resque' require_relative './attachments_helper' require_relative '../process/resize_job' # set up worker queue Resque.redis = Redis.new get '/' do 'OK' end post '/resize/notify' do # receives a 'store' notification from Mailgun. # enqueue a set of ResizeJob workers, one for each image attachment. # return a 200 OK to indicate success, # return a 406 Not Acceptable to reject the message, # or any other status code to have Mailgun retry the notifiation later. # see https://documentation.mailgun.com/user_manual.html#routes for more. logger.info("incoming from #{params['sender']}") begin sender = params.fetch('sender') attachments = parse_attached_images(params.fetch('attachments')) rescue => e logger.info("bad request, rejecting: #{e}") return 406 # reject end begin attachments.each do |attachment| logger.info("posting job: #{attachment}") Resque.enqueue(ResizeJob, sender, attachment) end rescue => e logger.info("ERROR: #{e}") return 500 # please retry end 200 # ok end
true
e3875dbddaa0570d0c2c8eff2801f3e5bbae5c88
Ruby
itggot-jacob-karlin/webbserver-slutprojekt
/auth.rb
UTF-8
2,052
3.03125
3
[]
no_license
require 'session' module Auth def open_database() db = SQLite3::Database.new('db/db.sqlite3') db.results_as_hash = true return db end def get_user_by_username(username, db) users = db.execute("SELECT * FROM users WHERE username = '#{username}'") if users.length == 0 return nil end return users[0] end def register_user(username, password, db) password_encrypted = BCrypt::Password.create(password) result = db.execute("INSERT INTO users(username, password) VALUES(?, ?)", [username, password_encrypted]) id = db.execute("SELECT id FROM users WHERE username = '#{username}'")[0]["id"] session[:user_id] = id end def login_user(username, password, db) users = db.execute("SELECT * FROM users WHERE username = '#{username}'") if users.length == 0 return -1 end users = users[0] if BCrypt::Password.new(users['password']) == password id = users['id'] session[:user_id] = id return id end return -1 end def logout_user() session[:user_id] = nil end def get_user_id() id = session[:user_id] if id == nil return -1 end return id end def is_logged_in() return get_user_id() != -1 end def get_result(db) result = db.execute("SELECT * FROM notes WHERE user_id=?", [session[:user_id]]) end def create_note(db, content,id) db.execute("INSERT INTO notes (user_id, content) VALUES (?,?)", [id, content]) end def get_result_note(db) note_result = db.execute("SELECT user_id FROM notes WHERE id=?", [note_id]) end def delete_note(db) if note_result.first["user_id"] == session[:user_id] db.execute("DELETE FROM notes WHERE id=?", [note_id]) redirect('/homepage') end else redirect('/homepage') end end
true
763e75b8105b70bc7af13b1d5b3090f1f553055c
Ruby
tribune/multipart_body
/test/test.rb
UTF-8
6,515
2.921875
3
[ "MIT" ]
permissive
require File.join(File.dirname(__FILE__), 'test_helper') require 'tempfile' class MultipartBodyTest < Test::Unit::TestCase context "MultipartBody" do setup do @hash = {:test => 'test', :two => 'two'} @parts = [Part.new('name', 'value'), Part.new('name2', 'value2')] @example_text = "------multipart-boundary-307380\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nvalue\r\n------multipart-boundary-307380\r\nContent-Disposition: form-data; name=\"name2\"\r\n\r\nvalue2\r\n------multipart-boundary-307380--" @file = Tempfile.new('file') @file.write('hello') @file.flush @file.open end should "return a new multipart when sent #from_hash" do multipart = MultipartBody.from_hash(@hash) assert_equal MultipartBody, multipart.class end should "create a list of parts from the hash when sent #from_hash" do multipart = MultipartBody.from_hash(@hash) assert_equal @hash, Hash[multipart.parts.map{|part| [part.name, part.body] }] end should "add to the list of parts when sent #new with a hash" do multipart = MultipartBody.new(@hash) assert_equal @hash, Hash[multipart.parts.map{|part| [part.name, part.body] }] end should "correctly add parts sent #new with parts" do multipart = MultipartBody.new(@parts) assert_same_elements @parts, multipart.parts end should "assign a boundary if it is not given" do multpart = MultipartBody.new() assert_match /[\w\d-]{10,}/, multpart.boundary end should "use the boundary provided if given" do multipart = MultipartBody.new(nil, "my-boundary") assert_equal "my-boundary", multipart.boundary end should "starts with a boundary when sent #to_s" do multipart = MultipartBody.new(@parts) assert_match /^--#{multipart.boundary}/i, multipart.to_s end should "end with a boundary when sent #to_s" do multipart = MultipartBody.new(@parts) assert_match /--#{multipart.boundary}--\z/i, multipart.to_s end should "contain the parts joined by a boundary when sent #to_s" do multipart = MultipartBody.new(@parts) assert_match multipart.parts.join("\r\n--#{multipart.boundary}\r\n"), multipart.to_s end should "contrsuct a valid multipart text when passed #to_s" do multipart = MultipartBody.new(@parts) multipart.boundary = '----multipart-boundary-307380' assert_equal @example_text, multipart.to_s end should "construct a file part when create from hash" do multipart = MultipartBody.new(:test => @file) multipart.boundary = '----multipart-boundary-672923' assert_equal 'hello', multipart.parts.first.body assert_not_nil multipart.parts.first.filename assert_match /------multipart-boundary-672923\r\nContent-Disposition: form-data; name=\"test\"; filename=\".*"\r\n\r\nhello\r\n------multipart-boundary-672923--/, multipart.to_s end end context "a Part" do setup do @part = Part @file = Tempfile.new('file') @file.write('hello') @file.flush @file.open end should "assign values when sent #new with a hash" do part = Part.new(:name => 'test', :body => 'content', :filename => 'name') assert_equal 'test', part.name assert_equal 'content', part.body assert_equal 'name', part.filename end should "assign values when sent #new with values" do part = Part.new('test', 'content', 'name') assert_equal 'test', part.name assert_equal 'content', part.body assert_equal 'name', part.filename end should "be happy when sent #new with args without a filename" do part = Part.new('test', 'content') assert_equal 'test', part.name assert_equal 'content', part.body assert_equal nil, part.filename end should "create an empty part when sent #new with nothing" do part = Part.new() assert_equal nil, part.name assert_equal nil, part.body assert_equal nil, part.filename end should "include a content type when one is set" do part = Part.new(:content_type => 'plain/text', :body => 'content') assert_match "Content-Type: plain\/text\r\n", part.header end should "include a content disposition when sent #header and one is set" do part = Part.new(:content_disposition => 'content-dispo', :body => 'content') assert_match "Content-Disposition: content-dispo\r\n", part.header end should "not include a content disposition of form-data when nothing is set" do part = Part.new(:body => 'content') assert_no_match /content-disposition/i, part.header end should "include a content disposition when sent #header and name is set" do part = Part.new(:name => 'key', :body => 'content') assert_match /content-disposition: form-data; name="key"/i, part.header end should "include no filename when sent #header and a filename is not set" do part = Part.new(:name => 'key', :body => 'content') assert_no_match /content-disposition: .+; name=".+"; filename="?.*"?/i, part.header end should "include a filename when sent #header and a filename is set" do part = Part.new(:name => 'key', :body => 'content', :filename => 'file.jpg') assert_match /content-disposition: .+; name=".+"; filename="file.jpg"/i, part.header end should "return the original body if encoding is not set" do part = Part.new(:name => 'key', :body => 'content') assert_equal 'content', part.encoded_body end # TODO: Implement encoding tests should "raise an exception when an encoding is passed" do part = Part.new(:name => 'key', :body => 'content', :encoding => :base64) assert_raises RuntimeError do part.encoded_body end end should "output the header and body when sent #to_s" do part = Part.new(:name => 'key', :body => 'content') assert_equal "#{part.header}\r\n#{part.body}", part.to_s end should "add the files content not the file when passed a file" do part = Part.new(:name => 'key', :body => @file) assert_equal 'hello', part.body end should "automatically assign a filename when passed a file to body" do part = Part.new(:name => 'key', :body => @file) assert_not_nil part.filename end end end
true
64162fd1f13f6c30c178e3ad1e8490da01afbfe8
Ruby
macressler/pakyow
/pakyow-support/lib/support/hash.rb
UTF-8
1,112
3.4375
3
[ "MIT" ]
permissive
class Hash def deep_merge(second) merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } self.merge(second, &merger) end def deep_merge!(second) merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge!(v2, &merger) : v2 } self.merge!(second, &merger) end # Creates an indifferent hash. This means that when indifferentized, this hash: # { 'foo' => 'bar' } # # Can be accessed like this: # { :foo => 'bar' } # def self.strhash(hash) indifferentize(hash) end # Converts keys to symbols. def self.symbolize_keys(hash) Hash[hash.map{|(k,v)| [k.to_sym,v]}] end # Converts keys/values to symbols. def self.symbolize(hash) Hash[hash.map{|(k,v)| [k.to_sym,v.to_sym]}] end protected # (see {strhash}) def self.indifferentize(hash) hash.each_pair do |key, value| hash[key] = indifferentize(value) if value.is_a? ::Hash end indifferent_hash.merge(hash) end # (see {strhash}) def self.indifferent_hash Hash.new { |hash,key| hash[key.to_s] if Symbol === key } end end
true
b671bbf09f86e9667a640c9e6c70f18e69c46b50
Ruby
gesarlhamo/algorithm-problems
/sum.rb
UTF-8
141
3.5
4
[]
no_license
def sum(array) running_sum = 0 for i in array running_sum = running_sum + i end return running_sum end puts sum([1,2,3,4,5,100])
true
af30cd86fb41bea74fc7d18a1e16b9091077c30a
Ruby
ebooshi/Chatroom-Modelado-y-Programacion-2018-1
/src/Sala.rb
UTF-8
1,333
3.171875
3
[]
no_license
# coding: utf-8 class Sala #Constructor único para la clase sala #Parámetro nombre: el nombre de la Sala #Parámetro dueño: el cliente que declara la sala def initialize(nombre, dueño) @clientes = Hash.new #hash que va a contener a los Socket @poblacion = 0 @dueño = dueño @nombre = nombre end #Regresa la variable @clientes def clientes() return @clientes end #Regresa la variable @población def poblacion() return @poblacion end #Regresa la variable @dueño def dueño() return @dueño end #Regresa la variable @nombre def nombre() return @nombre end #Parámetro cliente: el cliente a agregar a la sala #Revisa que el cliente no esté contenido en el diccionario de clientes #caso contrario agrega el cliente al diccionario def unirse(cliente) if @clientes[cliente] != nil return else @clientes[cliente] = cliente @poblacion += 1 end end #Parámetro cliente: el cliente a eliminar de la sala #busca el cliente en el diccionario de clientes, si no está contenido #no hace nada, en otro caso lo elimina def dejar(cliente) if @clientes[cliente] != nil @clientes.delete(:cliente) else cliente.puts "no perteneces a esta sala" end end end
true
eb333f6cc8aa62081aade398854d24b2b2628913
Ruby
BASIC-Belic/api-muncher
/test/lib/recipe_test.rb
UTF-8
1,881
2.875
3
[]
no_license
require 'test_helper' describe 'Recipe' do it "Cannot be initialized without a name" do expect { Recipe.new }.must_raise ArgumentError end it "Must initialize name properly" do channel = Recipe.new("Name") expect(channel.name).wont_be_nil expect(channel.name).must_equal "Name" end it 'must raise error for empty string name' do empty_name = "" expect{ Recipe.new(empty_name) }.must_raise ArgumentError end it 'must have default value for options' do recipe = Recipe.new("bologne") empty_list = ["N/A"] empty_string = "" missing_image = "http://vyfhealth.com/wp-content/uploads/2015/10/yoga-placeholder1.jpg" expect(recipe.ingredients).must_equal empty_list expect(recipe.uri).must_equal empty_string expect(recipe.url).must_equal empty_string expect(recipe.dietary_info).must_equal empty_list expect(recipe.health_info).must_equal empty_list expect(recipe.image_url).must_equal missing_image end it 'must be able to populate options' do options = { ingredients: ["ingredients"], uri: ["uri"], url: ["url"], dietary_info: ["dietary_info"], image_url: "image_url", health_info: ["health_info"] } recipe = Recipe.new("bologne", options) expect recipe.must_respond_to :ingredients expect(recipe.ingredients).must_equal ["ingredients"] expect recipe.must_respond_to :uri expect(recipe.uri).must_equal ["uri"] expect recipe.must_respond_to :url expect(recipe.url).must_equal ["url"] expect recipe.must_respond_to :dietary_info expect(recipe.dietary_info).must_equal ["dietary_info"] expect recipe.must_respond_to :image_url expect(recipe.image_url).must_equal "image_url" expect recipe.must_respond_to :health_info expect(recipe.health_info).must_equal ["health_info"] end end
true
d7f2b5eab3fa93c701f3e0ab3031e910ec747f42
Ruby
mzheng6/cs125-Honors
/Ghost.rb
UTF-8
1,717
3.078125
3
[]
no_license
class Ghost < GameObject def initialize(window, x, y, image) super @image, @image2, @image3, @image4 = *Image.load_tiles(window, image, 15, 15, false) @count = 0 end def draw() @image.draw(@x, @y, 1, 1.0, 1.0) end def getcount() return @count end def addcount() @count += 1 end def clearcount() @count = 0 end end dir = @ghost.getdir() ghostcoord = @ghost.getcoord() gx = ghostcoord[0] gy = ghostcoord[1] if @ghost.getcount() != 0 @ghost.addcount() if @ghost.getcount() == 16 @ghost.clearcount() end if dir == 3 @ghost.update(1, 0) #going to the right elsif dir == 2 @ghost.update(-1, 0) #going to the left elsif dir == 0 @ghost.update(0, -1) #take it back now yall (down) elsif dir == 1 @ghost.update(0, 1) #going up else @ghost.update(0, 0) end @ghost.setdir(dir) return end posdir= Array.new if @ghost.isValid?(gx + 15, gy) && dir !=2 posdir.push(3) end if @ghost.isValid?(gx-1, gy) && dir != 3 posdir.push(2) end if @ghost.isValid?(gx, gy+15) && dir !=1 posdir.push(0) end if @ghost.isValid?(gx, gy-1) && dir != 0 posdir.push(1) end tempdir = posdir.sample if tempdir == 3 @ghost.update(1, 0) #going to the right elsif tempdir == 2 @ghost.update(-1, 0) #going to the left elsif tempdir == 0 @ghost.update(0, -1) #take it back now yall (down) elsif tempdir == 1 @ghost.update(0, 1) #going up else @ghost.update(0, 0) end @ghost.setdir(tempdir) if tempdir != dir @ghost.addcount() end
true
99b6cc4a54a7da7ccebe7dd5e3cd4d571182105a
Ruby
oriolbcn/ironhack_week1_excercises
/blocks/fizzbuzzpro.rb
UTF-8
690
4.3125
4
[]
no_license
class FizzBuzz def initialize(conditions) @conditions = conditions end def run 1.upto(100) do |i| print_number(i) end end def print_number(number) result = "" @conditions.each do |condition| condition_result = condition.call(number) if condition_result result += condition_result end end if result == "" puts number else puts result end end end fizz = lambda do |i| if i % 3 == 0 return "fizz" end end buzz = lambda do |i| if i % 5 == 0 return "buzz" end end paff = lambda do |i| if i % 10 == 0 return "paff" end end FizzBuzz.new([fizz, buzz, paff]).run
true
4b0bd796e4c83360f444b3ce432894060dd81869
Ruby
andres/donor
/app/models/person/search.rb
UTF-8
549
2.625
3
[ "MIT" ]
permissive
class Person::Search attr_accessor :term def self.with( term ) s = Person::Search.new s.term = term s.search end def search Person.where(" ((first_name || ' ' || last_name) ILIKE :term) OR ((last_name || ' ' || first_name) ILIKE :term) OR (business_name ILIKE :term) OR first_name ILIKE :term OR last_name ILIKE :term OR business_name ILIKE :term", term: "%#{term}%"). order('last_name') end end
true
0807a07767f618c48bebc4d97c3237f6d4a1bb84
Ruby
JohnnyHandy/ruby-tutorial
/The_is_a?_Method.rb
UTF-8
57
2.75
3
[]
no_license
p [1,2,3].class p [1,2,3].is_a?(Array) p 1.is_a?(Integer)
true
2b0496399efdc51d8a2a8b38f9e8368767b754a2
Ruby
joshuakemp1/Ruby
/recurrsion_examples.rb
UTF-8
169
3.203125
3
[]
no_license
def game(variable) if variable == 0 return 1 else return game(variable -1) + game (variable -1) end end my_var = game 26 puts "#{my_var}"
true
1ba13aba6ef973d99c635853d41cf878f16c6c54
Ruby
lyuehh/program_exercise
/ruby/ruby_test/1/2yield_canshu.rb
GB18030
162
3.8125
4
[]
no_license
#һĴ def yield_an_arg puts "Yielding 10!" yield(10) end yield_an_arg {|x| puts "> Code block received this argument: #{x}" }
true
da50d4714ab69f4231307988f2e4cd827753981c
Ruby
davidhusa/quickevent
/app/models/page.rb
UTF-8
889
2.625
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
class Page < ActiveRecord::Base attr_accessible :content, :title, :event_id # this turns the title into something url-friendly before saving before_validation { |page| page.title = page.title.downcase.gsub(' ', '-') } validates :title, :uniqueness => true validates :title, :presence => true validates_format_of :title, :without => /\//, :message => "Cannot use forward slash in titles." validates_exclusion_of :title, :in => ["admin", "news", "map", "locations", "schedule", "twitter", "about", "locationjson"], :message => "That page title is reserved." # this makes it Title Case again def pretty_title self.title.gsub('-', ' ').titlecase end def short_content maxlength = 32 (self.content[0...maxlength] || "") + (self.content.length > maxlength ? "..." : "") end end
true
6d0d91dce3fa1decced7f1f32fcaed953a3a41cc
Ruby
kevxo/backend_module_0_capstone
/day_3/ex1.rb
UTF-8
980
4.21875
4
[]
no_license
people = 20 cats = 30 dogs = 15 if people < cats && dogs < people puts "Too many cats! The world is doomed!" end if people > cats puts "Not many cats! The world is saved!" end if people < dogs puts "The world is drooled on!" end if people > dogs puts "The world is dry!" end dogs += 5 if !people >= dogs puts "People are greater than or equal to dogs." end if people <= dogs || cats > dogs puts "People are less than or equal to dogs." end if people == dogs puts "People are dogs." end # Study drills. =begin 1. The if statement checks if the following condition is true. 2. Needs to be indented because thats where we will put what we want the computer to do if its true. Its inside of the scope of that condition. 3. If its not indented the computer wont do what you want it to do. 4.Yes you can put other boolean expressions. 5. If we change the initial conditions all the other conditions will be equal to something differen than the original. =end
true
148187e29319299841fe6484cdd9cf0e1c20cdbc
Ruby
ricofehr/nextdeploy
/ror/app/models/systemimagetype.rb
UTF-8
390
2.578125
3
[ "MIT" ]
permissive
# Store all exploitation system whi are the same type: unix / linux / windows mainly # # @author Eric Fehr (ricofehr@nextdeploy.io, github: ricofehr) class Systemimagetype < ActiveRecord::Base # One exploitation system is caracterised by one unique property type has_many :systemimages, dependent: :destroy # some properties are mandatory and must be well-formed validates :name, presence: true end
true
16b253a3a2c650ff3d2f943dd601372909d2e7e9
Ruby
mameyer/control-orogen-motion_controller
/scripts/helpers/general.rb
UTF-8
3,228
2.625
3
[]
no_license
#! /usr/bin/env ruby @inSim = true # Defines which kind of slam shuld be used, graph_slam or slam3d. @use_slam3d = false class TaskStruct attr_accessor :name attr_accessor :task attr_accessor :config def initialize() @config = Array.new @config << "default" end end def getTask(name, taskArray = nil) task = Orocos.name_service.get name if(taskArray) struct = TaskStruct.new() struct.name = name struct.task = task taskArray << struct end task end def addConfig(task, config, taskArray) searchedStruct = nil #this is slow, but we don't care for now... taskArray.each do |struct| if(task == struct.task) searchedStruct = struct break; end end if(!searchedStruct) raise("Task #{taks} is not registered") end searchedStruct.config << config end def setAllConfigs(taskArray) taskArray.each do |struct| puts("Applying config #{struct.config} to task #{struct.name}") Orocos.conf.apply(struct.task, struct.config, true) end end def setupAllTransformers(taskArray) taskArray.each do |struct| puts("Setting up Transformer for #{struct.name}") Bundles.transformer.setup(struct.task) end end def configureAll(taskArray) taskArray.each do |struct| puts("Configuring Task #{struct.name}") struct.task.configure() end end def startAll(taskArray) taskArray.each do |struct| puts("Starting Task #{struct.name}") struct.task.start() end end def wait_for(task_context, state) loop = true while loop if task_context.state == state puts "#{task_context.name}: state #{task_context.state} entered" loop = false end sleep(0.01) end end def task_in_exception(task) if(task.exception?) puts "Task #{task.name} is in exception state and will be restarted" task.reset_exception else return false end if(task.running?) task.stop end if(task.ready?) task.cleanup end task.configure task.start puts "Task #{task.name} has been restarted" return true end def start_task(task) if not task.running? task.configure task.start end end def stop_task(task) if task.running? task.stop wait_for(task, :STOPPED) end if task.ready? task.cleanup wait_for(task, :PRE_OPERATIONAL) end end def restart(task) if(task.exception?) task.reset_exception end if task.running? stop_task(task) end start_task(task) wait_for(task, :RUNNING) end def try_to_get_task(task_name, exit_on_failure=false) task = nil begin task = Orocos.name_service.get task_name puts "\n Task #{task_name} found" rescue Exception => e puts e.message puts "\nCould not find task #{task_name}. Retry (y/n)?" ret = $stdin.gets.chomp if(ret == 'y') return try_to_get_task(task_name) else if exit_on_failure exit(-1) end return nil end end return task end
true
7bb55ad6fa90f3339282bcc8b26c31dfc583a8f4
Ruby
ggwc82/airport_challenge
/spec/weather_spec.rb
UTF-8
249
2.734375
3
[]
no_license
require 'weather' describe Weather do subject(:weather) { Weather.new } describe "#condition" do it "returns sunny or stormy when called" do expect(weather.condition).to satisfy {|s| ["sunny", "stormy"].include?(s)} end end end
true
c548d801f35f2a1f5ac400192a83f84166cb0b72
Ruby
rongxanh88/cloney_island_airbnb
/app/services/cancellation_policy.rb
UTF-8
757
3.203125
3
[ "MIT" ]
permissive
class CancellationPolicy attr_reader :name, :refund, :description def initialize(name) @name = name set_refund set_description end private def set_refund if name == "Flexible" @refund = "100%" elsif name == "Moderate" @refund = "50%" else @refund = "0%" end end def set_description if name == "Flexible" @description = "Cancellation policy is flexible with 100% refund with at least 1 week notice." elsif name == "Moderate" @description = "Cancellation policy is moderate with 50% refund with at least 1 week notice." else @description = "Cancellation policy is strict with 0% refund once listing is reserved." end end end
true
89af0b796d35f2bda914b9f941667a02f7e0fbdd
Ruby
Sufl0wer/summer-2019
/3581/1/command_line_parser.rb
UTF-8
666
2.84375
3
[]
no_license
require 'optparse' class CommandLineParser class << self def read_args add_args = { 'file' => 'gems.yml' } OptionParser.new do |arg| pass_params(arg, add_args) end.parse! add_args end def find_gem_by_name(hash_gems, add_args) hash_gems.select! { |name, _| name.include?(add_args['name']) } end private def pass_params(arg, add_args) arg.on('-t', '--top = t', Integer) { |count| add_args['top'] = count } arg.on('-n', '--name = n', String) { |gem_name| add_args['name'] = gem_name } arg.on('-f', '--file = f', String) { |file_name| add_args['file'] = file_name } end end end
true
8f2e40ac61cb96710f1daa3b000435b19006d129
Ruby
fjur/Quick-Union
/Percolation/Percolation.rb
UTF-8
3,690
3.296875
3
[]
no_license
# public class Percolation { # public Percolation(int N) // create N-by-N grid, with all sites blocked # public void open(int i, int j) // open site (row i, column j) if it is not open already # public boolean isOpen(int i, int j) // is site (row i, column j) open? # public boolean isFull(int i, int j) // is site (row i, column j) full? # public boolean percolates() // does the system percolate? # public static void main(String[] args) // test client (optional) # } #we need to create two imaginary roots at TOP ROW and at BOTTOM ROW require_relative "WeightedQuickUnion" class Percolation attr_reader :percolation_values, :quick_union_values def initialize(n) @size = n @percolation_values = Array.new(n*n) { "B"} @quick_union_values = WeightedQuickUnion.new(n*n + 2) # 1(Top) + n*n + 1(bottom) end def open(i, j) #row, column row = (i - 1) column = (j - 1) current_index = row * @size + column if self.percolation_values[current_index] == "F" return end self.percolation_values[current_index] = "O" if i == 1 #Open top and make full union_virtual_top(current_index) elsif i == @size #connect to bottom virtual node union_virtual_bottom(current_index) end indicies = Hash.new(0) indicies[:left_index] = {row: i, column: (j - 1), valid: j == 1 ? false : true}#[row, column - 1, j == 1 ? false : true, left_index] indicies[:right_index] = {row: i, column: (j + 1), valid: j == @size ? false : true}#[row, column + 1, j == @size ? false : true, right_index] indicies[:top_index] = {row: (i - 1), column: j, valid: i == 1 ? false : true}#[(row - 1), column, i == 1 ? false : true, top_index] indicies[:bottom_index] = {row: (i + 1), column: j, valid: i == @size ? false : true}#[(row + 1), column, i == @size ? false : true, bottom_index]; #connect all open and full #check if I am connected to parent #update all the other open branches indicies.each do |index, value| section_index = (value[:row] - 1) * @size + (value[:column] - 1) if (is_full?(value[:row], value[:column]) || is_open?(value[:row], value[:column])) if value[:valid] == true self.quick_union_values.union(current_index, section_index) end end end if self.quick_union_values.connected(0, current_index) self.percolation_values[current_index] = "F" self.pretty_print indicies.each do |index, value| section_index = (value[:row] - 1) * @size + (value[:column] - 1) if (is_open?(value[:row], value[:column]) && value[:valid] == true) self.open(value[:row], value[:column]) end end end end def is_open?(i, j) row = (i - 1) column = (j - 1) current_index = row * @size + column self.percolation_values[current_index] == "O" ? true : false end def is_full?(i, j) row = (i - 1) column = (j - 1) current_index = row * @size + column self.percolation_values[current_index] == "F" ? true : false end def percolates? self.quick_union_values.connected(0, @size*@size+1) end def pretty_print @percolation_values.length.times do |i| print @percolation_values[i] + " " puts " " unless (i + 1) % @size != 0 end end private def union_virtual_top(index) self.quick_union_values.union(0, index) end def union_virtual_bottom(index) self.quick_union_values.union(@size**2 + 1, index) end end size = 20 a = Percolation.new(size) while !a.percolates? rand1 = rand 1..size rand2 = rand 1..size a.open(rand1, rand2) end puts a.percolates?
true
ae254d105d3b7ea2e341b11fd7458879a7a2e6b5
Ruby
BenTopping/traction-service
/app/models/ont/run_factory.rb
UTF-8
1,253
2.53125
3
[]
no_license
# frozen_string_literal: true # Ont namespace module Ont # RunFactory # Creates or updates a run from a list of flowcell metadata. class RunFactory include ActiveModel::Model validate :check_run def initialize(flowcell_specs = [], run = nil) @run = run || Ont::Run.new @old_flowcells = @run.flowcells.to_a build_flowcells(flowcell_specs) end attr_reader :run def save(**options) return false unless options[:validate] == false || valid? run.save(validate: false) old_flowcells.each(&:destroy) true end private attr_reader :old_flowcells def build_flowcells(flowcell_specs) run.flowcells.clear flowcell_specs.each do |flowcell_spec| # The flowcell requires a library, so if a library does not exist # the flowcell, and therefore factory, will be invalid. library = Ont::Library.find_by(name: flowcell_spec[:library_name]) run.flowcells.build(position: flowcell_spec[:position], run: run, library: library) end end def check_run errors.add('run', 'was not created') if run.nil? return if run.valid? run.errors.each do |k, v| errors.add(k, v) end end end end
true
b520c3a8a94d81a3c8e698efe57c7040bfa1824e
Ruby
Priya67/Daily_Work
/w2d3-master/poker/lib/card.rb
UTF-8
175
3.03125
3
[]
no_license
class Card attr_reader :number, :suit def initialize(number, suit) @number = number @suit = suit end end # card1 < card2 # # card1 == card2 # # [cards].sort
true
96da7e794487aa22636727c5d8c4dac8a5f6e930
Ruby
inyoungcome/ruby-des
/test/key_schedule_test.rb
UTF-8
1,579
2.53125
3
[ "MIT" ]
permissive
require 'test_helper' class KeyScheduleTest < Test::Unit::TestCase fixtures :key_schedule def setup @key_schedule = KeySchedule.new(key_schedule(:test_key)) end def test_class assert_kind_of KeySchedule, @key_schedule end def test_test_key assert_kind_of Array, @key_schedule.key assert_equal key_schedule(:test_key), @key_schedule.key end def test_sub_keys assert_kind_of Array, @key_schedule.sub_keys assert_equal key_schedule(:sub_key_1), @key_schedule.sub_keys[0] assert_equal key_schedule(:sub_key_2), @key_schedule.sub_keys[1] assert_equal key_schedule(:sub_key_3), @key_schedule.sub_keys[2] assert_equal key_schedule(:sub_key_4), @key_schedule.sub_keys[3] assert_equal key_schedule(:sub_key_5), @key_schedule.sub_keys[4] assert_equal key_schedule(:sub_key_6), @key_schedule.sub_keys[5] assert_equal key_schedule(:sub_key_7), @key_schedule.sub_keys[6] assert_equal key_schedule(:sub_key_8), @key_schedule.sub_keys[7] assert_equal key_schedule(:sub_key_9), @key_schedule.sub_keys[8] assert_equal key_schedule(:sub_key_10), @key_schedule.sub_keys[9] assert_equal key_schedule(:sub_key_11), @key_schedule.sub_keys[10] assert_equal key_schedule(:sub_key_12), @key_schedule.sub_keys[11] assert_equal key_schedule(:sub_key_13), @key_schedule.sub_keys[12] assert_equal key_schedule(:sub_key_14), @key_schedule.sub_keys[13] assert_equal key_schedule(:sub_key_15), @key_schedule.sub_keys[14] assert_equal key_schedule(:sub_key_16), @key_schedule.sub_keys[15] end end
true
9f371438d49332a1f4a355b2d0c7062b33ffa41f
Ruby
Boucherie/object_oriented_programming2
/vampire.rb
UTF-8
842
3.46875
3
[]
no_license
class Vampire attr_reader :name, :age attr_accessor :in_coffin, :drank_blood_today @@coven = [] def initialize(name, age) @name = name @age = age @in_coffin = false @drank_blood_today = false end def self.create fledgling = Vampire.new(name, age, in_coffin, drank_blood_today) @@coven << fledgling fledgling end def drink_blood if @drank_blood_today == false @drank_blood_today == true end def sunrise @@coven.each do |ind_vampire| if @drank_blood_today == false puts "Starved" @@coven.delete(ind_vampire) end if @in_coffin == false puts "Poof!" @@coven.delete(ind_vampire) end end end def sunset @drank_blood_today == false @in_coffin == false end def go_home @in_coffin == true end end
true
5c8520fe96ed47073d4504475e98dbd99ec4becf
Ruby
horandago/Waifu-Quest
/lib/Npc/barkeeper.rb
UTF-8
1,219
3.203125
3
[]
no_license
require_relative '../npc.rb' class Barkeeper < Npc attr_reader :deny ALE_COST = 10 def initialize @@shop_list = ['Ale', 'Exit'] @deny = "Barkeeper: Geeee aaaat ya god damn droonk!" end def speak @dialogue = ["VL1","VL2","VL3"] anim("#{@dialogue.sample}") end def shop anim("Wa can ee get fur yuu?") loop do puts "----------" puts "Buy\nSell\nExit" puts "----------" puts "#{$player.name}: #{$player.gp}gp" ans = gets.chomp.downcase until ans == "buy" || ans == "sell" || ans == "exit" ans = gets.chomp.downcase end if ans == "buy" puts "----------" puts "Ale - #{ALE_COST}gp" puts "Exit" puts "----------" ans = gets.chomp.downcase.capitalize! until @@shop_list.include? ans puts "Please type that correctly:" ans = gets.chomp.downcase.capitalize! end case ans when 'Exit' return speak when 'Ale' $inventory.buy(Ale.new, self) end elsif ans == "sell" anim("Barkeeper: \"This ere be a fookin poob ya dingus!!\"\n\"We dern wun yer\"\n...\n...\n\"yer\"\n..\n\"fookin ell\"\n...\nThe bar keeper is way too drunk to deal with sales") elsif ans == "exit" break end end end end $barkeeper = Barkeeper.new
true
4a089ff22d07d14c664c8ec5d4a860b9e5ae24c9
Ruby
aronsonben/School-Projects
/CMSC330/p2_OCaml/p2a_OCaml-Basics/testing/framework/test.rb
UTF-8
10,759
2.703125
3
[]
no_license
require_relative "test_utils.rb" require "yaml" require "fileutils" require "logger" require "open3" class TestCase @@MODULE_DIR_PREFIX = "module" @@MODULE_CONFIG_FILE = "module.yml" @@MODULE_EXPECTED_OUTPUT_FILE = "expected_output" @@MODULE_STUDENT_OUTPUT_FILE = "student_output" @@MODULE_STUDENT_ERROR_FILE = "student_error" # Create a logger that really functions more like a discretionary print system @@LOGGER = Logger.new(STDOUT) @@LOGGER.level = Logger::INFO @@LOGGER.formatter = proc { |severity, datetime, progname, msg| "#{msg}\n" } # All we need to know to run a test case is: # - What it's called # - Where it is # - How many modules it has def initialize(test_name, test_type, test_dir, num_modules) @leavenotrace = false # Parse flags like a caveman ARGV.each{|flag| # -d switches into debug mode if (flag == "-v") @@LOGGER.level = Logger::DEBUG @@LOGGER.info{"Starting in verbose mode"} elsif (flag == "-nt") @@LOGGER.info{"Starting in notrace mode (auto-deletes output files)"} @leavenotrace = true end } @test_name = test_name @test_type = test_type @@LOGGER.info{"================================================="} @@LOGGER.info{"Running test: #{test_type} #{test_name}"} @@LOGGER.debug{"Initializing testing setup..."} # Ensure that the test directory exists unless File.directory?(test_dir) @@LOGGER.fatal{"Test directory (#{test_dir}) was not found"} exit 2 else @test_dir = test_dir if test_dir =~ /^\.\// @test_dir = test_dir[2..-1] elsif test_dir =~/^\.\\\\/ @test_dir = test_dir[3..-1] end @@LOGGER.debug{"\tTest directory: #{@test_dir}"} end @num_modules = num_modules @module_configs = Array.new(@num_modules) @@LOGGER.debug{"\tNumber of test modules: #{@num_modules}"} ############################################## # Validate that all necessary files are here # ############################################## @@LOGGER.debug{"Validating module structure..."} # Ensure that every module has the necessary components @num_modules.times{|i| @@LOGGER.debug{"\tValidating files for module #{i}... "} unless File.directory?(get_module_dir i) integrity_exit "Missing module directory for module #{i}" end unless File.exists?(get_module_config_file i) integrity_exit "Missing module config file for module #{i}" end unless File.exists?(get_module_output_file i) integrity_exit "Missing module output file for module #{i}" end # Load the config file @module_configs[i] = YAML::load_file(get_module_config_file i) # This might not be how this works if @module_configs[i] == nil integrity_exit "Couldn't parse config file for module #{i}" end @@LOGGER.debug{"\t\tModule #{i} is valid!"} } @@LOGGER.debug{"All files validated, ready to test!"} end def integrity_exit(message) @@LOGGER.fatal{"TEST FILE INCONSISTENTY: #{message}"} exit 2 end # Runs all modules for this test def run fail_flag = false @num_modules.times{|module_num| @@LOGGER.info{"Running module #{module_num}"} ################################### # Poor man's dependency injection # ################################### # Map to absolute paths filename_map = {} module_dir = get_module_dir(module_num) @to_cleanup = [] at_exit{ @to_cleanup.each{|e| @@LOGGER.debug{"Cleaning local dependency '#{e}'"} FileUtils.rm e } } # First, find dependencies and remap standard_dependencies = get_config_attribute(module_num, "dependencies") local_dependencies = get_config_attribute(module_num, "local_dependencies") standard_dependencies = [] if standard_dependencies == nil local_dependencies = [] if local_dependencies == nil (standard_dependencies + local_dependencies).each{|dependency| @@LOGGER.debug{"\tSearching for dependency '#{dependency}'"} filename_map[dependency] = File.join(module_dir, dependency) in_local = filename_map[dependency] in_typed = File.join(module_dir, "..", "..", "..", "common", @test_type, dependency) in_all = File.join(module_dir, "..", "..", "..", "common", "all", dependency) in_home = File.join(module_dir, "..", "..", "..", "..", dependency) in_test_home = File.join(module_dir, "..", "..", "..", dependency) if (File.exists? in_local) @@LOGGER.debug{"\t\tFound '#{dependency}' in module directory"} elsif (File.exists? in_typed) filename_map[dependency] = in_typed @@LOGGER.debug{"\t\tFound '#{dependency}' in #{@test_type} resources directory"} elsif (File.exists? in_all) filename_map[dependency] = in_all @@LOGGER.debug{"\t\tFound '#{dependency}' in common resources directory"} elsif (File.exists? in_home) filename_map[dependency] = in_home @@LOGGER.debug{"\t\tFound '#{dependency}' in the project home directory"} elsif (File.exists? in_test_home) filename_map[dependency] = in_test_home @@LOGGER.debug{"\t\tFound '#{dependency}' in the testing home directory (for submit server use)"} else puts "Couldn't find dependency '#{dependency}'" exit 2 end # If it's a local dependency, copy it in and mark it for cleanup # Local dependencies should be used for things like dependencies to an OCaml file if local_dependencies.include?(dependency) @@LOGGER.debug{"\t\tPulling local dependency '#{dependency}'"} #stdout, stderr, status = Open3.capture3("cp #{filename_map[dependency]} #{in_local}") FileUtils.cp(filename_map[dependency], in_local) filename_map.delete dependency @to_cleanup.push in_local end } @@LOGGER.debug{"\tApplying resource mapping"} # Substitute absolute paths in for file names command = get_config_attribute(module_num, "command") filename_map.each_pair{|k, v| command.sub!(k, v)} ################################ # Actually run the test module # ################################ student_output = get_student_output_file(module_num) student_error = get_student_error_file(module_num) expected_output = get_module_output_file(module_num) # Run the test command and capture student outputs @@LOGGER.debug{"\tRunning test command: '#{command}'"} stdout, stderr, status = Open3.capture3(command) # Output student stdout @@LOGGER.debug{"\tOutputting student stdout to #{student_output}"} f = File.open(student_output, "w") f << stdout f.close # Output student stderr @@LOGGER.debug{"\tOutputting student stderr to #{student_error}"} if File.exists?(student_error) File.delete(student_error) end if !@leavenotrace && stderr != nil && stderr != "" e = File.open(student_error, "w") e << stderr e.close end if status == 0 @@LOGGER.debug{"\tComparing '#{student_output}' with '#{expected_output}'"} error_message = do_comparison(expected_output, student_output) else #@@LOGGER.debug{"\tThe test command exited with a non-zero status"} #@@LOGGER.debug{"STDOUT:"} #@@LOGGER.debug{`cat #{student_output}`} #@@LOGGER.debug{"STDERR:"} #@@LOGGER.debug{`cat #{student_error}`} error_message = "A non-zero exit status was received" end unless error_message == nil @@LOGGER.info{"\tModule #{module_num} has failed!"} @@LOGGER.info{"\tError message: '#{error_message}'"} fail_flag = true else @@LOGGER.info{"\tModule #{module_num} has passed!"} end #If in notrace mode, delete output files if @leavenotrace @@LOGGER.debug{"\tPerforming output cleanup (in notrace mode)"} [student_output, student_error].each{|f| @@LOGGER.debug{"\t\tRemoving #{f}"} if (File.exists?(f)) File.delete(f) end } end } unless fail_flag @@LOGGER.info{"Test passed!"} exit 0 else @@LOGGER.info{"Test failed!"} exit 1 end end ###################################################################### # Getters for filenames in case this kind of structure changes later # # #################################################################### def get_config_attribute(modulenum, attribute) @module_configs[modulenum][attribute] end def get_module_dir(modulenum) return File.join(@test_dir, "#{@@MODULE_DIR_PREFIX}#{modulenum}") end def get_module_config_file(modulenum) return File.join(get_module_dir(modulenum), @@MODULE_CONFIG_FILE) end def get_module_output_file(modulenum) return File.join(get_module_dir(modulenum), @@MODULE_EXPECTED_OUTPUT_FILE) end def get_student_output_file(modulenum) return File.join(get_module_dir(modulenum), @@MODULE_STUDENT_OUTPUT_FILE) end def get_student_error_file(modulenum) return File.join(get_module_dir(modulenum), @@MODULE_STUDENT_ERROR_FILE) end end
true
a7dc48918ec6ee2479f4ee54e78e19fad4ec512e
Ruby
mikylamoehlenbruck/rb101
/exercises/easy2.rb/ex2.rb
UTF-8
1,086
3.78125
4
[]
no_license
SQRMETERS_TO_SQRFEET = 10.7639 SQRFEET_TO_SQRINCHES = 12**2 SQRINCHES_TO_SQRCM = 100**2 def get_length_meters puts "Enter the length of the room in meters:" length = gets.chomp.to_f end def get_width_meters puts "Enter the width of the room in meters:" width = gets.chomp.to_f end def gets_length_feet puts "Enter the length of the room in feet:" length = gets.chomp.to_f end def gets_width_feet puts "Enter the width of the room in feet:" width = gets.chomp.to_f end length_meters = get_length_meters width_meters = get_width_meters sqr_meters = (length_meters * width_meters).round(2) sqr_feet = (sqr_meters * SQRMETERS_TO_SQRFEET).round(2) puts "The area of the room is #{sqr_meters} square meters (#{sqr_feet} square feet)" length_feet = gets_length_feet width_feet = gets_width_feet sqr_feet = (length_feet * width_feet).round(2) sqr_inches = (sqr_feet * SQRFEET_TO_SQRINCHES).round(2) sqr_cm = (sqr_inches * SQRINCHES_TO_SQRCM).round(2) puts "The area of the room is #{sqr_feet} square feet, #{sqr_inches} square inches and #{sqr_cm} square centimeters"
true
6d18a8107c4a5d58f0c7018eb6407081bdcf2d97
Ruby
zydronium/DevelopersAnonymous
/ruby/gilded_rose_test.rb
UTF-8
3,366
2.640625
3
[ "CC-BY-4.0", "CC-BY-3.0" ]
permissive
require 'test/unit' require_relative 'gilded_rose' class GildedRoseTest < Test::Unit::TestCase MAX_BACKSTAGE_SELLIN = 30 MAX_QUALITY = 50 attr_reader :gilded_rose, :items, :random def setup @gilded_rose = GildedRose.new @items = gilded_rose.make_items @random = Random.new(3456789) end def test_after_one_day repeat_update_quality(1) assert_equal(items.map(&:name), [ "+5 Dexterity Vest", "Aged Brie", "Elixir of the Mongoose", "Sulfuras, Hand of Ragnaros", "Backstage passes to a TAFKAL80ETC concert", "Conjured Mana Cake"] ) assert_equal([19, 1, 6, 80, 21, 5], items.map(&:quality)) assert_equal([9, 1, 4, 0, 14, 2], items.map(&:sell_in)) end def test_after_three_days repeat_update_quality(3) assert_equal(items.map(&:name), [ "+5 Dexterity Vest", "Aged Brie", "Elixir of the Mongoose", "Sulfuras, Hand of Ragnaros", "Backstage passes to a TAFKAL80ETC concert", "Conjured Mana Cake"] ) assert_equal([17, 4, 4, 80, 23, 3], items.map(&:quality)) assert_equal([7, -1, 2, 0, 12, 0], items.map(&:sell_in)) end def after_a_shitload_of_days repeat_update_quality(500) assert_equal(items.map(&:name), [ "+5 Dexterity Vest", "Aged Brie", "Elixir of the Mongoose", "Sulfuras, Hand of Ragnaros", "Backstage passes to a TAFKAL80ETC concert", "Conjured Mana Cake"] ) assert_equal([0, 50, 0, 80, 0, 0], items.map(&:quality)) assert_equal([-490, -498, -495, 0, -485, -497], items.map(&:sell_in)) end def test_backstage_pass_golden_copy items = a_bunch_of_backstage_passes items = a_bunch_of_backstage_passes repeat_update_quality(11) assert_equal( [5, 40, 49, 16, 6, 28, 42, 38, 24, 48, 24, 18, 7, 49, 6, 49, 19, 49, 11, 44, 18, 36, 9, 0, 8, 38, 2, 31, 22, 46, 19, 7, 28, 48, 3, 26, 39, 5, 22, 46, 4, 16, 1, 46, 39, 8, 48, 45, 6, 27, 16, 1, 24, 42, 45, 42, 6, 25, 29, 9, 1, 2, 1, 37, 2, 31, 25, 13, 30, 12, 44, 19, 6, 2, 36, 37, 29, 33, 27, 30, 31, 12, 23, 30, 2, 36, 35, 13, 4, 14, 22, 46, 33, 9, 44, 18, 33, 38, 28, 31], items.map(&:quality)) assert_equal( [23, 17, 14, 28, 28, 8, 4, 8, 26, 1, 17, 5, 23, 22, 23, 9, 27, 13, 3, 16, 28, 27, 7, 12, 14, 15, 8, 21, 0, 3, 10, 27, 15, 19, 17, 6, 17, 24, 24, 17, 0, 25, 9, 5, 22, 0, 29, 18, 23, 17, 22, 23, 11, 10, 18, 25, 5, 17, 14, 9, 15, 0, 6, 28, 5, 29, 24, 8, 28, 1, 29, 27, 14, 29, 13, 28, 14, 4, 23, 7, 18, 19, 27, 13, 0, 22, 28, 7, 5, 17, 3, 16, 29, 6, 24, 8, 0, 29, 23, 11] , items.map(&:sell_in)) end private def repeat_update_quality(n) n.times do gilded_rose.update_quality(items) end end def a_bunch_of_backstage_passes (0...100).map do a_random_backstage_pass end end def a_random_backstage_pass GildedRose::Item.new("Backstage passes to a TAFKAL80ETC concert", random_sell_in, random_quality) end def random_sell_in random.rand(0...MAX_BACKSTAGE_SELLIN) end def random_quality random.rand(0...MAX_QUALITY) end end
true
3fbbed50b015ae4333e74afbbb049a6c17cd7db2
Ruby
henryaj/word-frequency-counter
/count.rb
UTF-8
654
4.3125
4
[ "MIT" ]
permissive
# Word frequency counter by Henry Stanley puts "Please enter your text. >" text = gets.chomp words = text.split(" ") # takes 'text' and splits using a space as a delimiter, assigns those words to an array # set up a new hash called frequencies, with default value 0 frequencies = Hash.new(0) # iterate over the array of words, putting each into the hash and incrementing by 1 words.each do |x| frequencies[x] +=1 end # sort the frequencies, then reverse the order so it is descending frequencies = frequencies.sort_by {|a, b| b} frequencies.reverse! # print each word out in order frequencies.each do |word, value| puts word + " " + value.to_s end
true
0052029c8e0fa4bbe45bab53d0571840f2b655e8
Ruby
nelsonjma/sql_to_datafile
/study/threads/threads_demo_a.rb
UTF-8
1,032
3.625
4
[]
no_license
require 'rubygems' def funcA i=0 while i <=10 puts 'func A at: ' + Time.now.to_s + "\n" sleep(2) i=i+1 end return 69 end def funcB (0..10).each do puts 'func B at: ' + Time.now.to_s + "\n" sleep(2) end return 70 end puts 'Start Threads at: ' + Time.now.to_s ############# thread list ############# ths = [] ############# return data list ############# thsReturn = [] ############# generate threads that will return results to array list ############# 100.times do |i| ths[i] = Thread.new{thsReturn.push(funcA)} ths[i] = Thread.new{thsReturn.push(funcB)} end ############ Wait threads to end ############# while true # variable the control thread ends isthalive = false # check if all threads are alive ths.each do |th| isthalive = true if th.alive? end # if all threads are thead then end waiting break if !isthalive end ############### Show results from threads ################# thsReturn.each do |ret| puts ret end puts 'The end at: ' + Time.now.to_s
true
b87cdd09db4c2d9a8a955d8a038aed29712886fb
Ruby
saner/masterclass-res
/lib/aggregates/article.rb
UTF-8
626
2.53125
3
[]
no_license
require 'aggregate_root' module Aggregates class Article include AggregateRoot AlreadyCreated = Class.new(StandardError) def initialize(id) @id = id @state = :draft end def create(author:, title:, content:) raise AlreadyCreated if @state == :created apply ArticleCreated.new( data: { article_id: @id, author: author, title: title, content: content } ) end on ArticleCreated do |event| @author = event.data[:author] @title = event.data[:title] @content = event.data[:content] @state = :created end end end
true
f2955c315f7b6110d6436ff5cb63e4b940a093fd
Ruby
hanami/view
/lib/hanami/view/exposures.rb
UTF-8
1,822
2.578125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "tsort" require "dry/core/equalizer" module Hanami class View # @api private class Exposures include Dry::Equalizer(:exposures) include TSort attr_reader :exposures def initialize(exposures = {}) @exposures = exposures end def key?(name) exposures.key?(name) end def [](name) exposures[name] end def each(&block) exposures.each(&block) end def add(name, proc = nil, **options) exposures[name] = Exposure.new(name, proc, **options) end def import(name, exposure) exposures[name] = exposure.dup end def bind(obj) bound_exposures = exposures.each_with_object({}) { |(name, exposure), memo| memo[name] = exposure.bind(obj) } self.class.new(bound_exposures) end def call(input) # Avoid performance cost of tsorting when we don't need it names = if exposures.values.any?(&:dependencies?) # TODO: this sholud be cachable at time of `#add` tsort else exposures.keys end names .each_with_object({}) { |name, memo| next unless (exposure = self[name]) value = exposure.(input, memo) value = yield(value, exposure) if block_given? memo[name] = value } .tap { |hsh| names.each do |key| hsh.delete(key) if self[key].private? end } end private def tsort_each_node(&block) exposures.each_key(&block) end def tsort_each_child(name, &block) self[name].dependency_names.each(&block) if exposures.key?(name) end end end end
true
39a3ce9b10d3c9fbd43c6a9f4d56495c4fe3c29a
Ruby
boisyyy/ruby-challenges
/person.rb
UTF-8
499
3.953125
4
[]
no_license
class Person attr_accessor :name, :age attr_reader :birth_year def initialize(name, birth_year) @name = name @age = 2019 - birth_year.to_i @birth_year = birth_year end def to_s return "name: #{@name}, age: #{age}" end end person = Person.new("Janel", 1973) puts person person.name = "Vic" #to_s instant variable name #puts person #def name return @name #person.name = "Vic" #puts person.name #puts person #person.age = 12 #puts person.age
true
92a6ff14398963c79bb26c2cde8db125f6ce22e9
Ruby
activefx/data_miner
/lib/data_miner/step/sql.rb
UTF-8
3,643
2.59375
3
[ "MIT" ]
permissive
require 'csv' require 'tmpdir' require 'posix/spawn' require 'unix_utils' class DataMiner class Step # A step that executes a SQL, either from a string or as retrieved from a URL. # # Create these by calling +sql+ inside a +data_miner+ block. # # @see DataMiner::ActiveRecordClassMethods#data_miner Overview of how to define data miner scripts inside of ActiveRecord models. # @see DataMiner::Script#sql Creating a sql step by calling DataMiner::Script#sql from inside a data miner script class Sql < Step URL_DETECTOR = %r{^[^\s]*/[^\*]} # Description of what this step does. # @return [String] attr_reader :description # Location of the SQL file. # @return [String] attr_reader :url # String containing the SQL. # @return [String] attr_reader :statement # @private def initialize(script, description, url_or_statement, ignored_options = nil) @script = script @description = description if url_or_statement =~ URL_DETECTOR @url = url_or_statement else @statement = url_or_statement end end # @private def start if statement ActiveRecord::Base.connection.execute statement else tmp_path = UnixUtils.curl url send config[:adapter], tmp_path File.unlink tmp_path end end private def config if ActiveRecord::Base.respond_to?(:connection_config) ActiveRecord::Base.connection_config else ActiveRecord::Base.connection_pool.spec.config end end def mysql(path) connect = if config[:socket] [ '--socket', config[:socket] ] else [ '--host', config.fetch(:host, '127.0.0.1'), '--port', config.fetch(:port, 3306).to_s ] end argv = [ 'mysql', '--compress', '--user', config[:username], "-p#{config[:password]}", connect, '--default-character-set', 'utf8', config[:database] ].flatten File.open(path) do |f| pid = POSIX::Spawn.spawn(*(argv+[{:in => f}])) ::Process.waitpid pid end unless $?.success? raise RuntimeError, "[data_miner] Failed: ARGV #{argv.join(' ').inspect}" end nil end alias :mysql2 :mysql def postgresql(path) env = {} env['PGHOST'] = config['host'] if config['host'] env['PGPORT'] = config['port'].to_s if config['port'] env['PGPASSWORD'] = config['password'].to_s if config['password'] env['PGUSER'] = config['username'].to_s if config['username'] argv = [ 'psql', '--quiet', '--dbname', config[:database], '--file', path ].flatten child = POSIX::Spawn::Child.new(*([env]+argv)) $stderr.puts child.out $stderr.puts child.err unless child.success? raise RuntimeError, "[data_miner] Failed: ENV #{env.inspect} ARGV #{argv.join(' ').inspect} (#{child.err.inspect})" end nil end def sqlite3(path) argv = [ 'sqlite3', config[:database] ] File.open(path) do |f| pid = POSIX::Spawn.spawn(*(argv+[{:in => f}])) ::Process.waitpid pid end unless $?.success? raise RuntimeError, %{[data_miner] Failed: "cat #{path} | #{argv.join(' ')}"} end nil end end end end
true
6835b13b7f2fed79449b2b157c58b36ba11c6957
Ruby
joestephens/ruby-kickstart
/session1/3-challenge/7_string.rb
UTF-8
483
3.921875
4
[ "MIT" ]
permissive
# given a string, return the character after every letter "r" # # pirates_say_arrrrrrrrr("are you really learning Ruby?") # => "eenu" # pirates_say_arrrrrrrrr("Katy Perry is on the radio!") # => "rya" # pirates_say_arrrrrrrrr("Pirates say arrrrrrrrr") # => "arrrrrrrr" def pirates_say_arrrrrrrrr(string) chars = string.split(//) new_string = '' chars.each_with_index do |i, index| new_string << chars[index+1].to_s if i.downcase == "r" end new_string end
true
186fa87b8a6b9b1215f30ff700d2e0e80030d925
Ruby
y5f/Projects
/Mini comp /parser.rb
UTF-8
9,206
3.140625
3
[]
no_license
# -*- coding: utf-8 -*- require 'pp' require_relative 'lexer' require_relative 'ast' JAVA_TOKEN_DEF={ #Conditions :if => /if/, :else => /else/, :do => /do/, :while => /while/, :for => /for/, #Primitive types :int => /int/, :bool => /boolean/, :void => /void/, #Boolean :true => /true/, :false => /false/, #Misc :void => /void/, :class => /class/, :public => /public/, :private => /private/, :extends => /extends/, :static => /static/, :main => /main/, :string => /String/, :return => /return/, :this => /this/, #Punctuation :semicolon => /\;/, :dot => /\./, :colon => /:/, :comma => /\,/, :lbracket => /\(/, :rbracket => /\)/, :lsbracket => /\[/, :rsbracket => /\]/, :lsbrace => /\{/, :rsbrace => /\}/, #Operators :infeq => /<=/, :supeq => />=/, :sup => />/, :inf => /</, :not => /!/, :differ => /!=/, :eq => /\=/, :multiply => /\*/, :substract => /\-/, :plus => /\+/, :div => /\//, :or => /\|\|/, :and => /\&\&/, :ident => /[a-zA-Z][a-zA-Z0-9_]*/, :integer => /[0-9]+/, } class Parser attr_accessor :lexer def initialize verbose=false @lexer=Lexer.new(JAVA_TOKEN_DEF) @verbose=verbose end def parse filename str=IO.read(filename) @lexer.tokenize(str) parseProg() end def expect token_kind next_tok=@lexer.get_next if next_tok.kind!=token_kind puts "expecting #{token_kind}. Got #{next_tok.kind}" raise "parsing error on line #{next_tok.pos.first}" end return next_tok end def showNext @lexer.show_next end def acceptIt @lexer.get_next end def say txt puts txt if @verbose end def eof? @lexer.eof? end def lookahead k @lexer.lookahead(k) end #=========== parse method relative to the grammar ======== #Done def parseProg puts "parseProg" prog = Program.new prog.mainClass = parseMainClass() classNode = ClassSequence.new while !eof?() #stops when file ends classNode.list << parseClassDeclaration() end prog.classList = classNode return prog end #Done def parseMainClass puts "parseMainClass" expect :class mainClass = MainClass.new mainClass.name = parseIdentifier() expect :lsbrace expect :public expect :static expect :void expect :main expect :lbracket expect :string expect :lsbracket expect :rsbracket mainClass.args = parseIdentifier() expect :rbracket expect :lsbrace mainClass.statementList = parseStatementSequence() expect :rsbrace expect :rsbrace return mainClass end def parseClassDeclaration puts "parseClassDeclaration" expect :class classe = Klass.new classe.name = parseIdentifier() if showNext.kind == :extends acceptIt classe.legacy = parseIdentifier() end expect :lsbrace varList = VarSequence.new methList = MethSequence.new tmp = Variable.new while showNext.kind != :rsbrace tmp.modifier = parseModifier() tmp.type = parseType() tmp.name = parseIdentifier() if showNext.kind == :semicolon varList.list << parseVarDeclarationBis(tmp) elsif showNext.kind == :lbracket methList.list << parseMethodDeclaration(tmp) else puts "error" end end expect :rsbrace classe.varList = varList classe.methList = methList return classe end def parseVarDeclaration puts "parseVarDeclaration" var = Variable.new var.modifier = parseModifier() var.type = parseType() puts var.type.kind var.name = parseIdentifier() puts var.name return var end def parseVarDeclarationBis tmp puts "parseVarDeclarationBis" var = Variable.new var.modifier = tmp.modifier var.type = tmp.type var.name = tmp.name expect :semicolon return var end def parseMethodDeclaration tmp puts "parseMethodDeclaration" method = MethodDecl.new method.modifier = tmp.modifier method.type = tmp.type method.name = tmp.name nodeVar = VarSequence.new expect :lbracket if showNext.kind != :rbracket nodeVar.list << parseVarDeclaration() while showNext.kind == :comma acceptIt nodeVar.list << parseVarDeclaration() end end expect :rbracket method.varList = nodeVar expect :lsbrace method.stmtList = parseStatementSequence() if (showNext.kind == :return) and (method.type != :void) acceptIt method.output << parseExpression() expect :semicolon elsif (showNext.kind == :return) and (method.type == :void) puts "no return in void-type functions !" end expect :rsbrace return method end def parseModifier puts "parseModifier" modifier = Modifier.new if (showNext.kind == :public) or (showNext.kind == :private) modifier.kind = acceptIt else modifier.kind = nil end return modifier end def parseType puts "parseType" type = TypeDecl.new if (showNext.kind == :int) or (showNext.kind == :void) or (showNext.kind == :bool) type.kind = acceptIt else type.kind = parseIdentifier() end if showNext.kind == :lsbracket acceptIt expect :rsbracket end return type end #------------------------ Statements -----------------------# def parseStatement puts "parseStatement" statement = Statement.new if showNext.kind != :rsbrace case showNext.kind when :if then statement=parseIfStmt() when :while then statement=parseWhileStmt() when :for then statement=parseForStmt() when :lsbrace then acceptIt statement = parseStatementSequence() expect :rsbrace when :int, :bool, :void then statement = parseLocalVarDecl() else statement = parseExpression() expect :semicolon end end return statement end def parseIfStmt puts "parseIfStmt" ifStmt = IfStatement.new expect :if expect :lbracket ifStmt.cond = parseExpression() expect :rbracket ifStmt.ifStmtBlock = parseStatement() if showNext.kind == :else acceptIt ifStmt.elseStmtBlock = parseStatement() end return ifStmt end def parseWhileStmt puts "parseWhileStmt" whileStmt = WhileStatement.new expect :while expect :lbracket whileStmt.cond = parseExpression() expect :rbracket whileStmt.stmtBlock = parseStatement() return whileStmt end def parseForStmt puts "parseForStmt" forStmt = ForStatement.new expect :for expect :lbracket forStmt.beginCond = parseLocalVarDecl() forStmt.endCond = parseExpression() expect :semicolon forStmt.assignment = parseExpression() #/!\ not conform to grammar expect :rbracket forStmt.stmtBlock = parseStatement() return forStmt end def parseStatementSequence() puts "parseStatementSequence" statement = StatementSequence.new while showNext.kind != :rsbrace statement.list << parseStatement() end return statement end #------------------------ End statements -----------------------# #Checked def parseLocalVarDecl puts "parseLocalVarDecl" localVar = LocalVariable.new localVar.type = parseType() localVar.name = parseIdentifier() expect :eq localVar.expr = parseExpression() expect :semicolon return localVar end #TODO def parseExpression puts "parseExpression" expr = Expression.new if showNext.kind == :this expr.ref = parseReference() elsif showNext.kind == :new acceptIt expr.ident = parseIdentifier() if showNext.kind == :lbracket acceptIt expect :rbracket elsif showNext.kind == :lsbracket acceptIt expr.expr = parseExpression() expect :rsbracket else puts "error in parsing Expression" end elsif showNext.kind == :lbracket acceptIt expr.expr = parseExpression() expect :rbracket elsif (showNext.kind == :integer) or (showNext.kind == :true) or (showNext.kind == :false) expr.lit = parseLiteral() elsif showNext.kind == :not expr.op = acceptIt expr.expr = parseExpression() else expr.ref = parseReference() if showNext.kind == :eq acceptIt expr.expr = parseExpression() end end return expr end #TODO A tester sans le "this." def parseReference puts "parseReference" reference = Reference.new if showNext.kind == :this acceptIt expect :dot end reference.targetList << parseTarget() while showNext.kind == :dot acceptIt reference.targetList << parseTarget() end return reference end #Checked def parseTarget puts "parseTarget" target = Target.new target.ident = parseIdentifier() nodeExpr = ExpressionSequence.new if showNext.kind == :lsbracket acceptIt nodeExpr.list << parseExpression() expect :rsbracket elsif showNext.kind == :lbracket acceptIt if showNext.kind != :rbracket nodeExpr.list << parseExpression() while showNext.kind == :comma nodeExpr.list << parseExpression() end end expect :rbracket end target.exprList = nodeExpr return target end #TODO pas de reconnaissance de String def parseLiteral puts "parseLiteral" literal = Literal.new if (showNext.kind == :integer) or (showNext.kind == :true) or (showNext.kind == :false) literal.lit = acceptIt else literal.lit = nil end return literal end #Checked def parseIdentifier puts "parseIdentifier" ident = Identifier.new ident.name = expect(:ident) return ident end end
true
0f4067a2a0a57e5e0c4104f2012a83f2aa365adc
Ruby
glitterfang/muzukashi
/test_muzukashi.rb
UTF-8
1,619
2.640625
3
[]
no_license
require File.expand_path(File.dirname(__FILE__), "muzukashi") require 'shoulda' require 'test/unit' require 'fileutils' class MuzukashiTest < Test::Unit::TestCase CAGE_DIR = '.cage' def check_cage if File.exist?(".cage") FileUtils.rm_rf(".cage") end end context "making the cage" do setup do check_cage end should "succesfully create cage" do Muzukashi.create_cage(".") assert File.exist?(".cage") end should "fail if cage already exists" do Muzukashi.create_cage(".") assert_raises ArgumentError do Muzukashi.create_cage(".") end end end context "adding bugs to the cage" do setup do unless File.exist?(".cage") Dir.glob(".cage/*").each { |x| FileUtils.rm(x) } end end should "create a new bug in the cage" do assert Muzukashi.capture_bug("need to write more unit tests") end end context "reading the bugs" do setup do check_cage Muzukashi.create_cage(".") Muzukashi.capture_bug("starling boy") @bugs = Muzukashi.read_bugs end should "be successful" do assert @bugs end should "return hash of hashes of bugs" do assert @bugs.class == Hash end should "cache mapping to /tmp/muzukashi_cache.tmp" do assert File.exist?("/tmp/muzukashi_cache") end end context "removing the bugs" do setup do check_cage Muzukashi.create_cage(".") Muzukashi.capture_bug("starling") end should "be successful" do assert Muzukashi.remove_bug(1) end end end
true
64ba5ef1e677c400d3259aab210b52d059aa8b0d
Ruby
Mimerme/RTermGame
/RenderFactory.rb
UTF-8
856
2.984375
3
[]
no_license
require './RTermGame.rb' require './RTermGame.rb' class RenderFactory def initialize(size_x, size_y) @size_x = size_x @size_y = size_y #| -> #down -> @screen_buffer = Array.new(@size_y) {Array.new(@size_x) {:empty}} end #Clears the screen to setup for the next frame def clear_screen system "clear" or system "cls" end def buffer_at_position(x_pos, y_pos, sprite) @screen_buffer[y_pos][x_pos] = sprite end #dumps the current screen buffer def draw @screen_buffer.each do |buffer_x| line_buffer = "" buffer_x.each do |char_sprite| if char_sprite != :empty line_buffer << char_sprite else line_buffer << " " end end RTermGame.println line_buffer @screen_buffer = Array.new(@size_y) {Array.new(@size_x) {:empty}} end end end
true
9b0bfe52a4c7426d99516b0f17cf7d7035539888
Ruby
bigxiang/leetcode
/714.best-time-to-buy-and-sell-stock-with-transaction-fee/default.rb
UTF-8
484
3.125
3
[ "MIT" ]
permissive
# # @lc app=leetcode id=714 lang=ruby # # [714] Best Time to Buy and Sell Stock with Transaction Fee # # @lc code=start # @param {Integer[]} prices # @param {Integer} fee # @return {Integer} def max_profit(prices, fee) with_s = 0 without_s = 0 prices.each_with_index do |p, i| if i.zero? with_s = -p without_s = 0 next end with_s, without_s = [with_s, without_s - p].max, [without_s, with_s + p - fee].max end without_s end # @lc code=end
true
9a6062f38ede3753967659b335721a90540851f9
Ruby
jbvance/prime-ruby-v-000
/prime.rb
UTF-8
132
3.46875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(int) return false if int < 2 for num in 2..(int - 1) if (int % num) == 0 return false end end true end
true
7170e3d4e0731cf3afa98137dd0f52061fb201bd
Ruby
dearshrewdwit/bitmap_editor
/app/errors/bitmap_errors.rb
UTF-8
610
2.828125
3
[]
no_license
class BitmapError < StandardError end class InvalidCommand < BitmapError def initialize(command_letter) super("unrecognised command '#{command_letter}' :(") end end class InvalidParameters < BitmapError def initialize(msg = 'invalid parameters for command') super end end class NoImage < BitmapError def initialize(msg = "no image created yet") super end end class InvalidCoordinate < BitmapError def initialize(msg = "command contains an invalid coordinate") super end end class InvalidColour < BitmapError def initialize(msg = "Not a valid colour") super end end
true
3957fed3ae29ce70616d1fc2983068e5c16817e0
Ruby
ciprianna/06-23-foodz
/models/recipe.rb
UTF-8
2,043
3.109375
3
[]
no_license
class Recipe < ActiveRecord::Base validates :name, presence: true, uniqueness: true validates :recipe_type_id, presence: true validates :time_to_make, presence: true validates :information, presence: true has_and_belongs_to_many :foods # Returns recipes based on amount of time it takes to make # # time - String, indicating the amount of time it takes. Should be categories # of either "quick", "hour", or "long" # # Returns an Array of Objects def self.where_time(time) if time == "quick" results = Recipe.where("time_to_make <= 30") elsif time == "hour" results = Recipe.where(time_to_make: 30..65) elsif time == "long" results = Recipe.where("time_to_make > 65") end return results end # Utility method - collects the number of ingredients a recipe takes # # counts - Hash with recipe_ids from recipes_foods table # # Returns a Hash with recipe_ids (Integers) as keys and total ingredients used # as values (Integers) def self.ingredients(counts) recipe_ingredients = Hash.new 0 counts.each do |key, value| recipe = Recipe.find(key) number_of_foods = recipe.foods recipe_ingredients[key] = number_of_foods.length end return recipe_ingredients end # Utility method - Returns the percentage of user selected ingredients out of # total ingredients a recipe uses # # recipe_ingredients - Hash with recipe_ids (Integers) as keys and number of # recipe ingredients needed as the value (Integer) # counts - Hash with recipe_ids (Integers) as keys and number of user-selected # ingredients as values (Integers) # # Returns a Hash with recipe_ids (Integers) and percentage of ingredients # (Floats) that the user has available as the values def self.percentage_of_ingredients(recipe_ingredients, counts) in_order = {} recipe_ingredients.each do |rid, ings| x = counts[rid].to_f / ings in_order[rid] = x end return in_order end end
true
0a85f4a8a0ff5968f9a7d259ecdf475e005000d3
Ruby
patricewhite/Ruby
/Strings/string_interpolation.rb
UTF-8
368
4.71875
5
[]
no_license
# interpolation automatically converts to correct type name = "Patrice" p "Hello #{name}, how are you?" age = 24 #old way # to_s is to string p "I am " + age.to_s + " years old" #new way (Better) p "I am #{age} years old" p "The result of adding 1 + 1 is #{1 + 1}" p "In 5 years, I will be #{age + 5} years old" x = 5 y = 8 p "The sum of x and y is #{x + y}"
true
4ecedad5fe46159040e152c2df26954cb1b6f540
Ruby
imcodingideas/learning_ruby
/day_13/anagrams.rb
UTF-8
444
3.140625
3
[]
no_license
def canonical(letter) letter.split(//).sort! end def are_anagrams?(word_a, word_b) canonical(word_a) == canonical(word_b) end p are_anagrams?('omar', 'amor') p are_anagrams?('omar', 'amor') def anagrams_for(word, array) empty_array = [] letter = word.split(//).sort array.select do |word| x = word.split(//).sort empty_array << word if x == letter end empty_array end p anagrams_for('omar', %w(amor ramo hola gerardo))
true
33677a98cbd912519c0aeb342969106c4aef0c28
Ruby
shasbot/cse548-project2
/host-script/montool.rb
UTF-8
580
3.109375
3
[]
no_license
#! /usr/bin/ruby # SCRIPT to run on hosts, will parse data from other utilities, create syslog style events and add them to the database #variables to read from config use_w = TRUE # var #syslog event class class LogObject attr_accessor :timestamp, :pid, :hostname, :progname, :message def initialize(timestamp, pid, hostname, progname, message) @timestamp = timestamp @pid = pid @hostname = hostname @progname = progname @message = message end end anEvent = LogObject.new(:now, 12, :lick, :w, "wheeeee") puts anEvent.hostname #Parsing start
true
3295972cbfba3957af0de1d5f3f75ddc430d86a3
Ruby
phylor/techtalk-ruby-2.5
/performance.rb
UTF-8
943
3.21875
3
[]
no_license
require 'benchmark/ips' Benchmark.ips do |x| x.report "Large string interpolation" do |t| a = "Hellooooooooooooooooooooooooooooooooooooooooooooooooooo" b = "Wooooooooooooooooooooooooooooooooooooooooooooooooooorld" t.times { "#{a}, #{b}!" } end x.report "Small string interpolation" do |t| a = "Hello" b = "World" t.times { "#{a}, #{b}!" } end x.report "String prepend" do |t| a = "World" t.times { a.prepend("Hello") } end # also for min_by and max_by x.report "Enumerable sort_by" do |t| a = ['turtle', 'cat', 'fish', 'flamingo'] t.times { a.sort_by(&:length) } end x.report "Range min" do |t| range = (1..999999) t.times { range.min } end x.report "String scan - String pattern" do |t| a = "caterpillar" t.times { a.scan("cat") } end x.report "String scan - Regex pattern" do |t| a = "caterpillar" t.times { a.scan(/pill/) } end end
true
ccebce76fa163da5991ea38aeeff829dab4cc749
Ruby
oreillymedia/asciidoctor-htmlbook
/scripts/convert_book.rb
UTF-8
672
2.796875
3
[]
no_license
# This script runs through a book folder and converts all asciidoc files to htmlbook files require 'rubygems' require 'asciidoctor' require 'fileutils' book_folder = ARGV[0] raise "Book Folder does not exist: #{book_folder}" unless File.exists?(book_folder) Dir.glob("#{book_folder}**/*.{asciidoc,adoc,asc}") do |file| puts "Converting #{File.basename(file)}" asciidoc = File.open(file).read html = Asciidoctor.convert(asciidoc, :template_dir => "#{File.dirname(__FILE__)}/../htmlbook", :attributes => {'compat-mode' => 'true'}) filename = "#{File.dirname(file)}/#{File.basename(file,'.*')}.html" File.open(filename, 'w') { |file| file.write(html) } end
true
7480949a9101894174f2f153165325f9950d30d8
Ruby
iguto/nothello
/lib/board.rb
UTF-8
2,700
3.375
3
[]
no_license
require 'forwardable' # require 'marshal' class Board attr_accessor :panels, :panel_iterator SIZE = 8 DIRECTIONS = [:up, :right, :down, :left] def initialize create_empty_panels set_panel(Position.new(3,3), Panel::TYPE::WHITE) set_panel(Position.new(4,4), Panel::TYPE::WHITE) set_panel(Position.new(3,4), Panel::TYPE::BLACK) set_panel(Position.new(4,3), Panel::TYPE::BLACK) @pos = Position.new(0, 0) end # 指定位置のパネルを返す def panel(pos) @panels[pos.y][pos.x] end def set_panel(pos, type) @panels[pos.y][pos.x]= Panel.new(pos, type) end def put_stone(pos, type) return nil unless reversible?(pos, type) set_panel(pos, type) reverse(pos, type) end def reversible?(pos, type) PanelIterator::DIRECTIONS.each do |dir| return true if reversible_dir?(pos, type, dir) end false end def reverse(pos, type) PanelIterator::DIRECTIONS.each do |dir| reverse_dir(pos, type, dir) end end private def reverse_dir(pos, type, dir) return nil unless reversible_dir?(pos, type, dir) iterator = PanelIterator.new(@panels) iterator.set_pos(pos) panel = iterator.send(dir) while panel do break if panel.type == type set_panel(iterator.pos, iterator.panel.reverse) panel = iterator.send(dir) end end def reversible_dir?(pos, type, dir) reversible_count = 0 opposite_type = (type == Panel::TYPE::WHITE) ? Panel::TYPE::BLACK : Panel::TYPE::WHITE iterator = PanelIterator.new(@panels) iterator.set_pos(pos) panel = iterator.send(dir) while panel do return false if panel.empty? if panel.send("#{type}?") return false if reversible_count == 0 return true end reversible_count += 1 panel = iterator.send(dir) end false end def create_empty_panels @panels = Array.new(SIZE) { Array.new(SIZE) } @panels.map!.with_index do |row, y_index| row.map.with_index do |e, x_index| Panel.new(Position.new(x_index, y_index), Panel::TYPE::EMPTY) end end end end class OutOfBoardError < StandardError; end class PanelIterator DIRECTIONS = [:up, :down, :right, :left, :right_up, :left_up, :right_down, :left_down] attr_reader :pos def initialize(panels) @panels = panels @pos = Position.new(0,0) end def set_pos(pos) @pos = pos end def panel(pos = nil) pos ||= @pos @panels[pos.y][pos.x] end def method_missing(method, *args) return super unless DIRECTIONS.include? method pos = Marshal.load(Marshal.dump(@pos)).send(method) return nil if pos.nil? @pos = pos panel end end
true
66a6d6dc3a493be62c61bae7b26bd1a44a7a9702
Ruby
nbr625/Odin-Building-Blocks
/bubble_sort.rb
UTF-8
811
4.125
4
[]
no_license
## Takes an array of numbers and sorts them from lowest to largest def bubble_sort(array) misplaced = array.size - 1 while misplaced > 0 1.upto(misplaced) do |i| if array[i - 1] > array[i] array[i - 1], array[i] = array[i], array[i - 1] #blup, blup end end misplaced -= 1 end print array end ## Takes an array of strings and sorts them from shortest to longest def bubble_sort_by(array) misplaced = array.size - 1 while misplaced > 0 1.upto(misplaced) do |i| if yield(array[i - 1], array[i]) < 0 array[i - 1], array[i] = array[i], array[i - 1] end end misplaced -= 1 end print array end bubble_sort([6, 8, 7, 5, 3, 8, 9]) bubble_sort_by(["this", "sentence", "is", "utter", "nonesense"]) do |left,right| right.length - left.length end
true
d987e42faff9d8a24f2ce28fd22119a8f27cb013
Ruby
dustinsmith1024/bracket
/app/models/team.rb
UTF-8
5,974
3.09375
3
[]
no_license
class Team < ActiveRecord::Base default_scope order('division, seed') has_and_belongs_to_many :tags has_many :winners, :class_name => 'Game', :foreign_key => 'winner_id' has_many :team_ones, :class_name => 'Game', :foreign_key => 'team_one_id' has_many :team_twos, :class_name => 'Game', :foreign_key => 'team_two_id' has_many :users has_many :participants has_many :games, :through => :participants #has_many :purchases, :class_name => 'Sale', :foreign_key => 'buyer_id' validates_uniqueness_of :seed, :scope => :division def self.random self.find_by_id(rand(Team.count) + 1) end def self.winner(teams, user, name=false) if name==false up = 0; over = 0; teams = teams.sort ## FILL IN FROM USER -> MY TEAM # user_team = Team.find_by_name("Iowa") user_team = user.team ## FILL IN FROM USER -> TAGS EVENTUALLY, WHICH ARE FED FROM QUESTIONS! # user_tags = %w{Blue Yellow Bird} # user_tags << "Bird - Real" ## PUSH ON ONE WITH SPACES... user_tags = user.tags team_tags = user_team.tags.collect {|t| t.name} logger.info(user_tags) logger.info(team_tags) tmp_tags = [] teams.each_with_index do |t,index| ## PUSH TAG NAMES ONTO AN ARRAY tmp_tags[index] ||= Team.find_by_seed(t).tags.collect{|t|t.name} if index == 0 ## IF THE FIRST TEAM THEN INCREASE THE OVER VAR TO HELP THE BEST SEED WIN user_tags.each do |tag| ## LOOP THROUGH ALL TAGS TO SEE IF THEY MATCH if tmp_tags[index].include?(tag) over += 2 end end else ## IF THE SECOND TEAM THEN INCREASE THE UP VAR TO MAKE UNDERDOGS WIN user_tags.each do |tag| if tmp_tags[index].include?(tag) up += 2 end end end end #team_plus = 10 if Team.find(teams[0]) == user_team over += 5 logger.info("iowwwaaa1" + over.to_s) elsif Team.find(teams[1]) == user_team up += 10 logger.info("iowwwaaaaa2" + up.to_s) end # if teams[0] == 1 # ## ALL ODDS FOR 1 vs matchups # if teams[1] == 2 # teams.sample # end # end # SWITCH CASES TO FIND SECOND TEAM THEN PASS ODDS # IF 1-4 ODDS PASS A 4 TO .ods # THE TEAM THAT SHOULD WIN SHOULD BE FIRST AFTER ? logger.info("OVER: " + over.to_s + " UP: " + up.to_s) if teams[0] == 1 t = case teams[1] when 1..2 then self.ods(1 + over - up) ? 1 : 0 when 3..4 then self.ods(2 + over - up) ? 1 : 0 when 5..9 then self.ods(5 + over - up) ? 1 : 0 when 10..12 then self.ods(8 + over - up) ? 1 : 0 when 13..16 then self.ods(90 + over - up) ? 1 : 0 end end if teams[0] == 2 t = case teams[1] when 1..3 then self.ods(1 + over - up) ? 1 : 0 when 4..6 then self.ods(2 + over - up) ? 1 : 0 when 7..9 then self.ods(4 + over - up) ? 1 : 0 when 10..12 then self.ods(8 + over - up) ? 1 : 0 when 13..16 then self.ods(15 + over - up) ? 1 : 0 end end if teams[0] == 3 t = case teams[1] when 1..2 then self.ods(4 + over - up) ? 0 : 1 when 3..4 then self.ods(1 + over - up) ? 1 : 0 when 5..7 then self.ods(3 + over - up) ? 1 : 0 when 8..10 then self.ods(5 + over - up) ? 1 : 0 when 11..16 then self.ods(10 + over - up) ? 1 : 0 end end if teams[0] == 4 t = case teams[1] when 1..3 then self.ods(3 + over - up) ? 0 : 1 when 4..6 then self.ods(1 + over - up) ? 1 : 0 when 7..9 then self.ods(3 + over - up) ? 1 : 0 when 10..12 then self.ods(6 + over - up) ? 1 : 0 when 13..16 then self.ods(9 + over - up) ? 1 : 0 end end if teams[0] == 5 t = case teams[1] when 1..2 then self.ods(4 + over - up) ? 0 : 1 when 3..4 then self.ods(2 + over - up) ? 0 : 1 when 5..7 then self.ods(1 + over - up) ? 1 : 1 when 8..10 then self.ods(6 + over - up) ? 1 : 0 when 11..16 then self.ods(9 + over - up) ? 1 : 0 end end if teams[0] == 6 t = case teams[1] when 1..3 then self.ods(5 + over - up) ? 0 : 1 when 4..6 then self.ods(3 + over - up) ? 0 : 1 when 7..9 then self.ods(1 + over - up) ? 1 : 0 when 10..12 then self.ods(3 + over - up) ? 1 : 0 when 13..16 then self.ods(5 + over - up) ? 1 : 0 end end if teams[0] == 7 t = case teams[1] when 1..3 then self.ods(5 + over - up) ? 0 : 1 when 4..6 then self.ods(3 + over - up) ? 0 : 1 when 7..9 then self.ods(1 + over - up) ? 1 : 0 when 10..12 then self.ods(3 + over - up) ? 1 : 0 when 13..16 then self.ods(5 + over - up) ? 1 : 0 end end if teams[0] >= 8 ## ALL ODDS FOR 1 vs matchups t = case teams[1] # when 1..3 then self.ods(5) ? 0 : 1 # when 4..7 then self.ods(3) ? 0 : 1 when 8..9 then self.ods(1 + over - up) ? 1 : 0 when 10..12 then self.ods(3 + over - up) ? 1 : 0 when 13..16 then self.ods(5 + over - up) ? 1 : 0 # if teams[1] == 10 # t = self.ods(3) ? 1 : 0 # end end end logger.info(t) return teams[t] else ## RANDOMLY PICKS A TEAM...50/50 self.find(teams.sample).name end end def n if self.short_name.nil? return self.seed.to_s + ". " + self.name.to_s else return self.seed.to_s + ". " + self.short_name.to_s end end def self.ods(chance=0) ## RETURNS FALSE IF LESS THAN 1 # IF - then we need to switch the odds somewhow... if chance > 0 r = rand(chance) logger.info(r) # pp (r) (r<1) else r = rand(chance) logger.info(r.to_s + " upset possible" ) # pp (r) if r<1 false else true end end end def self.odds(t1, t2) if t1 > t2 tmp = t2 t2 = t1 t1 = tmp end if t1 == t2 return ".5".to_f end diff = t2 - t1 if diff < 2 return ".5".to_f end return t1/t2.to_f end end
true
db6cc41b6d87dba23d87f4f2f78691066621d7be
Ruby
philipesteiff/fastlane
/fastlane/actions/af_get_github_milestone.rb
UTF-8
5,096
2.5625
3
[ "MIT" ]
permissive
module Fastlane module Actions module SharedValues GITHUB_MILESTONE_NUMBER = :GITHUB_MILESTONE_NUMBER end # To share this integration with the other fastlane users: # - Fork https://github.com/KrauseFx/fastlane # - Clone the forked repository # - Move this integration into lib/fastlane/actions # - Commit, push and submit the pull request class AfGetGithubMilestoneAction < Action def self.run(params) require 'net/http' require 'net/https' require 'json' require 'base64' begin uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/milestones") # Create client http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER # Create Request req = Net::HTTP::Get.new(uri) # Add headers if params[:api_token] api_token = params[:api_token] req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" end req.add_field "Accept", "application/vnd.github.v3+json" # Fetch Request res = http.request(req) rescue StandardError => e Helper.log.info "HTTP Request failed (#{e.message})".red end case res.code.to_i when 200 milestones = JSON.parse(res.body) milestone = milestones.select {|milestone| milestone["title"] == params[:title]}.first if milestone == nil raise "No milestone found matching #{params[:title]}".red end Helper.log.info "Milestone #{params[:title]}: #{milestone["url"]}".green if params[:verify_for_release] == true raise "Milestone #{params[:title]} is already closed".red unless milestone["state"] == "open" raise "Milestone #{params[:title]} still has open #{milestone["open_issues"]} issue(s)".red unless milestone["open_issues"] == 0 raise "Milestone #{params[:title]} has no closed issues".red unless milestone["closed_issues"] > 0 Helper.log.info "Milestone #{params[:title]} is ready for release!".green end Actions.lane_context[SharedValues::GITHUB_MILESTONE_NUMBER] = milestone["number"] return milestone when 400..499 json = JSON.parse(res.body) raise "Error Retrieving Github Milestone (#{res.code}): #{json["message"]}".red else Helper.log.info "Status Code: #{res.code} Body: #{res.body}" raise "Retrieving Github Milestone".red end end ##################################################### # @!group Documentation ##################################################### def self.description "Get a Github Milestone, and optional verify its ready for release" end def self.available_options [ FastlaneCore::ConfigItem.new(key: :owner, env_name: "GITHUB_OWNER", description: "The Github Owner", is_string:true, optional:false), FastlaneCore::ConfigItem.new(key: :repository, env_name: "GITHUB_REPOSITORY", description: "The Github Repository", is_string:true, optional:false), FastlaneCore::ConfigItem.new(key: :api_token, env_name: "GITHUB_API_TOKEN", description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", is_string: true, optional: true), FastlaneCore::ConfigItem.new(key: :title, description: "The milestone title, typically the same as the tag", is_string: true, optional: false), FastlaneCore::ConfigItem.new(key: :verify_for_release, description: "Verifies there are zero open issues, at least one closed issue, and is not closed", is_string: false, default_value:false) ] end def self.output [ ['GITHUB_MILESTONE_NUMBER', 'The milestone number'] ] end def self.return_value "A Hash representing the API response" end def self.authors ["kcharwood"] end def self.is_supported?(platform) return true end end end end
true
10ecb15ffd5b30d32fd19ebd0dd1147b58568699
Ruby
benrodenhaeuser/exercises
/practice_problems/02_factorial.rb
UTF-8
2,100
4.3125
4
[]
no_license
# Write a method that takes an integer `n` in; it should return # n*(n-1)*(n-2)*...*2*1. Assume n >= 0. # # As a special case, `factorial(0) == 1`. # # Difficulty: easy. # Recursion def factorial(n) if n == 0 1 else n * factorial(n - 1) end end puts("\nTests for #factorial — recursive solution") puts("===============================================") puts( 'factorial(0) == 1: ' + (factorial(0) == 1).to_s ) puts( 'factorial(1) == 1: ' + (factorial(1) == 1).to_s ) puts( 'factorial(2) == 2: ' + (factorial(2) == 2).to_s ) puts( 'factorial(3) == 6: ' + (factorial(3) == 6).to_s ) puts( 'factorial(4) == 24: ' + (factorial(4) == 24).to_s ) puts("===============================================") # Iteration def factorial(n) factorial = 1 current = 1 while current <= n factorial = factorial * current current += 1 end factorial end puts("\nTests for #factorial — iterative solution") puts("===============================================") puts( 'factorial(0) == 1: ' + (factorial(0) == 1).to_s ) puts( 'factorial(1) == 1: ' + (factorial(1) == 1).to_s ) puts( 'factorial(2) == 2: ' + (factorial(2) == 2).to_s ) puts( 'factorial(3) == 6: ' + (factorial(3) == 6).to_s ) puts( 'factorial(4) == 24: ' + (factorial(4) == 24).to_s ) puts("===============================================") # Tail Recursion def factorial(n, acc = 1) if n == 0 acc else factorial(n - 1, n * acc) end end puts("\nTests for #factorial — tail recursion") puts("===============================================") puts( 'factorial(0) == 1: ' + (factorial(0) == 1).to_s ) puts( 'factorial(1) == 1: ' + (factorial(1) == 1).to_s ) puts( 'factorial(2) == 2: ' + (factorial(2) == 2).to_s ) puts( 'factorial(3) == 6: ' + (factorial(3) == 6).to_s ) puts( 'factorial(4) == 24: ' + (factorial(4) == 24).to_s ) puts("===============================================")
true
a02098430ac2106a830f530e0f01c96b9dda7493
Ruby
tfielder/sweater_weather
/app/services/giphy_request.rb
UTF-8
697
2.59375
3
[]
no_license
class GiphyRequest def initialize(term) @term = format_term(term) end def get_url get_giphy["data"][0]["url"] end private def format_term(term) term.gsub(/ /, '+') end def connection(url) connect = Faraday.new(:url => "#{url}") do |f| f.request :url_encoded f.adapter Faraday.default_adapter end end def get_giphy_response response = connection("https://api.giphy.com/v1/gifs/search").get '', giphy_keys end def giphy_keys { :api_key => ENV['giphy_api_key'], :q => "#{@term}" } end def parse(result) JSON.parse(result.body) end def get_giphy result = parse(get_giphy_response) end end
true
d1d8f32f84e71fa7192891ca587a4758ce8c33e8
Ruby
momajd/ruby-js-algorithms
/Ruby/strings/string_to_integer.rb
UTF-8
313
3.53125
4
[]
no_license
def to_integer(str) integer = 0 i = 0 neg = false if str[0] == "-" neg = true i += 1 end multiplier = 10**(str.length - 1 - i) while i < str.length digit = str[i].ord - "0".ord integer += multiplier * digit multiplier /= 10 i += 1 end neg ? integer * -1 : integer end
true
086df83e2ece8e52f5127dafa137b69021b737ae
Ruby
songzhou21/ruby
/sbxh/queue_thread.rb
UTF-8
254
3.234375
3
[]
no_license
require 'thread' q = Queue.new producer = Thread.new { 10.times { |i| q.push(i) sleep(1) } q.push(nil) } consumer = Thread.new { loop { i = q.pop break if i == nil puts i } } consumer.join
true
e824eab35a241b84f0a0fe7bbdede14bbfcefe38
Ruby
Intimaria/ttps-ruby-tests
/src/01/12_longitud.rb
UTF-8
86
2.90625
3
[]
no_license
def longitud(array) a = [] array.map { |x| a << (x.nil? ? 0 : x.length) } a end
true
a0ef4356d873eb6073ce1a13fae291a945e73097
Ruby
Hitendra1632/outlook_calendar
/lib/outlook_calendar/rest_caller.rb
UTF-8
657
2.71875
3
[]
no_license
module OutlookCalendar class RestCaller attr_reader :method, :url, :headers, :params def initialize(method, url, headers, params = {}) @method = method @url = url @headers = headers @params = params end def call parse_response end private def parse_response return nil unless response.present? JSON.parse(response) end def response @response ||= send(method.downcase) end def get RestClient.get url, headers end def post RestClient.post url, params, headers end def delete RestClient.delete url, headers end end end
true
fc0a98a741970fcd78069746fc3d166537a7e918
Ruby
mknycha/sports-events-scraper
/classes/models/general_event.rb
UTF-8
1,375
2.875
3
[]
no_license
# frozen_string_literal: true class GeneralEvent < ActiveRecord::Base EVENT_NAME_DELIMITER = ' v ' self.abstract_class = true validates :team_home, :team_away, :link, :reporting_time, :score_home, :score_away, :ball_possession_home, :ball_possession_away, :attacks_home, :attacks_away, :shots_on_target_home, :shots_on_target_away, :shots_off_target_home, :shots_off_target_away, :corners_home, :corners_away, presence: true def self.from_event(event) new.tap do |reported| reported.team_home, reported.team_away = event.name.split(EVENT_NAME_DELIMITER) reported.reporting_time = event.time reported.score_home = event.score_home reported.score_away = event.score_away reported.link = event.link reported.assign_fields_from_hashes(event) end end def assign_fields_from_hashes(event) %w[ball_possession attacks shots_on_target shots_off_target corners].each do |field| send("#{field}_home=", event.send(field)[:home]) send("#{field}_away=", event.send(field)[:away]) end end def to_s "TIME: #{reporting_time} SCORE: #{score_home}-#{score_away}" \ " NAME: #{team_home}-#{team_away} LINK: #{link}" end def winning_team score_home > score_away ? :home : :away end def losing_team winning_team == :home ? :away : :home end end
true
9ba5e135d71e852c104c83d5b746b1280537a316
Ruby
LelandCurtis/enigma
/spec/enigma_spec.rb
UTF-8
5,464
3.140625
3
[]
no_license
require 'simplecov' SimpleCov.start require 'date' require './lib/enigma' require './lib/cypher' require './lib/encoder' describe Enigma do before(:each) do @enigma = Enigma.new() end describe 'initialize' do it 'exists' do expect(@enigma).to be_a(Enigma) end it 'has attributes' do end end describe 'methods' do before(:each) do @message = 'hello world!' @key = '02715' @date = '040895' end describe ' #encrypt' do it 'returns a hash' do expect(@enigma.encrypt(@message, @key, @date)).to be_a(Hash) end it 'returns a hash with correct keys' do expected = [:encryption, :key, :date] expect(@enigma.encrypt(@message, @key, @date).keys).to eq(expected) end it 'returns correct key' do expect(@enigma.encrypt(@message, @key, @date)[:key]).to eq(@key) end it 'returns correct date' do expect(@enigma.encrypt(@message, @key, @date)[:date]).to eq(@date) end it 'returns string as encryption' do expect(@enigma.encrypt(@message, @key, @date)[:encryption]).to be_a(String) end it 'returns correct encryption' do message_1 = 'Hello World!' expect(@enigma.encrypt(message_1, @key, @date)[:encryption]).to eq('Keder Ohulw!') end it 'can use the default date of today' do allow(@enigma).to receive(:today).and_return("211111") message_1 = 'Hello World!' expect(@enigma.encrypt(message_1, @key)[:encryption]).to eq('NhdaucOdxow!') end end describe ' #decrypt' do before(:each) do @cyphertext = 'keder ohulw!' end it 'returns a hash' do expect(@enigma.decrypt(@cyphertext, @key, @date)).to be_a(Hash) end it 'returns a hash with correct keys' do expected = [:decryption, :key, :date] expect(@enigma.decrypt(@cyphertext, @key, @date).keys).to eq(expected) end it 'returns correct key' do expect(@enigma.decrypt(@cyphertext, @key, @date)[:key]).to eq(@key) end it 'returns correct date' do expect(@enigma.decrypt(@cyphertext, @key, @date)[:date]).to eq(@date) end it 'returns string as decryption' do expect(@enigma.decrypt(@cyphertext, @key, @date)[:decryption]).to be_a(String) end it 'returns correct decryption' do cyphertext_1 = 'Keder Ohulw!' expect(@enigma.decrypt(cyphertext_1, @key, @date)[:decryption]).to eq('Hello World!') end it 'can use the default date of today' do allow(@enigma).to receive(:today).and_return("211111") cyphertext_1 = 'NhdaucOdxow!' expect(@enigma.decrypt(cyphertext_1, @key)[:decryption]).to eq('Hello World!') end end describe ' #crack' do before(:each) do @message_3 = 'Hello World! end' @cyphertext_3 = 'Keder Ohulw!Thnw' end it 'returns a hash' do expect(@enigma.crack(@cyphertext_3, @date)).to be_a(Hash) end it 'returns a hash with correct keys' do expected = [:decryption, :key, :date] expect(@enigma.crack(@cyphertext_3, @date).keys).to eq(expected) end it 'returns correct key' do expect(@enigma.crack(@cyphertext_3, @date)[:key]).to eq(@key) end it 'returns correct date' do expect(@enigma.crack(@cyphertext_3, @date)[:date]).to eq(@date) end it 'decrypts a message using only a date' do expect(@enigma.crack(@cyphertext_3, @date)[:decryption]).to eq(@message_3) end it 'uses today as a default date if none given' do allow(@enigma).to receive(:today).and_return('040895') expect(@enigma.crack(@cyphertext_3)[:decryption]).to eq(@message_3) end end describe ' #crack_easy' do before(:each) do @message_4 = 'Hello World! end' @cyphertext_4 = 'Keder Ohulw!Thnw' end it 'returns a hash' do expect(@enigma.crack_easy(@cyphertext_4)).to be_a(Hash) end it 'returns a hash with correct keys' do expected = [:decryption, :key, :date] expect(@enigma.crack_easy(@cyphertext_4).keys).to eq(expected) end it 'returns correct key' do expect(@enigma.crack_easy(@cyphertext_4)[:key]).to eq("Key not needed for decryption") end it 'returns correct date' do expect(@enigma.crack_easy(@cyphertext_4)[:date]).to eq("Date not needed for decryption") end it 'decrypts a message using only a the message' do expect(@enigma.crack_easy(@cyphertext_4)[:decryption]).to eq(@message_4) end end describe ' #crack_hard' do before(:each) do @message_4 = 'Hello World! end' @cyphertext_4 = 'Keder Ohulw!Thnw' end it 'returns a hash' do expect(@enigma.crack_hard(@cyphertext_4)).to be_a(Hash) end it 'returns a hash with correct keys' do expected = [:decryption, :key, :date] expect(@enigma.crack_hard(@cyphertext_4).keys).to eq(expected) end it 'returns any key' do expect(@enigma.crack_hard(@cyphertext_4)[:key]).to be_a(String) end it 'returns any date' do expect(@enigma.crack_hard(@cyphertext_4)[:date]).to be_a(String) end it 'can decrypt a message using only a the cyphertext' do expect(@enigma.crack_hard(@cyphertext_4)[:decryption]).to eq(@message_4) end end end end
true
9a644e19c99f5997d81d1a0cbfd1d6e0ba3d046a
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/clock/cb4c30be58fa49f4bdbda89b9bf9692d.rb
UTF-8
500
3.40625
3
[]
no_license
class Clock attr_reader :hour, :minute def Clock.at (h, m = 0) c = Clock.new(h, m) end def initialize (h, m) @hour = h @minute = m end def to_s "%02d:%02d" % [@hour, @minute] end def + (d) m = @minute + d h = @hour while m >= 60 m -= 60 h += 1 end while m < 0 m += 60 h -= 1 end h = h % 24 Clock.at(h, m) end def - (d) self + (-d) end def == (c) @hour == c.hour and @minute == c.minute end end
true
a28671b0f60660634ae8bdd4fa65c21442f9cfc1
Ruby
DanielSLew/Ruby_Small_Problems
/Foundations/Advanced1/rotating_matrices.rb
UTF-8
814
4.34375
4
[]
no_license
# Write a method that takes a matrix and rotates it 90 degrees # Examples: matrix1 = [ [1, 5, 8], [4, 7, 2], [3, 9, 6] ] matrix2 = [ [3, 7, 4, 2], [5, 1, 0, 8] ] new_matrix1 = rotate90(matrix1) new_matrix2 = rotate90(matrix2) new_matrix3 = rotate90(rotate90(rotate90(rotate90(matrix2)))) p new_matrix1 == [[3, 4, 1], [9, 7, 5], [6, 2, 8]] p new_matrix2 == [[5, 3], [1, 7], [0, 4], [8, 2]] p new_matrix3 == matrix2 # Define a method rotate90 that takes 1 argument (matrix) def rotate90(matrix) matrix.each_with_object([]) do |arr, new_matrix| arr.each_with_index do |value, index| new_matrix.fetch(index) rescue new_matrix << [] new_matrix[index].unshift(value) end end end def rotate_matrix(matrix, rotation) (rotation/90).times {matrix = rotate90(matrix)} matrix end
true
2c2ce7b2e755842c9c3bab889a9d13a0449ef741
Ruby
GavinThomas1192/rubyOnRailsBasics
/rubyCollections/array_addition.rb
UTF-8
786
3.8125
4
[]
no_license
grocery_list = ["Milk", "Eggs", "Bread"] grocery_list << "Carrots" grocery_list.push("Potatoes") # PUTS VALUE IN FRONT grocery_list.unshift("Ice Cream") # This doesn't work unless its in an array grocery_list += ["Ice Cream", "Pie"] puts grocery_list # puts grocery_list.last # puts "Count! #{grocery_list.count}" # puts "Length! #{grocery_list.length}" # puts grocery_list.include?("eggs") # puts grocery_list.count("Ice Cream") last_item = grocery_list.pop puts "Last Item #{last_item}" puts "after pop #{grocery_list}" # GRABS First item in array puts "Shift #{grocery_list.shift}" # this captures the last two values from the array BUT DOES NOT REMOVE THEM drop_two_items = grocery_list.drop(2) # original array unmodified first_three_items = grocery_list.slice(0, 3)
true
2270dec78be91bf059deffc8a00bfadebe1f0dbc
Ruby
nickdba/Ruby
/subtitrari.rb
UTF-8
1,358
3.125
3
[]
no_license
# Print side by side vids and subs def print_side_by_side(vids, subs) for i in (0..vids.size-1) do printf "%-60s %-60s\n", File.basename(vids[i]), File.basename(subs[i]) end end # Mach subtitles names with video file names def match_names(vids,subs) for i in (0..vids.size-1) do vid = vids[i]; subt = subs[i] File.rename(subt, vid.sub(/\.[^.]+\z/,subt[-4,4])) end print_side_by_side(vids,subs) end # Replace romanian chars with english onces def replace_rom_chars(subs) subs.each do |subt| new_sub_text = File.read(subt).gsub("þ","t").gsub("º","s").gsub("ª","s") File.open(subt, "w") {|file| file.puts new_sub_text } end end ####################### # Main Body ####################### # Get the current path path = Dir.pwd+"/*" # Loop menu loop do # Reads the files from the current path vid_files = Dir["#{path}.avi", "#{path}.mpg", "#{path}.mkv"].sort sub_files = Dir["#{path}.srt", "#{path}.sub", "#{path}.txt"].sort # Print Menu printf("\n1. Print Side by Side\n2. Match Names\n3. Replace Romanian Chars\n0. Exit\n\nOption: ") opt = gets system "clear" # Action the option choosen case opt.to_i when 0; break when 1; print_side_by_side(vid_files, sub_files) when 2; match_names(vid_files, sub_files) when 3; replace_rom_chars(sub_files) else next end end
true
9b4ff97c4de5d87cebc7ca2e2cf5927782019230
Ruby
RandyCoffman/writing_string_methods
/delete_character_test.rb
UTF-8
610
3.15625
3
[]
no_license
require "minitest/autorun" require_relative "delete_character.rb" class Delete_method < Minitest::Test def test_boolean #This is made to pass so I can establish a base assert_equal(true, true) end def test_string assert_equal(String, delete("abc", "a").class) end def test_delete assert_equal("heo", delete("hello", "l")) end def test_delete2 assert_equal("gdbye", delete("goodbye", "o")) end def test_delete3 assert_equal("the cake s a le", delete("the cake is a lie", "i")) end def test_delete4 assert_equal("chickens ike cookies", delete("chickens like cookies", "l")) end end
true
8418d2cca2de9ed2281168541958e756d5d23b07
Ruby
Blakealtman123/Ixperience
/quizes/ruby_quiz.rb
UTF-8
2,134
5.15625
5
[]
no_license
# Yay shark cage diving! First, we will define a Fish class. class Fish def initialize(color, name, speed) @color = color @name = name @speed = speed @food = [] end def get_speed @speed > 20 ? "This fish swims super fast!" : "This fish is kinda slow" end end # STEP 4: Now we want to create a Shark class that is a child class of Fish. What do # we need to add to indicate that Shark inherits from Fish? class Shark < Fish def eat(fish) @food << fish end # STEP 5: Define a method called eat that takes an argument called fish. # In the method, append the new fish into the instance variable food. def binge_eat(lots_of_food) lots_of_food.each do |fish| eat(fish) end end # STEP 6: SHARKS ARE HUNGRY!!! Define a method called binge_eat, that takes in an array # of Fish called lots_of_food. Re-use the eat method defined in STEP 5 and apply it # to all elements in the array to make sure your shark eats all the food! def what_i_ate puts "I've eaten #{@food}!" end end nemo = Fish.new('orange', 'Nemo', 10) nemo.get_speed dory = Fish.new('blue','Dory', 25) dory.get_speed marlin = Fish.new('orange', 'Marlin', 20) Bruce = Shark.new('grey', 'Bruce', 40) shark_bait = [nemo,dory,marlin] Bruce.binge_eat(shark_bait) Bruce.what_i_ate # STEP 7: Let's instantiate some fish!!! Create an instance of fish in the variable "nemo", who is orange, # named Nemo, and swims 10 km/hr. Call "get_speed" on your new instance and puts the return value. # STEP 8: MORE FISH! Create 2 more instances of different types of fish, and save them to # variables. You decide what you want to call them! # STEP 9: Uh oh. There's a shark in these waters. Bruce stopped being vegetarian, and now says # "Fish are food, not friends". Yikes. Initialize an instance of Shark called Bruce who is gray # and can swim 40 km/hr. Save it to a variable called bruce. # STEP 10: BRUCE IS HUNGRY. Call "binge_eat" on bruce. Create an array of the Fish instances you # just created, and use that as the method arguments. # STEP 11: Bruce is happy. Call what_i_ate to see what he ate.
true
c7038a60f9381057b7eaedc504b8132d5ac922c7
Ruby
QPC-WORLDWIDE/rubinius
/lib/yaml/encoding.rb
UTF-8
612
2.8125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# # Handle Unicode-to-Internal conversion # module YAML # # Escape the string, condensing common escapes # def YAML.escape( value, skip = "" ) value.gsub( /\\/, "\\\\\\" ). gsub( /"/, "\\\"" ). gsub( /([\x00-\x1f])/ ) do |x| skip[x] || ESCAPES[ x.unpack("C")[0] ] end end # # Unescape the condenses escapes # def YAML.unescape( value ) value.gsub( /\\(?:([nevfbart\\])|0?x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/ ) { |x| if $3 ["#$3".hex ].pack('U*') elsif $2 [$2].pack( "H2" ) else UNESCAPES[$1] end } end end
true
c09fc190dd8bb3aa15a10e854019e5db831d6702
Ruby
sunaku/kwalify
/lib/kwalify/util.rb
UTF-8
4,223
2.796875
3
[ "MIT" ]
permissive
### ### $Rev$ ### $Release: 0.7.2 $ ### copyright(c) 2005-2010 kuwata-lab all rights reserved. ### module Kwalify module Util module_function ## ## expand tab character to spaces ## ## ex. ## untabified_str = YamlHelper.untabify(tabbed_str) ## def untabify(str, width=8) return str if str.nil? list = str.split(/\t/, -1) # if 2nd arg is negative then split() doesn't remove tailing empty strings last = list.pop sb = '' list.each do |s| column = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length n = width - (column % width) sb << s << (' ' * n) end sb << last if last return sb end ## traverse schema ## ## ex. ## schema = YAML.load_file('myschema.yaml') ## Kwalify::Util.traverse_schema(schema) do |rulehash| ## ## add module prefix to class name ## if rulehash['class'] ## rulehash['class'] = 'MyModule::' + rulehash['class'] ## end ## end def traverse_schema(schema, &block) #:yield: rulehash hash = schema _done = {} _traverse_schema(hash, _done, &block) end def _traverse_schema(hash, _done={}, &block) return if _done.key?(hash.__id__) _done[hash.__id__] = hash yield hash if hash['mapping'] hash['mapping'].each {|k, v| _traverse_schema(v, _done, &block) } elsif hash['sequence'] _traverse_schema(hash['sequence'][0], _done, &block) end end private :_traverse_schema ## traverse rule ## ## ex. ## schema = YAML.load_file('myschema.yaml') ## validator = Kwalify::Validator.new(schema) ## Kwalify::Util.traverse_rule(validator) do |rule| ## p rule if rule.classname ## end def traverse_rule(validator, &block) #:yield: rule rule = validator.is_a?(Rule) ? validator : validator.rule _done = {} _traverse_rule(rule, _done, &block) end def _traverse_rule(rule, _done={}, &block) return if _done.key?(rule.__id__) _done[rule.__id__] = rule yield rule rule.sequence.each do |seq_rule| _traverse_rule(seq_rule, _done, &block) end if rule.sequence rule.mapping.each do |name, map_rule| _traverse_rule(map_rule, _done, &block) end if rule.mapping end private :_traverse_rule ## ## get class object. if not found, NameError raised. ## def get_class(classname) klass = Object classname.split('::').each do |name| klass = klass.const_get(name) end return klass end ## ## create a hash table from list of hash with primary key. ## ## ex. ## hashlist = [ ## { "name"=>"Foo", "gender"=>"M", "age"=>20, }, ## { "name"=>"Bar", "gender"=>"F", "age"=>25, }, ## { "name"=>"Baz", "gender"=>"M", "age"=>30, }, ## ] ## hashtable = YamlHelper.create_hashtable(hashlist, "name") ## p hashtable ## # => { "Foo" => { "name"=>"Foo", "gender"=>"M", "age"=>20, }, ## # "Bar" => { "name"=>"Bar", "gender"=>"F", "age"=>25, }, ## # "Baz" => { "name"=>"Baz", "gender"=>"M", "age"=>30, }, } ## def create_hashtable(hashlist, primarykey, flag_duplicate_check=true) hashtable = {} hashlist.each do |hash| key = hash[primarykey] unless key riase "primary key '#{key}' not found." end if flag_duplicate_check && hashtable.key?(key) raise "primary key '#{key}' duplicated (value '#{hashtable[key]}')" end hashtable[key] = hash end if hashlist return hashtable end ## ## get nested value directly. ## ## ex. ## val = YamlHelper.get_value(obj, ['aaa', 0, 'xxx']) ## ## This is equal to the following: ## begin ## val = obj['aaa'][0]['xxx'] ## rescue NameError ## val = nil ## end ## def get_value(obj, path) val = obj path.each do |key| return nil unless val.is_a?(Hash) || val.is_a?(Array) val = val[key] end if path return val end end end
true
6ba88aa29dfe7197a4aec854f02d991ad92e7401
Ruby
phillyrb/ec2manage
/lib/ec2manage/structure.rb
UTF-8
1,005
2.6875
3
[]
no_license
require 'pathname' require 'json' require 'ostruct' class EC2Manage::Structure attr_reader :options attr_reader :zone, :ami, :keypair, :group attr_reader :volumes def initialize(options) @options = options load_template override_options end def override_options [:zone, :ami, :keypair, :group, :name].each do |key| instance_variable_set("@#{key}", options[key]) if options[key] end end def load_template data = JSON.parse(File.read(path)) data.each do |key, value| instance_variable_set("@#{key}", value) end @volumes.map! { |v| OpenStruct.new(v) } end def ensure_extension(template) if template !~ /\.json$/ template + '.json' else template end end def resolve(path) if path.exist? path.to_s else File.join(ENV['HOME'], EC2Manage.directory, path.basename) end end def path pathname = Pathname.new(ensure_extension(options[:template])) resolve(pathname) end end
true
0463b95df2ad0eba2b85aaaa5c2128f2894e65c6
Ruby
m1foley/fit-commit
/lib/fit_commit/validators/base.rb
UTF-8
1,041
2.65625
3
[ "MIT" ]
permissive
require "fit_commit/has_errors" module FitCommit module Validators class Base include FitCommit::HasErrors attr_accessor :branch_name, :config def initialize(branch_name, config) self.branch_name = branch_name self.config = config end @all = [] class << self attr_accessor :all def inherited(subclass) all << subclass end end def validate(lines) lines.each { |line| validate_line(line.lineno, line.text) } end def validate_line(*) fail NotImplementedError, "Implement in subclass" end def enabled? enabled_val = config.fetch("Enabled") if enabled_val.is_a?(Array) enabled_val.any? { |pattern| matches_branch?(pattern) } else enabled_val end end def matches_branch?(pattern) if pattern.is_a?(Regexp) pattern =~ branch_name else pattern == branch_name end end end end end
true
d4698d8b3570cc63d7a8c42343c7a446a0d8a773
Ruby
bbttxu/wuwt-strike
/pips.rb
UTF-8
900
2.84375
3
[]
no_license
#!/usr/bin/env ruby -wKU # ruby script written after reading http://wattsupwiththat.com/2010/08/02/noaa-graphs-62-of-continental-us-below-normal-in-2010/ # processing in post appears overly simplistic, does not take into account weights of variations require 'rubygems' require 'PixelCounter' require 'json' color_weights = { '#FFFF0000FFFF' => 0.5, '#99990000FFFF' => 0.75, '#66660000FFFF' => 1.0, '#00000000FFFF' => 1.25, '#00003333FFFF' => 1.5, '#00006666FFFF' => 1.75, '#3333CCCCFFFF' => 2.0, '#0000FFFFFFFF' => 2.25, '#0000FFFF9999' => 2.5, '#0000FFFF3333' => 2.75, '#0000FFFF0000' => 3.25, #spans two ranges 3.0 - 3.5 '#6666FFFF0000' => 3.5, '#CCCCFFFF0000' => 3.75, '#FFFFCCCC0000' => 4.0, '#FFFF99990000' => 4.25, '#FFFF33330000' => 4.5, '#FFFF00000000' => 4.75, } pc = PixelCounter.new results = pc.process( ARGV[0], color_weights ) puts results.to_json
true
a0509ec9ffb07417da0ad120d20f6da188bd88eb
Ruby
jrsacks/RubyVoiceControlledHomeAutomation
/code/lambda/ruby/tv_control.rb
UTF-8
2,329
2.625
3
[]
no_license
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'aws-sigv4' require 'net/http' require 'json' def send_to_sqs(key, secret, queue, message) url = queue + "?Action=SendMessage&MessageBody=#{URI.encode_www_form_component(message)}" signer = Aws::Sigv4::Signer.new( service: 'sqs', region: queue.split('.')[1], access_key_id: key, secret_access_key: secret ) signed_url = signer.presign_url(http_method: "GET", url: url) uri = URI.parse(queue) https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true request = Net::HTTP::Get.new(signed_url) https.request(request) end def lookup_channel(val) return val.to_s if val.to_i > 0 channels = { "cbs" => 602, "nbc" => 605, "abc" => 607, "wgn" => 609, "fox" => 612, "espn" => 681, "espn2" => 682 } channels[val.downcase].to_s end key = ENV["KEY"] secret = ENV["SECRET"] queue = ENV["SQS_QUEUE"] event = JSON.parse(ARGV[0]) intent = event["request"]["intent"] intent_name = intent["name"] commands = { "Off" => "/tv/power/off", "VolUp" => "/tv/volume/up", "VolDown" => "/tv/volume/down", "Mute" => "/tv/mute", "UnMute" => "/tv/unmute", "Back" => "/tivo/IRCODE/ENTER", "VolSet" => "/tv/volume/", "ChangeChannel" => "/tivo/ch/" } responses = { "Off" => "Now Turning off the TV", "VolUp" => "Turning Volume Up", "VolDown" => "Turning Volume Down", "Mute" => "Muting", "UnMute" => "Unmuting", "Back" => "Switching Back", "VolSet" => "Changing the volume to ", "ChangeChannel" => "Changing the channel to " } command = commands[intent_name] alexa_response = responses[intent_name] if intent_name == "VolSet" volume = intent["slots"]["Volume"]["value"].to_s command += volume alexa_response += volume end if intent_name == "ChangeChannel" channel = intent["slots"]["Channel"]["value"] channel_number = lookup_channel(channel) command += channel_number alexa_response += channel_number end send_to_sqs(key, secret, queue, command) STDOUT.puts({ version: "1.0", response: { outputSpeech: { type: "PlainText", text: alexa_response }, shouldEndSession: true } }.to_json)
true
0f36c843bcc93da4d13d6a64c5960470e02b1e92
Ruby
wonda-tea-coffee/atcoder
/abc/016/a.rb
UTF-8
66
2.71875
3
[]
no_license
m, d = gets.chomp.split.map(&:to_i) puts m % d == 0 ? 'YES' : 'NO'
true
6540f07ff5214d82197ba7c9e61c4cc5b6d74efb
Ruby
sonchez/course_101
/lesson3_practice_problems/practice_problems_medium_1/problem_5.rb
UTF-8
405
3.921875
4
[]
no_license
# the limit variable is not within the scope of the method. # Unless the method calls the variable as an argument, it cannot # enter the scope of the method. # solution below limit = 15 def fib(first_num, second_num, limit) while second_num < limit sum = first_num + second_num first_num = second_num second_num = sum end sum end result = fib(0, 1, limit) puts "result is #{result}"
true
29fb8e8096dbb246e53f5be9b82bcc9b1041ab04
Ruby
geremyCohen/battleship
/board.rb
UTF-8
3,622
3.84375
4
[ "MIT" ]
permissive
class Board < Hash MASQUERADE_SHIPS = false MAX_BOARD_LENGTH = 5 MAX_BOARD_WIDTH = 5 # TODO: Fix the legend, before and after of "MISS" is broken LEGEND = {"." => "Unknown", "I" => "Ship", "o" => "Miss", "+" => "Hit", "X" => "Entire Ship Sunk"} # on first turn, . is a unknown # on second turn, o is a miss attr_accessor :grave_yard attr_accessor :target_coordinates attr_accessor :my_name attr_accessor :opponents_name # TODO: Factor out a Player from the Board def initialize(player_map) # Layout Hash representation of grid, y's at a time MAX_BOARD_WIDTH.times do |x| MAX_BOARD_LENGTH.times do |y| # player_map[x] - represents the starting offset on the y-axis to lay down a 3 unit ship # y = column pointer for laying down ship # if we're not in an empty column, and our y is within the interval to lay down a ship, then lay down a ship unit if player_map[x] > -1 && (player_map[x] .. player_map[x] + 2).cover?(y) self[[x,y]] = 'I' else self[[x,y]] = '.' end end end @grave_yard = {} @grave_yard["total"] = 0 @my_name = self.object_id # Name is by default the object_id -- can be overwritten as needed for human names end def render puts "\nCurrent Game Board\n\n" pp LEGEND.to_a puts "\n\n 0 1 2 3 4" MAX_BOARD_WIDTH.times do |x| row = x.to_s MAX_BOARD_LENGTH.times do |y| row << " " << (MASQUERADE_SHIPS ? (self[[y,x]]).gsub("I", ".") : self[[y,x]]) end puts row end end def attack inital_value = self[@target_coordinates] case self[@target_coordinates] when '.' self[@target_coordinates] = 'o' print "(#{@target_coordinates}): #{LEGEND[self[@target_coordinates]]}!" when 'o' print "(#{@target_coordinates}): #{LEGEND[self[@target_coordinates]]}!" when '+' print "(#{@target_coordinates}): #{LEGEND[self[@target_coordinates]]}!" when 'X' print "(#{@target_coordinates}): #{LEGEND[self[@target_coordinates]]}!" when 'I' self[@target_coordinates] = '+' print "Attacking (#{@target_coordinates}): #{LEGEND[self[@target_coordinates]]}!" # figure out if we sunk the whole ship yet # if so, mark the whole ship sunk with 'X' char # Add the y element of the dead ship to the hash keyed by the x coordinate x = @target_coordinates[0] y = @target_coordinates[1] @grave_yard[x] = [] if @grave_yard[x].nil? @grave_yard[x].push(y) # TODO: Factor out the logic here, too fat # If there are 3 hits in this x, that means the whole ship is hit if @grave_yard[x].length == 3 # Mark the whole ship as destroyed puts " Ship Destroyed!" @grave_yard[x].each do |i| self[[x,i]] = "X" end # Add the tally to the grave @grave_yard["total"] += 1 puts "Incrementing grave total. Total sunk ships: #{@grave_yard["total"]}" # If the grave count is 3, end the game as a victory! if @grave_yard["total"] == 3 puts "\n\n\n*** Player #{self.opponents_name} is the winner! ***" puts "All Ships Sunk, Game Over Man!\n\n\n" exit end end end print " -- (But Already Taken!)" if inital_value == self[@target_coordinates] end def target print "\nEnter a coordinate pair to attack in the format: x,y " @target_coordinates = gets.split(",").map! {|x| x.to_i} end end
true
b56a45c12225e6b7230c0e7bfc2b3fe943292479
Ruby
alexvirga/deli-counter-nyc-web-060319
/deli_counter.rb
UTF-8
579
3.75
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
katz_deli = [] def line (katz_deli) if katz_deli.length == 0 puts "The line is currently empty." else prompt = "The line is currently:" for i in 0...katz_deli.length prompt += " #{i+1}. #{katz_deli[i]}" end puts prompt end end def take_a_number(katz_deli, name) katz_deli.push(name) puts "Welcome, #{name}. You are number #{katz_deli.length} in line." end def now_serving (katz_deli) if katz_deli.length == 0 puts "There is nobody waiting to be served!" else next_in_line = katz_deli.shift puts "Currently serving #{next_in_line}." end end
true
744791589ddbd2029795b1a72d6447463191d289
Ruby
dyevri/rubyway
/one-liners.rb
UTF-8
519
3.734375
4
[]
no_license
if 4 < 12 puts "That's right!" end puts "That's right!" if 4 < 12 puts "I like cheese!" unless 50 < 20 #Ternary Conditional Expsession if 40 < 2 puts 'Yes it is.' else puts 'No it is not' end puts 40 < 2 ? 'Yes it is' : 'No it is not' puts "How are you filling today?" feeling = gets.chomp.downcase case feeling when "happy" then puts "So glad to hear that!" when "sad" then puts "I'm sorry to hear that." when "tired" then puts "You should take a nap." else puts "I dont understand that feeling." end
true
e0a7c3b8ffd12bd04804600bd5fa6f2acc9cecb2
Ruby
TomK32/gallerize
/lib/gallerize_cli/image.rb
UTF-8
1,846
2.625
3
[]
no_license
require 'gallerize_cli/image/version' module GallerizeCli class Image include FileUtils::Verbose attr_reader :directory, :file_path, :versions class << self def generate_version_method(name) unless public_method_defined?("#{name}_url") define_method("#{name}_url") { self.versions[name].url } end end end def attributes @attributes ||= fetch_attributes end def original_url destination = File.join(directory.images_path, file_name) cp(file_path, destination) unless File.exists?(destination) destination.gsub(directory.output_path, config.site_url) end def initialize(directory, file_path) @success = true @directory = directory @file_path = file_path generate_version_methods end def process versions.each { |name, version| version.process } end def name return @name if defined?(@name) parts = file_name.split('.') parts.pop @name = parts.join('.') end def file_name @file_name ||= File.basename(file_path) end def config directory.config end def versions @versions ||= config.versions.inject({}) do |hash, (version_name, options)| hash[version_name] = GallerizeCli::Image::Version.new(self, version_name, options) hash end end def valid? versions.collect(&:valid?).include?(false) end private def fetch_attributes hash = {} if config.image_attributes.is_a?(Hash) hash = config.image_attributes[file_name] || {} end OpenStruct.new(hash) end def generate_version_methods versions.each do |name, version| self.class.generate_version_method(name) end end def success? @success end end end
true
8e383c9577f0818c824026b69d1b441403d30c8a
Ruby
brunocascio/UNLP-ruby-evaderApp
/test/models/person_test.rb
UTF-8
3,060
2.71875
3
[ "MIT" ]
permissive
require 'test_helper' class PersonTest < ActiveSupport::TestCase test "Creates people with valid data" do people().each do |p| assert p.save, "Should save a new person with valid data" end end test "Try to create person without data" do assert_not Person.new().save(), "Shouldn't create a new person without attributes" end test "Try to creates people with blank data" do assert_not Person.new(name: '', person_type: 'juridic', cuilt: '20-1235434-7').save(), "Shouldn't create a new person with blank name" assert_not Person.new(name: 'Name of a person', person_type: '', cuilt: '20-1235434-7').save(), "Shouldn't create a new person with blank person_type" assert_not Person.new(name: 'Name of a person', person_type: 'fisic', cuilt: '').save(), "Shouldn't create a new person with blank cuit" end test "Try to creates people with invalid data" do assert_not Person.new(name: '1234', person_type: 'juridic', cuilt: '20-1235434-7').save(), "Shouldn't create a new person with numeric name" assert_not Person.new(name: 'a', person_type: 'juridic', cuilt: '20-1235434-7').save(), "Shouldn't create a new person with < 2 chars" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '209812-asas-1').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '209812').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '20-12-12').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '2-1-1').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '0-0-0').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '--').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '00000000--').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_not Person.new(name: 'name of person', person_type: 'juridic', cuilt: '0-0000000-').save(), "Shouldn't create a new person with invalid cuil/cuit format" assert_raises(ArgumentError){ Person.new(person_type: 'not_a_valid_person_type') } end test "Try to creates person with duplicated cuilt" do people(:personWithName).save() assert_not Person.new(cuilt: people(:personWithName).cuilt, name: 'other person', person_type: 'fisic').save(), "Shouldn't create a new person with duplicated cuilt" end test "Try to delete all people" do Person.all.each do |p| if (p.invoices.count == 0) assert p.destroy(), "Should delete a person." else assert_not p.destroy(), "Shouldn't delete person #{p.id}: #{p.name} with associated invoices." end end end end
true
50105247c571cc97f4d3227699d55dbd1491eef6
Ruby
maxerogers/Ruby-KNN
/knn.rb
UTF-8
1,143
3.828125
4
[]
no_license
# Step 1 calculate the Euclidean distance from the test vector from the training vectors # Step 2 Sort the results and determine the min K neighbors # Step 3 Print classification puts "K-Nearest Neighbor" class Neighbor attr_accessor :klass, :vector #can't use class since its a keyword def initialize(klass, vector) @klass = klass @vector = vector end end training_data = [] File.open('data.dat').each do |line| line = line.split(" ").collect{|i| i.to_f} training_data.push Neighbor.new(line.pop,line) end def euclidean_distance(x,y) sum = 0.0 x.each_with_index do |xi, i| sum += (x[i] - y[i])**2 end return Math.sqrt(sum) end test_point = [8,6] results = {} training_data.each do |x| results[x] = euclidean_distance(x.vector,test_point) end k = 3 puts "K: #{k}" results = results.sort_by {|_key, value| value} count = 1 classes = {} results.each do |key,value| break if count > 3 puts "#{key.klass} : #{value}" classes[key.klass] ||= 0 classes[key.klass] = classes[key.klass] + 1 count += 1 end klass = "" max = 0 classes.each do |c,v| if max < v max = v klass = c end end puts "It is a #{klass}" puts ""
true
a47ad976f124551d702b0d2a067f2f8eed00a7de
Ruby
Fromalaska49/ruby-hello-world
/bottles-of-beer.rb
UTF-8
179
2.6875
3
[]
no_license
<% for i in (99).downto(1) %> <%= i %> bottles of beer on the wall, <%= i %> bottles of beer, take one down, pass it around, <%= (i - 1) %> bottles of beer on the wall <% end %>
true
21cca923762c4c9ff9085a1a312aae769a85b3da
Ruby
CrazyJ100/math
/addition.rb
UTF-8
112
2.671875
3
[]
no_license
def add(arg1,arg2) arg1+arg2 end def divide(arg1,arg2) arg1/arg2 end def subtract(arg1,arg2) arg1-arg2 end
true
2d4b5d75b49f147ec0da51d33dbe57a8b66b6677
Ruby
da99/datoki
/specs/0030-matching.rb
UTF-8
3,186
2.609375
3
[ "MIT" ]
permissive
describe :matching do before { CACHE[:datoki_matching] ||= begin reset_db <<-EOF CREATE TABLE "datoki_test" ( id serial NOT NULL PRIMARY KEY, title varchar(15) NOT NULL, body text NOT NULL, age smallint NOT NULL ); EOF end } it "uses error message from :mis_match" do catch(:invalid) { Class.new { include Datoki table :datoki_test field(:title) { varchar 5, 15, lambda { |r, val| false }; mis_match "Title is bad." } field(:body) { text 5, 10 } field(:age) { smallint } def create clean :title, :body, :age end }.create(:title=>'title', :body=>'body', :age=>50) }.error[:msg].should.match /Title is bad/ end # === it uses error message from :mis_match it "inserts data into db if match w/Regexp matcher" do Class.new { include Datoki table :datoki_test field(:title) { varchar 5, 15, /title 4/ } field(:body) { text 5, 10 } field(:age) { smallint } def create clean :title, :body, :age end }.create(:title=>'title 4', :body=>'body 4', :age=>50) DB[:datoki_test].all.last.should == {:id=>1, :title=>'title 4', :body=>'body 4', :age=>50} end # === it inserts data into db if matcher returns true it "inserts data into db if lambda matcher returns true" do Class.new { include Datoki table :datoki_test field(:title) { varchar 5, 15, lambda { |r, val| true } } field(:body) { text 5, 10 } field(:age) { smallint } def create clean :title, :body, :age end }.create(:title=>'title 5', :body=>'body 5', :age=>50) DB[:datoki_test].all.last.should == {:id=>2, :title=>'title 5', :body=>'body 5', :age=>50} end # === it inserts data into db if matcher returns true it "throws :invalid if mis-match w/Regexp matcher" do catch(:invalid) { Class.new { include Datoki table :datoki_test field(:title) { varchar 5, 15, /\Agood\Z/; mis_match "Title is really bad." } field(:body) { text 5, 10 } field(:age) { smallint } def create clean :title, :body, :age end }.create(:title=>'baddd', :body=>'body', :age=>50) }.error[:msg].should.match /Title is really bad/ end # === it accepts a Regexp as a matcher it "throws :invalid if lambda matcher returns false" do r = catch(:invalid) { Class.new { include Datoki table :datoki_test field(:title) { varchar 5, 15, lambda { |r, v| false } } field(:body) { text 5, 10 } field(:age) { smallint } def create clean :title, :body, :age end }.create(:title=>'title', :body=>'body', :age=>50) } r.error[:msg].should.match /Title is invalid/ end # === it throws :invalid if matcher returns false end # === describe :matching
true
3e1ed6c3bf1472aae853891854eb662735166f87
Ruby
jgendrano/slack_project
/app/models/message.rb
UTF-8
2,894
2.625
3
[]
no_license
class Message < ActiveRecord::Base belongs_to :user belongs_to :channel def self.current_messages(current_user, channel) count = 1 user_list = self.get_username_list(current_user.token) raw_messages = self.get_messages_from_slack(current_user, channel) current_messages = raw_messages.map do |message| if message["user"].nil? slack_username = message["username"] else slack_username = user_list[message["user"]] end raw_slack_message = message["text"] while (raw_slack_message.include? "<mailto:") do x = raw_slack_message[/\<mailto.*?\>/] x.slice!(0..7) slack_message = raw_slack_message.sub!(raw_slack_message[/\<mailto.*?\>/], x.split("|")[0]) end while !(raw_slack_message[/\<.*?\>/].nil?) && (raw_slack_message[/\<.*?\>/].length == 12) do mod_user = raw_slack_message[/\<.*?\>/] mod_user.slice!(0..1) mod_user.slice!(-1) slack_message = raw_slack_message.sub!(raw_slack_message[/\<.*?\>/], user_list[mod_user]) end if !(raw_slack_message[/\<.*?\>/].nil?) && !(raw_slack_message.include? "http") && !(raw_slack_message.include? "<!") mod_user = raw_slack_message[/\@.*?\|/] x = mod_user.split("") x.shift x.pop slack_message = raw_slack_message.sub(raw_slack_message[/\<.*?\>/], user_list[x.join("")]) elsif !(raw_slack_message[/\<.*?\|/].nil?) && (raw_slack_message.include? "http") mod_user = raw_slack_message[/\@.*?\|/] mod_user.slice!(0) mod_user.slice!(-1) slack_message = raw_slack_message.sub!(raw_slack_message[/\<.*?\>/], user_list[mod_user]) else slack_message = raw_slack_message end timestamp = DateTime.strptime(message["ts"], '%s') id = count count = count + 1 new(slack_username: slack_username, ts: timestamp, slack_message: slack_message, id: id, user_id: current_user.id) end return current_messages end def self.get_messages_from_slack(current_user, channel) uri = URI("https://slack.com/api/channels.history?token=#{current_user.token}&channel=#{channel.channel_id}") response = Net::HTTP.get_response(uri) messages = JSON.parse(response.body)['messages'].reverse return messages end def self.get_username_list(token) uri = URI("https://slack.com/api/users.list?token=#{token}") response = Net::HTTP.get_response(uri) users = JSON.parse(response.body)['members'] user_list = Hash.new users.each do |user| if user["real_name"] == '' user_list[user["id"]] = "@#{user["name"]}" else user_list[user["id"]] = "@#{user["name"]} (#{user["real_name"]})" end end user_list end private def message_params params.require(:message).permit(:slack_username, :ts, :slack_message, :id) end end
true
94ecf06418c3ad7a0bfd0184fc0cbe96b0b4d1bb
Ruby
W1LBER/desafio_ciclos
/alfabeto.rb
UTF-8
162
3.171875
3
[]
no_license
def gen(user) a = "a" arr = [] user.times do |i| arr.push(a) a = a.next print arr.last end end gen(5)
true
9acb5bf2d9c307df974c5e4812c917dfed780fa1
Ruby
andrewcallahan/projecteuler
/16.rb
UTF-8
59
2.703125
3
[]
no_license
p (2**1000).to_s.split("").collect{ |i| i.to_i }.reduce(:+)
true
54228b345384cc1eaad5b0c4574fbb59fa0973ec
Ruby
bobcook/blog
/scripts/load-old-data.rb
UTF-8
2,080
2.734375
3
[]
no_license
require 'pg' class Loader def initialize @con = PG::Connection.new :host => 'ec2-54-243-50-213.compute-1.amazonaws.com', :port => '5432', :user => 'gdgallhkmzucyp', :password => 'BmSWLwkVV_Bfcjwz9sZPtSsIIX', :dbname => 'd5sm1n1kpsj2ta' end def load_posts posts = @con.exec "SELECT * FROM POSTS ORDER BY create_time" posts.each do |post| puts "Loading post with title: #{post['title']}" new_post = Post.create :title => post["title"], :content => post["content"], :created_at => post["create_time"], :updated_at => post["updated_at"], :user_id => 1, :status => post["status"] self.load_comments post, new_post self.load_tags post, new_post end end def load_comments(post, new_post) # create_time = sc.Column(sc.DateTime) # content = sc.Column(sc.String) # user_email = sc.Column(sc.String) # username = sc.Column(sc.String) # post_id = sc.Column(sc.Integer, sc.ForeignKey('posts.id')) comments = @con.exec "SELECT * FROM COMMENTS WHERE post_id='#{post["id"]}'" comments.each do |comment| puts "Loading comment with email: #{comment['user_email']}" Comment.create :email => comment['user_email'], :content => comment['content'], :name => comment['username'], :post_id => new_post.id, :created_at => comment['create_time'] end end def load_tags(post, new_post) # id = sc.Column(sc.Integer, primary_key=True) # post_id = sc.Column(sc.Integer, sc.ForeignKey('posts.id')) # tag_name = sc.Column(sc.String) tags = @con.exec "SELECT * FROM TAGS WHERE post_id='#{post["id"]}'" tags.each do |tag| puts "Loading tag with name: #{tag['tag_name']}" Tag.create :post_id => new_post.id, :name => tag['tag_name'] end end end loader = Loader.new loader.load_posts
true
77bc0fe0020544c3ad22a132bbd815cce8c82e02
Ruby
vonagam/dip
/app/models/game/engine/parser/map.rb
UTF-8
2,265
2.796875
3
[]
no_license
require 'yaml' require 'set' require_relative '../entity/area' require_relative '../entity/map' module Engine class Parser::Map attr_accessor :maps def initialize() @maps = {} map_path ||= File.expand_path('../maps/', File.dirname(__FILE__)) Dir.chdir map_path do Dir.glob "*.yaml" do |mapfile| read_map_file mapfile end end end def read_map_file(yaml_file) yamlmap = YAML::load_file yaml_file mapname = yaml_file.scan(/\A[^.]+/)[0].classify map = Map.new map.yaml_areas = yamlmap['Areas'].to_json borders_infos = {} yamlmap['Areas'].each do |name, info| neis = info['neis'] multicoast = neis.has_key?('water') && neis['water'].is_a?(Hash) if multicoast neis['water'].each do |location, water_neis| location_name = ("#{name}_#{location}").to_sym map.areas[location_name] = Area.new( location_name, :coast, false, info['full'].to_sym, false ) borders_infos[ location_name ] = { 'water' => water_neis } end neis.delete 'water' end map.areas[name.to_sym] = Area.new( name.to_sym, info['type'].to_sym, info.has_key?('center'), info['full'].to_sym, multicoast ) borders_infos[ name.to_sym ] = neis end borders_infos.each do |area_name, borders_info| areas = [ map.areas[ area_name ] ] if area_name =~ /\A(\w+)_/ areas.push map.areas[ $1.to_sym ] end areas.each do |area| borders_info.each do |type, neighbours| border_type = type == 'land' ? Area::LAND_BORDER : Area::SEA_BORDER neighbours.each do |neighbour| area.add_border map.areas[ neighbour.to_sym ], border_type if neighbour =~ /\A(\w+)_/ area.add_border map.areas[ $1.to_sym ], border_type end end end end end map.powers = yamlmap['Powers'].keys map.initial_state = Parser::State.new().to_state({ 'Powers' => yamlmap['Powers'] }) @maps[mapname] = map end end end
true
b333d39781af760269c78f45b86c40a7a91f3810
Ruby
colinhalexander/flavortown-practice
/flavor.rb
UTF-8
514
2.90625
3
[]
no_license
require_relative "./join_module.rb" class Flavor #extend Join::ClassMethods include Join::InstanceMethods attr_reader :description, :label @@all = [] def initialize(description, label) @description = description @label = label @@all << self end def self.all @@all end # def add_brand(brand) # FlavorBrand.new(self, brand) # end def brands FlavorBrand.all.select{|fb| fb.flavor == self}.map(&:brand).uniq end end
true
f7faaa8ef0318debc84a22f9bc86688ada282192
Ruby
applelele/cartoon-collections-onl01-seng-pt-030220
/cartoon_collections.rb
UTF-8
549
3.34375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def roll_call_dwarves(array) array.each_with_index do |dwarf, index| puts "/#{index+1}. *#{dwarf}/" end end def summon_captain_planet(array) array.map {|planeteer| "#{planeteer.capitalize}!"} end def long_planeteer_calls(array) array.any? {|planeteer| planeteer.length > 4} end def find_the_cheese(array) # the array below is here to help cheese_types = ["cheddar", "gouda", "camembert"] if array.any? {|food|cheese_types.include?(food)} return array.find{|food| cheese_types.include?(food)} else return nil end end
true
4a7925316acde50bd4f8689b52e76a56e5ba18ff
Ruby
Alurye/collections_practice_vol_2-nyc-web-031218
/collections_practice.rb
UTF-8
2,085
3.421875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# your code goes here require ('pry') def begins_with_r(array) # binding.pry array.all? {|tool| tool.start_with?('r') } end def contain_a(array) # contains_a = [] array.select {|element| element.include?('a') } end def first_wa(array) array.find {|word| if word.is_a? String word.start_with?("wa") end } end def remove_non_strings(array) array.delete_if {|type| !type.is_a? String } end def count_elements(array) #Iterate over the array #take original hash set count to 0 # take the original hash name set it as new name # new_name = og[:name] #iterate over the array again #if the current hash has the same name as new name then we increment the count on the og hash array.each do |orig_hash| orig_hash[:count] = 0 new_name = orig_hash[:name] array.each do |current| if current[:name] == new_name orig_hash[:count] += 1 end end end.uniq # counted = Hash.new(0) # array.each { |h| counted[h[:name]] += 1 } # counted = Hash[counted.map {|k,v| [k,v] }] # the_count = {} # count_array = [] # counted.each {|k,v| # # the_count[:name] = k # the_count[:count] = v # count_array << the_count # # } # count_array # binding.pry end def find_cool(array) cool_temp = [] array.select {|item| if item[:temperature] == "cool" item end } end def merge_data(keys, data) merge_data = [] #take each hash value of the keys array and set it to the first element of the data array keys.each {|key| merged_data << data.unshift(key) } merged_data end def organize_schools(hash) organized_schools = {} nyc_schools = [] sf_schools = [] chi_schools = [] hash.each {|school, city| # binding.pry if city[:location] == "NYC" nyc_schools << school organized_schools[city[:location]] = nyc_schools end if city[:location] == "SF" sf_schools << school organized_schools[city[:location]] = sf_schools end if city[:location] == "Chicago" chi_schools << school organized_schools[city[:location]] = chi_schools end } organized_schools end
true
647ffe9a3b8f71b0307ec01179c8377f3356d4d8
Ruby
pierre-pat/The-Nature-of-Code-Examples
/chp7_CA/NOC_7_02_GameOfLifeSimple/NOC_7_02_GameOfLifeSimple.rb
UTF-8
1,772
3.34375
3
[]
no_license
# The Nature of Code # NOC_7_02_GameOfLifeSimple class GOL def initialize(width, height) @w = 8 @rows = height / @w @cols = width / @w puts "rows: #{@rows} - @cols #{@cols}" init end def init @board = Array.new(@cols) do Array.new(@rows) { random(2).to_i } end end def generate nextgen = Array.new(@cols) { Array.new(@rows) { 0 } } (1...@cols-1).each do |x| (1...@rows-1).each do |y| neighbors = 0 (-1..1).each do |i| (-1..1).each do |j| if @board[x+i][y+j] == nil puts "x+i #{x+i} - y+j #{y+j}" end neighbors += @board[x+i][y+j] if @board[x+i][y+j] end end # A little trick to subtract the current cell's state since # we added it in the loop above neighbors -= @board[x][y] # rules of life if @board[x][y] == 1 and neighbors < 2 nextgen[x][y] = 0 # Loneliness elsif @board[x][y] == 1 and neighbors > 3 nextgen[x][y] = 0 # Overpopulation elsif @board[x][y] == 0 and neighbors == 3 nextgen[x][y] = 1 # Reproduction else nextgen[x][y] = @board[x][y] # Stasis end end end @board = nextgen end def display (0...@cols).each do |i| (0...@rows).each do |j| if @board[i][j] == 0 fill(120) else fill(255) end stroke(0) rect(i*@w, j*@w, @w, @w) end end end end def setup size(400, 400) frame_rate(24) @gol = GOL.new(width, height) end def draw background(255) @gol.generate @gol.display end # reset board when mouse is pressed def mouse_pressed @gol.init end
true
8c3e76fb06f14dfcbad34423091274bf2ef35d0a
Ruby
westernmilling/people_doc
/lib/people_doc.rb
UTF-8
9,118
2.546875
3
[ "MIT" ]
permissive
# frozen_string_literal: true # $LOAD_PATH.unshift File.dirname(__FILE__) require 'people_doc/version' require 'people_doc/httparty_request' require 'logger' module PeopleDoc RESPONSE_HANDLERS = { bad_request: ResponseHandlers::HandleBadRequest, not_found: ResponseHandlers::HandleNotFound, unauthorized: ResponseHandlers::HandleUnauthorized, unprocessable_entity: ResponseHandlers::HandleUnprocessableEntity, unknown: ResponseHandlers::HandleUnknownFailure }.freeze class BaseError < StandardError attr_reader :response def initialize(message = nil, response = nil) super(message) @response = response end end class BadRequest < BaseError; end class NotFound < BaseError; end class Unauthorized < BaseError; end class UnprocessableEntity < BadRequest; end class Token attr_accessor :access_token, :token_type, :expires_in def initialize(access_token, token_type, expires_in) @access_token = access_token @token_type = token_type @expires_in = expires_in end end module V1 class << self attr_accessor :api_key, :base_url, :logger ## # Configures default PeopleDoc REST APIv1 settings. # # @example configuring the client defaults # PeopleDoc::V1.configure do |config| # config.api_key = 'api_key' # config.base_url = 'https://api.staging.us.people-doc.com' # config.logger = Logger.new(STDOUT) # end # # @example using the client # client = PeopleDoc::V1::Client.new def configure yield self true end end ## # PeopleDoc REST API v1 Client class Client def initialize(options = {}) options = default_options.merge(options) @api_key = options.fetch(:api_key) @base_url = options.fetch(:base_url) @logger = options.fetch(:logger, Logger.new(STDOUT)) @request = HTTPartyRequest.new(@base_url, @logger, response_handlers) end ## # Get a resource # Makes a request for a resource from PeopleDoc and returns the response # as a raw {Hash}. # # @param [String] the resource endpoint # @return [Hash] response data def get(resource) @request .get(base_headers, "api/v1/#{resource}") rescue NotFound nil end ## # POST a resource # Makes a request to post new or existing resource details to PeopleDoc. # # @param [String] the resource endpoint # @param [Hash] payload data # @return [Hash] response data def post(resource, payload) @request.post( base_headers, "api/v1/#{resource}/", payload.to_json ) end ## # POST a file # ... # # @param [String] the resource endpoint # @param [...] file # @param [Hash] payload data # @return [Hash] response data def post_file(resource, file, payload) @request.post_file( base_headers.merge( 'Accept' => 'multipart/form-data' ), "api/v1/#{resource}/", file: file, data: payload ? payload.to_json : nil ) end protected def base_headers { 'Accept' => 'application/json', 'X-API-KEY' => @api_key, 'Content-Type' => 'application/json', 'Host' => uri.host, 'User-Agent' => 'PeopleDoc::V1::Client' } end ## # Default options # A {Hash} of default options populate by attributes set during # configuration. # # @return [Hash] containing the default options def default_options { api_key: PeopleDoc::V1.api_key, base_url: PeopleDoc::V1.base_url, logger: PeopleDoc::V1.logger } end def response_handlers RESPONSE_HANDLERS.merge( bad_request: PeopleDoc::ResponseHandlers::V1::HandleBadRequest ) end def uri @uri ||= URI.parse(@base_url) end end end module V2 class << self attr_accessor :application_id, :application_secret, :base_url, :client_id, :logger ## # Configures default PeopleDoc REST APIv1 settings. # # @example configuring the client defaults # PeopleDoc::V2.configure do |config| # config.application_id = 'application_id' # config.application_secret = 'application_secret' # config.base_url = 'https://apis.staging.us.people-doc.com' # config.client_id = 'client_id' # config.logger = Logger.new(STDOUT) # end # # @example using the client # client = PeopleDoc::V2::Client.new def configure yield self true end end ## # PeopleDoc REST API v2 Client class Client def initialize(options = {}) options = default_options.merge(options) @application_id = options.fetch(:application_id) @application_secret = options.fetch(:application_secret) @base_url = options.fetch(:base_url) @client_id = options.fetch(:client_id) @logger = options.fetch(:logger, Logger.new(STDOUT)) @request = HTTPartyRequest.new(@base_url, @logger, response_handlers) end def encoded_credentials EncodedCredentials.new(@application_id, @application_secret).call end ## # OAuth token # Performs authentication using client credentials against the # PeopleDoc Api. # # @return [Token] token details def token return @token if @token payload = { client_id: @client_id, grant_type: 'client_credentials', scope: 'client' } headers = { 'Accept' => 'application/json', 'Authorization' => "Basic #{encoded_credentials}", 'Content-Type' => 'application/x-www-form-urlencoded', 'Host' => uri.host, 'User-Agent' => 'PeopleDoc::V2::Client' } response = @request.post(headers, 'api/v2/client/tokens', payload) @token = Token.new( *response.values_at('access_token', 'token_type', 'expires_in') ) end ## # Get a resource # Makes a request for a resource from PeopleDoc and returns the response # as a raw {Hash}. # # @param [String] the resource endpoint # @return [Hash] response data def get(resource) @request .get(base_headers, "api/v2/client/#{resource}") rescue NotFound nil end ## # POST a file # ... # # @param [String] the resource endpoint # @param [...] file # @param [Hash] payload data # @return [Hash] response data def post_file(resource, file, payload = nil) @request.post_file( base_headers.merge( 'Content-Type' => 'multipart/form-data' ), "api/v2/#{resource}", file: file, data: payload ? payload.to_json : nil ) end ## # PUT a resource # Makes a request to PUT new or existing resource details to PeopleDoc. # # @param [String] the resource endpoint # @param [Hash] payload data # @return [Hash] response data def put(resource, payload) @request.put( base_headers, "api/v2/client/#{resource}", payload.to_json ) end protected def base_headers { 'Accept' => 'application/json', 'Authorization' => "Bearer #{token.access_token}", 'Content-Type' => 'application/json', 'Host' => uri.host, 'User-Agent' => 'PeopleDoc::V2::Client' } end ## # Default options # A {Hash} of default options populate by attributes set during # configuration. # # @return [Hash] containing the default options def default_options { application_id: PeopleDoc::V2.application_id, application_secret: PeopleDoc::V2.application_secret, base_url: PeopleDoc::V2.base_url, client_id: PeopleDoc::V2.client_id, logger: PeopleDoc::V2.logger } end def response_handlers RESPONSE_HANDLERS.merge( bad_request: PeopleDoc::ResponseHandlers::V2::HandleBadRequest, unauthorized: PeopleDoc::ResponseHandlers::V2::HandleUnauthorized ) end def uri @uri ||= URI.parse(@base_url) end end class EncodedCredentials def initialize(application_id, application_secret) @application_id = application_id @application_secret = application_secret end def call Base64.strict_encode64("#{@application_id}:#{@application_secret}") end end end end
true
7799714b671a470804d7bddf95a78fce20e88fbe
Ruby
gabpoiss/zebrasclub
/db/seeds.rb
UTF-8
1,078
2.59375
3
[]
no_license
puts "Cleaning database..." OrderItem.destroy_all Order.destroy_all Item.destroy_all Category.destroy_all puts "Creating categories..." # # New seed........ categories = ["skate", "helmet", "jersey", "pants", "armband"] categories.each do |category| Category.create(item_type: category) end # Skates sizes = ["extra small", "small", "medium", "large", "extra large"] # 1 puts "Creating Items...." require 'csv' csv_options = { col_sep: ';', quote_char: '"', headers: :first_row, row_sep: :auto } filepath = 'db/items.csv' CSV.foreach(filepath, csv_options) do |row| sizes.each do |size| Item.create(category_id: Category.where(item_type: row[4]).first.id, size: size, stock: rand(10..50), price: row[0], brand: row[1], description: row[2], picture: row[3]) end puts "Equipment Type: #{row[4].upcase} - ItemsBrand: #{row[1]}" end User.create(first_name: "Gabriel", last_name: "Poissant", email: "gab_hockey_64@hotmail.com", password: "123456") Order.create(user_id: User.first.id, shipping_address: "123 Fake Street", paid_status: false)
true
fd430d8e044d44a151deececf68027d226a14f21
Ruby
chickenriceplatter/advent_of_code
/2015/problem-18-1.rb
UTF-8
1,283
3.828125
4
[]
no_license
require 'pry' string = File.read("18-1-input.txt") def neighbors(x,y) locations = [] locations << [x+1, y] if((x+1) < 100) locations << [x-1, y] if((x-1) >= 0) locations << [x, y+1] if((y+1) < 100) locations << [x, y-1] if((y-1) >= 0) locations << [x-1, y-1] if(((x-1)>=0)&&((y-1)>=0)) locations << [x+1, y+1] if(((x+1)<100)&&((y+1)<100)) locations << [x-1, y+1] if(((x-1)>=0)&&((y+1)<100)) locations << [x+1, y-1] if(((x+1)<100)&&((y-1)>=0)) locations end def transform_string(input_string) array = input_string.strip.split("\n") array.map!{ |row| row.split("") } new_string = "" (0..99).each do |y| (0..99).each do |x| current_light = array[y][x] neighbor_locations = neighbors(x,y) neiboring_lights = neighbor_locations.map{ |each| array[each.last][each.first] } count = neiboring_lights.count("#") if current_light == "#" if((count==2)||(count==3)) new_string << "#" else new_string << "." end else if(count==3) new_string << "#" else new_string << "." end end end new_string << "\n" end new_string end 100.times do temp = string string = transform_string(temp) end puts string.count("#")
true