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
0688aa7a19bac3754f6364980da53c4ea0d76a8a
Ruby
TopWebGhost/Angular-Influencer
/Projects/miami_metro/doakes/code/shopstyle-pull-data-into-db.rb
UTF-8
11,627
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- require 'rubygems' require 'nokogiri' require 'open-uri' require 'net/http' require 'active_record' # Pseudo-code # 1. Accept cmd-line arguments: brand/store # 2. Call shopstyle URL with info, and process received arguments # 3. Write output to db def process_pernode_info(pernode, gender_val, time, brandinfo_arr) pr_id = pernode.xpath('//Product/Id') pr_name = pernode.xpath('//Product/Name') pr_br_name = pernode.xpath('//Product/BrandName') pr_currency = pernode.xpath('//Product/Currency') pr_price = pernode.xpath('//Product/Price') pr_instock = pernode.xpath('//Product/InStock') pr_retailer = pernode.xpath('//Product/Retailer') pr_category = pernode.xpath('//Product/Category') pr_saleprice = pernode.xpath('//Product/SalePrice') pr_image = pernode.xpath('//Product/Image/Url') pr_color = pernode.xpath('//Product/Color/Name') pr_size = pernode.xpath('//Product/Size/Name') pr_url = pernode.xpath('//Product/Url') # Get brand_id br_id = "" brandinfo_arr.each do |l| if (pr_br_name.text.strip.casecmp(l.name.strip) == 0) #print "Match: " + l.name.strip + " with " + pr_br_name.text + "\n" #print "Match: ID = " + l.id.to_s + "\n" br_id = l.id.to_s break end end # TODO: if br_id is nill, input new brand name and match with that ID # Get gender p_gender = gender_val # Get product categories (up to five supported right now) i = 0 p_cat = ['Empty', 'Empty', 'Empty', 'Empty', 'Empty'] pr_category.each do |l| p_cat[i] = l.text i += 1 break if (i > 4) end # Get saleprice if ((pr_saleprice.nil? == false) and (pr_saleprice.text.empty? == false)) p_saleprice = pr_saleprice.text else p_saleprice = pr_price.text end # Get image urls (for small, medium and large sizes) i = 0 p_img = ['Empty', 'Empty', 'Empty'] pr_image.each do |l| p_img[i] = l.text i += 1 break if (i > 2) end # Get available sizes p_size = [] pr_size.each do |l| #print "[" + l.text.to_s.strip + "], " p_size << "[" + l.text.downcase.strip + "], " end p_size << "[], " if p_size.length == 0 #print p_size.join + "\n" # Get available colors p_color = [] pr_color.each do |l| #print "[" + l.text.to_s.strip + "], " p_color << "[" + l.text.downcase.strip + "], " end p_color << "[], " if p_color.length == 0 #print p_color.join + "\n" #print pr_name.text + "\n" tmp_array = [br_id, pr_name.text, p_gender, p_cat[0], p_cat[1], p_cat[2], p_cat[3], p_cat[4], pr_price.text, p_saleprice, p_img[0], p_img[1], p_img[2], pr_url.text, p_size.join, p_color.join, pr_instock.text, pr_retailer.text, pr_currency.text] return tmp_array end def talk_to_db(dbname) brand_arr = [] item_cl_name_str = "" brand_cl_name_str = "" print "Connecting with database: " + dbname + " \n" # Establish connection to database ActiveRecord::Base.establish_connection(:adapter => 'postgresql', :host => '69.120.105.217', :port => '5432', :username => 'django_user', :password => 'mypassword', :database => dbname); # Determine table name and create corresponding Class # In table names, find one that includes "items" substring and capitalize! table_a = ActiveRecord::Base.connection.tables table_a.each do |l| if (l.index('_items') != nil) item_cl_name_str = l.capitalize! end if (l.index('_brands') != nil) brand_cl_name_str = l.capitalize! end end print "Inserting into table: " + item_cl_name_str + " with info from " + brand_cl_name_str + "\n" item_cl_name = Object.const_set(item_cl_name_str, Class.new(ActiveRecord::Base)) brand_cl_name = Object.const_set(brand_cl_name_str, Class.new(ActiveRecord::Base)) brand_arr[0] = brand_cl_name.find_by_name("Express") brand_arr[1] = brand_cl_name.find_by_name("J.Crew") brand_arr[2] = brand_cl_name.find_by_name("Banana Republic") return item_cl_name, brand_arr end def parse_product_info(filename, gender_arr, brand, time, dbname) item_cl_name, brand_arr = talk_to_db(dbname) i = 0 fp = [] filename.each do |l| puts "Parsing file: ", l fp = File.open(l) reader = Nokogiri::XML::Reader.from_io(fp) reader.each do |node| if node.name == 'Product' and node.node_type == Nokogiri::XML::Reader::TYPE_ELEMENT doc = Nokogiri::XML(node.outer_xml) filedata_arr = process_pernode_info(doc, gender_arr[i], time, brand_arr) item_cl_name.create(:brand_id => filedata_arr[0], :name => filedata_arr[1], :gender => filedata_arr[2], :cat1 => filedata_arr[3], :cat2 => filedata_arr[4], :cat3 => filedata_arr[5], :cat4 => filedata_arr[6], :cat5 => filedata_arr[7], :price => filedata_arr[8], :saleprice => filedata_arr[9], :insert_date => time.strftime("%Y-%m-%d %H:%M:%S"), :img_url_sm => filedata_arr[10], :img_url_md => filedata_arr[11], :img_url_lg => filedata_arr[12], :pr_url => filedata_arr[13], :pr_sizes => filedata_arr[14], :pr_colors => filedata_arr[15], :pr_instock => filedata_arr[16], :pr_retailer => filedata_arr[17], :pr_currency => filedata_arr[18] ) end end fp.close i += 1 end end # Read line-by-line and write to file def fetch_xml_into_file(url_str, fname) fp = File.open(fname, 'w') @doc = Nokogiri::XML(open(url_str)) fp.puts(@doc) fp.close end =begin The following two functions just construct and return shopstyle.com urls that allow us to fetch relevant information. We first use the apiGetCategoryHistogram method to fetch info on primary categories and counts. Total products per brand = sum(primary_category_cnt); =end def construct_ss_cathist_url(brand) if (brand.casecmp("jcrew") == 0) url_str = "http://api.shopstyle.com/action/apiGetCategoryHistogram?pid=uid289-3680017-16&fl=b284" elsif (brand.casecmp("express") == 0) url_str = "http://api.shopstyle.com/action/apiGetCategoryHistogram?pid=uid289-3680017-16&fl=b13342" elsif (brand.casecmp("bananarepublic") == 0) url_str = "http://api.shopstyle.com/action/apiGetCategoryHistogram?pid=uid289-3680017-16&fl=b2683" end end def construct_ss_apisearch_url(brand, category, min_idx, rec_cnt) if (brand.casecmp("jcrew") == 0) url_str = "http://api.shopstyle.com/action/apiSearch?pid=uid289-3680017-16&cat="+category.text+"&fl=b284"+"&min="+min_idx.to_s+"&count="+rec_cnt.to_s elsif (brand.casecmp("express") == 0) url_str = "http://api.shopstyle.com/action/apiSearch?pid=uid289-3680017-16&cat="+category.text+"&fl=b13342"+"&min="+min_idx.to_s+"&count="+rec_cnt.to_s elsif (brand.casecmp("bananarepublic") == 0) url_str = "http://api.shopstyle.com/action/apiSearch?pid=uid289-3680017-16&cat="+category.text+"&fl=b2683"+"&min="+min_idx.to_s+"&count="+rec_cnt.to_s end end =begin This function gets info on the primary categories, and the product 'count'. This information is used later when we pull all the information for each brand by pulling 'count' products for each 'primary category' =end def get_cathist_info_from_file(xml_filename_ch) fp_ch = File.open(xml_filename_ch, 'r') primary_cats = [] primary_cats_cnt = [] reader = Nokogiri::XML::Reader.from_io(fp_ch) reader.each do |node| if node.name == 'Category' and node.node_type == Nokogiri::XML::Reader::TYPE_ELEMENT doc = Nokogiri::XML(node.outer_xml) cat_id = doc.xpath('//Category/Id') parent_cat_id = doc.xpath('//Category/ParentId') cat_count = doc.xpath('//Category/Count') if ((not parent_cat_id.text.empty?) and (parent_cat_id.text == "clothes-shoes-and-jewelry")) primary_cats << cat_id primary_cats_cnt << cat_count end end end return primary_cats, primary_cats_cnt end =begin In this function, we use the shopstyle.com apiGetCategoryHistogram method to get info on the primary categories and their counts. We store this category histogram information in a file for later reference (if needed). =end def get_cathist_info(brand, time, xmlfilepath) init_url = construct_ss_cathist_url(brand) @doc = Nokogiri::XML(open(init_url)) xml_filename_ch = "%s%s%s%s%4d%s%02d%s%02d%s%02d%s%02d%s%02d%s%s" % [xmlfilepath, "/", brand.downcase, "-ss-", time.year, "-", time.month, "-", time.day, "-", time.hour, "-", time.min, "-", time.sec, "-categoryHist", ".xml"] puts xml_filename_ch fp_ch = File.open(xml_filename_ch, 'w') fp_ch.puts(@doc) fp_ch.close return get_cathist_info_from_file(xml_filename_ch) end def get_xml_data(brand, time, xmlfilepath) # First, we get the main categories per store primary_cats, primary_cats_cnt = get_cathist_info(brand, time, xmlfilepath) print "Primary categories: " + primary_cats.join(" ") + ", Counts: " + primary_cats_cnt.join(" ") + "\n" # Second, we get the number of items in the category, i.e. product_cnt xml_filename = [] gender_info = [] for i in 0..primary_cats_cnt.length-1 product_cnt = primary_cats_cnt[i].text.to_i print "Total product count: " + product_cnt.to_s + "\n" # Next, we fetch item info 250 items at a time (max. allowed pull number by shopstyle API) max_allowed_records = 250 # dictated by shopstyle.com API num_iter = product_cnt / max_allowed_records num_last_cnt = product_cnt % max_allowed_records print "Num iterations: "+num_iter.to_s+" "+num_last_cnt.to_s+"\n" min_cnt = 0 # Create file(s) and store XML data k = xml_filename.length for j in 0..num_iter url_str = construct_ss_apisearch_url(brand, primary_cats[i], min_cnt, max_allowed_records) l_fname = "%s%s%s%s%4d%s%02d%s%02d%s%02d%s%02d%s%02d%s%02d%s" % [xmlfilepath, "/", brand.downcase, "-ss-", time.year, "-", time.month, "-", time.day, "-", time.hour, "-", time.min, "-", time.sec, "-", j+k, ".xml"] print j.to_s + ": " + url_str + " " + l_fname + "\n" xml_filename << l_fname if primary_cats[i].text.include? "women" gender_info << 'F' elsif primary_cats[i].text.include? "mens" gender_info << 'M' else gender_info << 'O' end #fetch_xml_into_file(url_str, l_fname) min_cnt += 250 end end return xml_filename, gender_info end if __FILE__ == $0 if ARGV.length < 3 puts "Usage : ruby $0 brand /path/to/xml name_of_pg_db" puts "Example : ruby $0 express /home/kishore/workspace/miami_metro/doakes/xml-data devel_db" exit end store_name = ARGV[0] xmlfilepath = ARGV[1] dbname = ARGV[2] puts "Brand: " + store_name + ", xmlfilepath: " + xmlfilepath + ", dbname: " + dbname time = Time.new xml_fname, gender_arr = get_xml_data(store_name, time, xmlfilepath) i = 0 xml_fname.each do |l| print l + " " + gender_arr[i] + "\n" i += 1 end parse_product_info(xml_fname, gender_arr, store_name, time, dbname) end
true
cc0d7b2e93ccd04e8879ff1a583716382f20c568
Ruby
derrickreimer/mass_assignable
/test/mass_assignable_test.rb
UTF-8
3,270
2.734375
3
[ "MIT" ]
permissive
$:.unshift File.expand_path('../../lib', __FILE__) require 'mass_assignable' require 'minitest/autorun' require 'shoulda-context' class MassAssignableTest < Test::Unit::TestCase class Person include MassAssignable attr_accessor :name, :age, :height attr_mass_assignable :name, :age, :height end class Car include MassAssignable attr_mass_assignable :make attr_mass_assignable :model end class BlankClass include MassAssignable end class NothingAssignable include MassAssignable attr_mass_assignable end class ParanoidNothingAssignable include MassAssignable attr_mass_assignable! end class ProtectedAttributes include MassAssignable attr_accessor :name, :age, :height attr_mass_assignable :name end class ParanoidPerson include MassAssignable attr_accessor :name, :age, :height attr_mass_assignable! :name, :age, :height end context ".attr_mass_assignable" do should "set mass assignable attributes" do assert_equal [:name, :age, :height], Person.mass_assignable_attributes end should "set mass assignable attribute to an empty array if not called" do assert BlankClass.mass_assignable_attributes.is_a?(Array) assert BlankClass.mass_assignable_attributes.empty? end should "set mass assignable attribute to an empty array if no arguments given" do assert NothingAssignable.mass_assignable_attributes.is_a?(Array) assert NothingAssignable.mass_assignable_attributes.empty? end should "append attributes on multiple calls" do assert Car.mass_assignable_attributes.include?(:make) assert Car.mass_assignable_attributes.include?(:model) end should "not raise an exception for invalid mass assignment attempts" do person = Person.new person.attributes = { :gender => "male" } end end context ".attr_mass_assignable!" do should "set mass assignable attributes" do assert_equal [:name, :age, :height], ParanoidPerson.mass_assignable_attributes end should "set mass assignable attribute to an empty array if no arguments given" do assert ParanoidNothingAssignable.mass_assignable_attributes.is_a?(Array) assert ParanoidNothingAssignable.mass_assignable_attributes.empty? end should "raise an exception for invalid mass assignment attempts" do assert_raises(RuntimeError) do person = ParanoidPerson.new person.attributes = { :gender => "male" } end end end context "#attributes=" do should "set attribute values" do person = Person.new person.attributes = { :name => "Derrick", :age => 24, :height => 77 } assert_equal "Derrick", person.name assert_equal 24, person.age assert_equal 77, person.height end should "not overwrite unspecified attributes" do original_attr = { :name => "Derrick" } new_attr = { :age => 24, :height => 77 } person = Person.new person.attributes = original_attr person.attributes = new_attr assert_equal "Derrick", person.name assert_equal 24, person.age assert_equal 77, person.height end end end
true
2ee01de8e13fe363478b220d9aecbdc87bd4020c
Ruby
yugawara/MathAssistant
/stuff.rb
UTF-8
392
3.296875
3
[]
no_license
def f(size) values = [] var_masks = (0...size).to_a.reverse.map {|i| puts i; 2**i } puts var_masks 0.upto((2**size) - 1) do |cnt_mask| puts cnt_mask values << var_masks.map { |var_mask| shtuff = var_mask.to_s + ":" + cnt_mask.to_s + ":" + (var_mask & cnt_mask).to_s r = (var_mask & cnt_mask) == var_mask puts r.to_s + shtuff } puts "end" end return values end
true
b1604c59361361f5c73ca2bfd545b37c8a33110a
Ruby
kolasss/volt-testing
/app/lib/user_authentication/controller.rb
UTF-8
1,741
2.546875
3
[]
no_license
# аутентификация сделана частично # по туториалу http://adamalbrecht.com/2015/07/20/authentication-using-json-web-tokens-using-rails-and-react/ # метод user_not_authenticated определен в application_controller module UserAuthentication module Controller extend ActiveSupport::Concern private def require_login if !logged_in? user_not_authenticated end end def logged_in? !!current_user end def current_user @current_user ||= login_from_token end def login_from_token if auth_id_included_in_auth_token? Users::User.find_by_auth_id(decoded_auth_token[:auth_id]) end rescue JWT::VerificationError, JWT::DecodeError, JWT::InvalidIatError user_not_authenticated end # Authentication Related Helper Methods # ------------------------------------------------------------ def auth_id_included_in_auth_token? http_auth_token && decoded_auth_token && decoded_auth_token[:auth_id] end # Raw Authorization Header token (json web token format) # JWT's are stored in the Authorization header using this format: # Bearer somerandomstring.encoded-payload.anotherrandomstring def http_auth_token @http_auth_token ||= if request.headers['Authorization'].present? request.headers['Authorization'].split(' ').last end end # Decode the authorization header token and return the payload def decoded_auth_token @decoded_auth_token ||= UserAuthentication::AuthToken.decode(http_auth_token) end end end
true
9f01289206c64c1df1d89456f5042e3c9bc86c35
Ruby
ulizko/credit_calculator
/services/annuity.rb
UTF-8
692
3.703125
4
[]
no_license
class Annuity def initialize(amount, month_rate, term) @amount = amount @term = term @month_rate = month_rate @left = amount end def calculate (0...term).each_with_object([]) do |el, obj| obj << OpenStruct.new(base: base_sum, percents: percents, left: left, month_payment: month_payment) @left = (left - base_sum).round(2) end end private attr_reader :amount, :term, :month_rate, :left def base_sum (month_payment - percents).round(2) end def percents (left * month_rate).round(2) end def month_payment @month_payment ||= (amount * (month_rate + month_rate / ((1 + month_rate) ** term - 1))).round(2) end end
true
f22c1384a85fe4193e4d4ae68488100a4ea89111
Ruby
58496565/gemifresh
/gemifresh.rb
UTF-8
4,975
2.734375
3
[ "MIT" ]
permissive
require 'rubygems' require 'bundler' require 'time' require File.dirname(__FILE__) + '/lib/support' if ARGV.include?('--help') puts <<-HELP Usage: gemifresh [GEMFILE] [LOCKFILE] Both GEMFILE and LOCKFILE will default to "Gemfile" and "Gemfile.lock" in your current directory. Generally you'll simply invoke gemfresh from your Rails (or similar) project directory. Gemfresh will list three categories of gems: "Current" gems are up-to-date. "Obsolete" gems have a newer version than the one specified in your Gemfile "Updateable" gems have a newer version, and it is within the version in your Gemfile e.g. Gemfile: '~> 2.2.0' Gemfile.lock: 2.2.1 Latest: 2.2.2 Running bundle update will attempt to update these gems. Just because a gem is updateable or obsolete, doesn't mean it can be updated. There might be dependencies that limit you to specific versions. Check the bundler documentation (http://gembundler.com/) for more information on Gemfiles. HELP exit 1 end gemfile = ARGV[0] || './Gemfile' lockfile = ARGV[1] || './Gemfile.lock' unless File.exists?(gemfile) puts "Couldn't find #{gemfile}.\nRun gemfresh with --help if you need more information." exit -1 end unless File.exists?(lockfile) puts "Couldn't find #{lockfile}.\nRun gemfresh with --help if you need more information." exit -1 end puts "Checking your Gemfile.\n" Bundler.settings[:frozen] = true bundle = Bundler::Dsl.evaluate('./Gemfile', './Gemfile.lock', {}) deps = bundle.dependencies specs = bundle.resolve sources = {} results = { :current => [], :update => [], :obsolete => [] } count = 0 prereleases = 0 unavailable = 0 untracked = 0 dep_specs = deps.map { |dep| [dep, specs.find { |spec| spec.name == dep.name }] } dep_specs = dep_specs.select { |dep, spec| !spec.nil? && (spec.source.class == Bundler::Source::Rubygems) } if deps.empty? puts "No top-level RubyGem dependencies found in your Gemfile.\nRun gemfresh with --help if you need more information." exit true end print "Hitting up your RubyGems sources: " dep_specs.each do |dep, spec| name = dep.name gemdata = versions = false spec.source.remotes.each do |remote| begin next if remote.nil? reader = sources[remote] next if reader == :unavailable reader = sources[remote] = RubyGemReader.new(remote) if reader.nil? gemdata = reader.get("/api/v1/gems/#{name}.yaml") gemdata = YAML.load(gemdata) next if (gemdata && gemdata['version'].nil?) versions = reader.get("/api/v1/versions/#{name}.yaml") versions = YAML.load(versions) break unless !gemdata || !versions rescue SourceUnavailableError => sae sources[remote] = :unavailable end end if !gemdata || !versions || gemdata['version'].nil? unavailable =+ 1 print "x" else diff = SpecDiff.new(dep, spec, gemdata, versions) results[diff.classify] << diff prereleases +=1 if diff.prerelease? count += 1 print "." end STDOUT.flush end puts " Done!" if unavailable > 0 puts "\nCouldn't get data for #{unavailable} gem#{unavailable == 1 ? '' : 's'}. It might be the RubyGem source is down or unaccessible. Give it another try in a moment." end if prereleases > 0 puts "\nYou have #{prereleases} prerelease gem#{prereleases == 1 ? '' : 's'}. Prereleases will be marked with a '*'." end puts "\nThe following Gems are:" ages = results.values.flatten.group_by(&:build_age) {:none => 'No build dates available', :month1 => 'less than a month old', :month6 => 'less than 6 months old', :year1 => 'less than a year old', :more => 'more than a year old'}.each_pair do |key, value| next if ages[key].nil? puts "-- #{value}:" puts ages[key].map(&:to_s).join(', ') end if results[:current].empty? puts "\nYou don't have any current gems." else puts "\nThe following gems at the most current version: " puts results[:current].map(&:to_s).join(', ') end if results[:update].empty? puts "\nYou don't have any updatable gems." else puts "\nThe following gems are locked to older versions, but your Gemfile allows for the current version: " results[:update].each do |diff| puts " #{diff}, with #{diff.dep.requirement} could allow #{diff.version_available}" end puts "Barring dependency issues, these gems could be updated to current using 'bundle update'." end if results[:obsolete].empty? puts "\nYou don't have any obsolete gems." else puts "\nThe following gems are obsolete: " results[:obsolete].each do |diff| released = diff.version_build_date(diff.version_available) released = released.nil? ? '.' : ", #{released.strftime('%d %b %Y')}." suggest = diff.suggest suggest = suggest.nil? ? '' : "Also consider version #{suggest}." puts " #{diff} is now at #{diff.version_available}#{released} #{suggest}" end end exit results[:obsolete].empty?
true
c6ecca3d6e4b03bc885a68b5ba0bdbe776b57415
Ruby
ReliveRadio/reliveradio-plantasy
/app/app/models/jingle.rb
UTF-8
680
2.578125
3
[]
no_license
class Jingle < ActiveRecord::Base before_destroy :ensure_save_destroy before_destroy :remove_uploaded_audio has_many :playlist_entries validates :title, presence: true validates :duration, presence: true mount_uploader :audio, AudioUploader def playcount self.playlist_entries.count end private def remove_uploaded_audio # delete file from disk self.remove_audio! self.save end def ensure_save_destroy save_to_destroy = true # do not destroy episodes that are mapped to a playlist entry that is in danger zone self.playlist_entries.each do |entry| save_to_destroy = false if entry.isInDangerZone? end return save_to_destroy end end
true
878ce3f002a26062ec89edb7b3c22b5e0b28e966
Ruby
jgarber/redcloth-treetop
/spec/redcloth/parser/inline_parser_spec.rb
UTF-8
5,109
3.15625
3
[ "MIT" ]
permissive
require File.dirname(__FILE__) + "/../../spec_helper" require 'redcloth/parser/inline' module RedCloth module Parser describe InlineParser do before :each do @parser = InlineParser.new end def parse(string) @parser.parse_or_fail(string) end def parsed_sexp(string) parse(string).map {|e| e.to_sexp} end ### plain text ### it "should parse a plain-text phrase" do parsed_sexp("Just plain text.").should == ["Just plain text."] end it "should parse two basic sentences" do parsed_sexp("One sentence. Two.").should == ["One sentence. Two."] end it "should parse a phrase with asterisks that is not a strong phrase" do parsed_sexp("yes * we * can").should == ["yes * we * can"] end it "should parse a phrase that is not a strong because it has space at the end" do parsed_sexp("yeah *that's * it!").should == ["yeah *that's * it!"] end ### strong ### it "should parse a strong phrase" do parsed_sexp("*strong phrase*").should == [[:strong, {}, ["strong phrase"]]] end it "should parse a strong phrase surrounded by plain text" do parsed_sexp("plain *strong phrase* plain").should == ["plain ", [:strong, {}, ["strong phrase"]], " plain"] end it "should allow a strong phrase at the end of a sentence before punctuation" do parsed_sexp("Are you *veg*an*?").should == ["Are you ", [:strong, {}, ["veg*an"]], "?"] end it "should parse a bold phrase inside a strong phrase" do parsed_sexp("*this is **bold** see*").should == [[:strong, {}, [ "this is ", [:bold, {}, ["bold"]], " see"]]] end it "should parse an emphasized phrase inside a strong phrase" do parsed_sexp("*_em in strong_*").should == [[:strong, {}, [ [:em, {}, ["em in strong"]]]]] end ### em ### it "should parse an emphasized phrase" do parsed_sexp("_emphasized_").should == [[:em, {}, ["emphasized"]]] end it "should allow an emphasized phrase at the end of a sentence before punctuation" do parsed_sexp("Are you _sure_?").should == ["Are you ", [:em, {}, ["sure"]], "?"] end it "should parse a strong phrase inside an emphasized phrase" do parsed_sexp("_*strong in em*_").should == [[:em, {}, [ [:strong, {}, ["strong in em"]]]]] end it "should parse a bold phrase inside an emphasized phrase" do parsed_sexp("_**bold in em**_").should == [[:em, {}, [ [:bold, {}, ["bold in em"]]]]] end ### bold ### it "should parse a bold phrase" do parsed_sexp("**bold phrase**").should == [[:bold, {}, ["bold phrase"]]] end it "should parse a bold phrase surrounded by plain text" do parsed_sexp("plain **bold phrase** plain").should == ["plain ", [:bold, {}, ["bold phrase"]], " plain"] end it "should allow a bold phrase at the end of a sentence before punctuation" do parsed_sexp("Are you **veg*an**?").should == ["Are you ", [:bold, {}, ["veg*an"]], "?"] end it "should parse a strong phrase inside a bold phrase" do parsed_sexp("**this is *strong* see**").should == [[:bold, {}, [ "this is ", [:strong, {}, ["strong"]], " see"]]] end it "should parse an emphasized phrase inside a bold phrase" do parsed_sexp("**_em in bold_**").should == [[:bold, {}, [ [:em, {}, ["em in bold"]]]]] end ### italics ### it "should parse an italic phrase" do parsed_sexp("__italic phrase__").should == [[:italic, {}, ["italic phrase"]]] end it "should parse an emphasized phrase inside an italic phrase" do parsed_sexp("__this is _emphasized_ see__").should == [[:italic, {}, [ "this is ", [:em, {}, ["emphasized"]], " see"]]] end it "should parse a strong phrase inside an italic phrase" do parsed_sexp("__*strong in italic*__").should == [[:italic, {}, [ [:strong, {}, ["strong in italic"]]]]] end it "should parese a bold phrase inside an italic phrase" do parsed_sexp("__this is **bold** see__").should == [[:italic, {}, [ "this is ", [:bold, {}, ["bold"]], " see"]]] end ### double quotation ### it "should parse a quotation" do parsed_sexp(%{"I think, therefore, I am"}).should == [[:double_quote, {}, ["I think, therefore, I am"]]] end end end end
true
f564a635bf4aff9336ed2dfa5be3edc6f8ee7b1e
Ruby
bg/vmsruby
/rubicon_vms/builtin/testmodule.rb
UTF-8
9,971
2.78125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
$: << File.dirname($0) << File.join(File.dirname($0), "..") require 'rubicon' $m0 = Module.nesting unless defined? ExpectedException Version.less_than("1.7") do ExpectedException = NameError end Version.greater_or_equal("1.7") do ExpectedException = NoMethodError end end class TestModule < Rubicon::TestCase # Support stuff module Mixin MIXIN = 1 def mixin end end module User USER = 2 include Mixin def user end end module Other def other end end class AClass def AClass.cm1 "cm1" end def AClass.cm2 cm1 + "cm2" + cm3 end def AClass.cm3 "cm3" end private_class_method :cm1, "cm3" def aClass end def aClass1 end def aClass2 end private :aClass1 protected :aClass2 end class BClass < AClass def bClass1 end private def bClass2 end protected def bClass3 end end MyClass = AClass.clone class MyClass public_class_method :cm1 end # ----------------------------------------------------------- def test_CMP # '<=>' assert_equal( 0, Mixin <=> Mixin) assert_equal(-1, User <=> Mixin) assert_equal( 1, Mixin <=> User) Version.less_than("1.7") do assert_equal(1, Mixin <=> User) end assert_equal( 0, Object <=> Object) assert_equal(-1, String <=> Object) assert_equal( 1, Object <=> String) end def test_GE # '>=' assert(Mixin >= User) assert(Mixin >= Mixin) assert(!(User >= Mixin)) assert(Object >= String) assert(String >= String) assert(!(String >= Object)) end def test_GT # '>' assert(Mixin > User) assert(!(Mixin > Mixin)) assert(!(User > Mixin)) assert(Object > String) assert(!(String > String)) assert(!(String > Object)) end def test_LE # '<=' assert(User <= Mixin) assert(Mixin <= Mixin) assert(!(Mixin <= User)) assert(String <= Object) assert(String <= String) assert(!(Object <= String)) end def test_LT # '<' assert(User < Mixin) assert(!(Mixin < Mixin)) assert(!(Mixin < User)) assert(String < Object) assert(!(String < String)) assert(!(Object < String)) end def test_VERY_EQUAL # '===' assert(Object === self) assert(Rubicon::TestCase === self) assert(TestModule === self) assert(!(String === self)) end def test_ancestors assert_equal([User, Mixin], User.ancestors) assert_equal([Mixin], Mixin.ancestors) ancestors_obj = Object.ancestors ancestors_str = String.ancestors if defined?(PP) # when issuing 'AllTests.rb' then PP gets added ancestors_obj.delete(PP::ObjectMixin) ancestors_str.delete(PP::ObjectMixin) end assert_equal([Object, Kernel], ancestors_obj) assert_equal([String, Enumerable, Comparable, Object, Kernel], ancestors_str) end def test_class_eval Other.class_eval("CLASS_EVAL = 1") assert_equal(1, Other::CLASS_EVAL) assert(Other.constants.include?("CLASS_EVAL")) end def test_const_defined? assert(Math.const_defined?(:PI)) assert(Math.const_defined?("PI")) assert(!Math.const_defined?(:IP)) assert(!Math.const_defined?("IP")) end def test_const_get assert_equal(Math::PI, Math.const_get("PI")) assert_equal(Math::PI, Math.const_get(:PI)) end def test_const_set assert(!Other.const_defined?(:KOALA)) Other.const_set(:KOALA, 99) assert(Other.const_defined?(:KOALA)) assert_equal(99, Other::KOALA) Other.const_set("WOMBAT", "Hi") assert_equal("Hi", Other::WOMBAT) end def test_constants assert_equal(["MIXIN"], Mixin.constants) assert_equal(["MIXIN", "USER"], User.constants.sort) end def test_included_modules assert_equal([], Mixin.included_modules) assert_equal([Mixin], User.included_modules) incmod_obj = Object.included_modules incmod_str = String.included_modules if defined?(PP) # when issuing 'AllTests.rb' then PP gets added incmod_obj.delete(PP::ObjectMixin) incmod_str.delete(PP::ObjectMixin) end assert_equal([Kernel], incmod_obj) assert_equal([Enumerable, Comparable, Kernel], incmod_str) end def test_instance_methods Version.less_than("1.8.1") do # default value is false assert_equal(["user"], User.instance_methods) assert_equal(["mixin"], Mixin.instance_methods) assert_equal(["aClass"], AClass.instance_methods) end Version.greater_or_equal("1.8.1") do # default value is true ary_user = User.instance_methods assert_equal(true, ary_user.include?("user")) # we expect more than our 'user' method to be returned. assert_equal(true, ary_user.size > 1) # we expect ONLY than our 'mixin' method to be returned. ary_mixin = Mixin.instance_methods assert_equal(["mixin"], ary_mixin) ary_class = AClass.instance_methods assert_equal(true, ary_class.include?("aClass")) # we expect more than our 'aClass' method to be returned. assert_equal(true, ary_class.size > 1) end assert_equal(["mixin", "user"], User.instance_methods(true).sort) assert_equal(["mixin"], Mixin.instance_methods(true)) Version.less_than("1.8.1") do assert_equal(["aClass"], AClass.instance_methods(true) - Object.instance_methods(true) ) end Version.greater_or_equal("1.8.1") do assert_set_equal(["aClass", "aClass2"], AClass.instance_methods(true) - Object.instance_methods(true) ) end end def test_method_defined? assert(!User.method_defined?(:wombat)) assert(User.method_defined?(:user)) assert(User.method_defined?(:mixin)) assert(!User.method_defined?("wombat")) assert(User.method_defined?("user")) assert(User.method_defined?("mixin")) end def test_module_eval User.module_eval("MODULE_EVAL = 1") assert_equal(1, User::MODULE_EVAL) assert(User.constants.include?("MODULE_EVAL")) User.instance_eval("remove_const(:MODULE_EVAL)") assert(!User.constants.include?("MODULE_EVAL")) end def test_name assert_equal("Fixnum", Fixnum.name) assert_equal("TestModule::Mixin", Mixin.name) assert_equal("TestModule::User", User.name) end def test_private_class_method assert_raise(ExpectedException) { AClass.cm1 } assert_raise(ExpectedException) { AClass.cm3 } assert_equal("cm1cm2cm3", AClass.cm2) end def test_private_instance_methods Version.less_than("1.8.1") do # default value is false assert_equal(["aClass1"], AClass.private_instance_methods) assert_equal(["bClass2"], BClass.private_instance_methods) end Version.greater_or_equal("1.8.1") do # default value is true a = AClass.private_instance_methods assert_equal(true, a.include?("aClass1")) # we expect more than our 'aClass1' method to be returned. assert_equal(true, a.size > 1) b = BClass.private_instance_methods assert_equal(true, b.include?("bClass2")) # we expect more than our 'bClass2' method to be returned. assert_equal(true, b.size > 1) end assert_set_equal(["bClass2", "aClass1"], BClass.private_instance_methods(true) - Object.private_instance_methods(true)) end def test_protected_instance_methods Version.less_than("1.8.1") do # default value is false assert_equal(["aClass2"], AClass.protected_instance_methods) assert_equal(["bClass3"], BClass.protected_instance_methods) end Version.greater_or_equal("1.8.1") do # default value is true a = AClass.protected_instance_methods assert_equal(true, a.include?("aClass2")) # we expect more than our 'aClass2' method to be returned. assert_equal(true, a.size == 1) b = BClass.protected_instance_methods assert_equal(true, b.include?("bClass3")) # we expect more than our 'bClass3' method to be returned. assert_equal(true, b.size > 1) end assert_set_equal(["bClass3", "aClass2"], BClass.protected_instance_methods(true) - Object.protected_instance_methods(true)) end def test_public_class_method assert_equal("cm1", MyClass.cm1) assert_equal("cm1cm2cm3", MyClass.cm2) assert_raise(ExpectedException) { eval "MyClass.cm3" } end def test_public_instance_methods Version.less_than("1.8.1") do # default value is false assert_equal(["aClass"], AClass.public_instance_methods) assert_equal(["bClass1"], BClass.public_instance_methods) end Version.greater_or_equal("1.8.1") do # default value is true a = AClass.public_instance_methods assert_equal(true, a.include?("aClass")) # we expect more than our 'aClass' method to be returned. assert_equal(true, a.size > 1) b = BClass.public_instance_methods assert_equal(true, b.include?("bClass1")) # we expect more than our 'bClass1' method to be returned. assert_equal(true, b.size > 1) end end def test_s_constants c1 = Module.constants Object.module_eval "WALTER = 99" c2 = Module.constants assert_equal(["WALTER"], c2 - c1) end module M1 $m1 = Module.nesting module M2 $m2 = Module.nesting end end def test_s_nesting assert_equal([], $m0) assert_equal([TestModule::M1, TestModule], $m1) assert_equal([TestModule::M1::M2, TestModule::M1, TestModule], $m2) end def test_s_new m = Module.new assert_instance_of(Module, m) end end Rubicon::handleTests(TestModule) if $0 == __FILE__
true
99ca1af4e3b185a112d066119c05f11d22fc9862
Ruby
jameslvdb/dungeons-and-dragons-srd
/lib/tasks/import/weapons.rb
UTF-8
2,324
3.078125
3
[]
no_license
require 'json' def format_description(w, name) description = '' entries = w['entries'].first['entries'] if entries.length == 1 description += TextSubstitution.format_entry(entries.first) else w['entries'].each do |entry| description += TextSubstitution.format_entry(entry) end end description end file = 'public/data/weapons.json' doc = File.open(file) formatted = TextSubstitution.format(doc.read) parsed = JSON.parse(formatted) weapons = parsed['weapons'] weapon_types = { 'M' => 'melee', 'R' => 'ranged' } # split the string and multiply str[0] by cp (1), sp (10), gp (100) def format_value(value) str = value.split if str[1] == 'gp' return str[0].to_i * 100 elsif str[1] == 'sp' return str[0].to_i * 10 elsif str[1] == 'cp' return str[0].to_i end str[0].to_i end def create_weapon_property_associations(weapon, w) if w['property'] w['property'].each do |property| # 'S' is a special case, don't create an association if property == 'S' weapon.description = w['entries'].first['entries'].first next end if !weapon.weapon_properties.exists?(abbreviation: property) weapon.weapon_properties << WeaponProperty.find_by(abbreviation: property) end end end # return the Weapon object at the end weapon end def create_dart(w) weapon = Weapon.find_or_initialize_by(name: 'darts (4)') weapon.weapon_type = 'ranged' weapon.damage_type = Damage::DAMAGE_TYPES[w['dmgType']] weapon.damage = w['dmg1'] weapon.category = w['weaponCategory'].downcase weapon.value = 20 weapon.weight = 1 weapon.range = w['range'] weapon = create_weapon_property_associations(weapon, w) weapon.save! end weapons.each do |w| # do something different for the 'Dart' entry if w['name'] == 'Dart' create_dart(w) next end weapon = Weapon.find_or_initialize_by(name: w['name'].downcase) weapon.weapon_type = weapon_types[w['type']] weapon.damage_type = Damage::DAMAGE_TYPES[w['dmgType']] weapon.damage = w['dmg1'] weapon.two_handed_damage = w['dmg2'] weapon.category = w['weaponCategory'].downcase weapon.value = format_value(w['value']) weapon.weight = w['weight'] || 0 weapon.range = w['range'] weapon = create_weapon_property_associations(weapon, w) weapon.save! end
true
2d90cb2e4aa3c4309c1a64a9ad873c191f192c33
Ruby
doetlingerlukas/crypto
/decode_natural_number.rb
UTF-8
611
3.46875
3
[]
no_license
#!/usr/bin/env ruby def decode(number) len = 3 # Initial length is 3 bits. i = 0 numbers = [] while i < number.length raise "#{number} is not a code word." if (i + len) >= number.length n = number[i...(i + len)].to_i(2) i += len if number[i] == '0' i += 1 numbers << n len = 3 else len = n end end numbers end [ '1001011110000110000', '1001011111111000', '10010111111110001001010101100010', ].each do |number| begin decoded_number = decode(number) puts "#{number} == #{decoded_number}" rescue => e STDERR.puts e end end
true
2c1f99c304cc57cc8a79fde8630dfa2215172074
Ruby
tomxgab/chatango-messenger
/script.rb
UTF-8
1,319
2.765625
3
[]
no_license
require "./chatango_home.rb" require "set" $acc = ["name", "password"] def lSent $sent = Set.new(File.read("sent").split(";")) end def sSent File.open("sent", "w") do |f| f.write($sent.to_a.join(";")) end end lSent $ch = Chatango_Home.new("c1.chatango.com", "5222", nil, $acc[0], $acc[1]) msg = "", puts {"Logging in."} trap("INT") do puts "Interrupted." exit end $ch.main() do |event, data| case(event) when "on_clist_load" puts "Logged in, performing search..." $usrs_raw = $ch.do_user_search({ "ss" => "", "o" => "yes", "i" => "", "ama" => "150", "ami" => "13", "f" => "0", "t" => "5000", "c" => "", "s" => "" }).keys $usrs = (Set.new($usrs_raw) - Set.new($sent)).to_a puts "Done, users found: #{$usrs.join(", ")}" puts "Is this okay? (Y/N)" print "> " inp = $stdin.gets.chomp if(inp == "y" || inp == "Y") puts "Messaging." else puts "Aborting..." exit end i = 0 Thread.new do $usrs.each do |usr| puts "Messaging #{usr}" $ch.do_msg(usr, msg) $sent << usr sSent i += 1 puts "#{usr} (#{i}/#{$usrs.length})" sleep(3) end sleep(3) $ch.do_disconnect puts "dun :3" end when "on_message" puts "#{data[:name]}: #{data[:msg]}" end end
true
ac292d324b0207027d47b6b3cd2b10648fa1a481
Ruby
beeblebrox/dax
/dax/lib/db.rb
UTF-8
4,904
2.671875
3
[ "MIT" ]
permissive
require 'rubygems' require 'bundler/setup' require "json" require "date" require "digest/sha1" require 'set' require 'pathname' require 'logger' require 'listen' class DB < Logger::Application def initialize(options=nil) super("Dax::DB") self.level = Logger::INFO raise ArgumentError, "Need :db_location and :files_location." unless options.respond_to? 'has_key?' raise ArgumentError, "Database location (:db_location) not provided." if ! options.has_key? :db_location raise ArgumentError, "Files location (:files_location) not provided." if ! options.has_key? :files_location @db_location = options[:db_location] @files_location = options[:files_location] @initialized = false @dirty = false end def init return if @initialized @initialized = true read_db @listener = Listen.to(@files_location) do |modified, added, removed| begin log DEBUG, "Entered listener" modified.each { |file| refresh_file file } added.each { |file| refresh_file file } log DEBUG, "Exited Listener" rescue log DEBUG, $!.inspect, $@ end end @listener.start log DEBUG, "Started listener" end def cleanup return unless @initialized @listener.stop if @listener save log DEBUG, "Stopped listener." end def refresh init refresh_db end def save init save_db end def additional_compared_to (db) set1 = @db[:files].to_set set1.subtract(db.files.to_set) end def files @db[:files] end def first_file_with_checksum(checksum) idx = index() nil unless idx.key? [checksum] idx[checksum] end def index rebuild_index if @dirty @index end private def rebuild_index @index = Hash.new files = @db[:files].dup files = files.sort_by do |file| file[:name] end files.each do |info| @index[info[:sha]] = info[:name] if ! @index.key? info[:sha] end @dirty = false end def refresh_db @db = { :lastmodified => DateTime.now.rfc3339, :files => [ ] } add_dir @files_location, Pathname.new(@files_location).realpath @dirty = true end def refresh_file(aname) log DEBUG, "Refreshing file..#{aname}" digest = "NA" File.open(aname, "r") do |file| log DEBUG, "Reading file..." head = file.read((2^20) * 100) next if !head log DEBUG, "Creating digest." digest = Digest::SHA1.hexdigest head log DEBUG, "Digest created." end result = nil log DEBUG, "Creating curdir" curdir = Pathname.new(@files_location).expand_path log DEBUG, "Making relative directory with: #{curdir} and #{aname}" name = Pathname.new(aname).relative_path_from(curdir).to_s log DEBUG, "Derived #{name}" log DEBUG, "Doing index search" @db[:files].index do |hash| log DEBUG, "Checking hash." if hash[:name] == name result = hash true else false end end if result # Already exists, refresh log DEBUG, "Refreshing existing result." result[:sha] = digest log DEBUG, "Assigned new digest." else log DEBUG, "Adding new entry." #new entry @db[:files] += [ { :name => name, :sha => digest } ] end @dirty = true log DEBUG, "Exiting refresh_file" rescue log DEBUG, $!.inspect, $@ end def add_dir(path, originalpath) Dir.foreach path do |name| next if name == "." next if name == ".." rname = nil begin rname = File.expand_path name, path rescue log DEBUG, $!.inspect, $@ next end next unless rname if Dir.exists? rname add_dir(rname, originalpath) next end next unless File.file? rname rpath = Pathname.new(rname) rpath = rpath.relative_path_from(originalpath).to_s begin File.open(rname, "r") do |file| head = file.read((2^20) * 100) next if !head digest = Digest::SHA1.hexdigest head @db[:files] += [ { :name => rpath, :sha => digest } ] end rescue log DEBUG, $!.inspect, $@ end end end def read_db @db = { } fname = @db_location File.open(fname, "a+") do |file| begin @db = JSON.parse(file.read(), :symbolize_names => true) rescue log DEBUG, $!.inspect @db = { :lastmodified => DateTime.now.rfc3339, :files => [ ] } end end @dirty = true end def save_db fname = @db_location File.open(fname, "w") do |file| begin file.write(JSON.pretty_generate ( @db ) ) rescue log DEBUG, $!.inspect log DEBUG, "Could not save database!" end end end end
true
c1a092b83132e7325f6125eedc5b004b9a6735c1
Ruby
danpersa/edge-state-machine
/spec/state_spec.rb
UTF-8
2,236
2.890625
3
[]
no_license
require 'spec_helper' class StateTestSubject include EdgeStateMachine state_machine do end end class Car include EdgeStateMachine state_machine do state :parked state :running state :driving event :turn_key do transition :from => :parked, :to => :running, :on_transition => :start_engine end event :start_driving do transition :from => :parked, :to => :driving, :on_transition => [:start_engine, :loosen_handbrake, :push_gas_pedal] end end def event_fired(current_state, new_state, event) end %w!start_engine loosen_handbrake push_gas_pedal!.each do |m| define_method(m){} end end def new_state(options={}) EdgeStateMachine::State.new(@state_name) end describe EdgeStateMachine::State do before do @state_name = :astate @machine = StateTestSubject.state_machine end it 'should set the name' do new_state.name.should == :astate end it 'should set the display_name from name' do new_state.display_name.should == 'Astate' end it 'should set the display_name from method' do state = new_state state.use_display_name('A State') state.display_name.should == 'A State' end it 'should set the options and expose them as options' do new_state.options.should_not == nil end it 'should be equal to a symbol of the same name' do new_state.should == :astate end it 'should be equal with a State with the same name' do new_state.should == new_state end it 'should send a message to the record for an action if the action is present as a symbol' do state = new_state state.enter :foo record = mock record.should_receive(:foo) state.execute_action(:enter, record) end it 'should send a message to the record for an action if the action is present as a string' do state = new_state state.enter 'foo' record = mock record.should_receive(:foo) state.execute_action(:enter, record) end it 'should call a proc, passing in the record for an action if the action is present' do state = new_state state.exit Proc.new {|r| r.foobar} record = mock record.should_receive(:foobar) state.execute_action(:exit, record) end end
true
77dfde106e6b46b1d00673acb3576a4ab19885df
Ruby
josephchin19293/ruby-kickstart
/session2/3-challenge/3_array.rb
UTF-8
378
3.9375
4
[ "MIT" ]
permissive
# Write a method named every_other_char for strings that, # returns an array containing every other character # # example: # "abcdefg".every_other_char # => "aceg" # "".every_other_char # => "" class String def every_other_char new_string = "" self.each_char.with_index { |c, index| index.odd? ? new_string << "" : new_string << c } new_string end end
true
0407ea1e3782b8cedb4c4232e691c5b8b03b4a34
Ruby
RumaniKafle/ITSC3155_SPRING2019_800991130
/ruby_calisthenics1/lib/fun_with_strings.rb
UTF-8
1,081
3.609375
4
[]
no_license
module FunWithStrings def palindrome? letters = self.downcase.scan(/\w/) letters == letters.reverse end def count_words # your code here hash = Hash.new self.downcase.gsub(/[^a-z\s]/ , '').split.each do |word| if hash[word] != nil hash[word] +=1 else hash[word] = 1 end end hash end def anagram_groups # your code here words = self.split output = Array.new words.each_with_index do |word, index| unless output.any? { |arr| arr.include? (word) } temp_array = Array.new temp_array.push(word) words[index+1..-1].each do |secondword| if word.checkAnagram(secondword) temp_array.push(secondword) end end output.push(temp_array) end end output end def checkAnagram(word) self.downcase.chars.sort.join == word.downcase.chars.sort.join end end # make all the above functions available as instance methods on Strings: class String include FunWithStrings end
true
83cc391162fd245a15a33c20f08f7216051bf69e
Ruby
barkerest/barkest_core
/app/controllers/status_controller.rb
UTF-8
4,932
2.875
3
[ "MIT" ]
permissive
## # A fairly simple system status controller. # # The status system revolves around the GlobalStatus class and the WorkPath#system_status_file contents. # When a long running process acquires a lock with the GlobalStatus, then it can update the status freely # until it releases the lock. This controller simply checks the GlobalStatus lock and reads the # WorkPath#system_status_file contents to construct the object that gets returned to the client. # # See the methods below for more information on how this works. # class StatusController < ApplicationController before_action :check_for_user ## # Gets the current system status from the beginning of the system status log. # # Status is returned as a JSON object to be consumed by Javascript. # # error:: # The +error+ field alerts the consumer to any application error that may have occurred. # # locked:: # The +locked+ field lets the consumer know whether the system is currently busy with a # long running task. # # status:: # The +status+ field gives the main status for the system at the time of the request. # # percentage:: # The +percentage+ field gives the progress for the current system status. # If blank, there is no reported progress and the consumer should hide the progress bar. # If set to '-', and +locked+ is false, then the consumer should decide whether # to show the percentage (100%) or keep the progress bar hidden. # If set to an integer between 0 and 100, then the consumer should show the progress bar # with the specified percentage. # # contents:: # The +contents+ field contains the status log file up to this point. # Requests to #first will contain the entire log file, whereas subsequent requests to # #more will contain any data added to the log file since #first or #more was last # requested. The consumer should append the +contents+ field to its existing log to # reconstruct the log data in entirety. # If +error+ is true, then this will contain the error message and should be treated # differently from the successful requests. def first self.start_position = 0 build_status render json: @status.to_json end ## # Gets any status changes since the last call to +first+ or +more+. # # Status is returned as a JSON object to be consumed by Javascript. # # See #first for a description of the JSON object returned. def more build_status render json: @status.to_json end ## # Shows the dedicated status reporting page. # # This action should not be invoked directly, instead use the StatusHelper#show_system_status helper # method with the long running code as a block. def current @inital_status = BarkestCore::GlobalStatus.current[:message] end ## # Shows the status testing page. # # This page provides five examples of how to implement status display. def test flag = (params[:flag] || 'menu').underscore.to_sym if flag != :menu show_system_status( url_on_completion: status_test_url, completion_button: 'Test Again', main_status: 'Running test process' ) do |status| sleep 0.5 File.open(BarkestCore::WorkPath.system_status_file, 'wt') do |f| 2.times do |i| f.write("Before loop status message ##{i+1}.\n") f.flush sleep 0.1 end sleep 0.5 status.set_percentage(0) if flag == :with_progress 15.times do |t| c = (t % 2 == 1) ? 3 : 5 c.times do |i| f.write("Pass ##{t+1} status message ##{i+1}.\n") f.flush sleep 0.1 end status.set_percentage((t * 100) / 15) if flag == :with_progress sleep 0.5 end end end end end private def check_for_user authorize! true end def start_position session[:system_status_position] || 0 end def start_position=(value) session[:system_status_position] = value end def build_status start = start_position cur = BarkestCore::GlobalStatus.current @status = { error: false, locked: cur[:locked], status: cur[:message], percentage: cur[:percent] } begin raise StandardError.new('No system status.') unless File.exist?(BarkestCore::WorkPath.system_status_file) File.open(BarkestCore::WorkPath.system_status_file, 'r') do |f| @status[:contents] = f.read end if start > 0 && @status[:contents].length >= start @status[:contents] = @status[:contents][start..-1] end start += @status[:contents].length rescue Exception => err @status[:contents] = err.message @status[:error] = true end self.start_position = start end end
true
1a348be21f2df1b047cb05534df7e7fb75d849fc
Ruby
cayblood/sbn
/lib/sbn/variable.rb
UTF-8
7,792
2.53125
3
[ "MIT" ]
permissive
module Sbn class Variable attr_reader :name, :states, :parents, :children, :probability_table, :probabilities def initialize(net, name = '', probabilities = [0.5, 0.5], states = [:true, :false]) @net = net @@variable_count ||= 0 @@variable_count += 1 name = "variable_#{@@variable_count}" if name.is_a? String and name.empty? @name = name.to_underscore_sym @children = [] @parents = [] @probabilities = [] @sample_points = [] @states = [] @state_frequencies = {} # used for storing sample points set_states(states) set_probabilities(probabilities) net.add_variable(self) end def ==(obj); test_equal(obj); end def eql?(obj); test_equal(obj); end def ===(obj); test_equal(obj); end def to_s @name.to_s end def to_xmlbif_variable(xml) xml.variable(:type => "nature") do xml.name(@name.to_s) @states.each {|s| xml.outcome(s.to_s) } xml.property("SbnVariableType = #{self.class.to_s}") yield(xml) if block_given? end end def to_xmlbif_definition(xml) xml.definition do xml.for(@name.to_s) @parents.each {|p| xml.given(p.name.to_s) } xml.table(@probability_table.transpose.last.join(' ')) yield(xml) if block_given? end end def to_json_variable { name: @name.to_s, states: @states.map(&:to_s), probability_table: @probability_table, probabilities: @probabilities, parents: @parents.map(&:name), type: 'nature' } end def self.from_json(net, json) json = JSON.load(json) unless json.is_a?(Hash) new(net, json[:name], json[:probabilities], json[:states]).tap do |var| var.set_probability_table json[:probability_table] end end def to_json_definition { name: @name, given: @parents.map(&:name), table: @probability_table.transpose.last.map(&:to_s) } end def set_states(states) states.symbolize_values! @states = states generate_probability_table end def set_probability(probability, event) event = @net.symbolize_evidence(event) unless can_be_evaluated?(event) raise "A valid state was not supplied for variable #{@name} and all its parents in call to set_probability()" end combination_for_this_event = [] @parents.each {|p| combination_for_this_event << event[p.name] } combination_for_this_event << event[@name] index = state_combinations.index(combination_for_this_event) @probabilities[index] = probability generate_probability_table end def add_child(variable) add_child_no_recurse(variable) variable.add_parent_no_recurse(self) end def add_parent(variable) add_parent_no_recurse(variable) variable.add_child_no_recurse(self) end def set_probabilities(probs) @probabilities = probs generate_probability_table end def evidence_name # :nodoc: @name end def add_child_no_recurse(variable) # :nodoc: return if variable == self or @children.include?(variable) if variable.is_a?(StringVariable) @children.concat variable.covariables else @children << variable end variable.generate_probability_table end def add_parent_no_recurse(variable) # :nodoc: return if variable == self or @parents.include?(variable) if variable.is_a?(StringVariable) @parents.concat variable.covariables else @parents << variable end generate_probability_table end def set_in_evidence?(evidence) # :nodoc: evidence.has_key?(evidence_name) end def get_observed_state(evidence) # :nodoc: evidence[@name] end # A variable can't be evaluated unless its parents have # been observed def can_be_evaluated?(evidence) # :nodoc: returnval = true parents.each {|p| returnval = false unless p.set_in_evidence?(evidence) } returnval end # In order to draw uniformly from the probabilty space, we can't # just pick a random state. Instead we generate a random number # between zero and one and iterate through the states until the # cumulative sum of their probabilities exceeds our random number. def get_random_state(event = {}) # :nodoc: seek_state {|s| evaluate_marginal(s, event) } end # similar to get_random_state() except it evaluates a variable's markov # blanket in addition to the variable itself. def get_random_state_with_markov_blanket(event) # :nodoc: evaluations = [] @states.each {|s| evaluations << evaluate_markov_blanket(s, event) } evaluations.normalize! seek_state {|s| evaluations.shift } end def generate_probability_table # :nodoc: @probability_table = nil if @probabilities and @probabilities.size == state_combinations.size probs = @probabilities.dup @probability_table = state_combinations.collect {|e| [e, probs.shift] } end end def set_probability_table(cpt) @probability_table = cpt end def evaluate_marginal(state, event) # :nodoc: temp_probs = @probability_table.dup remove_irrelevant_states(temp_probs, state, event) sum = 0.0 temp_probs.each {|e| sum += e[1] } sum end def transform_evidence_value(val) # :nodoc: val.to_underscore_sym end private def seek_state sum = 0.0 num = rand returnval = nil @states.each do |s| returnval = s sum += yield(s) break if num < sum end returnval end def state_combinations all_states = [] @parents.each {|p| all_states << p.states } all_states << @states Combination.new(all_states).to_a end def remove_irrelevant_states(probabilities, state, evidence) # remove the states for this variable probabilities.reject! {|e| e.first.last != state } index = 0 @parents.each do |parent| unless parent.set_in_evidence?(evidence) raise "Marginal cannot be evaluated because there are unset parent variables" end probabilities.reject! {|e| e.first[index] != parent.get_observed_state(evidence) } index += 1 end probabilities end def evaluate_markov_blanket(state, event) returnval = 1.0 temp_probs = @probability_table.dup remove_irrelevant_states(temp_probs, state, event) temp = get_observed_state(event) event[@name] = state returnval *= evaluate_marginal(state, event) @children.each {|child| returnval *= child.evaluate_marginal(child.get_observed_state(event), event) } event[@name] = temp returnval end def test_equal(variable) returnval = true net_name = variable.instance_eval('@net.name') returnval = false unless @net.name == net_name returnval = false unless variable.class == self.class and self.is_a? Variable returnval = false unless returnval and @name == variable.name if returnval parent_names = [] variable.parents.each {|p| parent_names << p.name.to_s } my_parent_names = [] @parents.each {|p| my_parent_names << p.name.to_s } returnval = false unless parent_names.sort == my_parent_names.sort returnval = false unless @states == variable.states table = variable.probability_table.transpose.last my_table = @probability_table.transpose.last returnval = false unless table == my_table end returnval end end end
true
ecdab1d63958be46d5538cc58d0045e9c88b4d2a
Ruby
TeruhisaShibuya/local-scraper
/nokogiricss.rb
UTF-8
1,433
2.96875
3
[]
no_license
require 'open-uri' require 'nokogiri' #スクレイピング先のURLを指定 url = 'https://www.antonia.it/153_christian-louboutin' #決まり文句登場 charset = nil html = open(url) do |f| charset = f.charset #文字種別を取得 f.read #htmlを読み込んで変数htmlに渡す end #docというオブジェクトを作成 中身HTML doc = Nokogiri::HTML.parse(html, nil, charset) #表示したい内容 doc.○○ で表示 #base = doc.xpath('//*[@id="wrapper"]/div/div/div[2]') #xpathの書き方 crawlp = doc.xpath('//*[@id="womanList"]') #p crawlp #これで指定ポイントの全ての画像url部分は取れている #p crawlp.css('a').css('img') #最初の画像のurlの値だけ返す #最初だけになってしまう #p crawlp.css('a').css('img').attribute('src') #最初の画像のurlの値だけ返す→OK #p crawlp.css('a').css('img').attribute('src').value #画像の取得は終了 #crawlp.css('a').css('img').each do |f| # image = f.attribute('src').value # p image #end #画像のリンクURLの取得 #crawlp.css('a').each do |f| # url = f.attribute('href').value # p url #end #画像とリンクURLの保存 crawlp.css('a').css('img').each do |f| image = f.attribute('src').value url = f.parent.attribute('href').value @new = Item.new(:link_url => url, :image_url=> image ) @new.save end #p crawlp.css('a').css('href').attribute('src') #p crawlp.css('a')
true
7fbeffe14de9c3ae9e9ea66e9b8a62aeb25bb729
Ruby
Digi-Cazter/easyload
/lib/easyload/singleton_extensions.rb
UTF-8
3,496
2.828125
3
[]
no_license
# -*- encoding: utf-8 -*- require 'easyload/helpers' require 'monitor' module Easyload LOAD_LOCK = Monitor.new # The singleton methods that are defined for a module that includes {Easyload}. module SingletonExtensions # The root path that easyload should use when loading a child constant for this module. # # Defaults to the path component form of the class/module's name attr_reader :easyload_root # Sets easyload_root. def easyload_from(root_path) @easyload_root = root_path.to_s end # Converts a CamelCased symbol into a path component. # # * A +Single+ symbol becomes +single+. # * +MultiWordSymbols+ become +multi_word_symbols+. # * +ACRONYMS+ are treated like words: +acronyms+. # * +ABCFoo+ is considered to be a mix of acronyms and words: +abc_foo+. def easyload_path_component_for_sym(sym) path = sym.to_s.dup path.gsub!(/([A-Z]+)([A-Z][a-z]+)/, '\1_\2_') path.gsub!(/([A-Z][a-z]+)/, '\1_') path.gsub!(/_+/, '_') path.chomp!('_') path.downcase! end # The meat of easyloading happens here. # # @private def const_missing(sym) if not self.instance_variable_defined? :@easyload_root $stderr.puts "You must call easyload_from() before you can easyload #{self}::#{sym}" return super(sym) end path_component = self.easyload_path_component_for_sym(sym) easyload_path = File.join(@easyload_root, "#{path_component}.rb") # Do we have a file to easyload? path_to_easyload = Helpers.find_loadable_file(easyload_path) if path_to_easyload.nil? raise NameError.new("Unknown constant #{self}::#{sym} - tried to easyload it from '#{@easyload_root}/#{path_component}'", sym) end file_source = File.read(path_to_easyload) # Perform the easyload. LOAD_LOCK.synchronize do $parent = self self.module_eval(file_source, path_to_easyload) end #puts "====" #puts self #puts "====" # Perform the easyload with a manual eval. module_eval doesn't allow for relative constants # in the easyloaded file, so we need to manually construct the context to evaluate within. #context_type = self.class == Class ? 'class' : 'module' #begin # ROOT_BINDING.eval("#{context_type} #{self.name}; #{file_source}; end") #rescue # puts "#{context_type} #{self.name}; #{file_source}; end" # raise #end #::Kernel.eval("#{context_type} #{self.name}; #{file_source}; end") #puts "----" #easyload_binding = self.module_eval('::Kernel.binding') #easyload_binding.eval(file_source, path_to_easyload) #self.instance_eval do # ::Kernel.eval(file_source, nil, path_to_easyload) #end #global_eval("#{context_type} #{self.name}; #{file_source}; end") # Did we get our target constant? if not self.const_defined? sym raise LoadError.new("Attempted to easyload #{sym} from '#{path_to_easyload}', but it doesn't appear to exist in that source file.") end # Make sure that we propagate easyload behaviors target_const = self.const_get(sym) class << target_const include SingletonExtensions end target_const.easyload_from(File.join(self.easyload_root, path_component)) return self.const_get(sym) end end end
true
62d33c3c09840f978b35517636a0399d73de6650
Ruby
rranelli/git_multicast
/lib/git_multicast/repository_fetcher.rb
UTF-8
1,363
2.640625
3
[ "MIT" ]
permissive
require_relative 'repository_fetcher/github' require_relative 'repository_fetcher/bitbucket' require 'net/http' require 'json' module GitMulticast class RepositoryFetcher FETCHER_ADAPTER_ZIP = [ [Bitbucket, Adapter::Bitbucket], [Github, Adapter::Github] ] FETCHERS, ADAPTERS = FETCHER_ADAPTER_ZIP.transpose def self.get_all_repos_from_user(username) FETCHER_ADAPTER_ZIP.flat_map do |fetcher, adapter| raw_repos = fetcher.get_all_repos_from_user(username) raw_repos.map { |raw_repo| adapter.new(raw_repo).adapt } end end def self.get_repo(url) raw_repo = fetcher_by_url(url).get_repo(url) adapter_by_url(url).new(raw_repo).adapt end def self.get_repo_parent(url) get_repo(url).parent end def self.zip_by_url(url) fetchers_names = FETCHERS.map do |fetcher| match = fetcher.to_s.match(/Fetcher::(.*)$/) match[1].downcase if match end triples = ([url] * FETCHERS.size).zip(fetchers_names, FETCHER_ADAPTER_ZIP) triples.find { |u, name, _| u.match name }.last end def self.fetcher_by_url(url) zip_by_url(url).first end def self.adapter_by_url(url) zip_by_url(url).last end def self.make_struct(hash) RecursiveOpenStruct.new(hash, recurse_over_arrays: true) end end end
true
5ff38a664f6197ad70d87729ebbd53b96f1480da
Ruby
UpSumTech/simple_service_provider
/spec/lib/simple_service_provider/base_spec.rb
UTF-8
1,564
2.65625
3
[ "MIT" ]
permissive
require 'spec_helper' describe SimpleServiceProvider::Base do class TestConsultant < SimpleServiceProvider::Base attr_reader :bar, :baz attribute :foo, String validates :foo, :presence => true before_work :_set_baz def run @bar = @foo.split('_') end def run! raise "foo must contain an underscore" unless @foo.include?('_') @bar = @foo.split('_') end private def _set_baz @baz = "blah" end end subject { TestConsultant.new(:foo => "foo_bar_baz") } describe "#work" do context "when the consultant is valid" do it "should perform the job" do subject.work subject.bar.should eq(['foo', 'bar', 'baz']) end end context "when the consultant is invalid" do subject { TestConsultant.new } it "should not perform the job" do subject.work subject.bar.should be_nil end end it "should run the callbacks for work" do subject.work subject.baz.should eq("blah") end end describe "#work!" do context "when the consultant is valid" do it "should perform the job" do subject.work! subject.bar.should eq(['foo', 'bar', 'baz']) end end context "when the consultant is invalid" do subject { TestConsultant.new } it "should not perform the job" do expect { subject.work! }.to raise_exception end end it "should run the callbacks for work" do subject.work! subject.baz.should eq("blah") end end end
true
28ff4a4be11c6faa2f26482b1e15bdfe2ea49fc1
Ruby
SawyerMerchant/project_cli_mastermind
/secret.rb
UTF-8
508
3.125
3
[]
no_license
class Secret COLORS = %W[r g b y p o] #initialize def initialize #secret end # user input for secret def create_secret @code = [] 4.times { |item| @code[item] = COLORS.sample } p @code end # "close" and "exact" peg logic def check_guess(guess) check_close(guess) #check_exact(guess) end def check_close(guess) close_counter = 0 guess.each do |color| close_counter += 1 if @code.include?(color) end end def check_exact(guess) end end
true
1a06f3f452fb548ac2783bf2b1a58a58161ff11b
Ruby
lothar59/robot_rspec_cucumber
/spec/robotsimulator/game_spec.rb
UTF-8
1,900
3.03125
3
[]
no_license
require 'spec_helper' module RobotSimulator describe Game do let(:output) { double('output').as_null_object } let(:game) { Game.new(output) } describe "#start" do it "sends a welcome message" do output.should_receive(:puts).with('Welcome to Robot Simulator!') game.start end it "prompts for the place of the robot" do output.should_receive(:puts).with('Place Robot :') game.start end end end describe Robot do let(:output) { double('output').as_null_object } let(:robot) { Robot.new(output) } describe "#place" do it "sends a message of the place of the robot" do output.should_receive(:puts).with('PLACE 0,0,NORTH') robot.place('00N') end it "should set the position of the robot" do robot.place('11E') robot.x.should == 1 && robot.y.should == 1 && robot.direction.should == 'E' end end describe "#command" do it "redirects the command to the right command" do robot.command('PLACE 00N') # TODO : Stub test end end describe "#move" do it "moves the robot one unit forward in the facing direction" do robot.place('00N') robot.move robot.x.should == 0 && robot.y.should == 1 && robot.direction.should == 'N' end end describe "#report" do it "should report the position of the robot" do robot.place('33N') output.should_receive(:puts).with('Output: 3, 3, NORTH') robot.report end end describe "#left" do it "should rotate the robot to the left" do robot.place('44S') robot.left robot.direction.should == 'E' end end describe "#right" do it "should rotate the robot to the right" do robot.place('42E') robot.right robot.direction.should == 'S' end end end end
true
ace7000697f009e16a0235b49820cc655c04a7ee
Ruby
kylesnowschwartz/rails_chess
/app/services/validate_bishop_move.rb
UTF-8
616
2.75
3
[]
no_license
class ValidateBishopMove < ValidatePieceMove def potential_moves all_diagonal_pieces .reject { |piece| piece.same_color?(@bishop) } .map { |piece| board.position(piece) } .uniq end private def all_diagonal_pieces moves = @bishop.possible_placements(from) left_to_right = pieces_on_diagonal(moves[:left_to_right]) right_to_left = pieces_on_diagonal(moves[:right_to_left]) enclosed_inclusive_subset(left_to_right) + enclosed_inclusive_subset(right_to_left) end def pieces_on_diagonal(diagonal) board.current_positions.values_at(*diagonal) end end
true
57613fd2cc4d64cbf9d5d8d0a861ad50fba4f895
Ruby
Manzane/gorillatrip
/app/services/vaccine_progression_constructor.rb
UTF-8
926
2.578125
3
[]
no_license
class VaccineProgressionConstructor def initialize(travel_country, travel) @travel_country = travel_country @travel = travel end def save country = Country.find(@travel_country.country_id) vaccines = country.vaccines # binding.pry country.vaccines.where('"systematic" = true').each do |vaccine| vp = VaccineProgression.where("vaccine_id = #{vaccine.id} AND travel_id = #{@travel.id}") if !vp.empty? svp = StayVaccineProgression.create!(travel_country_id: @travel_country.id, vaccine_progression_id: vp.ids.first) svp.save else new_vp = VaccineProgression.create(vaccine_id: vaccine.id, done: false, travel_id: @travel.id) if new_vp.save svp = StayVaccineProgression.create!(travel_country_id: @travel_country.id, vaccine_progression_id: new_vp.id) svp.save! end end end # binding.pry true end end
true
e74ad26c61d2749e8255cd19b1b39c15a3a50e39
Ruby
soilforlifeforms/forms
/lib/mxit_rails/styles.rb
UTF-8
1,745
3.015625
3
[ "MIT" ]
permissive
module MxitRails module Styles # Not sure whether a Constant is the neatest/nicest way of storing these? StyleList = {} def self.get name StyleList[name.to_sym] end def self.add name, content content.strip! if content[-1] != ';' content += ';' end StyleList[name.to_sym] = content end Emoticons = { happy: [':)', ':-)'], sad: [':(', ':-('], winking: [";)", ";-)"], excited: [':D', ':-D'], shocked: [':|', ':-|'], surprised: [':O', ':-O'], tongue_out: [':P', ':-P'], embarrassed: [':$', ':-$'], cool: ['8-)'], heart: ['(H)'], flower: ['(F)'], # V 3.0. smileys male: ['(m)'], female: ['(f)'], star: ['(*)'], chilli: ['(c)'], kiss: ['(x)'], idea: ['(i)'], extremely_angry: [':e', ':-e'], censored: [':x', ':-x'], grumpy: ['(z)'], coffee: ['(U)'], mr_green: ['(G)'], # V 5.0 smileys sick: [':o('], wtf: [':{', ':-{'], in_love: [':}', ':-}'], rolling_eyes: ['8-o', '8o'], crying: [':\'('], thinking: [':?', ':-?'], drooling: [':~', ':-~'], sleepy: [':z', ':-z'], liar: [':L)'], nerdy: ['8-|', '8|'], pirate: ['P-)'], bored: [':[', ':-['], cold: [':<', ':-<'], confused: [':,', ':-,'], hungry: [':C', ':-C'], stressed: [':s', ':-s'], } def self.add_emoticons source output = source Emoticons.each do |name, searches| searches.each do |search| output.gsub! search, "<span class=\"emoticon #{name}\" title=\"#{name} #{search}\">#{search}</span>" end end output end end end
true
5c1e67ed5be03313f8e5c2116d7a881d055fc8be
Ruby
rstawarz/capybara_page_object
/lib/capybara_page_object/class_methods.rb
UTF-8
8,414
2.96875
3
[ "MIT" ]
permissive
module CapybaraPageObject module ClassMethods # # Set some values that can be used within the class. This is # typically used to provide values that help build dynamic urls in # the page_url method # # @param [Hash] the value to set the params # def params=(the_params) @params = the_params end # # Return the params that exist on this page class # def params @params ||= {} end # # Specify the url for the page. A call to this method will generate a # 'goto' method to take you to the page. # # @param [String] the url for the page. # @param [Symbol] a method name to call to get the url # def page_url(url) define_method("goto") do visit self.page_url_value end define_method('page_url_value') do url end end alias_method :page_path, :page_url # # Creates a method that compares the expected_title of a page against the actual. # @param [String] expected_title the literal expected title for the page # @param [Regexp] expected_title the expected title pattern for the page # @return [boolean] # @raise An exception if expected_title does not match actual title # # @example Specify 'Google' as the expected title of a page # expected_title "Google" # page.has_expected_title? # def expected_title(expected_title) define_method("has_expected_title?") do page.has_title?(expected_title) end end # # Creates a method that provides a way to initialize a page based upon an expected element. # This is useful for pages that load dynamic content. # @param [Symbol] the name given to the element in the declaration # @param [optional, Integer] timeout default value is 5 seconds # @return [boolean] # # @example Specify a text box named :address expected on the page within 10 seconds # expected_element(:address, 10) # page.has_expected_element? # def expected_element(element_name) define_method("has_expected_element?") do args = self.send("#{element_name}_selector") page.assert_selector(*args) true end end # # Creates a method that provides a way to initialize a page based upon an expected element to become visible. # This is useful for pages that load dynamic content and might have hidden elements that are not shown. # @param [Symbol] the name given to the element in the declaration # @param [optional, Integer] timeout default value is 5 seconds # @param [optional, boolean] also check that element to be visible if set to true # @return [boolean] # # @example Specify a text box named :address expected on the page within 10 seconds # expected_element_visible(:address, 10) # page.has_expected_element_visible? # def expected_element_visible(element_name, timeout=Capybara.default_wait_time) define_method("has_expected_element_visible?") do expect(self.send("#{element_name}_element")).to be_visible end end # # adds a method to return a collection of generic Element objects # for a specific tag. # #def elements(name, tag=:element, identifier={:index => 0}, &block) ## default tag to :element ## ## elements 'button', css: 'some css' ## ## is the same as ## ## elements 'button', :element, css: 'some css' ## #if tag.is_a?(Hash) #identifier = tag #tag = :element #end #define_method("#{name}_elements") do #return call_block(&block) if block_given? #platform.elements_for(tag, identifier.clone) #end #end # # adds a method to return a page object rooted at an element # # @example # page_section(:navigation_bar, NavigationBar, :id => 'nav-bar') # # will generate 'navigation_bar' and 'navigation_bar?' # #def page_section(name, section_class, identifier) #define_method(name) do #platform.page_for(identifier, section_class) #end #end # # adds a method to return a collection of page objects rooted at elements # # @example # page_sections(:articles, Article, :class => 'article') # # will generate 'articles' # #def page_sections(name, section_class, identifier) #define_method(name) do #platform.pages_for(identifier, section_class) #end #end # # adds a method that will return an indexed property. The property will respond to # the [] method with an object that has a set of normal page_object properties that # correspond to the definitions included in the identifier_list parameter, with the # "what" of the "how and what" substituted based on the index provided to the [] # method. # # @example # indexed_property(:title, [ # [:text_field, :field_1, :id => 'table[%s].field_1'], # [:button, :button_1, :id => 'table[%s].button_1'], # [:text_field, :field_2, :name => 'table[%s].field_2'] # ]) # # will generate a title method that responds to []. title['foo'] will return an object # # that responds to the normal methods expected for two text_fields and a button with the # # given names, using the given how and what with 'foo' substituted for the %s. title[123] # # will do the same, using the integer 123 instead. # # #def indexed_property (name, identifier_list) #define_method("#{name}") do #IndexedProperties::TableOfElements.new(@browser, identifier_list) #end #end def add_element_accessor_method(name, element_klass, finder_options) finder_options = finder_options.dup finder_args = extract_finder_args(finder_options) element_klass ||= CapybaraPageObject::Element define_method("#{name}_element") do e = find(*finder_args) element_klass.new(e, self) end define_method("#{name}_selector") do |options={}| [finder_args.first, finder_args[1], finder_args[2].merge(options)] end end def add_element_query_method(name, finder_options) finder_options = finder_options.dup finder_args = extract_finder_args(finder_options) define_method("has_#{name}?") do |options = {}| args = self.send("#{name}_selector", options) has_selector?(*args) end define_method("has_no_#{name}?") do |options = {}| args = self.send("#{name}_selector", options) has_no_selector?(*args) end define_method("assert_has_#{name}") do |options = {}| args = self.send("#{name}_selector", options) assert_selector(*args) end define_method("assert_has_no_#{name}") do |options = {}| args = self.send("#{name}_selector", options) assert_no_selector(*args) end end def add_value_accessor_method(name) define_method(name) do self.send("#{name}_element").value end end def add_text_accessor_method(name) define_method(name) do self.send("#{name}_element").text end end def add_value_mutator_method(name) define_method("#{name}=") do |value| self.send("#{name}_element").set(value) end end def add_click_method(name) define_method(name) do self.send("#{name}_element").click end end def extract_finder_args(finder_options={}) finder_type, finder_param = extract_finder_type!(finder_options, :class, :css, :id, :xpath) finder_options.delete(finder_type) case finder_type when :class [:css, ".{finder_param}", finder_options] when :id [:css, "##{finder_param}", finder_options] when :css [finder_type, finder_param, finder_options] when :xpath [finder_type, finder_param, finder_options] else raise "oops" end end def extract_finder_type!(options, *types) found_keys = options.select{|k,v| types.include?(k)} unless found_keys.length == 1 raise "Incorrect finder type specified '#{found_keys.keys.join(', ')}' - only one of #{types.join(', ')} can be specified at a time." end found_keys.to_a.first end end end
true
d12547e9b5d4f4331119e56e01dc6f3aef623175
Ruby
floraison/raabro
/spec/failure_spec.rb
UTF-8
2,273
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# # specifying raabro # # Thu Aug 10 07:52:29 JST 2017 # require 'spec_helper' module Sample::ToPlus include Raabro # parse def sp_star(i); rex(nil, i, /\s*/);end def to_space(i); seq(nil, i, :to, :sp_star); end def to_plus(i); rep(:tos, i, :to_space, 1); end # rewrite def rewrite(t) [ :ok, t.string ] end end module Sample::Fun include Raabro # parse # # Last function is the root, "i" stands for "input". def pa(i); rex(nil, i, /\(\s*/); end def pz(i); rex(nil, i, /\)\s*/); end def com(i); rex(nil, i, /,\s*/); end def num(i); rex(:num, i, /-?[0-9]+\s*/); end def args(i); eseq(:arg, i, :pa, :exp, :com, :pz); end def funame(i); rex(:funame, i, /[a-z][a-z0-9]*/); end def fun(i); seq(:fun, i, :funame, :args); end def exp(i); alt(:exp, i, :fun, :num); end # rewrite # # Names above (:num, :fun, ...) get a rewrite_xxx function. # "t" stands for "tree". # # The trees with a nil name are handled by rewrite_(tree) a default # rewrite function def rewrite_num(t); t.string.to_i; end def rewrite_fun(t) [ t.children[0].string ] + t.children[1].odd_children.collect { |a| rewrite(a) } end end describe 'Raabro and parse failure' do describe 'when there is a syntax error' do it 'points at the error' do t = Sample::Fun.parse('f(a, b') expect(t).to eq(nil) expect( Sample::Fun.parse('f(a, b', error: true) ).to eq( [ 1, 4, 3, 'parsing failed .../:exp/:fun/:arg', "f(a, b\n ^---" ] ) end end describe 'when not all is consumed' do it 'points at the start of the remaining input' do t = Sample::ToPlus.parse('totota') expect(t).to eq(nil) expect( Sample::ToPlus.parse('totota', error: true) ).to eq( [ 1, 5, 4, 'parsing failed, not all input was consumed', "totota\n ^---" ] ) end it 'points at the start of the remaining input (multiline)' do s = "toto\r\n ta" t = Sample::ToPlus.parse(s) expect(t).to eq(nil) expect( Sample::ToPlus.parse(s, error: true) ).to eq( [ 2, 3, 8, 'parsing failed, not all input was consumed', " ta\n ^---" ] ) end end end
true
f45e46ed876808d3930f7fc45b2215ba562ec5be
Ruby
hermetique/warbride-engine
/app/main.rb
UTF-8
3,843
2.9375
3
[ "MIT" ]
permissive
require "app/storybox.rb" require "app/storyevent.rb" def quick_reset $gtk.reset $gtk.console.animation_duration = 0 end quick_reset def setup args if(args.state.tick_count == 0) args.state.session_tick = 0 args.state.debug_messages = [] $gtk.console.animation_duration = 0 args.state.layout.dialogue = StoryBox.new({ body: {x: 310, y: 230, w: 59, h: 7, font: "font/euler.otf"}, name: {x: 310, y: 280, font: "font/euler.otf"} }) args.state.story = StoryEvent.new(args.state.layout.dialogue) args.state.story << { name: "Warbride", text: "I am Warbride! I am wedded to war! Conquest is my love, and battle is my passion. The whole world shall bow before me, and all who oppose me will fall in their time. If you love life, surrender now, but if you do not, then face me in battle." } args.state.story << { name: "Some guy", text: %Q( That's a nice speech, very inspirational. Tell me though, does it work for you? It sounds like you've rehearsed it pretty well, maybe you've used it on many other warriors, many of them much more weak-willed than I am. So tell me, has it ever worked for you, even on the most timid of opponents? If you need time to think of one, I can wait. I'm in no rush. ).strip } args.state.story << { name: "Warbride", text: %Q( The great general Another Guy, known for his wisdom and his devotion to his people, showed great prudence. He knew that he could not beat me, and he knew that I would crush his people and burn their villages, and take their food for my soldiers. Instead he came, not to fight, but to bargain. I will admit that I was disappointed, but I am only half-barbaric, and so I put forward my demands to him. He, putting the wellbeing of his people above his own ego and desire for conquest, handed over rulership. It is not so bad, living in my empire. We are prosperous, and cosmopolitan. Within my empire there is complete freedom of movement, and so all of the cultures absorbed into my empire mingle freely, and exchange their ideas. You think that because I am a barbarian, my land must be barbaric, but I have no desire to crush a people who are loyal to me, who submit to my law and my rule. But how is your land? Do your people prosper? ).strip } args.state.story << { name: "Some Guy's lieutenant", text: "Do not believe her, my lord. Word of her atrocities has spread throughout the land. She brings only death and suffering wherever she goes." } args.state.story.start end args.state.layout.background ||= { x: 0, y: 0, w: 1280, h: 720, path: 'art/desert.png', angle: 0 } args.state.layout.text_box ||= { x: 290, y: 0, w: 700, h: 300, path: 'art/text box.png', angle: 0 } end def tick args setup args if args.inputs.keyboard.key_down.space args.state.story.advance end if args.inputs.keyboard.key_down.backspace args.state.story.back end draw args args.state.session_tick += 1 debug_display args end def draw args args.outputs.sprites << args.state.layout.background args.outputs.sprites << args.state.layout.text_box args.state.layout.dialogue.draw args.outputs end def debug_log message $args.state.debug_messages << message end def debug_display args max_messages = 35 message_height = 20 if(args.state.debug_messages.length > max_messages) message_offset = -max_messages else message_offset = 0 end line_offset = 0 args.state.debug_messages[message_offset,max_messages].each do |message| args.outputs.labels << [ 10, 720-line_offset, message ] line_offset += message_height end end
true
9b7523ae03381253ef08d782e7c82e27df9048ec
Ruby
garnieretienne/ant-web
/test/models/user_test.rb
UTF-8
1,147
2.59375
3
[]
no_license
require 'test_helper' class UserTest < ActiveSupport::TestCase test "should not save an user with no name, email nor password" do user = User.new assert_not user.save, "Saved an user with no name nor email address" assert user.errors.messages[:name].include?("can't be blank"), "No error message for the blank name attribute" assert user.errors.messages[:email].include?("can't be blank"), "No error message for the blank email address attribute" assert user.errors.messages[:password].include?("can't be blank"), "No error message for the blank password attribute" end test "should not save a new user with an already registered email address" do user = User.first new_user = User.new(name: "New User", email: user.email) assert_not new_user.save, "Saved an user with an existing email address" assert new_user.errors.messages[:email].include?("has already been taken"), "No error message for the duplicate email address attribute" end test "could have mailing lists" do user = User.first assert user.mailing_lists, "No mailing list accessors" end end
true
bc01f369a96cc731f504443b2be553cb7a97bd59
Ruby
dsinn/project_euler
/src/039.rb
UTF-8
824
3.3125
3
[]
no_license
#!/usr/bin/env ruby t0 = Time.now require_relative 'projecteuler' limit = 10**3 half_limit = limit >> 1 # Euclid's formula # a = m^2 - n^2, b = 2mn, c = m^2 + n^2 for m > n where (m + n) & 1 == 1 and gcd(m, n) == 1 count = Array.new(half_limit + 1) { 0 } # Perimeter is always even, so save some memory (1..(-0.5 + Math.sqrt(0.25 + half_limit)).to_i).each do |m| # Solve 2m^2 + 2m = limit ((m & 1) + 1).step(m - 1, 2) do |n| # Each number in [1 .. m-1] with different parity if gcd(m, n) == 1 # m and n must be coprime half_perimeter = m * (m + n) # Collect like terms in a + b + c and then simplify half_perimeter.step(half_limit, half_perimeter) do |hp| count[hp] += 1 end end end end max = count.each_with_index.max puts "count[#{max[1] << 1}] = #{max[0]}" puts "#{Time.now - t0} s"
true
6c0854229829562d871bde8a74ce7a882b8abea2
Ruby
sekoudosso82/Ruby_essential
/one_to_many.rb/drink.rb
UTF-8
1,819
3.828125
4
[]
no_license
# require 'pry' # RUN RUBY FILE # ruby file_name.rb # global var better to define outside the class # preced with $ sign # $global = "global" class Drink # # GETTER # attr_reader :alcoholic, :name, :size, :ingredients, :beef # # SETTER # attr_writer :alcoholic, :name, :size, :ingredients, :beef # ACCESSOR => combine GETTER and SETTER attr_accessor :alcoholic, :name, :size, :ingredients, :beef # class var @@all = [] # preced with @@ sign # instance var # preced with @ sign # constructor def initialize (name, size, alcoholic, ingredients) @name = name @size = size @alcoholic = alcoholic @ingredients = ingredients @@all << self end # instance methods # getter method => report an attributes within in class # equivalent to attr_reader # def alcoholic # @alocoholic # end # def name # @name # end # setter method => change value stored on instance variable # equivalent to attr_writer # def size(new_size) # @size = new_size # end def change_ingredients(target_ingredient, new_ingredient) end def calculate_tax puts "calculating taxe" end # SELF CONCEPT: self reffer to curent instance class/ method / var def print_details self.calculate_tax # reffer to current intance puts " this is a #{@name} " end # class methods => stuff the entire class can do # def self.method_name # end def self.all puts @@all end def self.compte_instance puts @@all.length end end # tenary # condition ? true_case : false_case
true
5adddb2478c885ed05a7240eb0e7d0b2490ac38d
Ruby
menor/dbc_flashcards_and_todos
/part2_ruby-flashcards-2-mvc-pattern-challenge/solutions/sample_25.rb
UTF-8
2,071
3.796875
4
[]
no_license
class FlashModel attr_reader :contents, :cards def initialize(file) @contents = read_from_file(file) end def read_from_file(file) open(file) {|f| f.readlines} end def create_cards cards = [] @contents.each_slice(3) do |qa_pair| cards << FlashCard.new(qa_pair[0].strip, qa_pair[1].strip.upcase, 1, false) end cards end end class FlashCard < Struct.new(:question, :answer, :tries, :answered) end class FlashController MAX_GUESSES = 3 def initialize(file) @model = FlashModel.new(file) @view = FlashView.new @view.welcome_message(file) end def play_game @num_correct = 0 cards = @model.create_cards.shuffle cards.each {|card| guess(card) unless card.answered} until cards.all? {|card| card.answered} @view.game_over_message(@num_correct, cards) end def guess(card) tries = 0 correct = false @view.ask_question(card.question) until tries >= MAX_GUESSES || correct #DISASTER @view.try_again unless tries.zero? user_input = STDIN.gets.chomp.upcase correct = (user_input == card.answer) @view.respond_to_answer(correct) card.tries += 1 unless correct tries += 1 card.answered = true if correct && tries == 1 end @view.reveal(card.answer) if tries == MAX_GUESSES end end class FlashView def ask_question(question) puts question print "Your answer: " end def respond_to_answer(right_or_wrong) puts right_or_wrong ? "Well done!" : "Nope!" end def try_again print "Try again: " end def game_over_message(num_correct, cards) puts puts "=======GAME OVER=======" puts "Your results:" cards.each do |card| puts "#{card.answer.upcase} took you #{card.tries} tries." puts end end def reveal(answer) puts "The answer to the question is '#{answer}'" end def welcome_message(file) puts "Welcome to Ruby Flash Cards! You are using the deck '#{file}.'" puts end end controller = FlashController.new(ARGV.first) controller.play_game
true
c9981d8b18ecee70a750516c0ae18ea68c0ff523
Ruby
dst87/Advent-of-Code
/2022/day11.rb
UTF-8
2,282
3.46875
3
[]
no_license
#!/usr/bin/env ruby require 'colorize' input = File.read("input/day11.txt") def generateMonkeys(input) monkeyStrings = input.split("\n\n") monkeys = [] monkeyStrings.each do |monkeyString| items = monkeyString.match(/items: (.+)/)[1].split(", ").map!(&:to_i) operationMatch = monkeyString.match(/old (?<operator>\+|\*) (?<value>\d+|old)/) testValue = monkeyString.match(/by (\d+)/)[1].to_i trueMonkey = monkeyString.match(/true:.* (\d+)/)[1].to_i falseMonkey = monkeyString.match(/false:.* (\d+)/)[1].to_i monkeys << { items: items, operation: operationMatch, testValue: testValue, trueMonkey: trueMonkey, falseMonkey: falseMonkey, inspectionCount: 0 } end return monkeys end puts "\nPart 1".red.on_black.underline monkeys = generateMonkeys(input) 20.times do monkeys.each do |monkey| monkey[:items].size.times do item = monkey[:items].shift opVal = monkey[:operation][:value] == "old" ? item : monkey[:operation][:value].to_i case monkey[:operation][:operator] when "+" item = item + opVal when "*" item = item * opVal end item = (item / 3).floor pass = item % monkey[:testValue] == 0 luckyMonkey = pass ? monkey[:trueMonkey] : monkey[:falseMonkey] monkeys[luckyMonkey][:items].append(item) monkey[:inspectionCount] += 1 end end end puts values = monkeys.map { |m| m[:inspectionCount] }.sort[-2...].inject(:*) puts "\nPart 2".red.on_black.underline monkeys = generateMonkeys(input) # I would never in a million years have worked this out. Not my work. magicNumber = monkeys.map { |m| m[:testValue] }.inject(:*) 10000.times do monkeys.each do |monkey| monkey[:items].size.times do item = monkey[:items].shift opVal = monkey[:operation][:value] == "old" ? item : monkey[:operation][:value].to_i case monkey[:operation][:operator] when "+" item = item + opVal when "*" item = item * opVal end # The reason this works is a bit beyond me. Not my work. item = item % magicNumber pass = item % monkey[:testValue] == 0 luckyMonkey = pass ? monkey[:trueMonkey] : monkey[:falseMonkey] monkeys[luckyMonkey][:items].append(item) monkey[:inspectionCount] += 1 end end end puts values = monkeys.map { |m| m[:inspectionCount] }.sort[-2...].inject(:*)
true
39a9a678ea80a1a24d28b63b8704d8b2cbbd19f1
Ruby
thebravoman/software_engineering_2014
/class004/Lubomir_Yankov_Class4_2.rb
UTF-8
1,186
2.765625
3
[]
no_license
hash = Hash.new exercise = ["2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"] i = 0 k = 0 sum = 0 Dir.glob("#{ARGV[0]}/**/*.*") do |myFile| short_name = myFile.split('/').last full_name = myFile.split('/').last.split('.').first.split('_') name = short_name.split('.').first.split('_') task = short_name.split('.').first.split('_').last student = name.collect{|x| "#{name[0].capitalize}"+" #{name[1]}"} student_extension = myFile.split('/').last.split('.').last student_name = "#{student[0]}" if name[0] == '' || name[1] == '' || name[2] == '' elsif full_name.length == 3 if exercise.include? "#{task}" if hash[student_name] != nil currentUserFiles = hash[student_name] currentUserFiles << task.to_i else hash[student_name] = [] currentUserFiles = hash[student_name] currentUserFiles << task.to_i hash[student_name]=currentUserFiles end end end end sorted_hash = hash.sort_by {|student_name, value| student_name} sorted_hash.each do |student_name, value| value = value.sort.uniq value.each do |e| sum += e.to_i end puts "#{student_name},#{value.join(",")},#{sum}" sum = 0 end
true
dd70ba3a2ef865f9aad87ff234dd8a70906b614f
Ruby
jeffreybasurto/CoralMud
/lib/commands/ichannels.rb
UTF-8
379
2.65625
3
[]
no_license
class Player ### If no argument display all available channels. def cmd_ichannels command_table_entry, arg buf = "The following commands are available:" + ENDL i = 0 $imc_channel_list.each_pair do |k,v| i += 1 z = "[On]" buf << v[1] + ("[" + i.to_s + "] " + v[0]).ljust(25) + k.to_s.ljust(12) + z + ENDL end text_to_player buf end end
true
30c5a9fa431451f307a4292717be029c93873dc3
Ruby
tedcheng/flynride
/app/helpers/riders_helper.rb
UTF-8
520
2.5625
3
[]
no_license
module RidersHelper def generateMapUrl(rankResults) @colors = ["black","blue","red","green"] @base_map_url = "http://maps.googleapis.com/maps/api/staticmap?sensor=false&size=900x300&maptype=roadmap&" @base_map_url += "markers=color:#{@colors[0]}|label:You|#{current_rider.final_dest}&" rankResults.each_with_index do |result, idx| @base_map_url += "markers=color:#{@colors[idx+1]}|label:#{(idx + 97).chr.capitalize}|#{result[:final_dest]}&" break if idx == 2 end @base_map_url end end
true
bcc6d578c07b6cb364aa5b9d4263391fa2938429
Ruby
newstime/newstime_web
/app/helpers/format_helpers.rb
UTF-8
666
2.953125
3
[]
no_license
module FormatHelpers def format_currency(value) return unless value if value <= 0 "FREE" elsif value < 1.00 "%.f¢" % (value.round(2)*100) else "$%.2f" % value.round(2) end end def format_transaction_amount(value) return unless value if value.zero? "$0.00" elsif value > 0 "$%.2f" % value.round(2) else "($%.2f)" % value.round(2).abs end end def format_date(date, format=:short) case format when :short then date.strftime("%m/%d/%Y") when :long then date.strftime("%A, %B %e, %Y") end end def format_size(size, units="Mb") "#{size}#{units}" end end
true
835beb2f7aa900095f076009c5daef8b3a94d044
Ruby
hashcrof/Algorithms
/move_zeroes.rb
UTF-8
568
3.65625
4
[]
no_license
# @param {Integer[]} nums # @return {Void} Do not return anything, modify nums in-place instead. def move_zeroes(nums) n = nums.length return n if n < 1 #pointer i points to el = 0 #point j points to el != 0 i = j = 0 while j < n #increments j until nums[j] is not zero if nums[j] != 0 temp = nums[i] nums[i] = nums[j] nums[j] = temp i += 1 end j += 1 end i end =begin Mistakes Did not swap nums[i] & nums[j] initially Incremented i before swap =end
true
0cfef138fdb273f306bc901e014832473ef99918
Ruby
ViolaCrellin/chitter-challenge
/spec/features/peeps_feature_spec.rb
UTF-8
1,380
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'spec_helper' # require 'timecop' feature 'Public Peeps' do scenario 'Users can post a peep to the chitter homepage' do post_peep expect(page).to have_content 'Here\'s Johny' end scenario 'Users can see everyons\'s in reverse chronological order' do post_peep post_peep_2 expect('Another futile peep').to appear_before 'Here\'s Johny' end context 'Date and timestamping peeps'do before do Timecop.freeze(Time.local(1990)) end after do Timecop.return end scenario 'Users can see what date and time peeps were posted and who by' do post_peep expect(page).to have_content '12:00AM' expect(page).to have_content '01/01/1990' expect(page).to have_content 'Le Jockey' end end context 'Invalid peeps' do scenario 'If there is no user logged in you cannot peep' do post_peep_no_author expect(page).to have_content 'This is a members only cult. IMPOSTER' expect(page).not_to have_content 'Here\'s Johny' expect{post_peep_no_author}.not_to change(Peep, :count) end scenario 'Peeps have a limit of 140 characters' do post_peep_long expect(page).to have_content 'Keep it brief' expect(page).not_to have_content 'Too long for Hound. Hound is crying' expect{post_peep_long}.not_to change(Peep, :count) end end end
true
2889b08958e031b5ae72f9500fafa8815af7c97f
Ruby
firaschaabani1/ruby-object-initialize-lab-onl01-seng-pt-120819
/lib/dog.rb
UTF-8
167
2.515625
3
[]
no_license
dog.new def initialize (dog) if dog.initialize : @name puts "name" if else dog.initialize : @breed puts "breed" else puts Mutt end end end
true
358b03616167bc20eac3a01f639048d381e335ec
Ruby
navychen2003/javen
/release/lightning/current/lib/ruby/shell/commands/user_permission.rb
UTF-8
671
2.546875
3
[]
no_license
module Shell module Commands class UserPermission < Command def help return <<-EOF Show all permissions for the particular user. Syntax : user_permission <table> For example: bigdb> user_permission bigdb> user_permission 'table1' EOF end def command(table=nil) #format_simple_command do #admin.user_permission(table) now = Time.now formatter.header(["User", "Table,Family,Qualifier:Permission"]) count = security_admin.user_permission(table) do |user, permission| formatter.row([ user, permission]) end formatter.footer(now, count) end end end end
true
675768025888547a8744e17bae7f1f7d7ef78305
Ruby
Yorickov/railway
/lib/services/service.rb
UTF-8
1,194
3.125
3
[]
no_license
class Service def initialize(options) @station_klass = options[:station_klass] @train_klass = options[:train_klass] @carriage_klass = options[:carriage_klass] @route_klass = options[:route_klass] end protected def input_index(array, name) puts "enter index of #{name} or X to exit" array.each.with_index(1) { |item, index| puts "\t#{index}. #{item}" } choice = gets.chomp return if choice.downcase == 'x' index = choice.to_i - 1 index.between?(0, array.size - 1) ? index : input_index(array, name) end def find_station return if station_klass.all.empty? station_index = input_index(station_klass.stations_list, 'station') station_klass.all[station_index.to_i] if station_index end def find_route return if route_klass.all.empty? str_routes = route_klass.all.map(&:show_stations) route_index = input_index(str_routes, 'route') route_klass.all[route_index] if route_index end def find_train return if train_klass.all.empty? str_trains = train_klass.all.values.map(&:info) train_index = input_index(str_trains, 'train') train_klass.all.values[train_index] if train_index end end
true
1e6bfb5f75a8d0f6c751edcce02fb04af9cf2387
Ruby
tlalexan/knife-rackspace-database
/lib/chef/knife/rackspace_database_user_delete.rb
UTF-8
1,243
2.75
3
[ "Apache-2.0" ]
permissive
require 'chef/knife' require 'chef/knife/rackspace_base' require 'chef/knife/rackspace_database_instance_related' module KnifePlugins class RackspaceDatabaseUserDelete < Chef::Knife include Chef::Knife::RackspaceBase include Chef::Knife::RackspaceDatabaseBase include Chef::Knife::RackspaceDatabaseInstanceRelated banner "knife rackspace database user delete INSTANCE_NAME USER_NAME [USER_NAME ...]" def run $stdout.sync = true pop_instance_arg users = @name_args.map do |user_name| user = @instance.users.find { |u| u.name == user_name } if user.nil? ui.error("User #{user_name} not found") exit 1 end user end if users.empty? show_usage ui.error("USER_NAME required") exit 1 end if users.count > 1 msg_pair("User Names", users.map {|u| u.name }.join(", ")) ui.confirm("Do you really want to delete these users") else msg_pair("User Name", users.first.name) ui.confirm("Do you really want to delete this user") end users.each do |user| user.destroy ui.warn("Deleted user #{user.name}") end end end end
true
b87955be02e97f3948c327988f24ff823bc9ce55
Ruby
angmeng/icode-erp
/app/models/setting.rb
UTF-8
643
2.546875
3
[]
no_license
class Setting < ActiveRecord::Base before_save :check_directory, :check_trailing_slash protected def check_directory puts "start checking..." begin [backup_path, source_path].each do |folder| if not File.directory?(folder) Dir.mkdir(folder) puts "creating directory....." end end rescue self.backup_path = "#{Rails.root.to_s}\\public\\" end puts "End checking ..." end def check_trailing_slash if backup_path[-1] != "\\" self.backup_path += "\\" end if source_path[-1] != "\\" self.source_path += "\\" end end end
true
db140319d530865c8c8f0eb203faa30a1a2c76eb
Ruby
Sborden7/W3D2
/aa_questions/questions_database.rb
UTF-8
11,416
2.84375
3
[]
no_license
require 'sqlite3' require 'singleton' class QuestionsDatabase < SQLite3::Database include Singleton def initialize super('questions.db') self.type_translation = true self.results_as_hash = true end end class User attr_accessor :fname, :lname def self.all users = QuestionsDatabase.instance.execute('SELECT * FROM users') users.map { |user| User.new(user) } end def self.find_by_id(id) data = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM users WHERE id = ? SQL User.new(data.first) end def self.find_by_name(fname, lname) users = QuestionsDatabase.instance.execute(<<-SQL, fname, lname) SELECT * FROM users WHERE fname = ? AND lname = ? SQL users_by_name = users.map{|user| User.new(user)} return users_by_name.first if users_by_name.count == 1 users_by_name end def initialize(options) @id = options['id'] @fname = options['fname'] @lname = options['lname'] end def save if @id QuestionsDatabase.instance.execute(<<-SQL, @fname, @lname, @id) UPDATE users SET fname = ?, lname = ? WHERE id = ? SQL else QuestionsDatabase.instance.execute(<<-SQL, @fname, @lname) INSERT INTO users (fname, lname) VALUES (?, ?) SQL @id = QuestionsDatabase.instance.last_insert_row_id end end def liked_questions QuestionLike.liked_questions_for_user_id(@id) end def authored_questions Question.find_by_author_id(@id) end def authored_replies Reply.find_by_user_id(@id) end def followed_questions QuestionFollow.followed_questions_for_user_id(@id) end def average_karma karma_store = QuestionsDatabase.instance.execute(<<-SQL, @id) SELECT -- COUNT(DISTINCT(questions.id)) ((COUNT(question_likes.question_id)) / (CAST(COUNT(DISTINCT(questions.id)) AS FLOAT))) AS average_karma FROM questions LEFT OUTER JOIN question_likes ON questions.id = question_likes.question_id WHERE questions.author_id = 1 GROUP BY questions.author_id SQL karma_store.first end end class Question attr_accessor :title, :body, :author_id def self.all questions = QuestionsDatabase.instance.execute('SELECT * FROM questions') questions.map{|question| Question.new(question)} end def self.most_liked(n) QuestionLike.most_liked_questions(n) end def self.find_by_author_id(author_id) questions = QuestionsDatabase.instance.execute(<<-SQL, author_id) SELECT * FROM questions WHERE author_id = ? SQL questions.map { |question| Question.new(question) } end def self.find_by_keyword_in_title(keyword) questions = QuestionsDatabase.instance.execute(<<-SQL, key: "%#{keyword}%") SELECT * FROM questions WHERE title LIKE :key SQL questions.map { |question| Question.new(question) } end def self.find_by_id(id) data = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM questions WHERE id = ? SQL Question.new(data.first) end def self.most_followed(n) QuestionFollow.most_followed_questions(n) end def initialize(options) @title = options['title'] @body = options['body'] @author_id = options['author_id'] @id = options['id'] end def save if @id QuestionsDatabase.instance.execute(<<-SQL, @title, @body, @author_id, @id) UPDATE questions SET title = ?, body = ?, author_id = ? WHERE id = ? SQL else QuestionsDatabase.instance.execute(<<-SQL, @title, @body, @author_id) INSERT INTO questions (title, body, author_id) VALUES (?, ?, ?) SQL @id = QuestionsDatabase.instance.last_insert_row_id end end def likers QuestionLike.likers_for_question_id(@id) end def num_likes QuestionLike.num_likes_for_question_id(@id) end def author User.find_by_id(@author_id) end def replies Reply.find_by_subject_id(@id) end def followers QuestionFollow.followers_for_question_id(@id) end end class QuestionFollow attr_accessor :user_id, :question_id def self.all question_follows = QuestionsDatabase.instance.execute("SELECT * FROM question_follows") question_follows.map { |follow| QuestionFollow.new(follow) } end def self.find_by_id(id) follow = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM question_follows WHERE id = ? SQL QuestionFollow.new(follow.first) end def self.find_by_user_id(user_id) follows = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM question_follows WHERE user_id = ? SQL follows.map { |follow| QuestionFollow.new(follow) } end def self.find_by_question_id(question_id) follows = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM question_follows WHERE question_id = ? SQL follows.map { |follow| QuestionFollow.new(follow) } end def self.followers_for_question_id(question_id) users = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM users JOIN question_follows ON users.id = question_follows.user_id WHERE question_id = ? SQL users.map { |user| User.new(user) } end def self.followed_questions_for_user_id(user_id) questions = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM questions JOIN question_follows ON questions.id = question_follows.question_id WHERE question_follows.user_id = ? SQL questions.map { |question| Question.new(question)} end def self.most_followed_questions(n) questions = QuestionsDatabase.instance.execute(<<-SQL, n) SELECT title, COALESCE(COUNT(*), 0) AS follow_count FROM questions JOIN question_follows ON questions.id = question_follows.question_id GROUP BY question_follows.question_id ORDER BY follow_count DESC LIMIT ? SQL questions.map { |question| Question.new(question) } end def initialize(options) @id = options['id'] @user_id = options['user_id'] @question_id = options['question_id'] end end class Reply attr_accessor :subject_id, :parent_reply_id, :user_id, :body def self.all replies = QuestionsDatabase.instance.execute('SELECT * FROM replies') replies.map {|reply| Reply.new(reply)} end def self.find_by_id(id) reply = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM replies WHERE id = ? SQL Reply.new(reply.first) end def self.find_by_subject_id(subject_id) replies = QuestionsDatabase.instance.execute(<<-SQL, subject_id) SELECT * FROM replies WHERE subject_id = ? SQL replies.map {|reply| Reply.new(reply)} end def self.find_by_parent_reply_id(parent_reply_id) replies = QuestionsDatabase.instance.execute(<<-SQL, parent_reply_id) SELECT * FROM replies WHERE parent_reply_id = ? SQL replies.map {|reply| Reply.new(reply)} end def self.find_by_user_id(user_id) replies = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM replies WHERE user_id = ? SQL replies.map {|reply| Reply.new(reply)} end def self.find_by_keyword_in_body(keyword) replies = QuestionsDatabase.instance.execute(<<-SQL, key: "%#{keyword}%") SELECT * FROM replies WHERE body LIKE :key SQL replies.map {|reply| Reply.new(reply)} end def initialize(options) @id = options['id'] @subject_id = options['subject_id'] @parent_reply_id = options['parent_reply_id'] @user_id = options['user_id'] @body = options['body'] end def save if @id QuestionsDatabase.instance.execute(<<-SQL, @subject_id, @parent_reply_id, @user_id, @body, @id) UPDATE replies SET subject_id = ?, parent_reply_id = ?, user_id = ?, body = ? WHERE id = ? SQL else QuestionsDatabase.instance.execute(<<-SQL, @subject_id, @parent_reply_id, @user_id, @body) INSERT INTO replies (subject_id, parent_reply_id, user_id, body) VALUES (?, ?, ?, ?) SQL @id = QuestionsDatabase.instance.last_insert_row_id end end def author User.find_by_id(@user_id) end def question Question.find_by_id(@subject_id) end def parent_reply Reply.find_by_id(@parent_reply_id) end def child_replies Reply.find_by_parent_reply_id(@id) end end class QuestionLike attr_accessor :user_id, :question_id def self.all likes = QuestionsDatabase.instance.execute('SELECT * FROM question_likes') likes.map {|like| QuestionLike.new(like)} end def self.most_liked_questions(n) questions = QuestionsDatabase.instance.execute(<<-SQL, n) SELECT title, COUNT(*) AS like_count FROM questions JOIN question_likes ON questions.id = question_likes.question_id GROUP BY question_likes.question_id ORDER BY like_count DESC LIMIT ? SQL questions.map { |question| Question.new(question) } end def self.find_by_id(id) like = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM question_likes WHERE id = ? SQL QuestionLike.new(like.first) end def self.liked_questions_for_user_id(user_id) likes = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM question_likes WHERE user_id = ? SQL likes.map {|like| QuestionLike.new(like)} end def self.find_by_question_id(question_id) likes = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM question_likes WHERE question_id = ? SQL likes.map {|like| QuestionLike.new(like)} end def self.likers_for_question_id(question_id) users = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM users JOIN question_likes ON question_likes.user_id = users.id WHERE question_likes.question_id = ? SQL users.map { |user| User.new(user)} end def self.num_likes_for_question_id(question_id) num_likes = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT COUNT(*) AS num_likes FROM question_likes WHERE question_id = ? GROUP BY question_id SQL num_likes.first['num_likes'] end def initialize(options) @id = options['id'] @user_id = options['user_id'] @question_id = options['question_id'] end end
true
cc615eca7bb09cf8db149b3ba2bf958afca49344
Ruby
bogrobotten/fetch
/lib/fetch/callbacks.rb
UTF-8
2,068
3
3
[ "MIT" ]
permissive
module Fetch module Callbacks def self.included(base) base.extend ClassMethods end private # Check if a callback has been used. def callback?(name) self.class.callbacks[name].any? end # Run specific callbacks. # # run_callbacks_for(:before_fetch) # run_callbacks_for(:progress, 12) # 12 percent done def run_callbacks_for(name, args, reverse) callbacks_for(name, reverse).map do |block| run_callback(block, args) end end def run_last_callback_for(name, args, reverse) if block = callbacks_for(name, reverse).last run_callback(block, args) end end def callbacks_for(name, reverse) callbacks = self.class.callbacks[name] callbacks = callbacks.reverse if reverse callbacks end def run_callback(block, args) instance_exec(*args, &block) end module ClassMethods # Hash of callback blocks to be called. def callbacks @callbacks ||= Hash.new { |h, k| h[k] = [] } end # Defines callback methods on the class level. def define_callback(*names) options = names.last.is_a?(Hash) ? names.pop : {} reverse = !!options[:reverse] names.each do |name| define_singleton_method name do |*values, &block| create_callback_for(name, values, block) end define_method name do |*args| run_callbacks_for(name, args, reverse).last end define_method "#{name}!" do |*args| run_last_callback_for(name, args, reverse) end end end def inherited(base) super callbacks.each do |name, callbacks| base.callbacks[name] = callbacks.dup end end private def create_callback_for(name, values, block) add_callback(name, ->{ values }) if values.any? add_callback(name, block) if block end def add_callback(name, block) callbacks[name] << block end end end end
true
b3d2b7a81cfb0e748cb34493c25e100799cd60a6
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/src/502.rb
UTF-8
145
2.953125
3
[]
no_license
def compute(a, b) diffs = i = 0 while i < a.length and i < b.length diffs += 1 if a[i] != b[i] i += 1 end diffs end
true
75dc5019616fe76bba6b8f66ec4825b32a87787d
Ruby
Nabox68/Mardi13-projet
/exo_14.rb
UTF-8
120
3.296875
3
[]
no_license
puts " Donne moi un nombre " nombre = gets.chomp nombre = nombre.to_i nombre.times do nombre -= 1 puts nombre end
true
1b92747557f09cdd57bf7a26e34ce3385dcd1739
Ruby
Kmullen444/RubyExercises
/adjacent_sum.rb
UTF-8
423
4.15625
4
[]
no_license
# def adjacent_sum(arr) # sum = [] # i = 0 # while i < arr.length-1 # sum << arr[i] + arr[i + 1] # i += 1 # end # return sum # end def adjacent_sum(arr) sum = [] arr.each_with_index do |num, i| if i != arr.length - 1 sum << num + arr[i + 1] end end return sum end print adjacent_sum([3, 7, 2, 11]) #=> [10, 9, 13] puts print adjacent_sum([2,5,1,9,2,4])# => [7,6,10,11,6] puts
true
a7b996c98b231baa57834ed352b3b15cdbf9495b
Ruby
philipla1989/curve-yc
/app/controllers/home_controller.rb
UTF-8
14,416
2.8125
3
[]
no_license
class HomeController < ApplicationController def index @stories = Story.all @ids = @stories.pluck(:id) @title = "Curve Your Career" @description = "Find fulfillment and happiness in your job. Hear about how people just like you were able to change careers." end def browse @title = "Curve Your Career | Browse" @description = "Browse stories based on what career changes are most relevant to you, ranging from people who started in Accounting to Software Development." end def about @title = "Curve Your Career | About" @description = "At Curve Your Career, you can browse stories from those who have been able to change their careers. You can learn about how they overcame barriers just like yours and what steps they took to make the transition." end def blog @title = "Curve Your Career | Blog" @description = "The best tips around how to overcome barriers and steps to changing your career" @content = {} @topics = Post.all.order(:topic).map(&:topic) @topics.each do |topic| @content[topic] = Post.where(topic: topic) end end def submit_story @title = "Curve Your Career | Submit" @description = "Share your own career change story so others gain the courage and guidance to change too." end def contact @title = "Curve Your Career | Contact" @description = "Interested in helping out with this project, sharing your insights, or just connecting with me? Email me at [email protected]" end def filter_by @search_ini = params[:ini_career_path] == "Anything" ? "" : params[:ini_career_path] @search_sub = params[:sub_career_path] == "Anything" ? "" : params[:sub_career_path] @stories = [] if @search_ini == "" && @search_sub == "" @stories = Story.all else stories_sub = Story.sub_career.where("careers.ini_career_path ilike :search AND careers.precedent_career != :search_i", search: "%#{@search_sub}%", search_i: "Initial") stories_ini = Story.sub_career.where("careers.ini_career_path ilike :search AND careers.precedent_career ilike :search_i", search: "%#{@search_ini}%", search_i: "Initial") stories_ini.each do |story| @stories << story if (story.careers.where("ini_career_path ilike :search AND precedent_career != :search_s", search: "%#{@search_sub}%", search_s: "Initial").count == 1) end stories_sub.each do |story| @stories << story if (story.careers.where(precedent_career: @search_ini).count == 1) end end @stories = @stories.uniq @ids = @stories.pluck(:id) @search_ini = "Anything" if @search_ini.empty? @search_sub = "Anything" if @search_sub.empty? end def sort_by ids = params[:ids].map(&:to_i) @stories = Story.where(id: ids) @careers = Career.where(story_id: ids) case params[:value] when "Newest" @stories = @stories.newest_first when "Oldest" @stories = @stories.oldest_first when "Longest" order_longest(@stories) when "Shortest" order_shortest(@stories) else @stories = Story.where(id: ids) end end def order_longest(stories) get_order_array(stories) @stories = Story.where(id: @ids) end def browse_by @type = params[:type] @career_path = {} @sub_career = Hash.new{|hsh,key| hsh[key] = {} } @story_ids = [] case @type when "explore" careers = Career.where(precedent_career: "Initial", ini_career_path: params[:career]).map(&:ini_career_path).uniq careers.each do |career| stories = Story.sub_career.where("careers.ini_career_path = ? AND careers.precedent_career = ?", career, "Initial") stories.each do |story| careers_array = story.careers.where.not(ini_career_path: career, precedent_career: "Initial") @precedent_career = "" careers_array.each do |career_item| if career_item.precedent_career == @precedent_career @sub_career[career_item.precedent_career] = @sub_career[career_item.precedent_career].present? ? @sub_career[career_item.precedent_career] << career_item.ini_career_path : [ career_item.ini_career_path ] @sub_career[career] = @sub_career[career].present? ? @sub_career[career] << career_item.ini_career_path : [ career_item.ini_career_path ] else @sub_career[career] = @sub_career[career].present? ? @sub_career[career] << career_item.ini_career_path : [ career_item.ini_career_path ] end @precedent_career = career_item.ini_career_path end @career_path = @career_path.deep_merge(@sub_career) end end when "pursue" careers = Career.where("precedent_career != ? AND ini_career_path = ?", "Initial", params[:career]) careers.each do |career| stories = Story.sub_career.where("careers.ini_career_path = ?", career.ini_career_path) stories.each do |story| if story.careers.count > 2 @careers_added = [] unless @story_ids.include?(story.id) Career.where("story_id = ? AND precedent_career != ?", story.id, "Initial").reorder('created_at DESC').each do |career_item| @careers_added << career_item.ini_career_path @sub_career[career_item.ini_career_path] = @sub_career[career_item.ini_career_path].present? ? @sub_career[career_item.ini_career_path] << story.careers.where.not(ini_career_path: @careers_added).map(&:ini_career_path) : story.careers.where.not(ini_career_path: @careers_added).map(&:ini_career_path) end @story_ids << story.id end else @sub_career[career.ini_career_path] = @sub_career[career.ini_career_path].present? ? @sub_career[career.ini_career_path] << career.precedent_career : [career.precedent_career] @sub_career[career.ini_career_path] = @sub_career[career.ini_career_path].uniq end end @career_path = @career_path.deep_merge(@sub_career) end else @career_path = nil end end def order_shortest(stories) get_order_array(stories) @stories = Story.find(@ids).sort_by {|m| @ids.reverse.index(m.id)} end def get_order_array(stories) hash = Hash.new{|hsh,key| hsh[key] = {} } @ids = [] stories.each do |story| if story.careers.present? size = 0 story.careers.each do |career| size += career.story_questions.size end hash["story_#{story.id}"].store 'size', size else hash["story_#{story.id}"].store 'size', 0 end hash["story_#{story.id}"].store 'story_id', story.id end hash.each do |key, val| @ids << val["story_id"] end end def browse_explore @title = "Curve Your Career | Browse | Explore" @description = "Browse career change stories based on your current career." @career_path = {} @sub_career = Hash.new{|hsh,key| hsh[key] = {} } careers = Career.where(precedent_career: "Initial").map(&:ini_career_path).uniq careers.each do |career| stories = Story.sub_career.where("careers.ini_career_path = ? AND careers.precedent_career = ?", career, "Initial") stories.each do |story| careers_array = story.careers.where.not(ini_career_path: career, precedent_career: "Initial") @precedent_career = "" careers_array.each do |career_item| if career_item.precedent_career == @precedent_career @sub_career[career_item.precedent_career] = @sub_career[career_item.precedent_career].present? ? @sub_career[career_item.precedent_career] << career_item.ini_career_path : [ career_item.ini_career_path ] @sub_career[career] = @sub_career[career].present? ? @sub_career[career] << career_item.ini_career_path : [ career_item.ini_career_path ] @sub_career[career] = @sub_career[career].uniq else @sub_career[career] = @sub_career[career].present? ? @sub_career[career] << career_item.ini_career_path : [ career_item.ini_career_path ] @sub_career[career] = @sub_career[career].uniq end @precedent_career = career_item.ini_career_path end @career_path = @career_path.deep_merge(@sub_career) end end end def browse_pursue @title = "Curve Your Career | Browse | Purse" @description = "Browse career change stories based on the specific career you want to transition into." @career_pursue = {} @career_path = Hash.new{|hsh,key| hsh[key] = {} } @story_ids = [] careers = Career.where.not(precedent_career: "Initial") careers.each do |career| stories = Story.sub_career.where("careers.ini_career_path = ?", career.ini_career_path) stories.each do |story| if story.careers.count > 2 @careers_added = [] unless @story_ids.include?(story.id) Career.where("story_id = ? AND precedent_career != ?", story.id, "Initial").reorder('created_at DESC').each do |career_item| @careers_added << career_item.ini_career_path @career_path[career_item.ini_career_path] = (@career_path[career_item.ini_career_path].present? && @career_path[career_item.ini_career_path] != story.careers.where.not(ini_career_path: @careers_added).map(&:ini_career_path)) ? @career_path[career_item.ini_career_path] << story.careers.where.not(ini_career_path: @careers_added).map(&:ini_career_path) : story.careers.where.not(ini_career_path: @careers_added).map(&:ini_career_path) end @story_ids << story.id end else @career_path[career.ini_career_path] = @career_path[career.ini_career_path].present? ? @career_path[career.ini_career_path] << career.precedent_career : [career.precedent_career] @career_path[career.ini_career_path] = @career_path[career.ini_career_path].uniq end end @career_pursue = @career_pursue.deep_merge(@career_path) end end def browse_stories_explore params[:sub_career] = params[:sub_career].gsub("-", " ") params[:ini_career] = params[:ini_career].gsub("-", " ") search_ini = params[:ini_career] == "Anything" ? "" : params[:ini_career] search_sub = params[:sub_career] == "Anything" ? "" : params[:sub_career] browse_stories(search_ini, search_sub) end def browse_stories_pursue params[:sub_career] = params[:sub_career].gsub("-", " ") params[:ini_career] = params[:ini_career].gsub("-", " ") search_ini = params[:ini_career] == "Anything" ? "" : params[:ini_career] search_sub = params[:sub_career] == "Anything" ? "" : params[:sub_career] browse_stories(search_ini, search_sub) end def browse_stories(search_ini, search_sub) @search_ini = search_ini @search_sub = search_sub @stories = [] stories_sub = Story.sub_career.where("careers.ini_career_path ilike :search AND careers.precedent_career != :search_i", search: "%#{@search_sub}%", search_i: "Initial") stories_ini = Story.sub_career.where("careers.ini_career_path ilike :search AND careers.precedent_career ilike :search_i", search: "%#{@search_ini}%", search_i: "Initial") stories_ini.each do |story| @stories << story if (story.careers.where("ini_career_path ilike :search AND precedent_career != :search_s", search: "%#{@search_sub}%", search_s: "Initial").count == 1) end stories_sub.each do |story| @stories << story if (story.careers.where(precedent_career: @search_ini).count == 1) end @stories = @stories.uniq @ids = @stories.pluck(:id) @title = [params[:ini_career], params[:sub_career]] respond_to do |format| format.html { render :stories } end end def dynamic_filter @values = [] case params[:type] when "ini_career" search_ini = params[:career] == "Anything" ? "" : params[:career] stories_i = Story.sub_career.where("careers.ini_career_path ilike :search AND precedent_career ilike :search_i", search: "%#{search_ini}%", search_i: "Initial") stories_p = Story.sub_career.where("careers.precedent_career ilike :search", search: "%#{search_ini}%") @stories = stories_i + stories_p @stories.uniq.each do |story| story.careers.each do |career| @values << career.ini_career_path if (career.precedent_career != "Initial" && career.ini_career_path != search_ini) end end @values = @values.sort! @type = :ini_career when "sub_career" search_ini = "" search_sub = params[:career] == "Anything" ? "" : params[:career] stories = Story.sub_career.where("careers.ini_career_path ilike :search AND careers.precedent_career != :search_s", search: "%#{search_sub}%", search_s: "Initial") stories.uniq.each do |story| story.careers.each do |career| @values << career.ini_career_path if ( career.precedent_career != search_sub && career.ini_career_path != search_sub) end end @values = @values.sort! @type = :sub_career else search_ini = "" search_sub = "" end @values = @values.uniq respond_to do |format| format.json { render json: [@values, @type] } end end end
true
59960fde41998d36baf96e2cf34cb687d475db52
Ruby
questionmarkexclamationpoint/evilution
/samples/triple.rb
UTF-8
790
2.953125
3
[ "MIT" ]
permissive
class Triple extend Evilution::Organism attr_accessor :one, :two, :three def fitness -((self.one + self.two + self.three) - 100).abs end def mutate! self.one = mutated_value(self.one, 0, 100, 0.1, 1) self.two = mutated_value(self.two, 0, 100, 0.1, 1) self.three = mutated_value(self.three, 0, 100, 0.1, 1) self end def recombine(other) Triple.new( one: (self.one + other.one) / 2, two: (self.two + other.two) / 2, three: (self.three + other.three) / 2 ) end def self.table_name :triples end def self.create_columns(table) super.create_columns(table) table.integer :one, null: false table.integer :two, null: false table.integer :three, null: false end end
true
e32f8a800c77040aed7318c82c99523c22fc7abf
Ruby
nico-ortiz/testVocacional-app
/services/SurveyServices.rb
UTF-8
2,388
2.765625
3
[ "MIT" ]
permissive
require "./models/init.rb" class SurveyServices def self.newSurvey(name) @survey = Survey.new(username: name) if @survey.save [201, { 'Location' => "surveys/#{@survey.id}" }, 'User created sucesfully'] @questions = Question.all return @survey, @questions else return ArgumentError end end def self.getAllSurveys() @surveys = Survey.all end def self.career_obtained(survey) # rubocop:todo Metrics/AbcSize, Metrics/MethodLength careersPoints = [] # rubocop:todo Layout/IndentationWidth, Naming/VariableName Career.all.each do |career| careersPoints.push({ 'career' => career.id, 'points' => 0 }) # rubocop:todo Naming/VariableName end choicesUser = survey.responses.map(&:choice_id) # rubocop:todo Naming/VariableName # Filtra las choices de Outcome, tal que estas choices son de las responses del user choices = Outcome.all.filter{ |elem| choicesUser.include? elem.choice_id} # rubocop:todo Naming/VariableName choices.each do |c| # rubocop:todo Naming/VariableName idx = careersPoints.index{ |elem| elem['career'] == c.career_id} # rubocop:todo Layout/IndentationWidth, Naming/VariableName # rubocop:enable Naming/VariableName if idx careersPoints[idx]['points'] += 1 # rubocop:todo Layout/IndentationWidth, Naming/VariableName end end # rubocop:todo Naming/VariableName careerWithMaxPoints = careersPoints.max_by{ |elem| elem['points']} # rubocop:todo Lint/UselessAssignment, Naming/VariableName # rubocop:enable Naming/VariableName end def self.responses(survey_id,choice_id) survey = Survey.find(id: survey_id) choice_id.each_with_index do |choice , i| response = Response.new(question_id: i+1, survey_id: survey.id, choice_id: choice) response.save end careerWithMaxPoints = self.career_obtained(survey) career_id = careerWithMaxPoints["career"] Finished_Survey.create(career_id: career_id) career = Career.find(id: career_id).name pointsTotal = careerWithMaxPoints["points"] survey.update career_id: career_id return career, pointsTotal end end
true
21461ace4937c38702dbbee47e694578b6263300
Ruby
xdougx/abstract_bundle
/lib/concerns/pagination_concern.rb
UTF-8
582
2.5625
3
[ "MIT" ]
permissive
# Module to manage pagination module PaginationConcern extend ActiveSupport::Concern PER_PAGE = 20 included do attr_reader(:current_page, :current_per_page) end def setup_pagination @current_page = params[:page] @current_per_page = params[:per_page] page per_page end def page current_page == 'all' ? current_page : get_page end def get_page @current_page = current_page.to_i current_page < 1 ? 1 : current_page end def per_page @current_per_page = current_per_page.blank? ? PER_PAGE : current_per_page.to_i end end
true
dca569275e33f8441a3523dd1f59145e75c99f92
Ruby
GaronHock/Homework
/anagrams/anagrams.rb
UTF-8
3,808
4.71875
5
[]
no_license
# Anagrams # Our goal today is to write a method that determines if two given words are anagrams. # This means that the letters in one word can be rearranged to form the other word. For example: # anagram?("gizmo", "sally") #=> false # anagram?("elvis", "lives") #=> true # Assume that there is no whitespace or punctuation in the given strings. # time complexity?? def anagram?(str1, str2) hash1 = Hash.new(0) hash2 = Hash.new(0) str1.each_char do |char| hash1[char] += 1 end str2.each_char do |char| hash2[char] += 1 end hash1 == hash2 end # p anagram?("gizmo", "sally") #false # p anagram?("elvis", "lives") #true # Phase I: # Write a method #first_anagram? that will generate and store #all the possible anagrams of the first string. Check if the second string is one of these. # Hints: # For testing your method, start with small input strings, otherwise you might wait a while # If you're having trouble generating the possible anagrams, look into this method. # What is the time complexity of this solution? What happens if you increase the size of the strings? # time complexity: O(n!) ==> n * (n-1)! def first_anagram?(str1, str2) possible = str1.chars.permutation.to_a possible.include?(str2.chars) end # p first_anagram?("dog", "god") # true # p first_anagram?("dog", "cat") # false # Phase II: # Write a method #second_anagram? that iterates over the first string. For each letter in the first string, find the index of that letter in the second string (hint: use Array#find_index) and delete at that index. The two strings are anagrams if an index is found for every letter and the second string is empty at the end of the iteration. # Try varying the length of the input strings. What are the differences between #first_anagram? and #second_anagram?? # iterate through str1 # if char.include?(str2) # index at str2 = "" # O(n) def second_anagram?(str1, str2) str1_array = str1.chars str2_array = str2.chars str1_array.each_with_index do |char, idx| if str2_array.include?(char) index2 = str2_array.index(char) str2_array[index2] = "" end end str2_array.join.empty? end # p second_anagram?("dog", "god") # true # p second_anagram?("dog", "cat") # false # Phase III: # Write a method #third_anagram? that solves the problem by sorting both strings alphabetically. # The strings are then anagrams if and only if the sorted versions are the identical. # What is the time complexity of this solution? Is it better or worse than #second_anagram?? # time complexity O(n) def third_anagram?(str1, str2) alpha = ("a".."z").to_a sorted_string_one = [] sorted_string_two = [] str1_array = str1.chars str2_array = str2.chars alpha.each_with_index do |char, idx| if str1_array.include?(char) sorted_string_one << char end end alpha.each_with_index do |char,idx| if str2_array.include?(char) sorted_string_two << char end end sorted_string_one == sorted_string_two end # p third_anagram?("dog", "god") # true # p third_anagram?("dog", "cat") # false # Phase IV: # Write one more method #fourth_anagram?. This time, use two Hashes to store the number of times each letter appears in both words. Compare the resulting hashes. # What is the time complexity? # Bonus: Do it with only one hash. # Discuss the time complexity of your solutions together, then call over your TA to look at them. # O(n) def fourth_anagram?(str1, str2) count(str1) == count(str2) end def count(str) hash = Hash.new(0) str.each_char do |char| hash[char] += 1 end hash end p fourth_anagram?("dog", "god") # true p fourth_anagram?("dog", "cat") # false
true
b3fbd5a106dda2c76cf5e379b6ed12243f726899
Ruby
andyrow123/CodeWars
/katas/6kyu/duplicate_encoder.rb
UTF-8
1,390
4.0625
4
[]
no_license
# The goal of this exercise is to convert a string to a new string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. # # Examples: # # "din" => "(((" # # "recede" => "()()()" # # "Success" => ")())())" # # "(( @" => "))((" # # # Notes: # # There is a flaw in the JS version, that may occur in the random tests. Do not hesitate to do several attempts before modifying your code if you fail there. # # Assertion messages may be unclear about what they display in some languages. If you read "...It Should encode XXX", the "XXX" is actually the expected result, not the input! (these languages are locked so that's not possible to correct it). def duplicate_encode(word) result = "" letter_array = word.downcase.each_char letter_count = letter_array.group_by(&:chr).map {|k, v| [k, v.size] } letter_array.each { |letter| letter_value = letter_count.select { |let| let[0] == letter}.map { |k, v| v.to_i} letter_value[0] > 1 ? result += ")" : result += "(" } result end duplicate_encode("din") duplicate_encode("recede") duplicate_encode("Success") duplicate_encode("(( @") # 1. get letters & count how many of each # 2. compare to original word and replace
true
b30858b9e2dcf2d46a158d34725e82af1df76e1e
Ruby
austinnormancore/ruby_binary_search_tree
/binary_search_tree.rb
UTF-8
3,510
3.59375
4
[]
no_license
class Node attr_accessor :data, :left, :right def initialize(data, left=nil, right=nil) @data = data @left = left @right = right end end class Tree attr_accessor :root def initialize(array) @array = array.uniq.sort! @root = build_tree(@array) unless array.nil? end def build_tree(array=@array) return if array.length < 1 mid = (array.length - 1) / 2 left = build_tree(array[0...mid]) right = build_tree(array[(mid + 1)...array.length]) root = Node.new(array[mid], left, right) return root end def insert(value, node = @root) return warn "Already exists" if (inorder().include?(value)) if value < node.data if node.left insert(value, node.left) else node.left = Node.new(value) end elsif value > node.data if node.right insert(value, node.right) else node.right = Node.new(value) end end end def delete(value, node = @root) return warn "Not in tree" if !(inorder().include?(value)) if value < node.data node.left = delete(value, node.left) elsif value > node.data node.right = delete(value, node.right) #no children elsif node.left.nil? && node.right.nil? node = nil #one child elsif node.left.nil? node = node.right elsif node.right.nil? node = node.left #two children else replacement = inorder(node.right)[0] delete(replacement) node.data = replacement end node end def find(value, node=@root) return "not found" if !(inorder().include?(value)) if value == node.data return node elsif value < node.data find(value, node.left) else find(value, node.right) end return node end def levelorder(node=@root) queue = [node] output = [] while !queue.empty? current = queue.shift output << current.data yield(current) if block_given? if current.left queue.push(current.left) end if current.right queue.push(current.right) end end return output end def inorder(node=@root, output = []) return if node.nil? inorder(node.left, output) output << node.data inorder(node.right, output) output end def preorder(node=@root, output = []) return if node.nil? output << node.data preorder(node.left, output) preorder(node.right, output) output end def postorder(node=@root, output = []) return if node.nil? postorder(node.left, output) postorder(node.right, output) output << node.data output end def depth(node=@root, counter=0) return counter if node.nil? left = depth(node.left, counter + 1) right = depth(node.right, counter + 1) left > right ? left : right end def balanced? left = depth(self.root.left) right = depth(self.root.right) (left - right).abs <= 1 ? true : false end def rebalance initialize(self.inorder) end end #driver script my_array = (Array.new(15) { rand(1..100) }) my_tree = Tree.new(my_array) puts "balanced?: " + my_tree.balanced?.to_s puts "level order: " + my_tree.levelorder.to_s puts "in order: " + my_tree.inorder.to_s puts "pre order: " + my_tree.preorder.to_s puts "postorder: " + my_tree.postorder.to_s puts "inserting 101, 102, 103" my_tree.insert(101) my_tree.insert(102) my_tree.insert(103) puts "balanced?: " + my_tree.balanced?.to_s puts "rebalancing" my_tree.rebalance puts "balanced?: " + my_tree.balanced?.to_s puts "level order: " + my_tree.levelorder.to_s puts "in order: " + my_tree.inorder.to_s puts "pre order: " + my_tree.preorder.to_s puts "postorder: " + my_tree.postorder.to_s
true
8c6b22468a82c341eb1133142b46f890efd8050f
Ruby
DefactoSoftware/MedischRekenenArcade
/lib/answer_handler/challenge_answer_handler.rb
UTF-8
908
2.53125
3
[]
no_license
class ChallengeAnswerHandler < AnswerHandler attr_reader :challenge, :user_challenge STANDARD_DEATH_CEILING = 3 def initialize(session, current_user, user_challenge, skill) super(session, current_user, skill) @challenge = user_challenge.challenge @user_challenge = user_challenge end def handle! super end def finished @finished ||= user_challenge.amount_good >= challenge.number_of_problems end def dead? @dead ||= session.damage && session.damage > STANDARD_DEATH_CEILING end def update_user_challenge! if dead? || finished reset_challenge! end end def redirect_path(_problem) if dead? || finished Rails.application .routes .url_helpers .challenges_path else Rails.application .routes .url_helpers .challenge_path(challenge.name) end end end
true
f9e732601bda0030c8bf3a498eaba099a69f0c52
Ruby
saifulAbu/leetcode
/771_jewel_and_stone.rb
UTF-8
352
3.640625
4
[]
no_license
require 'set' # @param {String} j # @param {String} s # @return {Integer} def num_jewels_in_stones(j, s) jewels = Set.new j.each_char do |jewel| jewels.add jewel end jewel_count = 0 s.each_char do |stone| jewel_count += 1 if jewels.include? stone end jewel_count end J = "z" S = "aAAbbbb" p num_jewels_in_stones J, S
true
06e77144a2794832825ed26f8ceaab29dabcf27e
Ruby
wahl77/Automatic-Website
/spec/facebook_spec.rb
UTF-8
1,660
2.546875
3
[]
no_license
require "spec_helper" describe "Facebook" do it "wish happy birthday", js: true do visit "http://www.facebook.com/events/list" user_info = get_user_info fill_in "email", with: user_info[:email] fill_in "pass", with: user_info[:password] click_on "Log In" #within "span.fbRemindersTitle" do find("strong").click end #within("#birthday_reminders_link") do find("i").click end #page.all(:css, "textarea[title$='Write a birthday wish on his timeline...']").each {|x| x.set(get_message)} #page.all(:css, "textarea[title$='Write a birthday wish on her timeline...']").each {|x| x.set(get_message)} page.all(:css, "textarea[title*='birthday']").each {|x| x.set(get_message); counter +=1} end # Get user information either from an environment variable of via keychain if using MacOSX and no environment variables # are set. Information is returned in the form of a hash with keys email and password def get_user_info # Return env variable if it is set pid = {} key_chain_data = `security find-internet-password -g -s www.facebook.com 2>&1` pid[:password] = ENV['FACEBOOK_PASS'] ? ENV['FACEBOOK_PASS'] : key_chain_data.scan(/password: .*/).first.scan(/\".*\"/).first.gsub(/\"/, "") pid[:email] = ENV['FACEBOOK_USER'] ? ENV['FACEBOOK_USER'] : key_chain_data.scan(/acct.*/).first.scan(/\".*\"/).first.gsub(/\"/, "").gsub("<blob>=", "") return pid end # Default message that is send # Further implementation will allow to send different messages to different people def get_message(user = nil) return "Happy birthday!!! (This was an automatically generated message)\n" end end
true
b316a51bbda1c31068d68c477b9968e7b4617988
Ruby
DetectiveAzul/cc_hw_w2d1
/Library/library.rb
UTF-8
759
3.671875
4
[]
no_license
class Library attr_reader :books def initialize(books) @books = books end def get_book_information_by_title(book_title) for book in @books return book if book[:title] == book_title end return nil end def get_book_rental_details_by_title(book_title) book = get_book_information_by_title(book_title) return book[:rental_details] if book != nil end def add_book(new_book) @books << { title: new_book, rental_details: { student_name: "", date: "" } } end def rent_book(book_title, student_name, due_date) rental_details = get_book_rental_details_by_title(book_title) rental_details[:student_name] = student_name rental_details[:date] = due_date end end
true
58d8e25f85d267a1b14c53cc3ae090e87541c0cb
Ruby
ChildeRowland/Above_Average
/Above_Average/app/models/travel.rb
UTF-8
3,952
2.828125
3
[]
no_license
class Travel < ActiveRecord::Base validates :walk, :inclusion => { :in => 0..1000000, :message => "numbers only please, no decimals or symbols"}, :exclusion => { :in => -1000000..-1, :message => "No negitive values please."} validates :bicycle, :inclusion => { :in => 0..1000000, :message => "numbers only please, no decimals or symbols"}, :exclusion => { :in => -1000000..-1, :message => "No negitive values please."} validates :train, :inclusion => { :in => 0..1000000, :message => "numbers only please, no decimals or symbols"}, :exclusion => { :in => -1000000..-1, :message => "No negitive values please."} validates :bus, :inclusion => { :in => 0..1000000, :message => "numbers only please, no decimals or symbols"}, :exclusion => { :in => -1000000..-1, :message => "No negitive values please."} validates :car, :inclusion => { :in => 0..1000000, :message => "numbers only please, no decimals or symbols"}, :exclusion => { :in => -1000000..-1, :message => "No negitive values please."} validates :plane, :inclusion => { :in => 0..1000000, :message => "numbers only please, no decimals or symbols"}, :exclusion => { :in => -1000000..-1, :message => "No negitive values please."} # validates_format_of # validates :walk, # :numericality => {:message => "Numbers only please, no decimals."} # validates :bicycle, # :numericality => {:message => "Numbers only please, no decimals."} # validates :train, # :numericality => {:message => "Numbers only please, no decimals."} # validates :bus, # :numericality => {:message => "Numbers only please, no decimals."} # validates :car, # :numericality => {:message => "Numbers only please, no decimals."} # validates :plane, # :numericality => {:message => "Numbers only please, no decimals."} attr_accessor :walk_string attr_accessor :bicycle_string attr_accessor :train_string attr_accessor :bus_string attr_accessor :car_string attr_accessor :plane_string before_save :sum_walked_distance before_save :sum_bicycle_distance before_save :sum_train_distance before_save :sum_bus_distance before_save :sum_car_distance before_save :sum_plane_distance before_save :normalize before_save :aggregate belongs_to :user WALK_POUNDS_CO2 = 0 BICYCLE_POUNDS_CO2 = 0 TRAIN_POUNDS_CO2 = 0.33 BUS_POUNDS_CO2 = 0.66 CAR_POUNDS_CO2 = 0.84 PLANE_POUNDS_CO2 = 1.0 private def sum_walked_distance walk_list = self.walk_string.split(" ") total = 0 walk_list.each do |num| total += num.to_f end self.walk = total / 5280 end def sum_bicycle_distance bicycle_list = self.bicycle_string.split(" ") total = 0 bicycle_list.each do |num| total += num.to_i end self.bicycle = total end def sum_train_distance train_list = self.train_string.split(" ") total = 0 train_list.each do |num| total += num.to_i end self.train = total end def sum_bus_distance bus_list = self.bus_string.split(" ") total = 0 bus_list.each do |num| total += num.to_i end self.bus = total end def sum_car_distance car_list = self.car_string.split(" ") total = 0 car_list.each do |num| total += num.to_i end self.car = total end def sum_plane_distance plane_list = self.plane_string.split(" ") total = 0 plane_list.each do |num| total += num.to_i end self.plane = total end def normalize self.normalized_walk = self.walk * WALK_POUNDS_CO2 self.normalized_bicycle = self.bicycle * BICYCLE_POUNDS_CO2 self.normalized_train = self.train * TRAIN_POUNDS_CO2 self.normalized_bus = self.bus * BUS_POUNDS_CO2 self.normalized_car = self.car * CAR_POUNDS_CO2 self.normalized_plane = self.plane * PLANE_POUNDS_CO2 end def aggregate self.total = self.normalized_walk + self.normalized_bicycle + self.normalized_train + self.normalized_bus + self.normalized_car + self.normalized_plane end end
true
1e7120efe6df89a232034afff866301e2b0bbaba
Ruby
lodqa/uri-forwarding-db
/app/lib/exceptions.rb
UTF-8
501
2.65625
3
[]
no_license
module Exceptions class PostProcessError < StandardError; end class GetCommandError < PostProcessError def initialize e super e end end class InvalidURIError < PostProcessError; end class GatewayError < PostProcessError def initialize(response) super "Gateway Error: the sever returns '#{response.code} #{response.message}'" end end class ParseError < PostProcessError def initialize super "Failed to parse the response body." end end end
true
ee5289598948dc60d2ad7b4bcfe74145379b52a4
Ruby
csoreff/ruby_linked_list
/lib/linked_list.rb
UTF-8
1,119
3.59375
4
[]
no_license
require 'pry' require_relative 'node' class LinkedList def initialize @head = nil end def prepend(info) @head = Node.new(info, @head) end def each node = @head while !node.nil? yield node node = node.next_node end end def to_s string = [] self.each { |node| string << node.info } string = string.join(", ") "LinkedList(#{string})" end def [](index) index_counter = 0 node = @head until index_counter == index node = node.next_node unless node.nil? index_counter += 1 end node.nil? ? nil : node end def insert(index, value) if index == 0 self.prepend(value) else index_counter = 0 node = @head while index_counter < index - 1 node = node.next_node unless node.nil? index_counter += 1 end if node.nil? nil else node.next_node = Node.new(value, node.next_node) end end end def remove(index) if index == 0 @head = @head.next_node else self[index-1].next_node = self[index+1] end end end
true
eb503f2e2f440fb60979fb60d569fb1b1daf19e4
Ruby
r-goodman/Hokuto-no-Kaimono
/app/models/basket.rb
UTF-8
611
2.640625
3
[]
no_license
class Basket < ActiveRecord::Base attr_accessible :purchased_at has_many :line_items has_one :transaction def total_price line_items.to_a.sum(&:unit_price) end # def initialize # @items = [] # end # def addToBasket(track_id) # currentItem = @items.find { |item| item == track_id } # unless currentItem # @items << track_id # end # end # def removeFromBasket(basket, track_id) # currentItem = @items.find { |item| item == track_id } # @items.each do |item| # if item == currentItem # basket.items.delete(item) # end # end # end end
true
28ec69b3b185f2e78451926be5d0088e518d4a16
Ruby
rhawkenson/hangman
/hangman.rb
UTF-8
5,848
4.15625
4
[]
no_license
#-----Psuedocode----- # 1. Load dictionary # 2. Choose random word between 5 and 12 characters # 3. Add hangman interface # 4. Display letters chosen so far: correct and incorrect # - Make chosen word an array and match the correct letter to #index_of # - Do not allow the user to guess the same letter more than once # 5. Create turns, prompt for user guess # 6. Update the display after each turn # - Write to the document for purposes of saving the file # - Base the stick man's growths on the length of a guesses array # - Add all occurrences of the letter in the word to the display # 7. If guesses = 0, end the game and reveal the word # 8. Give player the option to save and quit at the beginning of each turn # 9. At beginning, allow new game to start or open and continue saved game require 'yaml' class Word attr_reader :game_word def initialize @game_word = char_limit(random_line) end private def random_line dictionary = File.readlines("dictionary.txt") line_number = rand(0..(dictionary.length)) chosen_line = dictionary[line_number].downcase.chomp chosen_line end def char_limit(word) if word.length > 12 char_limit(random_line) elsif word.length < 5 char_limit(random_line) else word end end end class GameBoard attr_reader :game_word def initialize @game_word = Word.new.game_word beginning end def beginning puts "\n\n\n\n\n Welcome to hangman! Would you like to start a new game or open a saved game? Type 'new' for a new game or type 'open' to open a saved game" game = gets.chomp if game == 'new' puts "\n\n\n\n\nInstructions: You have 10 guesses to figure out the secret word. Only incorrect guesses will count against you. If you want to quit and save, type 'save' instead of your guess during any turn." guesses_remaining = 10 @correct_guesses = Array.new(@game_word.length, "_") @incorrect_guesses = Array.new PlayGame.new(@game_word, guesses_remaining, @correct_guesses, @incorrect_guesses) elsif game == 'open' PlayGame.load_game else "Invalid selection. Type 'new' for a new game or type 'open' to open a saved game" beginning end end def self.display @display = puts " ___ | | #{$inserted_shapes[0]} | #{$inserted_shapes[6]}#{$inserted_shapes[2]}#{$inserted_shapes[1]}#{$inserted_shapes[3]}#{$inserted_shapes[7]} | #{$inserted_shapes[8]}#{$inserted_shapes[4]} #{$inserted_shapes[5]}#{$inserted_shapes[9]} | ____|____" end end class PlayGame attr_accessor :word, :word_arr, :guesses, :correct, :incorrect, :save def initialize(word, guesses, correct = yaml[0].correct, incorrect = yaml[0].incorrect) @word = word @word_arr = @word.split("") @guesses = guesses @correct = correct @incorrect = incorrect @save = false play end def play until (@word_arr == @correct) || (@guesses == 0) || (@save == true) do puts "\n\nWhat is your guess?" user_guess = gets.chomp evaluate(user_guess) end if @guesses == 0 puts "The word you were looking for was '#{@word}'\n\n" elsif @word_arr == @correct puts "YOU WIN! You are a master wordsmith. Congratulations!\n\n" elsif @save == true puts "You have chosen to save and exit. To reopen this game, start Hangman and type 'open' when prompted." else puts "Hmm something is not working properly..\n\n" end end def evaluate(guess) if guess == 'save' @save = true save_game elsif guess.length > 1 puts "Invalid guess. Please only enter one letter with no special characters or spaces" elsif(@correct.include? guess) || (@incorrect.include? guess) puts "You have already guessed that letter. Please try again." elsif @word_arr.include? guess @word_arr.each_with_index do |letter, index| if letter == guess @correct[index] = letter end end else @incorrect.push(guess) @guesses -= 1 $inserted_shapes.insert(@incorrect.length-1, $hangman_shapes[@incorrect.length-1]) end display_update end def display_update GameBoard.display puts "\nCorrect guesses: #{@correct.join}" puts "Incorrect guesses: #{@incorrect.join}" puts "Remaining guesses: #{@guesses}" end def save_game puts "What username would you like to use to save your game?" username = gets.chomp dirname = "saved_games" Dir.mkdir(dirname) unless File.exist? dirname puts "You game file is called 'saved_games/#{username}.yml" filename = "saved_games/#{username}.yml" File.open(filename, 'w') { |f| YAML.dump([] << self, f) } exit end def self.load_game unless Dir.exist?('saved_games') puts 'No saved games found. Starting new game...' GameBoard.new return end games = saved_games deserialize(load_file(games)) end def self.load_file(games) loop do puts "What username did you use to save your game?" puts "Users:" puts saved_games username = gets.chomp file = "#{username}" return username if saved_games.include?(file) puts 'The game you requested does not exist.' end end def self.deserialize(username) yaml = YAML.load_file("./saved_games/#{username}.yml") PlayGame.new(yaml[0].word, yaml[0].guesses, yaml[0].correct, yaml[0].incorrect) end def self.saved_games Dir['./saved_games/*'].map { |file| file.split('/')[-1].split('.')[0] } end end $inserted_shapes = [" "," "," "," "," "," "," "," "," "," ",] $hangman_shapes = ["O","|","-","-","/","\\","`","`","_","_"] Hangman = GameBoard.new
true
ef7ba06e2a0d5f70b1fcf9b66095ed7a4ca46411
Ruby
solnic/sql
/lib/sql/generator/emitter/conditional_parenthesis.rb
UTF-8
708
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# encoding: utf-8 module SQL module Generator class Emitter # Add conditional parenthesization to an emitter module ConditionalParenthesis # Emit contents of the block within parenthesis when necessary # # @return [Boolean] # # @api private def parenthesis parenthesize? ? super : yield end # Test if the expression needs to be parenthesized # # @return [Boolean] # # @api private def parenthesize? fail NotImplementedError, "#{self}##{__method__} is not implemented" end end # ConditionalParenthesis end # Emitter end # Generator end # SQL
true
442a7bd5844c2e7bffbf79b1046cb11e48e13daa
Ruby
jacksimmonds0/Music-Library
/app/models/album.rb
UTF-8
619
2.578125
3
[]
no_license
class Album < ActiveRecord::Base belongs_to :artist belongs_to :genre has_many :songs, dependent: :destroy validates :name, presence: true # same year validation as in the artist model validates :year, presence: true, :inclusion => 1900..Time.now.year # paperclip gem used to add album artwork to the application has_attached_file :image, styles: { large: "600x600>", medium: "300x300>", thumb: "150x150#"} validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ # method to get the total number of songs for the tracks in the album def total_songs self.songs.size end end
true
73b25bb0620830635360ba22a417fa8e012a80d1
Ruby
abdellani/solved-challenges
/leetcode/15. 3Sum.rb
UTF-8
1,384
3.25
3
[]
no_license
=begin source: https://leetcode.com/problems/3sum/ =end # @param {Integer[]} nums # @return {Integer[][]} def three_sum(nums) p=Hash.new(0) n=Hash.new(0) z=0 nums.each do |num| case true when num==0 z+=1 when num>0 p[num]+=1 when num<0 n[num]+=1 end end results=[] results<<[0,0,0]if z>2 pn=p.keys nn=n.keys #p+p+n=0 #p+0+n=0 #n+n+p=0 #p+p+n=0 i=0 a= pn[i] results<<[a,a,-2*a] if p[a]>1 and n[-2*a]>0 while i<pn.length-1 a= pn[i] j=i+1 b= pn[j] results<<[b,b,-2*b] if p[b]>1 and n[-2*b]>0 while j<pn.length b= pn[j] results<<[a,b,-(a+b)] if n[-(a+b)]>0 j+=1 end i+=1 end #n+n+p=0 i=0 a= nn[i] results<<[a,a,-2*a] if n[a]>1 and p[-2*a]>0 while i<nn.length-1 a= nn[i] j=i+1 b= nn[j] results<<[b,b,-2*b] if n[b]>1 and p[-2*b]>0 while j<nn.length b= nn[j] results<<[a,b,-(a+b)] if p[-a-b]>0 j+=1 end i+=1 end #p+0+n=0 if z>0 i=0 while i<pn.length a= pn[i] results<<[a,-a,0] if n[-a]>0 i+=1 end end return results
true
3565bf084998bdf18eae09c4cda0aaa5b487d461
Ruby
puppetlabs/puppet-resource_api
/lib/puppet/resource_api/simple_provider.rb
UTF-8
2,796
2.53125
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true module Puppet; end # rubocop:disable Style/Documentation module Puppet::ResourceApi # This class provides a default implementation for set(), when your resource does not benefit from batching. # Instead of processing changes yourself, the `create`, `update`, and `delete` functions, are called for you, # with proper logging already set up. # Note that your type needs to use `name` as its namevar, and `ensure` in the conventional way to signal presence # and absence of resources. class SimpleProvider def set(context, changes) changes.each do |name, change| is = if context.type.feature?('simple_get_filter') change.key?(:is) ? change[:is] : (get(context, [name]) || []).find { |r| r[:name] == name } else change.key?(:is) ? change[:is] : (get(context) || []).find { |r| r[:name] == name } end context.type.check_schema(is) unless change.key?(:is) should = change[:should] raise 'SimpleProvider cannot be used with a Type that is not ensurable' unless context.type.ensurable? is = SimpleProvider.create_absent(:name, name) if is.nil? should = SimpleProvider.create_absent(:name, name) if should.nil? name_hash = if context.type.namevars.length > 1 # pass a name_hash containing the values of all namevars name_hash = {} context.type.namevars.each do |namevar| name_hash[namevar] = change[:should][namevar] end name_hash else name end if is[:ensure].to_s == 'absent' && should[:ensure].to_s == 'present' context.creating(name) do create(context, name_hash, should) end elsif is[:ensure].to_s == 'present' && should[:ensure].to_s == 'absent' context.deleting(name) do delete(context, name_hash) end elsif is[:ensure].to_s == 'present' context.updating(name) do update(context, name_hash, should) end end end end def create(_context, _name, _should) raise "#{self.class} has not implemented `create`" end def update(_context, _name, _should) raise "#{self.class} has not implemented `update`" end def delete(_context, _name) raise "#{self.class} has not implemented `delete`" end # @api private def self.create_absent(namevar, title) result = if title.is_a? Hash title.dup else { namevar => title } end result[:ensure] = 'absent' result end end end
true
f67249ccba056d6a4d9099d31041b3e0a55adcee
Ruby
sarah12345/pair-matcher
/app/services/pair_matcher_service.rb
UTF-8
630
2.921875
3
[]
no_license
class PairMatcherService class << self def generate_pairs(team_id) eligible_members = Member.where(team_id: team_id).to_a pairs = [] while eligible_members.present? do pairs << generate_pair(eligible_members) end pairs end private def generate_pair(members) member1 = pull_random_member_from_list(members) member2 = pull_random_member_from_list(members) Pair.new(member1: member1, member2: member2) end def pull_random_member_from_list(members) random_number = rand(members.size) members.delete_at(random_number) end end end
true
c3a95b44b30678e22f7b585139dc69af5228cfe3
Ruby
mahalingaprabu/Myproject
/lib/role.rb
UTF-8
451
2.78125
3
[]
no_license
class Role attr_reader :key, :id private @@roles=Set.new @@role_id_map={} def initialize(key,id) @key=key @id=id @@roles << self @@role_id_map[id]=self end public None=Role.new(:none,0) Admin=Role.new(:admin,1) LeaveApprover=Role.new(:leave_approver,2) def self.roles @@roles end def to_s {@key => @id} end def self.find(role_id) @@role_id_map[role_id] end def self.find_all(*role_ids) role_ids.collect{|x| @@role_id_map[x]} end end
true
df394c1808824f28c2b53baf0810ecb78602496b
Ruby
warren34/morpionjeu
/morpiongames/lib/app/game.rb
UTF-8
3,798
3.625
4
[]
no_license
class Game attr_accessor :player1, :player2, :board_game # method creating 2 players and the board def initialize @player1 = Player.new("X") @player2 = Player.new("O") @board_game = Board.new end # method puting the symbol of the players in the grid def placement(player) puts "Merci de rentrer ton choix de case #{player.name}" choice = gets.chomp.to_sym #we check the choice made by the player is the valide key while !(@board_game.hash_board.has_key?(choice)) || @board_game.hash_board[choice] != " " puts "Merci de rentrer une position valide et libre" choice = gets.chomp.to_sym end #we put the symbol of the player in the case @board_game.hash_board[choice] = player.symbol end # method checking if a player won, if yes which player def victory? #victory player1 if @board_game.hash_board[:a1] == @player1.symbol && @board_game.hash_board[:b1] == @player1.symbol && @board_game.hash_board[:c1] == @player1.symbol || @board_game.hash_board[:a2] == @player1.symbol && @board_game.hash_board[:b2] == @player1.symbol && @board_game.hash_board[:c2] == @player1.symbol || @board_game.hash_board[:a3] == @player1.symbol && @board_game.hash_board[:b3] == @player1.symbol && @board_game.hash_board[:c3] == @player1.symbol || @board_game.hash_board[:a1] == @player1.symbol && @board_game.hash_board[:a2] == @player1.symbol && @board_game.hash_board[:a3] == @player1.symbol || @board_game.hash_board[:b1] == @player1.symbol && @board_game.hash_board[:b2] == @player1.symbol && @board_game.hash_board[:b3] == @player1.symbol || @board_game.hash_board[:c1] == @player1.symbol && @board_game.hash_board[:c2] == @player1.symbol && @board_game.hash_board[:c3] == @player1.symbol || @board_game.hash_board[:a1] == @player1.symbol && @board_game.hash_board[:b2] == @player1.symbol && @board_game.hash_board[:c3] == @player1.symbol || @board_game.hash_board[:c1] == @player1.symbol && @board_game.hash_board[:b2] == @player1.symbol && @board_game.hash_board[:a3] == @player1.symbol return @player1 #victory player2 elsif @board_game.hash_board[:a1] == @player2.symbol && @board_game.hash_board[:b1] == @player2.symbol && @board_game.hash_board[:c1] == @player2.symbol || @board_game.hash_board[:a2] == @player2.symbol && @board_game.hash_board[:b2] == @player2.symbol && @board_game.hash_board[:c2] == @player2.symbol || @board_game.hash_board[:a3] == @player2.symbol && @board_game.hash_board[:b3] == @player2.symbol && @board_game.hash_board[:c3] == @player2.symbol || @board_game.hash_board[:a1] == @player2.symbol && @board_game.hash_board[:a2] == @player2.symbol && @board_game.hash_board[:a3] == @player2.symbol || @board_game.hash_board[:b1] == @player2.symbol && @board_game.hash_board[:b2] == @player2.symbol && @board_game.hash_board[:b3] == @player2.symbol || @board_game.hash_board[:c1] == @player2.symbol && @board_game.hash_board[:c2] == @player2.symbol && @board_game.hash_board[:c3] == @player2.symbol || @board_game.hash_board[:a1] == @player2.symbol && @board_game.hash_board[:b2] == @player2.symbol && @board_game.hash_board[:c3] == @player2.symbol || @board_game.hash_board[:c1] == @player2.symbol && @board_game.hash_board[:b2] == @player2.symbol && @board_game.hash_board[:a3] == @player2.symbol return @player2 else return false end end # method checking if the result is a draw def draw? !(@board_game.hash_board.value?(" ")) end # method displaying the result of the game def show_result if victory? == @player1 || victory? == @player2 puts "Bravo !!! Tu as gagné #{victory?.name}" else puts "C'est un match nul !!!" end end end
true
d3bee783c72e4bb43ada2c7e1a7349552dd31438
Ruby
C1C0/minesweeper_ruby
/v_palovic_291219/module-Random.rb
UTF-8
1,251
3.015625
3
[ "MIT" ]
permissive
module RD def generateBombs(fields, maxBombs, size, notX, notY) planted = 0 x = 0 y = 0 # siblingsX = [-1,0,+1,+1,+1,0,-1,-1] # siblingsY = [-1,-1,-1,0,+1,+1,+1,0] while planted < maxBombs for i in fields bomb = rand(0..1) #put bombs only if ... if x != notX && y != notY && x != notX -1 && y != notY-1 && x != notX && y != notY-1 && x != notX +1 && y != notY-1 && x != notX +1 && y != notY && x != notX +1 && y != notY+1 && x != notX && y != notY+1 && x != notX -1 && y != notY+1 && x != notX -1 && y != notY fields[[x,y]].state = bomb if bomb == 1 planted += 1 else end end #first do columns x += 1 if x > size[0] #then next row if y == size[1] break end x = 0 y += 1 end end x = 0 y = 0 end end end
true
800157d596ea79b52fead5a4ceda31ef7846a6b4
Ruby
thoumc/ar-exercises
/exercises/exercise_6.rb
UTF-8
892
2.65625
3
[]
no_license
require_relative '../setup' require_relative './exercise_1' require_relative './exercise_2' require_relative './exercise_3' require_relative './exercise_4' require_relative './exercise_5' puts "Exercise 6" puts "----------" @store1.employees.create( first_name: "Manager1", last_name: "Virani", hourly_rate: 60 ) @store1.employees.create( first_name: "StaffA", last_name: "A", hourly_rate: 40 ) @store1.employees.create( first_name: "StaffB", last_name: "B", hourly_rate: 40 ) @store2.employees.create( first_name: "Manager2", last_name: "Jerry", hourly_rate: 60 ) @store2.employees.create( first_name: "StaffC", last_name: "C", hourly_rate: 40 ) @store2.employees.create( first_name: "StaffD", last_name: "D", hourly_rate: 40 ) @store2.employees.create( first_name: "StaffE", last_name: "E", hourly_rate: 40 ) # Your code goes here ...
true
ec57328425c833efed40612d0989bdf770a75a1d
Ruby
stephensxu/rpn-calculator
/lib/rpn_expression.rb
UTF-8
1,443
4.03125
4
[ "MIT" ]
permissive
require "stack" def factorial(n) result = 1 n.downto(1) do |i| result *= i end result end SYMBOL_TABLE = { "+" => lambda { |stack, x, y| x + y }, "-" => lambda { |stack, x, y| x - y }, "*" => lambda { |stack, x, y| x * y }, "!" => lambda { |stack, n| factorial(n) }, "%" => lambda { |stack, n| x % y }, "if" => lambda { |stack, x, y, z| x == 0 ? y : z }, ">" => lambda { |stack, x, y| x > y ? 1 : 0 }, "loop" => lambda do |stack, n| op = stack.pop if op == "add" result = 0 n.times do result += stack.pop end result elsif op == "mul" result = 1 n.times do result *= stack.pop end result end end } class RPNExpression def initialize(expr) @expr = expr end def evaluate stack = Stack.new tokens.each do |token| if numeric?(token) stack.push(token.to_i) elsif operator?(token) args = [] (SYMBOL_TABLE[token].arity - 1).times do args.unshift(stack.pop) end stack.push(call_operator(stack, token, *args)) else stack.push(token) end end stack.pop end private def tokens @expr.split(" ") end def numeric?(token) token =~ /^-?\d+$/ end def operator?(token) SYMBOL_TABLE.key?(token) end def call_operator(stack, operator, *args) SYMBOL_TABLE[operator].call(stack, *args) end end
true
5473d3728a8eb442c3e92c1f56491f7f147dfe56
Ruby
gd875/interpolation-super-power-bootcamp-prep-000
/lib/display_rainbow.rb
UTF-8
356
3.78125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your #display_rainbow method here def color_printer(color) return "#{color[0].upcase}: #{color}" end def display_rainbow(colors) puts "#{color_printer(colors[0])}, #{color_printer(colors[1])}, #{color_printer(colors[2])}, #{color_printer(colors[3])}, #{color_printer(colors[4])}, #{color_printer(colors[5])}, #{color_printer(colors[6])}" end
true
8f8e6d5c56b46c5703f19328cdd2ea0b1bacf9e6
Ruby
Krhorsch/oo-cash-register-v-000
/lib/cash_register.rb
UTF-8
855
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class CashRegister attr_accessor :items, :discount, :total, :last_transaction def initialize(discount = 0) @total = 0 @discount = discount @items = [] end def add_item(item, price, quantity=1) new_total = total + price * quantity self.last_transaction = price * quantity self.total = new_total self.total counter = 0 while counter < quantity do self.items << item counter += 1 end end def apply_discount new_total = self.total - (self.total*discount/100) self.total = new_total if self.discount == 0 "There is no discount to apply." else "After the discount, the total comes to $#{self.total}." end end def void_last_transaction new_total = self.total - self.last_transaction self.total = new_total end end
true
13d7e670200304eecbcf70acc73796354bb098c4
Ruby
verynear/energia-calc
/vendor/gems/kilomeasure/spec/kilomeasure/formula_spec.rb
UTF-8
960
2.609375
3
[]
no_license
require 'kilomeasure/formula' describe Kilomeasure::Formula do describe '#run' do it 'calculates an expression' do formula = described_class.new(name: :foo, expression: '1 + 1') formula.run expect(formula.value).to eq(2) end it 'substitutes provided inputs' do formula = described_class.new(name: :foo, expression: 'apple + banana') formula.run(apple: 1, banana: 2) expect(formula.value).to eq(3) end it 'raises an exception if a dependency is missing' do formula = described_class.new(name: :foo, expression: 'apple + banana') expect { formula.run(apple: 1) } .to raise_error(ArgumentError, 'Missing required inputs [:banana]') end end describe '#dependencies' do it 'lists out variable names for formula' do formula = described_class.new(name: :foo, expression: 'apple + banana') expect(formula.dependencies).to eq([:apple, :banana]) end end end
true
2f07f8dfd046aafe0c5f33dbb55b3452ee81ad8a
Ruby
wfslithtaivs/AA_Homeworks_and_Projects
/ClassesBorcsh/w1d3/recursion.rb
UTF-8
3,621
3.796875
4
[]
no_license
# range def range(first, last) return [first] if first == last range(first, last - 1) + [last] end # exponential def exp(b, n) n == 0 ? 1 : exp(b, n-1) * b end p exp(2, 2) p exp(2, 8) p exp(3, 3) p exp(10, 3) def exp2(b, n) return 0 if n == 0 return b if n == 1 if n.even? holder = exp2(b, n / 2) holder * holder else holder = exp2(b, (n-1)/2) b * holder * holder end end p exp2(2, 2) p exp2(2, 8) p exp2(3, 3) p exp2(10, 3) # deep dup def deepdup(arr) arr.map{|el| el.is_a?(Array) ? deepdup(el) : el} end robot_parts = [ ["nuts", "bolts", "washers"], ["capacitors", "resistors", "inductors"] ] robot_parts_copy = deepdup(robot_parts) # shouldn't modify robot_parts robot_parts_copy[1] << "LEDs" # but it does p robot_parts[1] # => ["capacitors", "resistors", "inductors", "LEDs"] #recursive def fib(n) return if n < 1 return [1] if n == 1 return [1,1] if n == 2 lastfib = fib(n - 1) lastfib << lastfib.last(2).reduce(:+) end p fib(2) p fib(3) p fib(4) p fib(15) #iterative fib def fib_iterative(n) result = [1,1] return [] if n < 1 return result[0..0] if n == 1 return result if n == 2 (n-2).downto(1) do result << result.last(2).reduce(:+) end result end p fib_iterative(2) p fib_iterative(3) p fib_iterative(4) p fib_iterative(15) #array subsets def subsets(array) return [[]] if array.empty? return [[], array] if array.length == 1 s = subsets(array[0..-2]) s + s.map{|arr| arr + [array.last]} end p subsets([]) == [[]] p subsets([1]) == [[], [1]] p subsets([1, 2]) == [[], [1], [2], [1, 2]] p subsets([1, 2, 3]) == [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] # permutations def permutations(array) return [array] if array.length == 1 return [array, array.reverse] if array.length == 2 array.map do |el| perm = permutations(array - [el]) [([el] + perm[0]).flatten] + [([el] + perm[1]).flatten] end.flatten 1 end p permutations([1, 2, 3]) == [1,2,3].permutation.to_a # b search def bsearch(array, target) return nil if array.empty? || array.first > target || array.last < target half = array.length / 2 first_half = array[0...half] second_half = array[half + 1..-1] if array[half] == target half elsif array[half] > target bsearch(first_half, target) else bs = bsearch(second_half, target) bs.nil? ? nil : half + bs + 1 end end p "-------B-Search-------------" p bsearch([1, 2, 3], 1) # == 0 p bsearch([2, 3, 4, 5], 3) # == 1 p bsearch([2, 4, 6, 8, 10], 6) # == 2 p bsearch([1, 3, 4, 5, 9], 5) # == 3 p bsearch([1, 2, 3, 4, 5, 6], 6) # == 5 p bsearch([1, 2, 3, 4, 5, 6], 0) # == nil p bsearch([1, 2, 3, 4, 5, 7], 6) # == nil p bsearch([1, 3, 5, 7, 9, 12], 11) # == nil # Merge sort def merge(arr1, arr2) res = [] until arr1.empty? && arr2.empty? if arr1.empty? res += arr2 arr2 = [] elsif arr2.empty? res += arr1 arr1 = [] elsif arr1.first >= arr2.first res << arr2.shift else res << arr1.shift end end res end p "------Merge sorted arrays------" p merge([1, 2, 5], [3, 4, 6]) def mergesort(array) return array if array.length < 2 half = array.length / 2 first_half = mergesort(array[0...half]) second_half = mergesort(array[half..-1]) merge(first_half, second_half) end p "------Sort array------" p mergesort([1, 2, 5, 3, 4, 6].reverse.shuffle) p "------Make Change-------" def greedy_make_change(amount, coins = [25, 10, 5, 1]) coins.sort.reverse.map do |coin| f = amount/coin amount %= coin Array.new(f){coin} end.flatten end p greedy_make_change(24, [10, 7, 1])
true
b1d330ebb0318c03982180a0f6227a3e3101dd3b
Ruby
klavinslab/ProtocolsForReview
/manager/protocol/make_media_for_comp_cell_batch/protocol.rb
UTF-8
1,604
3.03125
3
[]
no_license
# This is a default, one-size-fits all protocol that shows how you can # access the inputs and outputs of the operations associated with a job. # Add specific instructions for this protocol! class Protocol def main operations.make show do title "Gather the Following Items:" check "#{operations.length} 1 L bottle(s)" check "#{operations.length} 500 mL bottle(s)" check "50% Glycerol" end show do title "Add 50% Glycerol to 500mL bottles" note "using a serological pipette, add 100 mL of 50% Glycerol to each 500mL bottle" end show do title "Measure Water and Mix" note "Take the bottle to the DI water carboy and add water up to the 500 mL mark. Mix solution" end show do title "Label and bring over to the autoclaving station" note "Label bottle(s) with '10% Glycerol', your initials, the date, and #{operations.map { |op| op.output("Glycerol").item.id }.to_sentence}" note "Bring to autoclave station" end show do title "Prepare DI water" note "fill each 1L bottle with filtered water to the 1 L mark" note "Label bottle(s) with 'DI water' your initials, the date, and #{operations.map { |op| op.output("Glycerol").item.id }.to_sentence}" note "bring to autoclave station" end operations.each do |op| op.output("Water").item.move "Bench" op.output("Glycerol").item.move "Bench" end operations.store interactive: false return {} end end
true
e9f74cd46b3558d0b643021fcd745faa4001a57a
Ruby
adar4reg/ci-scripts
/testlink/testlink_import_test_case_systemtest.rb
UTF-8
6,563
2.546875
3
[]
no_license
#!/usr/bin/env ruby require 'csv' require 'xmlrpc/client' require 'spreadsheet' xlsfile = ARGV[0] def get_test_project_id args = {devKey: @key, testprojectname: 'DEMO'} r = @server.call('tl.getTestProjectByName', args) r['id'] end def create_test_suite(suite, parentid) if parentid == '' args = {devKey: @key, testsuitename: suite, prefix: 'DEMO'} r = @server.call('tl.getTestSuite', args) if r.size == 0 @args = {devKey: @key, testprojectid: @test_project_id, testsuitename: suite} r = @server.call('tl.createTestSuite', @args) end id = r[0]['id'] else args = {devKey: @key, testsuiteid: parentid} r = @server.call('tl.getTestSuitesForTestSuite', args) @action = 'create' if r.size != 0 if r.has_key? 'name' if r['name'] == suite id = r['id'] @action = '' end else r.each {|hash| if hash[1]['name'] == suite id = hash[1]['id'] @action = '' break end } end end if @action == 'create' @args = {devKey: @key, testprojectid: @test_project_id, testsuitename: suite, parentid: parentid} r = @server.call('tl.createTestSuite', @args) id = r[0]['id'] end end id end def create_test_case(suite, testcasename, summary, preconditions, steps, top_suite_id, importance) test_suite_id = create_test_suite(suite, top_suite_id) args = {devKey: @key, testprojectid: @test_project_id, testsuiteid: test_suite_id, testcasename: testcasename, authorlogin: 'dicktsai', preconditions: preconditions, summary: summary, steps: steps, importance: importance} r = @server.call('tl.createTestCase', args) puts r end @server = XMLRPC::Client.new2( uri = 'http://testlink.arimacomm.com.tw/testlink/lib/api/xmlrpc/v1/xmlrpc.php') @key = "a3395724f6e5d163350946345886d571" @test_project_id = get_test_project_id Spreadsheet.client_encoding = 'UTF-8' path = '/media/d/workspace/st/' file = path + xlsfile book = Spreadsheet.open file sheets = book.worksheets sheets.each{ |s| @suite = s.name if @suite == 'Subject' || @suite == 'Subject ' || @suite == 'subject' || @suite == 'subject ' sheet0 = book.worksheet @suite if sheet0[3,8] != nil && sheet0[3,8].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[4,8].lstrip.rstrip elsif sheet0[3,7] != nil && sheet0[3,7].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[4,7].lstrip.rstrip elsif sheet0[4,8] != nil && sheet0[4,8].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[5,8].lstrip.rstrip elsif sheet0[4,7] != nil && sheet0[4,7].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[5,7].lstrip.rstrip elsif sheet0[5,8] != nil && sheet0[5,8].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[6,8].lstrip.rstrip elsif sheet0[5,7] != nil && sheet0[5,7].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[6,7].lstrip.rstrip elsif sheet0[6,8] != nil && sheet0[6,8].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[7,8].lstrip.rstrip elsif sheet0[6,7] != nil && sheet0[6,7].downcase.lstrip.rstrip == 'subject' @top_suite = sheet0[7,7].lstrip.rstrip end parentid = '' @top_suite = @top_suite.gsub('\\','').gsub('Functionality','').gsub('functionality','').lstrip.rstrip @top_suite_id = create_test_suite(@top_suite, parentid) end sheetname = @suite.downcase.lstrip.rstrip if sheetname != 'check point' && sheetname != 'subject' && sheetname != 'summary' && sheetname != 'history' && sheetname != 'abbreviation' && sheetname != 'history' && sheetname != 'top app' sheet1 = book.worksheet @suite @suite = @suite.lstrip.rstrip parentid = '' @test_project_id = get_test_project_id sheet1.each do |row| if row[0] != nil && row[0].to_s.downcase.match('[a-z][0-9]') && !row[0].to_s.match('\AStep[0-9]{1,3}\Z') && !row[0].to_s.match('\Astep[0-9]{1,3}\Z') || row[0].to_s.downcase.match('^youtube....[0-9]{1,3}') && !row[0].to_s.match('\Acase[0-9]\Z') @step_array = [] @stid = row[0] @step = 1 sheet1.each do |row| @info_id = row[0].to_s if row[0] != nil && row[0].to_s.downcase.match('[a-z][0-9]') && !row[0].to_s.match('\AStep[0-9]{1,3}\Z') && !row[0].to_s.match('\Astep[0-9]{1,3}\Z') || row[0].to_s.downcase.match('^youtube....[0-9]{1,3}') && !row[0].to_s.match('\Acase[0-9]\Z') @info_id_bak = @info_id else @info_id = @info_id_bak end if @info_id == @stid if row[0] != nil && row[0].to_s.downcase.match('[a-z][0-9]') && !row[0].to_s.match('\AStep[0-9]{1,3}\Z') && !row[0].to_s.match('\Astep[0-9]{1,3}\Z') || row[0].to_s.downcase.match('^youtube....[0-9]{1,3}') && !row[0].to_s.match('\Acase[0-9]\Z') @testcasename = row[1] @importance = row[4] if row[4] == 'H' || row[4] == '1-High' @importance = 3 elsif row[4] == 'M' || row[4] == '2-Medium' || row[4] == '2-Meidum' @importance = 2 elsif row[4] == 'L' || row[4] == '3-Low' @importance = 1 end end if row[0].to_s.downcase.lstrip.rstrip.include?('preparation') || row[0].to_s.downcase.lstrip.rstrip.include?('precondition') if row[1] != nil @preconditions = row[1].to_s.lstrip.rstrip.gsub("\n","<\p>\n<p>") else @preconditions = row[1].to_s end end if row[0].to_s.downcase.include?('purpose') @summary = row[1].to_s.lstrip.rstrip.gsub("\n","<\p>\n<p>") end if row[0] != nil if row[0].class == Float || row[0].to_s.match('\A[0-9]{1,3}\Z') || row[0].to_s.match('\AStep[0-9]{1,3}\Z') && !row[0].to_s.match('\Acase[0-9]\Z') @step_description = row[1].to_s.lstrip.rstrip.gsub("\n","<\p>\n<p>") @expectedresult = row[2].to_s.lstrip.rstrip.gsub("\n","<\p>\n<p>") @step_hash = {step_number: @step, actions: @step_description, expected_results: @expectedresult, execution_type: '1'} @step_array.push(@step_hash) @step += 1 end end end end @testcasename = @stid.gsub(' ',' ') + ": " + @testcasename create_test_case(@suite, @testcasename, @summary, @preconditions, @step_array, @top_suite_id, @importance) end end end }
true
e28004e6515bf2005b90ce46919fad74d3b292df
Ruby
htachib/clerk
/lib/parsers/kehe_promotion.rb
UTF-8
1,497
2.546875
3
[]
no_license
module Parsers class KehePromotion < Base class << self def invoice_data(document) parsed_meta_data_cover(document).deep_merge( parsed_invoice_details(document) ).deep_merge(parsed_invoice_date(document)) end def parsed_meta_data_cover(document) parsed = {} data = get_raw_data(document,'meta_data_cover').map { |row| row.join(' ') } parsed['invoice_number'] = data[0].try(:split,'#').try(:last).strip parsed['po_num'] = data[2].try(:split,'#').try(:last).strip parsed['dc_num'] = data[3].try(:split,'#').try(:last).strip parsed['type'] = data[4].try(:split,' ').try(:last).strip parsed end def parse_cell(data, regex) data.select { |cell| cell.match?(regex) }.try(:first) end def parsed_invoice_details(document) parsed = {} data = get_raw_data(document,'invoice_details').flatten parsed['broker_id'] = parse_cell(data, /broker/i).scan(/\d+/)[0] parsed['chain'] = parse_cell(data, /chain/i).try(:split,' ').try(:last) parsed['chargeback_amount'] = parse_cell(data, /invoice.*total/i).try(:split,'$').try(:last) parsed['ep_fee'] = parse_cell(data, /ep.*fee/i).try(:split,'$').try(:last) parsed end def parsed_invoice_date(document) invoice_date = document['invoice_date'].try(:first).try(:values).try(:first) {'invoice_date' => invoice_date} end end end end
true
1f32b31675f6b215f2d70648f26baf24ff56a20b
Ruby
davepodgorski/Monday-19th
/car.rb
UTF-8
612
3.53125
4
[]
no_license
class Car @@default_colour = 'blue' @@cars_made = 0 def initialize(colour, owner) @owner = owner @mileage = 0 @colour = @@default_colour @broken = false @@cars_made += 1 end def self.cars_made return @@cars_made end def self-default_colour=(default_colour) @@default_colour = default_colour end def colour @colour end def colour=(colour) @colour = colour end def drive(distance) if !@broken @mileage += distance end end def crash(other_car) @broken = true if other_car != nil other_car.crash(nil) end end end
true
5f9ad3e68c9441a088594968f6c791b6e608fd09
Ruby
asseym/serp
/features/step_definitions/login_steps.rb
UTF-8
4,181
2.5625
3
[]
no_license
### UTILITY METHODS ### def create_visitor (user_factory=false) user_factory = :user if user_factory == false @visitor ||= FactoryGirl.attributes_for(user_factory) end def find_user @user ||= User.where(:email => @visitor[:email]).first end def create_unconfirmed_user create_visitor :superadmin sign_in create_visitor :unconfirmed_user create_staff_account visit destroy_user_session_path end def create_staff_account visit new_user_path fill_in "name", :with => @visitor[:name] fill_in "email", :with => @visitor[:email] fill_in "password", :with => @visitor[:password] fill_in "password_confirmation", :with => @visitor[:password_confirmation] select "staff", :from => :roles click_button "Create" end def create_user create_visitor delete_user @user = FactoryGirl.create(:user, @visitor) end def create_superadmin_user create_visitor :superadmin delete_user @user = FactoryGirl.create(:user, @visitor) end def delete_user @user ||= User.where(:email => @visitor[:email]).first @user.destroy unless @user.nil? end def sign_in visit new_user_session_path fill_in "login-email", with: @visitor[:email], match: :first fill_in "login-password", with: @visitor[:password], match: :first click_button "login-btn" end def sign_out visit destroy_user_session_path end ### GIVEN ### Given /^I exist as a user$/ do create_user end Given /^I am not logged in$/ do visit destroy_user_session_path end Given /^I am logged in$/ do create_user sign_in end Given /^I do not exist as a user$/ do create_visitor delete_user end Given /^I exist as an unconfirmed user$/ do create_unconfirmed_user end ### WHEN ### When(/^I sign in with valid credentials$/) do sign_in end When /^I sign in with invalid credentials$/ do create_visitor sign_in end When /^I sign out$/ do # visit destroy_user_session_path sign_out end When /^I return to the site$/ do visit '/' end When /^I sign in with a wrong email$/ do @visitor = @visitor.merge(:email => "[email protected]") sign_in end When /^I sign in with a wrong password$/ do @visitor = @visitor.merge(:password => "wrongpass") sign_in end When /^I edit my account details$/ do click_link "Edit account" fill_in "user_name", :with => "newname" fill_in "user_current_password", :with => @visitor[:password] click_button "Update" end When /^I look at the list of users$/ do visit users_path end ### THEN ### Then /^I should be signed in$/ do page.should have_content "Log out" page.should_not have_content "Sign up" page.should_not have_content "Login" end Then /^I should be signed out$/ do expect(page).to have_content "Sign In" expect(page).to have_button "Login" expect(page).to_not have_content "Log out" # expect(page).to_not have_link('Log out', href: destroy_session_path(user)) end Then /^I see an unconfirmed account message$/ do page.should have_content "You have to confirm your account before continuing." end Then /^show me the page$/ do save_and_open_page end Then /^I see a successful sign in message$/ do expect(page).to have_content "Signed in successfully." end Then /^I should see a successful sign up message$/ do page.should have_content "Welcome! You have signed up successfully." end Then /^I should see an invalid email message$/ do page.should have_content "Email is invalid" end Then /^I should see a missing password message$/ do page.should have_content "Password can't be blank" end Then /^I should see a missing password confirmation message$/ do page.should have_content "Password doesn't match confirmation" end Then /^I should see a mismatched password message$/ do page.should have_content "Password doesn't match confirmation" end Then /^I should see a signed out message$/ do page.should have_content "Signed out successfully." end Then /^I see an invalid login message$/ do expect(page).to have_content "Invalid email or password." end Then /^I should see an account edited message$/ do page.should have_content "You updated your account successfully." end Then /^I should see my name$/ do create_user page.should have_content @user[:name] end
true
580ae228a9747d23c09d6faadefe947375a205fd
Ruby
hannahgreen1/Bounty_hunters_lab
/models/creature.rb
UTF-8
2,496
3.265625
3
[]
no_license
require("pg") class Creature attr_accessor :name, :species, :location, :homeworld def initialize(options) @id = options["id"].to_i if options["id"] @name = options["name"] @species = options["species"] @location = options["location"] @homeworld = options["homeworld"] end def save() db = PG.connect({ dbname: "bounty_hunter", host: "localhost" }) sql = "INSERT INTO bounty_hunters (name, species, location, homeworld) VALUES ($1, $2, $3, $4) RETURNING id" values = [@name, @species, @location, @homeworld] db.prepare("save", sql) @id = db.exec_prepared("save", values)[0]["id"].to_i #always use this line db.close() end def update() db = PG.connect({ dbname: "bounty_hunter", host: "localhost" }) sql = "UPDATE bounty_hunters SET (name, species, location, homeworld) = ($1, $2, $3, $4) WHERE id = $5" values =[@name, @species, @location, @homeworld, @id] db.prepare("update", sql) db.exec_prepared("update", values) db.close() end def Creature.all db = PG.connect ({ dbname: "bounty_hunter", host: "localhost"}) sql = "SELECT * FROM bounty_hunters" db.prepare("all", sql) creature_hashes = db.exec_prepared("all") db.close() creature = creature_hashes.map { |creature_hash| Creature.new(creature_hash) } return creature end def Creature.delete_all() db = PG.connect ({ dbname: "bounty_hunter", host: "localhost"}) sql = "DELETE FROM bounty_hunters" db.prepare("delete_all", sql) db.exec_prepared("delete_all") db.close() end def delete() db = PG.connect({ dbname: "bounty_hunter", host: "localhost" }) sql = "DELETE FROM bounty_hunters WHERE id = $1" db.prepare("delete", sql) db.exec_prepared("delete", [@id]) db.close() end def Creature.find_by_name(name) db = PG.connect({ dbname: "bounty_hunter", host: "localhost" }) sql = "SELECT name FROM bounty_hunters WHERE name = $1" db.prepare("find_by_name", sql) db.exec_prepared("find_by_name", [name]) db.close() creature = name return creature end def Creature.find_by_id(id) db = PG.connect({ dbname: "bounty_hunter", host: "localhost" }) sql = "SELECT name FROM bounty_hunters WHERE id = $5" db.prepare("find_by_id", sql) db.exec_prepared("find_by_id", [id]) db.close() creature = id return creature end end
true
9fe892ffd0fa6fd1b7ad47050252cf8f011280b4
Ruby
ComPlat/sablon
/lib/sablon/processor/chem.rb
UTF-8
3,301
2.59375
3
[ "MIT" ]
permissive
# The code of that class was inspired in "kubido Fork - https://github.com/kubido/" module Sablon module Processor class Chem # PICTURE_NS_URI = 'http://schemas.openxmlformats.org/drawingml/2006/picture' # MAIN_NS_URI = 'http://schemas.openxmlformats.org/drawingml/2006/main' RELATIONSHIPS_NS_URI = 'http://schemas.openxmlformats.org/package/2006/relationships' IMG_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image' OLE_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject' def self.process(doc, properties, out) processor = new(doc, properties, out) processor.manipulate end def initialize(doc, properties, out) @doc = doc @properties = properties @out = out end def manipulate next_id = next_rel_id @@oles_rids = {} # @@imgs_rids = {} relationships = @doc.at_xpath('r:Relationships', r: RELATIONSHIPS_NS_URI) @@chems.to_a.each do |chems| # add_img_to_relationships is done in Sablon::Processor::Image add_ole_to_relationships(relationships, next_id, chems.ole) next_id += 1 end @doc end def add_ole_to_relationships(relationships, next_id, ole) relationships.add_child("<Relationship Id='rId#{next_id}' Type='#{OLE_TYPE}' Target='embeddings/#{ole.name}'/>") ole.rid = next_id @@oles_rids[ole.name.match(/(.*)\.[^.]+$/)[1]] = next_id end # def add_img_to_relationships(relationships, next_id, img) # relationships.add_child("<Relationship Id='rId#{next_id}' Type='#{IMG_TYPE}' Target='media/#{img.name}'/>") # img.rid = next_id # @@imgs_rids[img.name.match(/(.*)\.[^.]+$/)[1]] = next_id # end def self.add_chems_to_zip!(content, zip_out) (@@chems = get_all_chems(content)).each do |chem| add_imgs_to_zip!(chem.img, zip_out) add_oles_to_zip!(chem.ole, zip_out) end end def self.add_imgs_to_zip!(img, zip_out) zip_out.put_next_entry(File.join('word', 'media', img.name)) zip_out.write(img.data) end def self.add_oles_to_zip!(ole, zip_out) zip_out.put_next_entry(File.join('word', 'embeddings', ole.name)) zip_out.write(ole.data) end def self.list_ole_ids @@oles_rids end # def self.list_img_ids # @@imgs_rids # end def self.get_all_chems(content) result = [] if content.is_a?(Sablon::Chem::Definition) result << content elsif content && (content.is_a?(Enumerable) || content.is_a?(OpenStruct)) content = content.to_h if content.is_a?(OpenStruct) result += content.collect do |key, value| if value get_all_chems(value) else get_all_chems(key) end end.compact end result.flatten.compact end private def next_rel_id @doc.xpath('r:Relationships/r:Relationship', 'r' => RELATIONSHIPS_NS_URI).inject(0) do |max ,n| id = n.attributes['Id'].to_s[3..-1].to_i [id, max].max end + 1 end end end end
true
974efcdb0d97bbf8a48c3d70dd7ef285a86b7658
Ruby
jtanadi/LS-Exercises
/0-Basics/2-UserInput/print_something.rb
UTF-8
115
3.59375
4
[]
no_license
puts "Do you want me to print something? (y/n)" answer = gets.chomp.downcase puts answer == "y" ? "something" : ""
true
d647ab9723b6aa6910cf32050168345d40383475
Ruby
Runli/thinknetica
/lesson08/train_cargo.rb
UTF-8
242
2.890625
3
[]
no_license
require_relative 'train' # methods for Train type :cargo class TrainCargo < Train def initialize(number) super(number, :cargo) end def wagon_add(wagon) return unless @type == wagon.type super(wagon) end end
true
c1ec110d344d0f385d6b8b1611e439fafb6d4f79
Ruby
Elizabeth555/learn_to_program
/ch11-reading-and-writing/build_a_better_playlist.rb
UTF-8
820
3.828125
4
[]
no_license
def music_shuffle filenames filenames - filenames.sort len = filenames.length #sorts array of songs and gets length 2.times do l_idx =0 r_idx = len/2 shuf= [] #splits array into2. while shuf.length < len if shuf.length%2 ==0 shuf.push(filenames[r_idx]) r_idx = r_idx + 1 # pushes songs with random numbers into new array else shuf.push(filenames[l_idx]) l_idx = l_idx + 1 end end filenames = shuf end arr = [] cut = rand(len) idx = 0 while idx < len arr.push(filenames[(idx+cut)%len]) idx = idx + 1 end arr end songs = ['aaaaa', 'bbbbb', 'cccc', 'ddddd', 'eeeee', 'fffff'] puts (music_shuffle(songs))
true
476af38216eaeddacdecde0b63d89746351bdccf
Ruby
stephanschubert/blog
/app/models/blog/tag.rb
UTF-8
676
2.53125
3
[ "MIT" ]
permissive
module Blog class Tag include Mongoid::Document include Mongoid::Timestamps include Mongoid::Slug field :name, type: String validates_presence_of :name slug :name #has_and_belongs_to_many :posts embedded_in :post cattr_accessor :separator self.separator = ',' # Returns all unique (the name counts) tags embedded in posts. # TODO * Speed up. # * Ensure the first tag w/ a name is used because of slug # generation for the subsequent ones. def self.all Post.only(:tags).map(&:tags).flatten.inject({}) { |uniq, tag| uniq[tag.name] ||= tag uniq }.values end end end
true
148d96bd2bd0fde01c4156db98d889ecc44f941e
Ruby
mnoble/ChopperDropper
/lib/systems/wagon.rb
UTF-8
172
2.796875
3
[]
no_license
module Systems class Wagon attr_reader :wagon def initialize(wagon) @wagon = wagon end def call(delta) wagon.right(delta) end end end
true
a44cad9a2ff93b1e9ca4c7b9da7081da4d952b3f
Ruby
rodrigodealer/pet_project
/app/helpers/plans_helper.rb
UTF-8
278
2.65625
3
[]
no_license
module PlansHelper def real_name(name) case name when 'W' 'Semanal' when 'CW' 'Quinzenal' when 'M' 'Mensal' when 'FFD' '45 dias' when 'CM' 'Bimestral' when 'TM' '90 dias' else 'Outro' end end end
true
90bc22f94336444f4a89473bcb9ac10dfbd878a2
Ruby
lezoudali/ruby-playground
/test_first_ruby/12_rpn_calculator/rpn_calculator.rb
UTF-8
988
4.1875
4
[]
no_license
class RPNCalculator def initialize @nums = Array.new end def value @nums.last end def push(num) @nums << num end def plus if @nums.length >=2 @nums << @nums.pop + @nums.pop else raise "calculator is empty" end end def minus if @nums.length >=2 @nums << 0 - @nums.pop + @nums.pop else raise "calculator is empty" end end def divide if @nums.length >= 2 @nums << (1/@nums.pop.to_f)*(@nums.pop.to_f) else raise "calculator is empty" end end def times if @nums.length >= 2 @nums << @nums.pop * @nums.pop else raise "calculator is empty" end end def tokens(str) str.split(/\s+/).map do |elt| if ['+', '-', '*', '/'].include? elt elt.to_sym else elt.to_i end end end def evaluate(str) tokens(str).each do |elt| if elt == :+ plus() elsif elt == :- minus() elsif elt == :* times() elsif elt == :/ divide() else push(elt) end end value() end end
true
caf42cb505e1354c7888663e51d2a86db2e9f454
Ruby
nhatho89/my-inject
/spec/my_inject_spec.rb
UTF-8
2,862
3.640625
4
[]
no_license
require 'my_inject' describe Array do context 'my_inject' do it 'can sum a number without an initial value' do expect([1,2,3].my_inject{ |memo, value| memo += value }).to eq 6 end it 'can sum a number with an initial value' do expect([1,2,3].my_inject(1){ |memo, value| memo += value }).to eq 7 end it 'can multiple numbers' do expect([1,2,3].my_inject(&:*)).to eq 6 end it 'can multiple numbers with an initial value' do expect([1,2,3].my_inject(5,&:*)).to eq 30 end it 'can subtract numbers' do expect([1,2,3].my_inject(&:-)).to eq -4 end it 'can subtract numbers with an initial value' do expect([1,2,3].my_inject(9,&:-)).to eq 3 end it 'can divide numbers' do expect([100,2,2].my_inject(&:/)).to eq 25 end it 'can divide numbers with an initial value' do expect([100,2,2].my_inject(10000,&:/)).to eq 25 end it 'can find the longest word in an array of strings' do words = %w{ cat sheep bear } expect(words.my_inject{ |memo, word| memo.length > word.length ? memo : word }).to eq 'sheep' end it 'can convert a 2D Array into a Hash' do array = [['A', 'a'], ['B', 'b'], ['C', 'c']] hash = array.my_inject({}) do |memo, values| memo[values.first] = values.last memo end expect(hash).to eq({'A' => 'a', 'B' => 'b', 'C' => 'c' }) end it 'the orginal array is still the same' do original = [1,2,3,4] original.my_inject(&:+) expect(original).to eq [1,2,3,4] end end context 'recusive_inject' do it 'can sum a number without an initial value' do expect([1,2,3].recursive_inject{ |memo, value| memo += value }).to eq 6 end it 'can sum a number with an initial value' do expect([1,2,3].recursive_inject(1){ |memo, value| memo += value }).to eq 7 end it 'can multiple numbers' do expect([1,2,3].recursive_inject(&:*)).to eq 6 end it 'can multiple numbers with an initial value' do expect([1,2,3].recursive_inject(5,&:*)).to eq 30 end it 'can subtract numbers' do expect([1,2,3].recursive_inject(&:-)).to eq -4 end it 'can subtract numbers with an initial value' do expect([1,2,3].recursive_inject(9,&:-)).to eq 3 end it 'can divide numbers' do expect([100,2,2].recursive_inject(&:/)).to eq 25 end it 'can divide numbers with an initial value' do expect([100,2,2].recursive_inject(10000,&:/)).to eq 25 end it 'can find the longest word in an array of strings' do words = %w{ cat sheep bear } expect(words.recursive_inject{ |memo, word| memo.length > word.length ? memo : word }).to eq 'sheep' end it 'can convert a 2D Array into a Hash' do array = [['A', 'a'], ['B', 'b'], ['C', 'c']] hash = array.recursive_inject({}) do |memo, values| memo[values.first] = values.last memo end expect(hash).to eq({'A' => 'a', 'B' => 'b', 'C' => 'c' }) end end end
true
220ea6299714172d0c7e0865cecd7ef7f9f0786b
Ruby
PacktPublishing/Practical-OneOps
/Chapter 09/circuit-oneops-1-master/components/cookbooks/panos/libraries/dataaccess/key_request.rb
UTF-8
1,127
2.78125
3
[ "MIT" ]
permissive
require File.expand_path('../../models/key.rb', __FILE__) class KeyRequest def initialize(url, userid, password) fail ArgumentError, 'url cannot be nil' if url.nil? fail ArgumentError, 'userid cannot be nil' if userid.nil? fail ArgumentError, 'password cannot be nil' if password.nil? @url = url @userid = userid @password = password end def getkey begin key_response = RestClient::Request.execute( :method => :get, :verify_ssl => false, :url => @url, :headers => { :params => { :type => 'keygen', :user => @userid, :password => @password } } ) # parse the xml to get the key key_hash = Crack::XML.parse(key_response) Chef::Log.info("key_hash is: #{key_hash}") raise Exception.new("PANOS Error getting key: #{key_hash['response']['msg']}") if key_hash['response']['status'] == 'error' key = Key.new(key_hash['response']['result']['key']) return key rescue => e raise Exception.new("Excpetion getting key: #{e}") end end end
true
1ab7dbed5b469e15a103ea0ee2aae2c586c825d4
Ruby
SteveSnow/scorecard
/app/models/hole.rb
UTF-8
228
2.765625
3
[]
no_license
class Hole < ActiveRecord::Base has_one :yardage has_many :scores def number return self.name[1] end def course case self.name[0].upcase when 'W' return 'White' when 'R' return 'Red' when 'B' return 'Blue' end end end
true
e597277a9e929fc6433e9521f2831ab182e5052a
Ruby
aproperzi2/Math_Games_Ruby
/main.rb
UTF-8
548
3.640625
4
[]
no_license
require './player' require './question' require './helpers' puts "\n\n*************************" puts "Welcome to the Math Game!" puts "*************************\n\n" puts "Player 1 & Player 2 both have 3 lives." puts "Answer a question incorrectly, and lose a life." puts "If you lose all your lives, the game ends!\n\n" puts "Ready?\n\n" player1 = Player.new player2 = Player.new while player1.lives > 0 && player2.lives > 0 do logic(player1, player2, 1) logic(player1, player2, 2) end puts "\n----- GAME OVER -----" puts "\nGoodbye!\n\n"
true
61b5216557effa4a6491a573001f2e01b6c2bb1b
Ruby
micahlee/treequel
/experiments/paged_results_example.rb
UTF-8
928
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby -w # # Program to demonstrate the use of the LDAPv3 PagedResults control. This # control is interesting, because it requires the passing of controls in # both directions between the client and the server. require 'rubygems' require 'treequel' require 'treequel/controls/pagedresults' unless ARGV[0] $stderr.puts "Please give a page size." exit end page_size = ARGV[0].to_i dir = Treequel.directory dir.register_controls( Treequel::PagedResultsControl ) #Treequel.logger.level = Logger::DEBUG people = dir.ou( :people ).filter( :objectClass => 'person' ).with_paged_results( page_size ) count = page = 0 begin records = people.all count += records.length page += 1 $stderr.puts "Page %d has %d entries." % [ page, records.length ], "That's %d entries in total." % [ count ] $stderr.puts "Cookie is: 0x%s" % [ people.paged_results_cookie.unpack('H*').first ] end while people.has_more_results?
true