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
6d5ef8ed5e2846cc41efdc06fa1035efe4ed9845
Ruby
GabeP9195/ruby-challenges
/case.rb
UTF-8
427
3.53125
4
[]
no_license
puts "What's the weather like?" weather = gets.chomp case weather when "sunny" puts "Sunny out, go for a cruise in the convertible, top down time!" when "cloudy" puts "Grab an umbrella, it might rain" when "foggy" puts "Careful, it's foggy out" when "rainy" puts "Grab the umbrella, it's pouring cats and dogs out there!" when "snowy" puts "Better grab those snow boots!" else puts "Oh no, it's a Zombie Apolacyplse!" end
true
5dcbe0c9d4467187e1dcb81aa8768e58c4233895
Ruby
sushengloong/market_data
/lib/market_data.rb
UTF-8
323
2.609375
3
[ "MIT" ]
permissive
require "market_data/version" module MarketData class ResponseData attr_reader :status, :data def initialize status, data @status = status @data = data end end def self.for_symbol symbol ResponseData.new 200, { :open => 1, :high => 2, :low => 3, :close => 4, :volume => 5 } end end
true
0e578d16543004a61e2f0977e30d994f5ade3761
Ruby
JotaSe/undecided
/lib/undecided/decider.rb
UTF-8
663
3.046875
3
[ "MIT" ]
permissive
module Undecided class DeciderError < StandardError end # Evaluate boolean expression class Decider # Given a boolean expression and data to replace, return result def decide(rule, values, strict = true) rule = rule.clone values = values.clone error unless Undecided::Evaluator.valid?(rule, values, strict) # Sanitize data # Eval rules and values after process it, with safe data final_expression = Converter.replacing_variables(rule, values) eval final_expression rescue => e puts e.message error end def error raise DeciderError, 'Wrong data to perform' end end end
true
432e9ab0f681097150ad9a89c37ca86a454520ff
Ruby
z010155/portable-markov
/portable-markov.rb
UTF-8
13,175
2.90625
3
[ "MIT" ]
permissive
## Patent Portable Markov-in-a-box Generator # # This tool generates portable Markov chain-in-a-box scripts. # Essentially, this program generates self-sufficient scripts that quote # parts from their built-in chains. They could be used as motivational tools, # generating endless sentences of philosophical nature and quality. # # They could also be very inspirative, e.g. if you combine various types of # fanfiction, it could result in brand new, uncharted ideas being found. # It is up to you. # # (c) OrwellianStuff 2018, released under MIT License # $GEN_PATH = File.expand_path(File.dirname(__FILE__)) require 'json' require 'base64' require 'zlib' require 'date' # Main module module PortableMarkov # Markov chain class # # This class defines a structure for Markov chains class MarkovChain # Initialize a class # @param [Integer] level Level to use for this Markov chain def initialize(level) raise "Level must be an integer and nonzero!" unless (level.is_a?(Integer) && level > 0) @token_branches = Hash.new() {|hash, key| h = Hash.new(0); hash[key] = h;} # Generate a token hash, for which each nondefined entity we have an empty subhash, which returns zero @token_stack = [] # Stack of token identifiers @ids_to_translations = {} # Since tokens do not themselves convey any meaning, we store their "translations" in this hash. @translations_to_ids = {} # And vis a versa, since normal hashes do not have a bidirectional property @level = level # How many tokens' worth of recall we have? end # Finds the proper token identifier; if one doesn't exist, create a new one for it # @param [String] str Token to find or generate an identifier for def id_for_token(str) fstr = str.dup.freeze id = @translations_to_ids[fstr] # Nonexistent? Create a new one if id.nil? then id = (@ids_to_translations.keys.max || -1) + 1 @ids_to_translations[id] = fstr @translations_to_ids[fstr] = id end return id end # Ingests an single token # @param [String] str Token to ingest def ingest_token(str) identifier = id_for_token(str) @token_stack << identifier if (@token_stack.length > @level) # We now have more tokens than our recall is. branch_key = @token_stack[0..-2] * ':' # Form our branch key branches = @token_branches[branch_key] # Check our branches last_token = @token_stack[-1] # Get our last token branches[last_token] += 1 # Add one hit @token_stack.shift # Remove the first token, leaving our stack in correct state again end end # Resets the token stack, useful for adding new files in sequence def reset_token_stack() @token_stack = [] end # Generates a JSON bundle for this chain # @param [String] identifier Identifier/calling name # @return [String] JSON string def to_json(identifier) JSON::generate({"branches" => @token_branches, "name"=>identifier, "translations" => @ids_to_translations}) end attr_reader :token_branches, :ids_to_translations, :level end # Writes out a runnable file for a given Markov chain # @param [String] json JSON-string to save # @param [String] file_name Filename to save to # @param [Boolean] save_uncompressed If true, save uncompressed # @param [Boolean] save_json If true, save the JSON structure as well def self.write_runnable_module(json, file_name, save_uncompressed, save_json) #runner_lines = File.readlines(File.join($GEN_PATH, "runner.rb")) runner_lines = DATA.each_line.to_a # Read our runner from the DATA part # Filter out comments runner_lines.map! {|x| x.strip} runner_lines.reject! {|x| x.start_with?("#") || x == ""} # Merge into a single string runner_merged = runner_lines * "\n" runner_merged.sub!("<INVALID-DATA-REPLACE-ME>", Base64.encode64(json)) # Generate a stub for compression stub = <<~HEREDOC # Generated with Orwell's Patent Portable Markov-In-A-Box Generator, on #{DateTime.now.rfc3339} require 'zlib' require 'base64' $MY_FILE = __FILE__ $COMPRESSED_RUN = true eval(Zlib.inflate(Base64.decode64('<COMPRESSED-HERE>'))) HEREDOC # Finally, save File.open(file_name, "w") {|f| f.puts(save_uncompressed ? "$COMPRESSED_RUN = true;$MY_FILE = __FILE__\n"+runner_merged : stub.sub("<COMPRESSED-HERE>", Base64.encode64(Zlib::deflate(runner_merged))))} File.open(file_name + ".json", "w") {|f| f.puts json} if save_json end # In case we want to do token splitting, this function will be used # @param [String] The string to split into tokens # @return [Array<String>] Tokens def self.split_punctuation(str) token_stack = [] temp_str = "" punctuation_marks = [".", ",", " ", "?", "!", "\n"] str.gsub(/ +/, " ").gsub(/[\r\n]+/, "\n").chars.each do |chr| if punctuation_marks.include?(chr) unless (temp_str.length == 0) token_stack << temp_str temp_str = "" end token_stack << chr else temp_str << chr end end unless (temp_str.length == 0) token_stack << temp_str end return token_stack end # Generates a Markov chain, according to options # @param [Hash] Options def self.generate_markov(options) puts "Generating a Markov generator named '#{options[:name]}', saving to file '#{options[:output_file]}', using dictionaries:" options[:files].each {|x| puts "\t#{x}"} puts "Length of #{options[:level]}, #{options[:tokenize] ? "with" : "without"} sentence tokenization, #{options[:uncompressed] ? "uncompressed" : "compressed"}" puts "Newlines are#{options[:strip] ? "" : " not"} stripped" # Initialize the Markov class markov = MarkovChain.new(options[:level]) # Ingest each file options[:files].each do |filename| puts "Ingesting '#{filename}'..." filedata = File.read(filename) if options[:strip] # If stripping is on, change newlines to spaces. filedata.gsub!(/[\r\n]+/i, " ") end tokenized_filedata = options[:tokenize] ? split_punctuation(filedata) : filedata.chars tokenized_filedata.each {|k| markov.ingest_token(k)} options[:level].times {markov.ingest_token("")} # At the end of file, clean up by generating empty tokens markov.reset_token_stack() # And reset the stack finally end puts "Saving the output file#{options[:save_json] ? " and JSON" : ""}.." write_runnable_module(markov.to_json(options[:name]), options[:output_file], options[:uncompressed], options[:save_json]) puts "Done!" end # Main entry point of the program def self.main() puts "Orwell's Patent Portable Markov-in-a-box Generator. Copyright OrwellianStuff 2018\n" options = {:output_file => nil, :name => nil, :files => [], :level => 4, :tokenize => false, :uncompressed => false, :strip => false, :save_json => false} if ARGV.length < 3 puts "Usage: portable-markov.rb [options] name output_filename file1 [file2 ...]" puts "\t-level=<number of tokens to recall> -- How many tokens' recall we want to have?" puts "\t-sentences -- Shall we try to split according to sentences?" puts "\t-strip -- Shall newlines be stripped from the dictionaries?" puts "\t-uncompressed -- Save without compression?" puts "\t-save-json -- Save the JSON structure as well?" exit(1) end # Start by duplicating the ARGV table arglist = ARGV.dup # First, parse options while arglist.length > 0 do arg = arglist.shift if arg == "-" || !arg.start_with?("-") # Check for argument list termination arglist.unshift(arg) unless arg == "-" # This is fine, return this there break # And resume end # Does this match a level? if /-level=(?<level_arg>\d+)/i =~ arg level = level_arg.to_i if (level < 1) puts "Error: level must be greater than 0" exit(1) end options[:level] = level next # Next argument end # Simple parameters: shsh = {"-strip" => :strip, "-sentences" => :tokenize, "-uncompressed" => :uncompressed, "-save-json" => :save_json} if (val = shsh[arg]) != nil options[val] = true next end puts "Invalid argument: #{arg}" exit(2) end if arglist.length < 3 puts "You MUST specify at least 3 more parameters: name, output file, and a dictionary!" end # Now, we only have the ID name and files left options[:name] = arglist.shift.strip if options[:name].length < 1 puts "Your name must be nonempty!" exit(4) end options[:output_file] = arglist.shift # Take the first one as an output file # Check that each input file does infact exist arglist.each do |dictionary_file| if (!File.exist?(dictionary_file) || File.directory?(dictionary_file)) puts "Dictionary '#{dictionary_file}' does not exist or is a directory!" exit(3) end options[:files] << dictionary_file end # Everything seems fine generate_markov(options) end end PortableMarkov::main() if __FILE__==$0 __END__ ## Portable Markov-in-a-box Generator - Runner # # This file is the runner part for the generator. Observe that all lines beginning with a # will be stripped entirely, to save # valuable space! # require 'json' require 'base64' module PMRunner # Measuring print; once the limit is up, cut output # @param <Hash> limits Limits to abide and subtract # @param <String> str String to print def self.measuring_print(limits, str) # Take measures rwl = str.length slen = str.chars.select {|x| [".", ",", "!", "?"].include?(x)}.length # Print the string print str # Subtract.. limits[:sentences] -= slen unless limits[:sentences] == nil limits[:raw_length] -= rwl unless limits[:raw_length] == nil # .. did we go over the limit? Throw! throw(:over_limit) if limits.values.reject {|x| x.nil?}.any? {|val| val < 0} end # Once our limits have been determined, start printing. It happens here # @param <Hash> Limitations to obey # @param <Hash> JSON data structure to print with def self.print_random_sentences(orig_limits, json) catch(:over_limit) do limits = orig_limits.dup # Initialize a state, and print it out. state = json["branches"].keys.sample measuring_print limits, state.split(":").map {|x| json["translations"][x]}.reduce(:+) loop do next_state = json["branches"][state] next_index = next_state == nil ? nil : next_state.keys.map {|key| Array.new(json["branches"][state][key], key)}.flatten.sample # It may occur that we run out of possibilities. No panic then though # Simply recurse again, whilst retaining our current limit if next_index == nil print_random_sentences(limits, json) return end # Alright, we have a key. # Print out its translation measuring_print limits, json["translations"][next_index] # Then recompose our state string state = state.split(":")[1..-1].push(next_index) * ":" end end puts "" end # Once our data has been decoded, we enter this function # @param <Hash> Decoded JSON data def self.entrypoint(json) # In this JSON file, we expect to find: translations, branches, and name # Check if we have valid arguments set_sentences = nil set_raw_len = nil error = false # If no arguments, set sane defaults if ARGV.empty? set_sentences = 5 set_raw_len = 140 end # Go through arguments ARGV.each do |arg| # Note, magic variable assignment happens here! if /(?<sentence_limit>\d+)s/i =~ arg if (set_sentences != nil) error = true puts "Duplicate definition, define sentence limit only once." break else set_sentences = sentence_limit.to_i if set_sentences < 1 error = true puts "Sentence limit must be more than 0" end end end # .. and also here! if /(?<raw_limit>\d+)c/i =~ arg if (set_raw_len != nil) error = true puts "Duplicate definition, define raw limit only once." break else set_raw_len = raw_limit.to_i if set_raw_len < 1 error = true puts "Raw limit must be more than 0" end end end end # Check for errors or undefined exit(2) if (error) if (set_raw_len == nil && set_sentences == nil) puts "Use #{json["name"]} like: ruby #{$MY_FILE} <sentence limit>s <raw character limit>c" exit(1) end print_random_sentences({:sentences => set_sentences, :raw_length => set_raw_len}, json) end end # Usually, this should not be ran as a program - but if a special flag is set, then do so PMRunner.entrypoint(JSON.parse(Base64.decode64("<INVALID-DATA-REPLACE-ME>"))) if $COMPRESSED_RUN == true
true
86ba2b3e1573fef24080eaf7eb408f19b0999495
Ruby
MichaelMacLeod/w2d3_homework
/win_checker_runner.rb
UTF-8
436
3.296875
3
[]
no_license
# require_relative('win_checker') # win_checker = WinChecker.new # empty_board = [ [nil,nil,nil],[nil,nil,nil],[nil,nil,nil] ] # symbol = :o # puts "check that empty board doesn't win: expect that: #{win_checker.has_won?(symbol, board)} is false." # board_with_horizontal = [ [:o,:o,:o],[nil,nil,nil],[nil,nil,nil] ] # puts "check that horizontal line wins doesn't win: expect that: #{win_checker.has_won?(symbol, board)} is true."
true
75224d42a485accd3587f062d3df8a1ee5a675d0
Ruby
annamm77/FarMar
/specs/farmar_product_spec.rb
UTF-8
1,638
2.6875
3
[]
no_license
require_relative './spec_helper' describe FarMar::Product do before do @test_market = FarMar::Market.find(1) @test_product = FarMar::Product.find(1) end describe "self.all" do it "returns an array" do FarMar::Product.all.must_be_instance_of Array end it "returns an array of FarMar::Products instances" do FarMar::Product.all[1].must_be_instance_of FarMar::Product end end describe "self.find" do it "returns an instance of FarMar::Product when given a valid id" do @test_product.must_be_instance_of FarMar::Product end it "returns nil when given an invalid id" do FarMar::Product.find(9999999).must_equal nil end it "returns the correct instance when given a valid id" do @test_product.name.must_equal "Dry Beets" end end describe "self.by_vendor(vendor_id)" do it "returns an array" do FarMar::Product.by_vendor(1).must_be_instance_of Array end it "returns an array with an instances of FarMar::Product" do FarMar::Product.by_vendor(1)[0].must_be_instance_of FarMar::Product end it "returns the correct vendor information" do FarMar::Product.by_vendor(1)[0].name.must_equal "Dry Beets" end end describe "vendor method" do it "will return the correct vendor of a product" do @test_product.vendor.name.must_equal "Feil-Farrell" end end describe "sales method" do it "will return an array of FarMar::Sales instances" do @test_product.sales[0].must_be_instance_of FarMar::Sale end end describe "number_of_sales method" do it "will return the number of sales for a given product" do @test_product.number_of_sales.must_equal 7 end end end
true
f0124640f640e1d69cca3217a79dd69723c13b8b
Ruby
hungryed/email_thing
/find_bad_emails.rb
UTF-8
176
2.5625
3
[]
no_license
class FindBadEmails def initialize(filename) @filename = filename end def read_file f = File.new(@filename, "r") @results=f.readlines @results end end
true
3dd5dbcd6ec0aa1ebcf1a2f09fa030530b00d96c
Ruby
sideshowbandana/beautiful_pairs
/lib/beautiful_pairs.rb
UTF-8
590
3.359375
3
[ "MIT" ]
permissive
require "beautiful_pairs/version" module BeautifulPairs def solve puts run(gets.chomp.to_i, gets.chomp.split.map(&:to_i), gets.chomp.split.map(&:to_i)) end module_function :solve def run(length, a, b) counter = 0 a_hash = Hash.new(0) a.each do |n| a_hash[n] += 1 end b.each do |n| counter += 1 if (a_hash[n] -= 1) >= 0 end only_in_b = a_hash.find{|k,v| v < 0 } only_in_a = a_hash.find{|k,v| v > 0 } counter += 1 if only_in_b && only_in_a counter -= 1 if !only_in_b && !only_in_a counter end module_function :run end
true
30a080faa163f6542a8c800b9c2d6eeef3bfabfe
Ruby
Annabanana80/redditClone
/db/seeds.rb
UTF-8
1,457
2.6875
3
[]
no_license
require 'random_data' 5.times do User.create!( name: RandomData.random_name, email: RandomData.random_email, password: RandomData.random_sentence ) end users = User.all 15.times do Topic.create!( name: RandomData.random_sentence, description: RandomData.random_paragraph ) end topics = Topic.all # Create Posts 50.times do Post.create!( user: users.sample, topic: topics.sample, title: RandomData.random_sentence, body: RandomData.random_paragraph ) end posts = Post.all 20.times do SponsoredPost.create!( topic: topics.sample, title: RandomData.random_sentence, body: RandomData.random_paragraph, price: RandomData.random_number ) end sponsored_posts = SponsoredPost.all # Create Comments 100.times do Comment.create!( post: posts.sample, body: RandomData.random_paragraph ) end comments = Comments.all # Create Questions 50.times do Question.create!( title: RandomData.random_sentence, body: RandomData.random_paragraph ) end questions = Questions.all puts "Seed finished" puts "#{User.count} users created" puts "#{Topic.count} topics created" puts "#{Post.count} posts created" puts "#{SponsoredPost.count} sponsored posts created" puts "#{Comment.count} comments created" puts "#{Question.count} questions created" Advertisement.create(title: 'Sample Advertisement' , copy: 'Buy me!' , price: 99.99 )
true
c34bdc560833fb0bf20594ad8379570a97b92822
Ruby
FotoVerite/babygitter
/lib/babygitter/output_helpers/html_output.rb
UTF-8
6,117
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'cgi' require 'markaby' module Babygitter module HtmlOutput #Pluralizes the authors of a branch in a readable and gramatically correct manner # #authors_list([Matt, Allen]) => Matt and allen have #authors_list([Matt]) => Only Matt has def authors_list(array_of_authors) case array_of_authors.length when 1: 'Only ' + array_of_authors.first + ' has' else array_of_authors[0..-2].join(', ') + ' and ' + array_of_authors.last + ' have' end end #Pluralizes the branches in a XHTML correct manner with links to the branch headers def branch_names_list(branch_names) markaby do ul.page_control do for name in branch_names li do a name, :href => "##{name.underscore}" end end end end end #Output the git repo's branches details in a XHTML correct manner def branch_details(branches, remote_url) markaby do branches.map do |branch| h2.toggler.open "Branch #{branch.name}", :id => branch.name.gsub(/ /, '') div.toggle.branch do image_gallery(branch) if Babygitter.output_graphs div.branch_details do author_links(branch) branch_synopsis(branch) hr :class => "end_of_info" h3.toggler.open "#{branch.name} commit history" div.toggle do ul do branch_committer_detail(branch, branch.commits, remote_url) end end hr :class => "end_of_info" author_details(branch.name, branch.authors, remote_url, branch.total_commits) end end hr :class => "end_of_branch_info" end end end def image_gallery(branch) markaby do div.image_gallery do create_histograph_of_commits_by_author_for_branch(branch) + "\n" + create_stacked_bar_graph_of_commits_by_author_for_branch(branch) + "\n" + unless Babygitter.folder_levels.empty? || Babygitter.folder_levels == [0] Babygitter.folder_levels.map do |level| create_folder_graph(branch, level) end.join("\n") else "" end end end end def branch_synopsis(branch) markaby do p { "Last commit was " + link_to_github?(branch.latest_commit, remote_url) + " by #{branch.latest_commit.author.name} on #{branch.latest_commit.date_time_string}" } p "They have committed a total of #{pluralize(branch.total_commits, "commit", "commits")}" p "This is the designated master branch" if branch.is_master_branch p "There are #{branch.unique_commits.size} #{branch.unique_commits.size == 1 ? 'unique commit' : 'unique commits'} for this branch" p {"#{branch.name} branched at " + a( branch.branched_at.id_abbrev, :class => "branched_at_link", :href => "##{branch.name}_branched_here")} end end def author_details(branch_name, authors, remote_branch, total_for_branch) markaby do authors.map do |author| h3.toggler.open "#{author.name} commits for #{branch_name}", :id => "#{branch_name}_#{author.name.underscore}" div.toggle :id => author.name do create_bar_graph_of_commits_in_the_last_52_weeks(author) p "#{author.name} first commit for this branch was on #{author.began.date_time_string}" p "They have committed #{pluralize(author.total_committed, "commit")}" p "#{amount_committed_to_total(author, total_for_branch)} of the total for the branch" ul do committer_detail(author.commits, remote_url) end end end end end def amount_committed_to_total(author, total_for_branch) ((author.total_committed.to_f / total_for_branch)*100.round)/100 end def author_links(branch) names = branch.author_names markaby do p "#{pluralize(names.size, 'author')} #{names.size == 1 ? 'has' :'have'} committed to this branch" ul.page_control do for name in names li { a(name, :href =>"##{branch.name}_#{name.underscore}")} end end end end def committer_detail(commits, remote_url) markaby do commits.map do |commit| li { CGI::escapeHTML(commit.message) + cite("#{commit.author.name} #{commit.date_time_string}") + link_to_github?(commit, remote_url) } end end end def commit_classes(branch, commit) return "unique" if branch.unique_commits != nil && branch.unique_commits.map(&:id).include?(commit.id) return "branched" if branch.branched_at.id == commit.id end def branch_committer_detail(branch, commits, remote_url) markaby do commits.map do |commit| li :id => commit_id_class(branch, commit), :class => commit_classes(branch, commit) do CGI::escapeHTML(commit.message) + cite("#{commit.author.name} #{commit.date_time_string}") + link_to_github?(commit, remote_url) end end end end def commit_id_class(branch, commit) if commit.id == branch.branched_at.id "#{branch.name}_branched_here" else branch.name + "_" + commit.id end end def link_to_github?(commit, remote_url) remote_url == "" ? "<tt>#{commit.id_abbrev}</tt>" : "<tt><strong><a href='#{remote_url}/commit/#{commit.id}'>#{commit.id_abbrev}</a></strong></tt>" end def pluralize(count, singular, plural = nil) "#{count || 0} " + if count == 1 || count == '1' singular elsif plural plural elsif Object.const_defined?("Inflector") Inflector.pluralize(singular) else singular + "s" end end def markaby(&block) Markaby::Builder.set(:indent, 2) Markaby::Builder.new({}, self, &block).to_s end end end
true
16ba75bef65b41af036441f659e1f58a385d3c36
Ruby
rnovick13/advanced-hashes-hashketball-dc-web-111918
/hashketball.rb
UTF-8
4,984
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here! require "pry" def game_hash game = { :home => { :team_name => "Brooklyn Nets", :colors => ["Black", "White"], :players => { "Alan Anderson" => { number: 0, shoe: 16, points: 22, rebounds: 12, assists: 12, steals: 3, blocks: 1, slam_dunks: 1}, "Reggie Evans" => { number: 30, shoe: 14, points: 12, rebounds: 12, assists: 12, steals: 12, blocks: 12, slam_dunks: 7}, "Brook Lopez" => { number: 11, shoe: 17, points: 17, rebounds: 19, assists: 10, steals: 3, blocks: 1, slam_dunks: 15}, "Mason Plumlee" => { number: 1, shoe: 19, points: 26, rebounds: 12, assists: 6, steals: 3, blocks: 8, slam_dunks: 5}, "Jason Terry" => { number: 31, shoe: 15, points: 19, rebounds: 2, assists: 2, steals: 4, blocks: 11, slam_dunks: 1} } #players hash }, #home :away => { :team_name => "Charlotte Hornets", :colors => ["Turquoise", "Purple"], :players => { "Jeff Adrien" => { number: 4, shoe: 18, points: 10, rebounds: 1, assists: 1, steals: 2, blocks: 7, slam_dunks: 2}, "Bismak Biyombo" => { number: 0, shoe: 16, points: 12, rebounds: 4, assists: 7, steals: 7, blocks: 15, slam_dunks: 10}, "DeSagna Diop" => { number: 2, shoe: 14, points: 24, rebounds: 12, assists: 12, steals: 4, blocks: 5, slam_dunks: 5}, "Ben Gordon" => { number: 8, shoe: 15, points: 33, rebounds: 3, assists: 2, steals: 1, blocks: 1, slam_dunks: 0}, "Brendan Haywood" => { number: 33, shoe: 15, points: 6, rebounds: 12, assists: 12, steals: 22, blocks: 5, slam_dunks: 12} } #players hash } #away } #game hash end def num_points_scored(player_name) game_hash.each do |location, team_data| team_data.each do |att, value| if att == :players value.each do |player, data| if player == player_name data.each do |key, stat| if key == :points return stat end #key if end #data each end #player if end #values each end #if attribute end #team_data each end #game_hash each end #method def shoe_size(player_name) game_hash.each do |location, team_data| team_data.each do |att, value| if att == :players value.each do |player, data| if player == player_name data.each do |key, stat| if key == :shoe return stat.to_i end #key if end #data each end #player if end #values each end #if attribute end #team_data each end #game_hash each end #method def team_colors(team) team_color_scheme = [] if game_hash[:home][:team_name] == team team_color_scheme = game_hash[:home][:colors] elsif game_hash[:away][:team_name] == team team_color_scheme = game_hash[:away][:colors] else end #if return team_color_scheme end #method def team_names names_array = [] game_hash.each do |location, team_data| team_data.each do |key, value| if key == :team_name names_array << value end #if end #each end #each return names_array end #method def player_numbers(team) jerseys=[] if game_hash[:home][:team_name] == team game_hash[:home].each do |k , v| if k == :players v.each do |names, stats| stats.each do |key, value| if key == :number jerseys << value end #key if end #stat each end #v each end #player if end #home each elsif game_hash[:away][:team_name] == team game_hash[:away].each do |k, v| if k == :players v.each do |names, stats| stats.each do |key, value| if key == :number jerseys << value end #key if end #stat each end #v each end #player if end #away each else end #game_hash if return jerseys end #method def player_stats(player_name) if game_hash[:home][:players].include?(player_name) return game_hash[:home][:players][player_name] elsif game_hash[:away][:players].include?(player_name) return game_hash[:away][:players][player_name] else end #home if end #method def big_shoe_rebounds player_data = [] shoe_rebound = [] game_hash.each do |loc, team_data| team_data.each do |k, v| if k == :players v.each do |names,stats| stats.each do |stat, value| if stat == :shoe player_data << value end #shoe stat if if stat == :rebounds player_data << value end #rebound stat if end #stats each end #v each end #k if end #team_data each end #game_hash each player_data shoe_rebound = player_data.each_slice(2).to_a shoe_rebound.sort! shoe_rebound.flatten! shoe_rebound[-1] end #method
true
c7ad87c1a46daceb3e9cb771269f128752524154
Ruby
jasonchilcott/ruby-enumerables-hash-practice-emoticon-translator-lab-nyc01-seng-ft-082420
/lib/translator.rb
UTF-8
1,112
3.5
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# require modules here require "yaml" require "pry" def load_library(file_path) # code goes here emoticons = YAML.load_file(file_path) labeled_hash = {} emoticons.each do |key, value| # for each key, if it doesnt exist in labeled hash, create it, key value for each. labeled_hash[key] = {} labeled_hash[key][:english] = value[0] labeled_hash[key][:japanese] = value[1] end labeled_hash end def get_japanese_emoticon(file_path, emoticon) # code goes here results = "Sorry, that emoticon was not found" load_library(file_path).each do |meaning, emoticons| emoticons.each do |language, inner_value| if inner_value == emoticon results = load_library(file_path)[meaning][:japanese] end end end results end def get_english_meaning(file_path, emoticon) results = 'Sorry, that emoticon was not found'# code goes here load_library(file_path).each do |meaning, emoticons| emoticons.each do |language, inner_value| #if language is japanese if inner_value == emoticon results = meaning end end end results end
true
bba0406b9b3ef53fac20122df43a16ca87d1c79c
Ruby
ccgamble/black_thursday
/lib/invoice_item.rb
UTF-8
698
2.765625
3
[]
no_license
require 'pry' require 'bigdecimal' require 'time' class InvoiceItem attr_reader :id, :item_id, :invoice_id, :quantity, :unit_price, :created_at, :updated_at, :invoice_item_repository def initialize(column, parent = nil) @id = column[:id].to_i @item_id = column[:item_id].to_i @invoice_id = column[:invoice_id].to_i @quantity = column[:quantity].to_i @unit_price = BigDecimal.new(column[:unit_price].to_i)/BigDecimal(100) @created_at = Time.parse(column[:created_at]) @updated_at = Time.parse(column[:updated_at]) @invoice_item_repository = parent end def unit_price_in_dollars dollar_price = sprintf('%.02f', unit_price).to_f end end
true
86eacd74e7f1a40552848a7d4231737ff1cd5366
Ruby
uchennaanya/UCLinter
/lib/read_file.rb
UTF-8
436
3.15625
3
[ "MIT" ]
permissive
require 'colorize' class FileRead attr_reader :err_msg, :file_lines, :file_path, :file_lines_count def initialize(file_path) @err_msg = '' @file_path = file_path begin @file_lines = File.readlines(@file_path) @file_lines_count = @file_lines.size rescue StandardError => e @file_lines = [] @err_msg = "file name or path again\n".colorize(:light_red) + e.to_s.colorize(:red) end end end
true
7603b21189ea877fdadeb8f12d180e281ad5b261
Ruby
GabeHaff/tic-tac-toe-rb-online-web-sp-000
/lib/tic_tac_toe.rb
UTF-8
2,569
4.0625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end def input_to_index(input) input.to_i-1 end def move(display_board, index, character="X") display_board[index]=character end def position_taken?(board,index) if board[index]=="" || board[index]==" " || board[index]== nil return false else return true end end def valid_move?(board,index) if !position_taken?(board,index) && index.between?(0,8) return true else return false end end def move(display_board, index, character) display_board[index]=character end def turn(board) puts "Please enter 1-9:" input = gets.strip index = input_to_index(input) if valid_move?(board, index) token = current_player(board) move(board, index, token) display_board(board) else turn(board) end end def turn_count(board) counter= 0 board.each do |player| if player=="X" || player=="O" counter+=1 end end return counter end def current_player(board) turn=turn_count(board) if turn.even? return "X" else return "O" end end WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def won?(board) WIN_COMBINATIONS.each { |win_comb| win_index_1 = win_comb[0] win_index_2 = win_comb[1] win_index_3 = win_comb[2] position_1 = board[win_index_1] position_2 = board[win_index_2] position_3 = board[win_index_3] if position_1 == "X" && position_2 == "X" && position_3 == "X" return win_comb elsif position_1 == "O" && position_2 == "O" && position_3 == "O" return win_comb end } return false end def full?(board) if board.none? {|token|token== " "|| token=nil} return true else return false end end def draw?(board) if full?(board) &&!won?(board) return true else return false end end def over?(board) if draw?(board) && won?(board) return true elsif won?(board)&& !full?(board) || won?(board)&&full?(board) return true elsif draw?(board) return true else return false end end def winner(board) win = won?(board) if win == false return nil else if board[win[0]] == "X" return "X" else return "O" end end end def play(board) until over?(board) turn(board) end if won?(board) puts "Congratulations #{winner(board)}!" elsif draw?(board) puts "Cat's Game!" end end
true
dbe4ad287f9454c1fd231c29e8d24c4bfd50cf99
Ruby
unepwcmc/SAPI
/config/initializers/active_record_protected_deletion.rb
UTF-8
606
2.515625
3
[ "BSD-3-Clause" ]
permissive
module ProtectedDeletion # ideally override this def can_be_deleted? dependent_objects.empty? end # used to return informative error message on failed destroy def dependent_objects dependent_objects_map.map do |k, v| v.limit(1).count > 0 ? k : nil end.compact end protected # returns hash that maps the displayable name of a dependency # to a relation that returns dependent objects # e.g. for an object that has_many :foos: # {'amazingly important Foos' => foos} def dependent_objects_map {} end end ActiveRecord::Base.send :include, ProtectedDeletion
true
45670b3a8423dbbfeb238d242ccb71b606dc7cc3
Ruby
yana-gi/atcoder
/abc187/b/main_ans.rb
UTF-8
224
3.25
3
[]
no_license
n = gets.to_i # transpose x,y = n.times.map { gets.split.map(&:to_i) }.transpose ans = 0 (0..(n - 2)).each do |i| ((i + 1)..(n - 1)).each do |j| ans += 1 if (x[i] - x[j]).abs >= (y[i] - y[j]).abs end end puts ans
true
3f2dacab7d01301629bf60c36db6bc74b8786a9d
Ruby
alialsaihaty/augest-2015-ruby
/occurring_letter.rb
UTF-8
517
3.796875
4
[]
no_license
#Find a way that will return the letter that occurred most in a given string. For instance if you give it: Hello it will give back the letter:l puts "Please write any Word ?" sentence = gets.chomp # characters = sentence.chars hash = Hash.new(0) characters.each do |letter| hash[letter] += 1 end print hash.sortby {|k, v| v } puts hash.sortby {|k, v| v }.last[0] #a = letters.index('l') #puts a =begin c = wor.length d = c - 1 while 0 < c f = wor.count(wor[d]) puts f d -= 1 end ˜ =end
true
b2e923713fda768c91d67cced754302636808b5d
Ruby
emckean/quickscripts
/get_trending_concepts.rb
UTF-8
736
2.59375
3
[]
no_license
require 'csv' require 'cgi' require 'uri' api_token = 'REFRESH ME' #read in lists CSV file File.open(ARGV[0]) do |list_file| list_file.each do |line| guid = line.chomp # puts "" # puts "#{guid}" article = system ("curl https://api.helloreverb.com/v1/articles/id\\?guid=#{guid}\\&relatedArticleLimit=0\\&contentFormat=json-v1\\&api_token=#{api_token}") puts "#{article}," end # lists.each do |list| # guid = URI(list.url) # list_permalink = uri.path.sub( "/lists/", "" ) # puts "" # print "#{list_permalink}, #{list.topic}/n" # system ("curl \"https://api.helloreverb.com/v1/articles/id?guid={guid}&relatedArticleLimit=0&contentFormat=json-v1&api_token={api_token}\"") # end end
true
b524a57b300c504583b12d8f57670c2f521f09be
Ruby
cichlidx/ronco_et_al
/age_determination/ortholog_identification/src/get_rate_variation_from_log.rb
UTF-8
2,159
3.0625
3
[]
no_license
# m_matschiner Tue Jul 24 13:02:25 CEST 2018 module Enumerable def sum self.inject(0){|accum, i| accum + i } end def mean if self.length == 0 nil else self.sum/self.length.to_f end end end # Get the command line arguments. log_file_name = ARGV[0] # Read the BEAST log file. log_file = File.open(log_file_name) log_lines = log_file.readlines coefficients_of_variation = [] mutation_rates = [] out_of_comments = false coefficients_of_variation_index = nil mutation_rate_index = nil log_lines.each do |l| line_ary = l.split if line_ary[0].downcase == "sample" out_of_comments = true line_ary.size.times do |x| coefficients_of_variation_index = x if line_ary[x].match(/ucldStdev/) mutation_rate_index = x if line_ary[x].match(/mutationRate/) end elsif out_of_comments unless l[0] == "#" if coefficients_of_variation_index == 0 puts "ERROR: Column for coefficient of variation could not be found!" exit 1 end coefficients_of_variation << line_ary[coefficients_of_variation_index].to_f if mutation_rate_index == 0 puts "ERROR: Column for mutation rate could not be found!" exit 1 end mutation_rates << line_ary[mutation_rate_index].to_f end end end if coefficients_of_variation.size == 0 puts "ERROR: Coefficient of variation could not be read!" exit 1 end coefficients_of_variation = coefficients_of_variation[1..-1] number_of_burnin_samples = (coefficients_of_variation.size)/5 coefficients_of_variation_wo_burnin = coefficients_of_variation[number_of_burnin_samples+1..-1] coefficients_of_variation_wo_burnin_mean = coefficients_of_variation_wo_burnin.mean mutation_rates_wo_burnin = mutation_rates[number_of_burnin_samples+1..-1] mutation_rates_wo_burnin_mean = mutation_rates_wo_burnin.mean # Report the mean estimates for the coefficient of variation and the mutation rate. puts "#{mutation_rates_wo_burnin_mean}\t#{coefficients_of_variation_wo_burnin_mean}"
true
383d69aa29e286c44184cf14d418b88a393f2023
Ruby
hdgarrood/school_shop
/app/controllers/sales_controller.rb
UTF-8
1,114
2.515625
3
[]
no_license
require 'csv' class SalesController < ApplicationController before_filter :find_garment, :only => [:create, :new] # show a list of sales. Will soon also export CSV def index @sold_garments = Garment.sold respond_to do |format| format.html # show.html.haml format.csv { render :layout => false } end end # 'create' a new sale (sells a garment) def create if @garment.sell(params[:garment][:price]) flash[:notice] = t('garments.sold', :model => @garment) redirect_to @garment else handle_garment_already_sold end end # return a form for creating a new sale (ie selling a garment) def new handle_garment_already_sold if @garment.sold? end private def find_garment id = params[:garment_id] || (params[:garment] && params[:garment][:id]) @garment = id ? Garment.find(id) : Garment.new end # Handle occasions where a user is trying to sell a garment which has already # been sold. def handle_garment_already_sold flash[:warning] = t('garments.already_sold') redirect_to @garment end end
true
f2b1a7d1821e14f657caec2b0b94a9eb3d90ee6f
Ruby
raw1z/parchemin
/lib/parchemin/models/static.rb
UTF-8
830
2.875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# coding: utf-8 module Parchemin # This class represents a static content such as an about page class Static attr_reader :filename, :id # initializes the static content with its name def initialize(id) @id = id @filename = "#{Parchemin::Config.statics_path}/#{@id}.markdown" end # return the body of the static content. It is possible to prevent the markup's interpretation by passing false to the method. It is useful when you only have a paragraph and don't want to see <p></p> around it. def body(interpret_markdown=true) raise "#{@filename} doesn't exist." if not File.exist?(@filename) if interpret_markdown @body ||= RDiscount.new(File.read(@filename)).to_html else @body ||= File.read(@filename) end @body end end end
true
469a383390288b12a3fe38a335886aa22ec4e037
Ruby
jasoncomes/Random-Liquid-Filter
/rand.rb
UTF-8
364
2.890625
3
[]
no_license
# frozen_string_literal: true # rand / https://github.com/jasoncomes/Random-Liquid-Filter # Provides a randomized number up to the max number provided. # {{ max_number | rand }} module Rand def rand(input) max = input.to_i # Return 0 return max if max === 0 # Return Random.new.rand(max) end end Liquid::Template.register_filter(Rand)
true
2b9f066f64d64fcc0ba169bbf978550d79f76a94
Ruby
cnix/handy_capper
/lib/handy_capper/handy_capper.rb
UTF-8
7,290
3.34375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# Public: Various methods for scoring sailing regattas. # All methods are instance methods. # Currently only PHRF Time on Time and PHRF Time on Distance are supported. module HandyCapper # Public: Applies position and points to a group of results # # sort - Result attribute to sort by. (default: :corrected_time) # :one_design - sort by elapsed_time # :corrected_time - sort by corrected_time # # Examples # # # get some result objects from a database or something # results = Result.where('race_id = ?', 1) # # => [ #<Result ...>, #<Result ...>] # results.score(:corrected_time) # # returns results with position and points set # # => [ #<Result ...>, #<Result ...>] # results.first.position # # => 1 # results.first.points # # => 1 # # Returns receiver(Array) with position and points set for each item in the array def score(sort = :corrected_time) sort = (sort == :one_design) ? :elapsed_time : :corrected_time sorted_results = self.sort_by { |h| h[sort] } sorted_results.each_with_index do |result, index| result.position = index + 1 calculate_points(result, sorted_results.length) end sorted_results end # Public: Corects a result with the PHRF scoring system. # See http://http://offshore.ussailing.org/PHRF.htm # # options - Hash for setting a different PHRF scoring method (default: {}) # :formula - If you wish to use Time on Time, pass the Symbol :tot # Additionally, you can set the numerator and # denominator for the Time on Time formula by setting # values for :a & :b # :a - Set :a to a Fixnum to set the numerator of the formula # :b - Set :b to a Fixnum to set the denominator of the formula # # Examples # # # Assuming a class named Result in your application # result = Result.new({ # rating: 222, # start_time: '10:00:00', # finish_time: '11:30:30', # distance: 10.5 # }) # # result.phrf # # => #<Result ...> # result.elapsed_time # # => '01:30:30' # result.corrected_time # # => '00:59:50' # # # Using default settings for Time on Time formula # result.phrf(formula: :tot) # # => #<Result ...> # result.corrected_time # # => '01:16:12' # # # Change the denominator to accommodate conditions # result.phrf(formula: :tot, b: 480) # heavy air # # => #<Result ...> # result.corrected_time # # => '01:23:48' # # Returns receiver with elapsed_time and corrected_time set # Raises AttributeError if a required attribute is missing from the receiver def phrf(options={}) unless rating && start_time && finish_time raise AttributeError, "You're missing a required attribute to process this result" end self.elapsed_time = calculate_elapsed_time(self) if options[:formula] == :tot a = options[:a] || 650 # generic numerator b = options[:b] || 550 # average conditions ct_in_seconds = score_with_phrf_time_on_time(a,b) else ct_in_seconds = score_with_phrf_time_on_distance end self.corrected_time = convert_seconds_to_time(ct_in_seconds) self.elapsed_time = convert_seconds_to_time(self.elapsed_time) self end private # Internal: Calculate corrected time with PHRF Time on Distance # # result - corrected time in seconds # # Examples # # Result = Struct.new(:elapsed_time, :rating, :distance) # result = Result.new(5400, 222, 10.5) # result.score_with_phrf_time_on_distance # # => 3069 # # Returns a Fixnum def score_with_phrf_time_on_distance cf = self.rating et = self.elapsed_time d = self.distance (et - (d * cf)).round end # Internal: Calculate corrected time in seconds with PHRF Time on Time # # a - Numerator for TOT formula. Does not affect position. # b - Denominator for TOT formula. This one affects position. # # Examples # # Result = Struct.new(:elapsed_time, :rating) # result = Result.new(5400, 222) # result.score_with_phrf_time_on_time(b: 480) # # => 5000 # result.score_with_phrf_time_on_time(b: 600) # # => 4270 # # Returns a Fixnum representing corrected time in seconds def score_with_phrf_time_on_time(a, b) tcf = a.to_f / ( b.to_f + self.rating.to_f ) (self.elapsed_time * tcf).round end # Internal: Calculate delta in seconds between two time objects # # result - an object with a start_time and a finish_time attribute # # Examples # # Result = Struct.new(:start_time, :finish_time) # result = Result.new("10:00:00", "11:30:00") # calculate_elapsed_time(result) # # => 5400 # # Returns a Fixnum def calculate_elapsed_time(result) Time.parse(result.finish_time).to_i - Time.parse(result.start_time).to_i end # Internal: Covert seconds to a string of seconds # # seconds - a Fixnum representing time in seconds # # Examples # # convert_seconds_to_time(5400) # # => '01:30:00' # # Returns a string def convert_seconds_to_time(seconds) Time.at(seconds).gmtime.strftime('%R:%S') end # Internal: Calculate the points for a scored result # # result - A Result object # total_results - A Fixnum representing the number of results in the set # # Examples # # first_place_boat = Result.new({ # corrected_time: '01:30:41', # position: 1, # code: nil # }) # calculate_points(first_place_boat, 10) # # => #<Result ...> # first_place_boat.points # # => 1 # # dnf_boat = Result.new({ # corrected_time: nil, # position: 10, # code: 'DNF' # }) # calculate_points(dnf_boat, 10) # # => #<Result ...> # dnf_boat.points # # => 11 # # Returns the receiver with the points attribute set to a Fixnum def calculate_points(result, total_results) if result.code calculate_points_with_penalty(result, total_results) else result.points = result.position end result end # Internal: Calculate points based on a penalty code def calculate_points_with_penalty(result, total_results) if ONE_POINT_PENALTY_CODES.include?(result.code) result.points = total_results + 1 elsif TWENTY_PERCENT_PENALTY_CODES.include?(result.code) penalty_points = (total_results * 0.20).round if (penalty_points + result.position) > (total_results + 1) result.points = total_results + 1 else result.points = result.position + penalty_points end else result.points = result.position end result end # Internal: Array of String penalty codes that apply the n + 1 penalty where # n = the total number of entries for a fleet ONE_POINT_PENALTY_CODES = [ 'DSQ', 'DNS', 'DNC', 'DNF', 'OCS', 'BFD', 'DGM', 'DNE', 'RAF' ] # Internal: Array of String penalty codes that apply the 20% penalty TWENTY_PERCENT_PENALTY_CODES = [ 'ZFP', 'SCP' ] # Internal: Error that is raised when required attributes are missing from a # receiver for PHRF scoring class AttributeError < StandardError; end end
true
221f0dac2f6cae3c2fba3ca7d6256b6b54a45d3b
Ruby
mfliedner/codeeval-challenges
/string_permutations.rb
UTF-8
299
2.953125
3
[]
no_license
# Sample code to read in test cases: File.open(ARGV[0]).each_line do |line| # Do something with line, ignore empty lines #... line.chomp! unless line.empty? characters = line.split("") permutations = characters.permutation.to_a.map(&:join).sort puts permutations.join(",") end end
true
22658159b6b071ad1dfea1eafbefa329af02d753
Ruby
wesmangum/ruby-scavenger-hunt
/lib/integer_class.rb
UTF-8
373
3.65625
4
[]
no_license
require 'Prime' class Integer def factors a = (2..self).to_a a.keep_if { |x| self%x == 0 && x != self } # factors= [] # 2.upto(self) do |i| # if self%i == 0 # if i != 1 # factors << i # end # end # end # factors end def prime_factors self.factors.keep_if { |x| Prime.instance.prime?(x) } end end
true
18d79fee9f8512b05f08cb63113db089fe7a0569
Ruby
johncorderox/dojo
/learn/random_ruby/math.rb
UTF-8
443
3.4375
3
[]
no_license
class MathDojo def initialize @total = 0 end def add(*arguments) a = arguments.flatten @total += a.reduce(:+) self end def subtract(*arguments) a = arguments.flatten @total -= a.reduce(:+) self end def result puts "#{@total}" end end challenge1 = MathDojo.new.add(2).add(2, 5).subtract(3, 2).result challenge2 = MathDojo.new.add(1).add([3, 5, 7, 8], [2, 4.3, 1.25]).subtract([2,3], [1.1, 2.3]).result # => 23.15
true
052fbdcf5ad583a4841581bc174f84d7e890c399
Ruby
logstash-plugins/logstash-codec-cef
/lib/logstash/codecs/cef/timestamp_normalizer.rb
UTF-8
4,879
2.734375
3
[ "Apache-2.0" ]
permissive
# encoding: utf-8 require 'java' # The CEF specification allows a variety of timestamp formats, some of which # cannot be unambiguously parsed to a specific points in time, and may require # additional side-channel information to do so, namely: # - the time zone or UTC offset (which MAY be included in a separate field) # - the locale (for parsing abbreviated month names) # - the year (assume "recent") # # This normalizer attempts to use the provided context and make reasonable # assumptions when parsing ambiguous dates. class LogStash::Codecs::CEF::TimestampNormalizer java_import java.time.Clock java_import java.time.LocalDate java_import java.time.LocalTime java_import java.time.MonthDay java_import java.time.OffsetDateTime java_import java.time.ZoneId java_import java.time.ZonedDateTime java_import java.time.format.DateTimeFormatter java_import java.util.Locale def initialize(locale:nil, timezone:nil, clock: Clock.systemUTC) @clock = clock java_locale = locale ? get_locale(locale) : Locale.get_default java_timezone = timezone ? ZoneId.of(timezone) : ZoneId.system_default @cef_timestamp_format_parser = DateTimeFormatter .ofPattern("MMM dd[ yyyy] HH:mm:ss[.SSSSSSSSS][.SSSSSS][.SSS][ zzz]") .withZone(java_timezone) .withLocale(java_locale) end INTEGER_OR_DECIMAL_PATTERN = /\A[1-9][0-9]*(?:\.[0-9]+)?\z/ private_constant :INTEGER_OR_DECIMAL_PATTERN # @param value [String,Time,Numeric] # The value to parse. `Time`s are returned without modification, and `Numeric` values # are treated as millis-since-epoch (as are fully-numeric strings). # Strings are parsed unsing any of the supported CEF formats, and when the timestamp # does not encode a year, we assume the year from contextual information like the # current time. # @param device_timezone_name [String,nil] (optional): # If known, the time-zone or UTC offset of the device that encoded the timestamp. # This value is used to determine the offset when no offset is encoded in the timestamp. # If not provided, the system default time zone is used instead. # @return [Time] def normalize(value, device_timezone_name=nil) return value if value.kind_of?(Time) case value when Numeric then Time.at(Rational(value, 1000)) when INTEGER_OR_DECIMAL_PATTERN then Time.at(Rational(value, 1000)) else parse_cef_format_string(value.to_s, device_timezone_name) end end private def get_locale(spec) if spec.nil? Locale.get_default elsif spec =~ /\A([a-z]{2})_([A-Z]{2})\z/ lang, country = Regexp.last_match(1), Regexp.last_match(2) Locale.new(lang, country) else Locale.for_language_tag(spec) end end def parse_cef_format_string(value, context_timezone=nil) cef_timestamp_format_parser = @cef_timestamp_format_parser cef_timestamp_format_parser = cef_timestamp_format_parser.with_zone(java.time.ZoneId.of(context_timezone)) unless context_timezone.nil? parsed_time = cef_timestamp_format_parser.parse_best(value, ->(v){ ZonedDateTime.from(v) }, ->(v){ OffsetDateTime.from(v) }, ->(v){ resolve_assuming_year(v) }).to_instant # Ruby's `Time::at(sec, microseconds_with_frac)` Time.at(parsed_time.get_epoch_second, Rational(parsed_time.get_nano, 1000)) end def resolve_assuming_year(parsed_temporal_accessor) parsed_monthday = MonthDay.from(parsed_temporal_accessor) parsed_time = LocalTime.from(parsed_temporal_accessor) parsed_zone = ZoneId.from(parsed_temporal_accessor) now = ZonedDateTime.now(@clock.with_zone(parsed_zone)) parsed_timestamp_with_current_year = ZonedDateTime.of(parsed_monthday.at_year(now.get_year), parsed_time, parsed_zone) if (parsed_timestamp_with_current_year > now.plus_days(2)) # e.g., on May 12, parsing a date from May 15 or later is plausibly from # the prior calendar year and not actually from the future return ZonedDateTime.of(parsed_monthday.at_year(now.get_year - 1), parsed_time, parsed_zone) elsif now.get_month_value == 12 && (parsed_timestamp_with_current_year.plus_years(1) <= now.plus_days(2)) # e.g., on December 31, parsing a date from January 1 could plausibly be # from the very-near future but next calendar year due to out-of-sync # clocks, mismatched timezones, etc. return ZonedDateTime.of(parsed_monthday.at_year(now.get_year + 1), parsed_time, parsed_zone) else # otherwise, assume current calendar year return parsed_timestamp_with_current_year end end end
true
6c5a46172e08d8768d7a331b166ba4aae096a4f2
Ruby
toraritte/why_practice
/dwemthy.rb
UTF-8
1,647
3.796875
4
[]
no_license
class Creature # reimplementing in module? # trying it with method_missing? def self.mc class << self; self; end end # creates the class methods for storing the traits and attributes def self.traits( *attrib ) return @traits if attrib.empty? # storing the traits and values in a hash (@traits) # defines only setter methods but set attributes can # be checked with "traits" # eg. Dragon.traits => {:life=>1000, :strength=>500, :charisma=>120, :weapon=>900} attrib.each do |a| mc.class_eval do define_method( a ) do |value| @traits ||={} @traits[a] = value end end end # trait getters and setters for the instances of new creatures # eg. Dragon.new.life #=> 1000 attr_accessor( *attrib ) end # originally in the poignant guide it looked like below but # it is unnecessary because: # class_eval do ---> evaluates the code in the context of the class # define_method( :initialize ) do ---> therefore creating an instance method which is # ( the rest is the same) the same as "def initialize" and nothing justifies # its use. def initialize self.class.traits.each do |k,v| # passing the values to each new instance of instance_variable_set "@#{k}",v # Creature and its subclasses end end traits :life,:strength,:charisma,:weapon end class Dragon < Creature # these need to be class methods in creature -> self.traits life 1000 strength 500 charisma 120 weapon 900 end
true
64ad6be9fa0405058ced1dded96a98868ce286a6
Ruby
TIY-ATL-ROR-2016-Feb/lectures
/wk03-internets/tue/student.rb
UTF-8
550
3.375
3
[]
no_license
require "pry" require "./puppies" module Example class Student def initialize(first, last) @name = "#{first} #{last}" end def to_s "#<Student Name: #{@name}>" end end # Student here refers to the definition inside the module binding.pry end class Student def feed_me puts "SAMOAS SAMOAS SAMOAS!!!!" end def self.build_classroom students = [] 10.times do students.push(Student.new) end students end end # Student here refers to the definition outside the module binding.pry
true
7b3aafa4fbf3404d06498ee1f2ff5cfca6571bf9
Ruby
ssamuel56/fizzbuzz_array
/fizzbuzz_array_tdd.rb
UTF-8
1,303
3
3
[]
no_license
require_relative 'fizzbuzz_array.rb' require 'minitest/autorun' class Testing < Minitest::Test def test_array1 assert_equal(Array, fizz_array().class) end def test_array2 assert_equal([], fizz_array) end def test_buzz1 assert_equal([1], buzz(1, fizz_array)) end def test_buzz2 assert_equal(["mined"], buzz(15, fizz_array)) end def test_buzz3 assert_equal(["minds"], buzz(5, fizz_array)) end def test_buzz4 assert_equal(["mined minds"], buzz(3, fizz_array)) end def test_buzz5 assert_equal(["minds"], buzz(20, fizz_array)) end def test_buzz6 assert_equal([38], buzz(38, fizz_array)) end def test_buzz7 assert_equal(["mined"], buzz(75, fizz_array)) end def test_buzz8 assert_equal([8], buzz(8, fizz_array)) end def test_buzz9 assert_equal(["minds"], buzz(400, fizz_array)) end def test_buzz10 assert_equal([4], buzz(4, fizz_array)) end def test_buzz11 assert_equal([17], buzz(17, fizz_array)) end def test_buzz12 assert_equal([28], buzz(28, fizz_array)) end def test_buzz13 assert_equal([14], buzz(14, fizz_array)) end def test_buzz14 assert_equal(["mined minds"], buzz(84, fizz_array)) end def test_buzz15 assert_equal(["mined minds"], buzz(156, fizz_array)) end end
true
92fe9fc86f7e73bb8be5901672fdad0775679862
Ruby
naiginod/Foundations
/level3/medium2.rb
UTF-8
1,660
3.984375
4
[]
no_license
Question 1 munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" } } age_sum = 0 munsters.each do |name, details| if details["gender"] == "male" age_sum += details['age'] end end p age_sum Question 2 munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" } } munsters.each do |name, details| puts "#{name} is a #{details["age"]} year old #{details["gender"]}" end Question 3 def easy_method(a_string_param, an_array_param) a_string_param += "rutabaga" an_array_param << "rutabaga" return a_string_param, an_array_param end my_string = "pumpkins" my_array = ["pumpkins"] (my_string, my_array) my_string, my_array = easy_method(my_string, my_array) puts "My string looks like this now: #{my_string}" puts "My array looks like this now: #{my_array}" Question 4 sentence = "Humpty Dumpty sat on a wall." sentence.split(" ").reverse.join(" ") -- words = sentence.split(/\W/) words.reverse! backwards_sentence = words.join(' ') + '.' Question 5 34, because the method does not affect mutate the original object Question 6 Yes, because "munsters" does not get reassigned inside the method so the original is affected. Question 7 paper Question 8 "no" because methods return the last line by default and for foo() that is "yes". So bar("yes") throws a false for the question param =="no". False returns "no"
true
7867950b1e5d769acb3d05441e2aaf06482585df
Ruby
FarazPatankar/Ironhack
/week_0/ruby/Boggle_Board_One/boggle_board_one.rb
UTF-8
1,531
3.375
3
[]
no_license
#end class BoggleBoard attr_accessor :array_of_dices def initialize @array_of_dices = [] end def push_to_board @array_of_dices.push("AAEEGN") @array_of_dices.push("ELRTTY") @array_of_dices.push("AOOTTW") @array_of_dices.push("ABBJOO") @array_of_dices.push("EHRTVW") @array_of_dices.push("EHRTVW") @array_of_dices.push("CIMOTU") @array_of_dices.push("DISTTY") @array_of_dices.push("EIOSST") @array_of_dices.push("DELRVY") @array_of_dices.push("ACHOPS") @array_of_dices.push("HIMNQU") @array_of_dices.push("EEINSU") @array_of_dices.push("EEGHNW") @array_of_dices.push("AFFKPS") @array_of_dices.push("HLNNRZ") @array_of_dices.push("DEILRX") end def shake! single_letter_strings = '' @array_of_dices.each do |x| x = x.split(//) single_letter_strings << x.sample end four_letter_arrays = single_letter_strings.scan(/..../) row_one = four_letter_arrays[0] row_two = four_letter_arrays[1] row_three = four_letter_arrays[2] row_four = four_letter_arrays[3] row_one.gsub!(/(.{1})/, '\1 ') row_two.gsub!(/(.{1})/, '\1 ') row_three.gsub!(/(.{1})/, '\1 ') row_four.gsub!(/(.{1})/, '\1 ') if row_one.include? "Q" row_one.sub!("Q", "Qu") elsif row_two.include? "Q" row_two.sub!("Q", "Qu") elsif row_three.include? "Q" row_three.sub!("Q", "Qu") elsif row_four.include? "Q" row_four.sub!("Q", "Qu") end puts row_one puts row_two puts row_three puts row_four end end board = BoggleBoard.new board.push_to_board board.shake!
true
e3a3dff559939d654b60b3c24ae0d16e555d0848
Ruby
efertsch/phase-0-tracks
/boosters/week6_booster/classy_house.rb
UTF-8
1,453
4.1875
4
[]
no_license
require_relative 'classy_rooms' require_relative 'classy_items' class House attr_reader :rooms def initialize @rooms = [] end def add_room(room) if rooms.length < 11 @rooms << room true else false end end def total_value end def to_s house_str = "" @rooms.each do |room| house_str << room.to_s house_str << "\n\n" room.items.each do |item| house_str << item.to_s house_str << "\n" end house_str << "\n" end house_str end end #DRIVER CODE house = House.new living_room = Rooms.new("living room", 20, 20) sofa = Items.new("Sofa", "Green", 15000) lamp = Items.new("lamp", "beige", 100) living_room.items << sofa living_room.items << lamp kitchen = Rooms.new("Kitchen", 15, 20) sink = Items.new("sink", "white", 500) oven = Items.new("oven", "black", 1000) kitchen.items << sink kitchen.items << oven house.add_room(living_room) house.add_room(kitchen) puts house # SKILLS DEMONSTRATED # Defining classes # Setting instance attributes # Using attr_accessor and attr_reader # Writing instance methods # Spreading classes across multiple files (relatively new concept) #PSEDUDOCODE: BUILD A HOUSE OUT OF CLASSES # HOUSE CLASS # Attributes: #rooms (collection of rooms instances) # Methods: # getter for rooms # add_room (up to 10) # square_footage (adds up house square footage) # total value of house # to_s overrride
true
45528aa147958eb7eb3fe8081e0c55e871d9963e
Ruby
kaljt/intermediate_quiz_3
/Ex4.rb
UTF-8
873
3.828125
4
[]
no_license
def tricky_method_two(a_string_param, an_array_param) puts "a_string_param id #{a_string_param.object_id}" puts "an_array id #{an_array_param.object_id}" a_string_param.gsub!('pumpkins', 'rutabaga') puts "after gsub a_string id is #{a_string_param.object_id}" an_array_param = ['pumpkins', 'rutabaga'] puts "after assign an_array id is #{an_array_param.object_id}" end my_string = "pumpkins" puts "my_string object id #{my_string.object_id}" my_array = ["pumpkins"] puts "my_array object id #{my_array.object_id}" tricky_method_two(my_string, my_array) puts "after method call my_string id is #{my_string.object_id}" puts "after method call my_array is is #{my_array.object_id}" #will print "rutabaga" for my_string #and will print ["pumpkins"] for my_array puts "My string looks like this now: #{my_string}" puts "My array looks like this now: #{my_array}"
true
421d55194edecafab4790a3bf40c1ab3f66eb818
Ruby
regularfry/ducks
/lib/ducks/protocol.rb
UTF-8
1,963
2.984375
3
[ "MIT" ]
permissive
# encoding: utf-8 module Ducks # We subclass Module so that Ruby knows to pick out the constant # name for #inspect class Protocol < Module def initialize( &blk ) @methods = [] instance_exec &blk end def defines( *args ) @methods << args end def implemented_by?( potential_anatid ) @methods.all?{ |method_name,arity = :any,*_| check_method( potential_anatid, method_name, arity ) } end def implemented_by_class?( potential_anatidae ) @methods.all?{ |method_name, arity = :any, *_| check_instance_method( potential_anatidae, method_name, arity ) } end def missing_methods( potential_anatid ) @methods.reject{ |method_name, arity = :any, *_| check_method( potential_anatid, method_name, arity) }.map{ |first, *second| first } end private def arities_match?( protocol_arity, method_arity ) protocol_arity == method_arity end def check_method( potential_anatid, method_name, arity ) if potential_anatid.public_methods.include? method_name if arity == :any true else method = potential_anatid.method method_name arities_match? arity, method.arity end elsif potential_anatid.respond_to? method_name # looser test because we can't test arity, but we don't generate # any false positives as a consequence. true end end def check_instance_method( potential_anatidae, method_name, arity ) # This is slightly problematic, because we generate false # positives. if potential_anatidae.public_instance_methods.include? method_name if arity == :any true else method = potential_anatidae.instance_method method_name arities_match? arity, method.arity end end end end def self.protocol(&blk) Protocol.new &blk end end
true
070ea332526727603eb6bca1b22e910a7eebcdf0
Ruby
zachlp2016/market_1901
/lib/market.rb
UTF-8
1,503
3.46875
3
[]
no_license
class Market attr_reader :name, :vendors def initialize(name) @name = name @vendors = [] end def add_vendor(vendor) @vendors << vendor end def vendor_names vendor_name_arr = [] @vendors.each do |vendor| vendor_name_arr << vendor.name end return vendor_name_arr end def vendors_that_sell(item) vendors_that_sell_arr = [] @vendors.each do |vendor| vendor.inventory.each do |inventory| if inventory[0] == item vendors_that_sell_arr << vendor end end end return vendors_that_sell_arr end def sorted_item_list sorted_item_list_arr = [] @vendors.each do |vendor| vendor.inventory.each do |inventory| sorted_item_list_arr << inventory[0] end end return sorted_item_list_arr.sort.uniq end def total_inventory total_inventory_hash = Hash.new{0} @vendors.each do |vendor| vendor.inventory.each do |inventory| total_inventory_hash[inventory[0]] += inventory[1] end end return total_inventory_hash end def sell(item, count) total_inventory.each do |inventory| if inventory[0] == item && inventory[1] >= count @vendors.each do |vendor| vendor.inventory.each do |inventory| if inventory[0] == item vendor.inventory[item] = inventory[1] - count end end end return true end end return false end end
true
20c7aa690ab30300287db0350ae6d9554d53c227
Ruby
CharlesABlum/CS214
/10/ruby/Bird.rb
UTF-8
543
3.6875
4
[]
no_license
# Bird.rb | Defines a Bird superclass to be extended by specific bird # sub-classes. # # Begun by: Dr. Adams, for CS 214 at Calvin College. # Completed by:Charles Blum # Date:29 April 2014 #################################################### class Bird attr_reader :name def initialize(name) @name = name end def call "Squaaaaaaaaaaaawk!" end def className self.class.to_s end def print puts name + ' ' + className + " just " + movement + " and said " + call end def movement "flew past" end end
true
bae3d6f5d30151346b149d21d2c8e68eb8d042f1
Ruby
AlexNimoy/RubyPatterns
/structural/flyweight/main.rb
UTF-8
1,159
3.609375
4
[]
no_license
# frozen_string_literal: true # Unit class Unit attr_accessor :x, :y def initialize(shared, unit_type) @shared = shared @unit_type = unit_type end end # Shared data for Cavalry class UnitCavalryShared def initialize @name = 'cavalry' @sprite = 'sp.jpg' @sound = 'igogo.mp3' @speep = 10 @horse_texture = 'horse.jpg' end end # Shared data for Infantry class UnitInfantryShared def initialize @name = 'Infantry' @sprite = 'in.jpg' @sound = 'ura.mp3' @speep = 5 end end # Army actions class Army attr_reader :units def initialize(units) @units = units end def move(x_coordinate, y_coordinate) @units.each do |unit| unit.x = x_coordinate unit.y = y_coordinate end end end # shared data cavalry_shared = UnitCavalryShared.new infantry_shared = UnitInfantryShared.new # create units cavalry_unit = Unit.new(cavalry_shared, 'cavalry') cavalry_unit.x = 1 cavalry_unit.y = 2 infantry_unit = Unit.new(infantry_shared, 'infantry') infantry_unit.x = 2 infantry_unit.y = 2 # group army army = Army.new([cavalry_unit, infantry_unit]) # move army.move(5, 5) p army.units
true
fd5e176c13ab21973d4be42e341223cde8108d6f
Ruby
httplab/insales_app_core
/lib/insales_app_core/account_setting.rb
UTF-8
1,369
2.578125
3
[]
no_license
class InsalesAppCore::AccountSetting attr_accessor :name, :title, :description, :type, :control, :required def initialize(&block) block.call(self) if block_given? end def get_value(raw_value, acc) if raw_value.nil? val = @default_value.respond_to?(:call) ? @default_value.call(acc) : @default_value if val.nil? return nil else val = get_value(val, acc) acc.set_setting(self.name, val) return val end end case @type when :integer raw_value.to_i when :boolean [1, '1', 'true', true, 'on', :on, :true].include?(raw_value) when :string_set raw_value.split('%') else raw_value end end def prepare_value(user_value) case @type when :boolean if [1, '1', 'true', true, 'on', :on, :true].include?(user_value) 'true' else 'false' end when :string_set user_value.map(&:to_s).uniq.join('%') else user_value end end def default_value(val = nil, &block) @default_value = if val.nil? block else val end end def allowed_values=(val = nil, &block) @allowed_values = val || block end def allowed_values(acc) if @allowed_values.respond_to?(:call) @allowed_values.call(acc) else @allowed_values end end end
true
26b246f1505e47b75b448b17b68f68804e32e7e1
Ruby
cowboy-cod3r/sandbox
/00-tests/03/reverse/exec.rb
UTF-8
204
3.25
3
[]
no_license
#!/opt/apps/ruby/ruby/bin/ruby def reverse_words_and_letters(sentence) return sentence.reverse end sentence = "Reverse this sentence along with the letters." puts reverse_words_and_letters(sentence)
true
38f67d8e75cf6fc7c1accd2b3d510b2ba30babc6
Ruby
celluloid/celluloid
/lib/celluloid/task/threaded.rb
UTF-8
1,515
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Celluloid class Task # Tasks with a Thread backend class Threaded < Task # Run the given block within a task def initialize(type, meta) @resume_queue = Queue.new @exception_queue = Queue.new @yield_mutex = Mutex.new @yield_cond = ConditionVariable.new @thread = nil super end def create # TODO: move this to ActorSystem#get_thread (ThreadHandle inside Group::Pool) thread = Internals::ThreadHandle.new(Thread.current[:celluloid_actor_system], :task) do begin ex = @resume_queue.pop raise ex if ex.is_a?(TaskTerminated) yield rescue ::Exception => ex @exception_queue << ex ensure @yield_mutex.synchronize do @yield_cond.signal end end end @thread = thread end def signal @yield_mutex.synchronize do @yield_cond.signal end @resume_queue.pop end def deliver(value) raise DeadTaskError, "cannot resume a dead task" unless @thread.alive? @yield_mutex.synchronize do @resume_queue.push(value) @yield_cond.wait(@yield_mutex) raise @exception_queue.pop until @exception_queue.empty? end rescue ThreadError raise DeadTaskError, "cannot resume a dead task" end def backtrace @thread.backtrace end end end end
true
2573fac7c9a54b1d55e7559a60b0b669cdcc620a
Ruby
ogom/grant-front
/lib/grant-front/diagram.rb
UTF-8
1,064
2.65625
3
[ "MIT" ]
permissive
module GrantFront class Diagram class << self def draw(options={}) puts self.new(options).create end end def initialize(options={}) @options = options end def create policies = [] GrantFront::Policy.all(@options).each do |policy| if @options[:classes].nil? or @options[:classes].include?(policy.klass) policies << GrantFront::Policy.find(policy.klass) end end text = '' policies.each do |policy| text += "\n### #{policy.name}\n\n" if policy.roles.count > 0 text += "||#{policy.roles.join('|')}|\n" text += "|:-|#{policy.roles.map{':-:'}.join('|')}|\n" policy.methods.keys.each do |method| raw = "|#{method}|" policy.roles.each do |role| raw += 'o' if policy.methods[method].include?(role) raw += '|' end text += "#{raw}\n" end else text += "* no policy\n" end end text end end end
true
203903ca177ba573acf9f6e91d62f0c6d7e662a6
Ruby
B-Graziani/blog
/db/seeds.rb
UTF-8
1,195
2.765625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts "cleaning DB" Flat.destroy_all puts "creating DB" flat1 = { title: "title 1", address: "address1", description: "description1description1description1description1", stars: "1"} flat2 = { title: "title 2", address: "address2", description: "description2description2description2description2", stars: "2"} flat3 = { title: "title 3", address: "address3", description: "description3description3description3description3", stars: "3"} flat4 = { title: "title 4", address: "address4", description: "description4description4description4description4", stars: "4"} flat5 = { title: "title 5", address: "address5", description: "description5description5description5description5", stars: "5"} Flats = [] [flat1, flat2, flat3, flat4, flat5].each_with_index do |attributes, index| flat = Flat.create!(attributes) Flats << flat end
true
1221ddd4c7c9e97540f3018841b9dcd81b3f8688
Ruby
zhimin/rwebunit
/lib/rwebunit/driver.rb
UTF-8
24,732
2.8125
3
[ "MIT" ]
permissive
# convenient methods to drive the browser. # # Instead of # browser.click_button("submit") # You can just use # click_button("submit") # require File.join(File.dirname(__FILE__), 'itest_plugin') require File.join(File.dirname(__FILE__), 'popup') require 'timeout' require 'uri' module RWebUnit module Driver include RWebUnit::ITestPlugin include RWebUnit::Popup @@default_polling_interval = 1 # second @@default_timeout = 30 # seconds # open a browser, and set base_url via hash, but does not acually # # example: # open_browser :base_url => http://localhost:8080 # # There are 3 ways to set base url # 1. pass as first argument # 2. If running using iTest2, used as confiured # 3. Use default value set def open_browser(base_url = nil, options = {}) base_url ||= $ITEST2_PROJECT_BASE_URL base_url ||= $BASE_URL raise "base_url must be set" if base_url.nil? default_options = {:speed => "fast", :visible => true, :highlight_colour => 'yellow', :close_others => true, :start_new => false, # start a new browser always :go => true} options = default_options.merge options options[:firefox] = true if "Firefox" == $ITEST2_BROWSER || "Firefox" == $BROWSER ($ITEST2_HIDE_BROWSER) ? $HIDE_IE = true : $HIDE_IE = false if base_url =~ /^file:/ uri_base = base_url else uri = URI.parse(base_url) uri_base = "#{uri.scheme}://#{uri.host}:#{uri.port}" end if options[:start_new] @web_browser = WebBrowser.new(uri_base, nil, options) else @web_browser = WebBrowser.reuse(uri_base, options) # Reuse existing browser end if base_url =~ /^file:/ goto_url(base_url) # for files, no base url else (uri.path.length == 0) ? begin_at("/") : begin_at(uri.path) if options[:go] end return @web_browser end alias open_browser_with open_browser # return the underlying RWebUnit::Browser object def browser @web_browser end # Close the current browser window (started by the script). If no browser started, then close # all browser windows. # def close_browser if @web_browser # Old iTest2 version # @web_browser.close_browser unless $ITEST2_LEAVE_BROWSER_OPEN_AFTER_RUN @web_browser.close_browser else WebBrowser.close_all_browsers end end alias close_ie close_browser # Close all opening browser windows # def close_all_browsers if is_firefox? FireWatir::Firefox.close_all else Watir::IE.close_all end end # Verify the next page following an operation. # # Typical usage: # login_page.click_login # expect_page HomePage def expect_page(page_clazz, argument = nil) if argument page_clazz.new(@web_browser, argument) else page_clazz.new(@web_browser) end end def context @web_browser.context end # Starting browser with a URL # # Example: # begin_at("http://www.itest2.com") def begin_at(url) dump_caller_stack @web_browser.begin_at(url) end # Return the Watir::IE instance # def ie @web_browser.ie end # Return the FireWatir::Firefox instance # def firefox @web_browser.firefox end def is_firefox? @web_browser.is_firefox? if @web_browser end # Go to another page on the testing site. # # open_browser("http://www.itest2.com") # goto_page("/demo") # visit page http://www.itest2.com/demo # def goto_page(page) operation_delay dump_caller_stack @web_browser.goto_page(page) if @web_browser end alias visit goto_page # Go to another web site, normally different site being tested on # # open_browser("http://www.itest2.com") # goto_url("http://myorganized.info") def goto_url(url) @web_browser.goto_url url end # Attach to existinb browser window # # attach_browser(:title, ) def attach_browser(how, what, options = {}) options.merge!(:browser => is_firefox? ? "Firefox" : "IE") begin options.merge!(:base_url => browser.context.base_url) rescue => e puts "error to attach to browser: #{e}" end WebBrowser.attach_browser(how, what, options) end # Reuse current an opened browser window instead of opening a new one # example: # use_current_browser(:title, /.*/) # use what ever browser window # use_current_browser(:title, "iTest2") # use browser window with title "iTest2" def use_current_browser(how = :title, what = /.*/) @web_browser = WebBrowser.attach_browser(how, what) end ## # Delegate to WebTester # # Note: # label(:id, "abc") # OK # label(:id, :abc) # Error # # Depends on which object type, you can use following attribute # More details: http://wiki.openqa.org/display/WTR/Methods+supported+by+Element # # :id Used to find an element that has an "id=" attribute. Since each id should be unique, according to the XHTML specification, this is recommended as the most reliable method to find an object. * # :name Used to find an element that has a "name=" attribute. This is useful for older versions of HTML, but "name" is deprecated in XHTML. * # :value Used to find a text field with a given default value, or a button with a given caption, or a text field # :text Used for links, spans, divs and other element that contain text. # :index Used to find the nth element of the specified type on a page. For example, button(:index, 2) finds the second button. Current versions of WATIR use 1-based indexing, but future versions will use 0-based indexing. # :class Used for an element that has a "class=" attribute. # :title Used for an element that has a "title=" attribute. # :xpath Finds the item using xpath query. # :method Used only for forms, the method attribute of a form is either GET or POST. # :action Used only for form elements, specifies the URL where the form is to be submitted. # :href Used to identify a link by its "href=" attribute. # :src Used to identify an image by its URL. # # area <area> tags # button <input> tags with type=button, submit, image or reset # check_box <input> tags with type=checkbox # div <div> tags # form <form> tags # frame frames, including both the <frame> elements and the corresponding pages # h1 - h6 <h1>, <h2>, <h3>, <h4>, <h5>, <h6> tags # hidden <input> tags with type=hidden # image <img> tags # label <label> tags (including "for" attribute) # li <li> tags # link <a> (anchor) tags # map <map> tags # radio <input> tags with the type=radio; known as radio buttons # select_list <select> tags, known as drop-downs or drop-down lists # span <span> tags # table <table> tags, including row and cell methods for accessing nested elements # text_field <input> tags with the type=text (single-line), type=textarea (multi-line), and type=password # p <p> (paragraph) tags, because [:area, :button, :cell, :checkbox, :div, :form, :frame, :h1, :h2, :h3, :h4, :h5, :h6, :hidden, :image, :li, :link, :map, :pre, :row, :radio, :select_list, :span, :table, :text_field, :paragraph, :file_field, :label].each do |method| define_method method do |*args| dump_caller_stack # add check for @web_browser, in case the moudule included without init browser @web_browser.send(method, *args) if @web_browser end end alias td cell alias check_box checkbox # seems watir doc is wrong, checkbox not check_box alias tr row [:back, :forward, :refresh].each do |method| define_method(method) do dump_caller_stack operation_delay @web_browser.send(method) if @web_browser end end alias refresh_page refresh alias go_back back alias go_forward forward [:images, :links, :buttons, :select_lists, :checkboxes, :radios, :text_fields].each do |method| define_method method do dump_caller_stack @web_browser.send(method) if @web_browser end end # Check one or more checkboxes with same name, can accept a string or an array of string as values checkbox, pass array as values will try to set mulitple checkboxes. # # page.check_checkbox('bad_ones', 'Chicken Little') # page.check_checkbox('good_ones', ['Cars', 'Toy Story']) # [:set_form_element, :click_link_with_text, :click_link_with_id, :submit, :click_button_with_id, :click_button_with_name, :click_button_with_caption, :click_button_with_value, :click_radio_option, :clear_radio_option, :select_file_for_upload, :check_checkbox, :uncheck_checkbox, :select_option].each do |method| define_method method do |*args| dump_caller_stack operation_delay @web_browser.send(method, *args) if @web_browser end end alias enter_text set_form_element alias set_hidden_field set_form_element alias click_link click_link_with_text alias click_button_with_text click_button_with_caption alias click_button click_button_with_caption alias click_radio_button click_radio_option alias clear_radio_button clear_radio_option # for text field can be easier to be identified by attribute "id" instead of "name", not recommended though def enter_text_with_id(textfield_id, value) dump_caller_stack operation_delay text_field(:id, textfield_id).set(value) end def contains_text(text) @web_browser.contains_text(text) end # Click image buttion with image source name # # For an image submit button <input name="submit" type="image" src="/images/search_button.gif"> # click_button_with_image("search_button.gif") def click_button_with_image_src_contains(image_filename) dump_caller_stack operation_delay found = nil raise "no buttons in this page" if buttons.length <= 0 buttons.each { |btn| if btn && btn.src && btn.src.include?(image_filename) then found = btn break end } raise "not image button with src: #{image_filename} found" if found.nil? found.click end alias click_button_with_image click_button_with_image_src_contains def new_popup_window(options) @web_browser.new_popup_window(options) end # Warning: this does not work well with Firefox yet. def element_text(elem_id) @web_browser.element_value(elem_id) end # Identify DOM element by ID # Warning: it is only supported on IE def element_by_id(elem_id) @web_browser.element_by_id(elem_id) end # --- # For debugging # --- def dump_response(stream = nil) @web_browser.dump_response(stream) end # For current page souce to a file in specified folder for inspection # # save_current_page(:dir => "C:\\mysite", filename => "abc", :replacement => true) def save_current_page(options = {}) default_options = {:replacement => true} options = default_options.merge(options) if options[:dir] # already defined the dir to_dir = options[:dir] elsif $ITEST2_RUNNING_SPEC_ID && $ITEST2_WORKING_DIR $ITEST2_DUMP_DIR = File.join($ITEST2_WORKING_DIR, "dump") FileUtils.mkdir($ITEST2_DUMP_DIR) unless File.exists?($ITEST2_DUMP_DIR) spec_run_id = $ITEST2_RUNNING_SPEC_ID spec_run_dir_name = spec_run_id.to_s.rjust(4, "0") unless spec_run_id == "unknown" to_dir = File.join($ITEST2_DUMP_DIR, spec_run_dir_name) else to_dir = ENV['TEMP_DIR'] || "C:\\temp" end if options[:filename] file_name = options[:filename] else file_name = Time.now.strftime("%m%d%H%M%S") + ".html" end Dir.mkdir(to_dir) unless File.exists?(to_dir) file = File.join(to_dir, file_name) content = page_source base_url = @web_browser.context.base_url current_url = @web_browser.url current_url =~ /(.*\/).*$/ current_url_parent = $1 if options[:replacement] && base_url =~ /^http:/ File.new(file, "w").puts absolutize_page_hpricot(content, base_url, current_url_parent) else File.new(file, "w").puts content end end # <link rel="stylesheet" type="text/css" href="/stylesheets/default.css" /> # '<script type="text/javascript" src="http://www.jeroenwijering.com/embed/swfobject.js"></script>' # <script type="text/javascript" src="/javascripts/prototype.js"></script> # <script type="text/javascript" src="/javascripts/scriptaculous.js?load=effects,builder"></script> # <script type="text/javascript" src="/javascripts/extensions/gallery/lightbox.js"></script> # <link href="/stylesheets/extensions/gallery/lightbox.css" rel="stylesheet" type="text/css" /> # <img src="images/mission_48.png" /> def absolutize_page(content, base_url, current_url_parent) modified_content = "" content.each_line do |line| if line =~ /<script\s+.*src=["'']?(.*)["'].*/i then script_src = $1 substitute_relative_path_in_src_line(line, script_src, base_url, current_url_parent) elsif line =~ /<link\s+.*href=["'']?(.*)["'].*/i then link_href = $1 substitute_relative_path_in_src_line(line, link_href, base_url, current_url_parent) elsif line =~ /<img\s+.*src=["'']?(.*)["'].*/i then img_src = $1 substitute_relative_path_in_src_line(line, img_src, base_url, current_url_parent) end modified_content += line end return modified_content end # absolutize_page referencs using hpricot # def absolutize_page_hpricot(content, base_url, parent_url) begin require 'hpricot' doc = Hpricot(content) base_url.slice!(-1) if ends_with?(base_url, "/") (doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || ""} (doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || ""} (doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || ""} return doc.to_html rescue => e absolutize_page(content, base_url, parent_url) end end ## # change # <script type="text/javascript" src="/javascripts/prototype.js"></script> # to # <script type="text/javascript" src="http://itest2.com/javascripts/prototype.js"></script> def absolutify_url(src, base_url, parent_url) if src.nil? || src.empty? || src == "//:" || src =~ /\s*http:\/\//i return src end return "#{base_url}#{src}" if src =~ /^\s*\// return "#{parent_url}#{src}" if parent_url return src end # substut def substitute_relative_path_in_src_line(line, script_src, host_url, page_parent_url) unless script_src =~ /^["']?http:/ host_url.slice!(-1) if ends_with?(host_url, "/") if script_src =~ /^\s*\// # absolute_path line.gsub!(script_src, "#{host_url}#{script_src}") else #relative_path line.gsub!(script_src, "#{page_parent_url}#{script_src}") end end end def ends_with?(str, suffix) suffix = suffix.to_s str[-suffix.length, suffix.length] == suffix end # current web page title def page_title @web_browser.page_title end # current page source (in HTML) def page_source @web_browser.page_source end # return plain text view of page def page_text @web_browser.text end # return the text of specific (identified by attribute "id") label tag # For page containing # <label id="preferred_ide">iTest2</label> # label_with_id("preferred_ids") # => iTest2 def label_with_id(label_id) label(:id, label_id.to_s).text end # return the text of specific (identified by attribute "id") span tag # For page containing # <span id="preferred_recorder">iTest2/Watir Recorder</span> # span_with_id("preferred_recorder") # => iTest2/Watir Recorder def span_with_id(span_id) span(:id, span_id).text end # return the text of specific (identified by attribute "id") ta tag # For page containing # <td id="preferred_recorder">iTest2/Watir Recorder</span> # td_with_id("preferred_recorder") # => iTest2/Watir Recorder def cell_with_id(cell_id) cell(:id, cell_id).text end alias table_data_with_id cell_with_id def is_mac? RUBY_PLATFORM.downcase.include?("darwin") end def is_windows? RUBY_PLATFORM.downcase.include?("mswin") or RUBY_PLATFORM.downcase.include?("mingw32") end def is_linux? RUBY_PLATFORM.downcase.include?("linux") end # Support browser (IE) operations using unicode # Example: # click_button("Google 搜索") def support_utf8 if is_windows? require 'win32ole' WIN32OLE.codepage = WIN32OLE::CP_UTF8 end end alias support_unicode support_utf8 #= Convenient functions # # Using Ruby block syntax to create interesting domain specific language, # may be appeal to someone. # Example: # on @page do |i| # i.enter_text('btn1') # i.click_button('btn1') # end def on(page, &block) yield page end # fail the test if user can perform the operation # # Example: # shall_not_allow { 1/0 } def shall_not_allow(&block) operation_performed_ok = false begin yield operation_performed_ok = true rescue end raise "Operation shall not be allowed" if operation_performed_ok end alias do_not_allow shall_not_allow # Does not provide real function, other than make enhancing test syntax # # Example: # allow { click_button('Register') } def allow(&block) yield end alias shall_allow allow alias allowing allow # try operation, ignore if errors occur # # Example: # failsafe { click_link("Logout") } # try logout, but it still OK if not being able to (already logout)) def failsafe(&block) begin yield rescue =>e end end alias fail_safe failsafe # Execute the provided block until either (1) it returns true, or # (2) the timeout (in seconds) has been reached. If the timeout is reached, # a TimeOutException will be raised. The block will always # execute at least once. # # This does not handle error, if the given block raise error, the statement finish with error # Examples: # wait_until {puts 'hello'} # wait_until { div(:id, :receipt_date).exists? } # def wait_until(timeout = @@default_timeout || 30, polling_interval = @@default_polling_interval || 1, &block) waiter = Watir::Waiter.new(timeout, polling_interval) waiter.wait_until { yield } end # Wait for specific seconds for an Ajax update finish. # Trick: In your Rails application, # :loading => "Element.show('search_indicator'); # :complete => "Element.hide('search_indicator'); # # <%= image_tag("indicator.gif", :id => 'search_indicator', :style => 'display:none') %> # # Typical usage: # ajax_wait_for_element("search_indicator", 30) # ajax_wait_for_element("search_indicator", 30, "show") # ajax_wait_for_element("search_indicator", 30, "hide") # ajax_wait_for_element("search_indicator", 30, "show", 5) # check every 5 seconds # # Warning: this method has not been fully tested, if you are not using Rails, change your parameter accordingly. # def ajax_wait_for_element(element_id, seconds, status='show', check_interval = @@default_polling_interval) count = 0 check_interval = 1 if check_interval < 1 or check_interval > seconds while count < (seconds / check_interval) do search_indicator = @web_browser.element_by_id(element_id) search_indicator_outer_html = search_indicator.outerHtml if search_indicator if status == 'hide' return true if search_indicator_outer_html and !search_indicator_outer_html.include?('style="DISPLAY: none"') else return true if search_indicator_outer_html and search_indicator_outer_html.include?('style="DISPLAY: none"') end sleep check_interval if check_interval > 0 and check_interval < 5 * 60 # wait max 5 minutes count += 1 end return false end #Wait the element with given id to be present in web page # # Warning: this not working in Firefox, try use wait_util or try instead def wait_for_element(element_id, timeout = @@default_timeout, interval = @@default_polling_interval) start_time = Time.now #TODO might not work with Firefox until @web_browser.element_by_id(element_id) do sleep(interval) if (Time.now - start_time) > timeout raise RuntimeError, "failed to find element: #{element_id} for max #{timeout}" end end end =begin # TODO: Firewatir does not suport retrieving style or outerHtml # http://jira.openqa.org/browse/WTR-260 # http://code.google.com/p/firewatir/issues/detail?id=76 # # Max timeout value is 10 minutes # def ajax_call_complete_after_element_hidden(elem_id, check_start = 0.5, timeout = 5, interval = 0.5, &block) yield sleep check_start # the time allowed to perform the coomplete timeout = 10 * 60 if timeout > 10 * 600 or timeout <= 0 begin Timeout::timeout(timeout) { begin elem = element_by_id(elem_id) while elem do puts "outer=>#{elem.outerHtml}|" puts "style =>#{elem.attribute_value('style')}|" sleep interval elem = element_by_id(elem_id) end rescue => e puts e end } rescue Timeout::Error # Too slow!! raise "Too slow, wait max #{timeout} seconds, the element #{elem_id} still there" end end =end # Try the operation up to specified times, and sleep given interval (in seconds) # Error will be ignored until timeout # Example # repeat_try(3, 2) { click_button('Search' } # 3 times, 6 seconds in total # repeat_try { click_button('Search' } # using default 5 tries, 2 second interval def repeat_try(num_tries = @@default_timeout || 30, interval = @@default_polling_interval || 1, &block) num_tries ||= 1 (num_tries - 1).times do |num| begin yield return rescue => e # puts "debug: #{num} failed: #{e}" sleep interval end end # last try, throw error if still fails begin yield rescue => e raise e.to_s + " after trying #{num_tries} times every #{interval} seconds" end yield end # TODO: syntax # Try the operation up to specified timeout (in seconds), and sleep given interval (in seconds). # Error will be ignored until timeout # Example # try { click_link('waiting')} # try(10, 2) { click_button('Search' } # try to click the 'Search' button upto 10 seconds, try every 2 seconds # try { click_button('Search' } def try(timeout = @@default_timeout, polling_interval = @@default_polling_interval || 1, &block) start_time = Time.now last_error = nil until (duration = Time.now - start_time) > timeout begin return if yield last_error = nil rescue => e last_error = e end sleep polling_interval end raise "Timeout after #{duration.to_i} seconds with error: #{last_error}." if last_error raise "Timeout after #{duration.to_i} seconds." end alias try_upto try ## # Convert :first to 1, :second to 2, and so on... def symbol_to_sequence(symb) value = { :zero => 0, :first => 1, :second => 2, :third => 3, :fourth => 4, :fifth => 5, :sixth => 6, :seventh => 7, :eighth => 8, :ninth => 9, :tenth => 10 }[symb] return value || symb.to_i end end end
true
cfe086bc45c0758975fd2ec94f361d39ffea9177
Ruby
jsoong1962/square_array-nyc-web-080618
/square_array.rb
UTF-8
124
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) # your code here arr = [] array.each do |element| arr.push(element**2) end arr end
true
bcc2abe5bee52baa5b4b79921f81715cc13f675b
Ruby
acook/logsaber
/lib/logsaber/log.rb
UTF-8
1,875
2.984375
3
[ "MIT" ]
permissive
module Logsaber class Log class << self def create *args default_options = { output: $stdout, level: :info, appname: nil, formatter: Logsaber::Formatter.new } options = Options.extract_from args, default_options, :output self.new *options end end SEVERITY_LEVELS ||= [:debug, :info, :warn, :error, :fatal, :off] def initialize output, level, appname, formatter self.output = output @level = level.to_sym @appname = appname @formatter = formatter.set_log self unless SEVERITY_LEVELS.include? @level then raise "Invalid level: #{level.inspect}.\nUse one of: #{SEVERITY_LEVELS}" end end attr_accessor :output, :level, :appname, :formatter SEVERITY_LEVELS.each do |method_name| next if method_name == :off eval <<-END_OF_METHOD def #{method_name} *args, &block log :#{method_name}, *args, &block end END_OF_METHOD end def output= new_output @output = [new_output].flatten.map {|io| outputize(io) } end protected def log severity, *details, &block return unless loggable? severity message, object = Entry.create(details, &block).parse out format(severity, message) object end def out text output.each do |io| io.puts text io.flush end end def format *args formatter.format *args end def loggable? severity SEVERITY_LEVELS.index(severity) >= SEVERITY_LEVELS.index(level) end def outputize new_output if new_output.is_a? String then File.new new_output, 'a' elsif new_output.respond_to? :puts then new_output else raise "invalid output object: #{new_output.inspect}" end end end end
true
75809483de818eaebd64ff869c1c252949d2c6bf
Ruby
jamesclarkson97/W2D2_homework_bear_river_fish_classes
/river.rb
UTF-8
426
3.71875
4
[]
no_license
class River attr_reader :name def initialize(name) @name = name @fish = [] end def fish_population() return @fish end def add_fish(new_fish) @fish.push(new_fish) end def add_fishes(river, new_fishes) for fish in new_fishes river.add_fish(fish) end end def remove_fish(old_fish) @fish.delete(old_fish) end end
true
60cd7748852b5c2e9a4706699095291312b7044c
Ruby
sabind/learn-2-code-ruby
/strings_arrays/encode_chars.rb
UTF-8
2,588
3.90625
4
[ "MIT" ]
permissive
# The logic here is used all the time by web applications. There are certain # characters that cannot be placed in a URL. However sometimes it's required # that they get sent as URL parameters. The process of replacing these characters # in the URL is called URL Encoding. for this example we're going to replace the # characters we target with # simple encoding will walk the string and build a new string with the results # it accepts the string as well as a map so we know what we want to replace as # well as what the intended replacement is. def simple_encode(input, key_map) # NEVER trust input to be valid. Always double check it. if !input return nil end if !key_map return input end encoded_string = '' input.chars.each do |character| if key_map[character] encoded_string += key_map[character] else encoded_string += character end end encoded_string end # We can do this function in place. The thing to note is if we're replacing a # letter in a string in place by inserting more letters we're actually moving # all the letters after the insertion over and that's an expensive CPU operation # when the string gets very long. For example if we have to replace the first # letter in the string with two letters we have to move all of the letters in the # string over one to make room. Also notice the ! in the method name. This means # we're modifying in place and the side_effects will change the input permanently def in_place_encode!(input, key_map) # NEVER trust input to be valid. Always double check it. if !input return nil end if !key_map return input end # we can not use an 'iterator for this operation. Iterators like 'each' do not # work well with insertion and deletation. Since we're growing the array by # inserting potentially longer sequences we'll create some straange behavior. # For that reason we have to use a simple for loop. i = 0 while i < input.length do if key_map[input[i]] # Save the length. We're going to be modifying stuff so we won't be able # to retrieve this one we modify the string key_map_length = key_map[input[i]].length input[i] = key_map[input[i]] # increment the index by length of the new value since we're inserting the # new characters and we don't want to encode the encoding. i += key_map_length else i +=1 end end # note the lack of a return. We are modifying in place so the input variable # passed in will be updated already. end
true
53db7bfde9bee7e42dd0620d0e7c813a43ff3005
Ruby
nick-zhang/ruby-practice
/user.rb
UTF-8
585
3.171875
3
[]
no_license
require 'Virtus' class User include Virtus.model attribute :name, String attribute :age, Integer attribute :birthday, DateTime end user = User.new(:name => 'Piotr', :age => 31) user.attributes # => { :name => "Piotr", :age => 31, :birthday => nil } puts user.name # => "Piotr" puts user.age user.age = '31' # => 31 puts user.age.class # => Fixnum user.birthday = 'November 18th, 1983' # => #<DateTime: 1983-11-18T00:00:00+00:00 (4891313/2,0/1,2299161)> # mass-assignment user.attributes = { :name => 'Jane', :age => 21 } puts user.name # => "Jane" puts user.age # => 21
true
383dfb54e085cbfc34e4d7c5901e1ba8dbe88a6d
Ruby
codejlo/phase-0-tracks
/ruby/arrays_drill.rb
UTF-8
845
3.484375
3
[]
no_license
# arrays_drill.rb # Jason Lorentzen, Brett Buller ### Release 2-1 and 2-2 ### def build_array(a, b, c) x = [] return x.push(a, b, c) end def add_to_array(my_new_array, a) my_new_array.push(a) end ### Release 1-1 to 1-8 ### yosemite = [] yosemite.push("half dome", "sequoia", "tent", 17, "San Francisco") p yosemite yosemite.delete_at(2) p yosemite yosemite.insert(2, "waterfall") p yosemite yosemite.shift p yosemite yosemite.include?("sequoia") if yosemite.include?("sequoia") == true puts "Yosemite includes the element 'sequoia'." else puts "Yosemite does not include the element 'sequioa'." end dachshund = ["chase", "pumpkin", "toolongtocare"] combined_array = yosemite + dachshund p combined_array ### Release 2-1 and 2-2 continued ### p build_array(1, "two", nil) p add_to_array([], "a") p add_to_array(["a", "b", "c", 1, 2], 3)
true
1f8c59470b1b776d7b8b0a6f2200ee14bfc74799
Ruby
thiagogabriel/Zine
/app/models/user.rb
UTF-8
655
2.71875
3
[]
no_license
class User < ActiveRecord::Base attr_accessible :encoded_password, :login, :password validates_length_of :login, :within => 3..20 validates_presence_of :encoded_password, :message => "can't be blank" validates_uniqueness_of :login def self.login(login, password) user = User.find_by_login login if user and user.encoded_password == Digest::SHA1.hexdigest("vbjsdgbndfb" + password) user else nil end end def password "" end def password=(new_password) if new_password.length > 0 self.encoded_password = Digest::SHA1.hexdigest("vbjsdgbndfb" + new_password) else nil end end end
true
dc997a578b68a11ab39977af91e3ce4ff6225f00
Ruby
madking55/ruby_exercises
/initialize/lib/quail.rb
UTF-8
92
2.875
3
[]
no_license
class Quail attr_reader :name def initialize(name) @name = name.capitalize end end
true
45c2288ea84cd3db8446dd38270057a286489ca3
Ruby
dishapatelcodes/ttt-10-current-player-q-000
/lib/current_player.rb
UTF-8
241
3.234375
3
[]
no_license
def turn_count(board) player_turns = 0 board.each do |character| if character == "X" || character == "O" player_turns +=1 end end player_turns end def current_player(board) turn_count(board).even? ? "X" : "O" end
true
0c4dcdba2dda10e18c52d563b9462a9516e46a08
Ruby
HollyM021980/wdi_1_ruby_assessment_objects
/objects.rb
UTF-8
1,379
4.5625
5
[]
no_license
#### Question 1 # Define a class called `Pet`, and a class `Dog` that inherits from `Pet`. # Got this wrong, the inheritance syntax should only be 1 "<" class Pet end class Dog < Pet end #### Question 2 # Copy your class definitions from question 1 here. # Then add an initializer to the `Pet` class that accepts a "name" argument # and stores the value as an instance variable. class Pet def initialize(name) @name = name end end class Dog < Pet def initialize(name="Fido") #Although not wrong, this wasn't in the specs.. @name = name end end #### Question 3 # Copy your class definitions from question 2 here. # Then add an instance method called `bark` to the `Dog` class that returns the # string "bark bark". class Pet def initialize(name) @name = name end end class Dog < Pet def bark return "BARK BARK!!" end end #### Question 4 # Write code that would create a new instance of the `Dog` class with the # name "Lassie", and call the `bark` method on it. lassie_dog = Dog.new("Lassie") lassie_dog.bark #### Question 5 # Write code to create a new array containing 3 dog names (as strings). # Then write code to add the string "is a good dog!" to every name. # Save the result in a new array, but don't output anything to the Terminal. dog_names = ["Nibbler", "Lassie", "Fido"] dog_names.map { |dog| dog + " is a good dog!!" }
true
2f941edda3311d9f0154b684c8f41db8613f62d1
Ruby
natey37/leetcode-problems
/merge_arrays.rb
UTF-8
994
4.46875
4
[]
no_license
=begin Interview Cake - Merge Arrays We have our lists of orders sorted numerically already, in arrays. Write a method to merge our arrays of orders into one sorted array. For example: my_array = [3, 4, 6, 10, 11, 15] alices_array = [1, 5, 8, 12, 14, 19] puts merge_arrays(my_array, alices_array) # Prints [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19] =end def merge_arrays(arr1, arr2) size = (arr1 + arr2).length new_array = [] current_idx1 = 0 current_idx2 = 0 current_idx_merged = 0 while current_idx_merged < size arr1_exhausted = current_idx1 >= arr1.length arr2_exhausted = current_idx2 >= arr2.length if !arr1_exhausted && (arr2_exhausted || (arr1[current_idx1] < arr2[current_idx2])) new_array[current_idx_merged] = arr1[current_idx1] current_idx1 += 1 else new_array[current_idx_merged] = arr2[current_idx2] current_idx2 += 1 end current_idx_merged += 1 end return new_array end
true
7b2aff24ba3704d0c7cf6d8c636c2be0705acd39
Ruby
JArthurJohnston/Parser
/lib/syntax_tree/argument_node.rb
UTF-8
370
2.65625
3
[]
no_license
require_relative 'abstract_syntax_tree_node' module Parser module ParseTrees class ArgumentNode < AbstractSyntaxTreeNode attr_reader :name, :value def initialize(name, value = nil) super() @name = name @value = value end def has_default_value? !@value.nil? end end end end
true
13ed5c152c13126350d7fc74fb7a0c548f938d8e
Ruby
ChenningZhang/OskiMart
/spec/controllers/conversations_controller_spec.rb
UTF-8
3,974
2.765625
3
[]
no_license
require 'rails_helper' #ConversationsController includes: #GET #new renders the page for creating a new conversation #POST #create creates a new conversation and redirects to the conversation's show path #GET #show renders a conversation's path #GET #index renders the view that manages all conversations #POST #reply replies to a message and then redirects to the conversation's show path #THE FOLLOWING METHODS ARE LIKELY SUBJECT FOR REFACTORING AND NOT YET TESTED #POST #restore ressurects a message from the trash #DELETE #empty_trash takes out the trash #DELETE #destroy RSpec.describe ConversationsController, :type => :controller do describe "GET #new" do subject{get :new} login_user it 'renders the page for creating a new conversation' do expect(subject).to render_template('new') end end describe "POST #create" do create_second_user login_user it 'creates a new conversation for chatting, with the first message' do expect{ post :create, message: {:body => "This is a body", :subject => "This is a subject"}, recipients: [@user2.id], commit: "Send" }.to change(@user2.mailbox.inbox, :count).by(1) expect(response).to redirect_to(conversation_path(@user2.mailbox.inbox.first)) end #create another test to make sure a user can't message to himself? end describe "GET #show" do send_message_from_1_to_2_and_3 login_second_user it 'shows a message if it exists and the user is one of the members' do get :show, id: @conversation.id expect(response).to render_template("show") end it 'marks a message as read for only the user who opened it and no one else' do expect(@conversation.is_unread?(@user3)).to be true expect(@conversation.is_unread?(@user2)).to be true get :show, id: @conversation.id expect(@conversation.is_unread?(@user3)).to be true expect(@conversation.is_unread?(@user2)).to be false end end describe "GET #index" do subject{get :index} login_user it 'renders the inbox page for the current user' do expect(subject).to render_template('index') end end describe "POST #reply" do send_message_from_1_to_2_and_3 login_second_user it 'increases the number of receipts in a conversation by 1' do expect{ post :reply, id: @conversation.id, body: "Test reply", commit: "Send Message" }.to change(@conversation.receipts_for(@user2), :count).by(1) end end describe "DELETE #destroy" do send_message_from_1_to_2_and_3 login_second_user it 'ensures that the message will be gone from the user\'s inbox and into the trash' do expect(@user2.mailbox.trash.size).to eq(0) expect(@user2.mailbox.inbox.size).to eq(1) expect{ delete :destroy, id: @conversation.id }.to change(@user2.mailbox.inbox, :count).by(-1) expect(@user2.mailbox.inbox.size).to eq(0) expect(@user2.mailbox.trash.size).to eq(1) end end describe "POST #restore" do send_message_from_1_to_2_and_3 delete_conversation_for_2 login_second_user it 'should take a deleted convo out from the deleted box and into the inbox' do expect(@user2.mailbox.trash.size).to eq(1) expect(@user2.mailbox.inbox.size).to eq(0) expect{ post :restore, id: @conversation.id }.to change(@user2.mailbox.inbox, :count).by(1) expect(@user2.mailbox.trash.size).to eq(0) expect(@user2.mailbox.inbox.size).to eq(1) end end describe "DELETE #empty_trash" do send_message_from_1_to_2_and_3 send_message_from_2_to_1 delete_conversation_for_2 login_second_user it 'should remove all messages from the trash. No other boxes should be affected' do expect(@user2.mailbox.trash.size).to eq(1) expect(@user2.mailbox.inbox.size).to eq(0) expect(@user2.mailbox.sentbox.size).to eq(1) expect{ delete :empty_trash }.to change(@user2.mailbox.trash, :count).by(-1) expect(@user2.mailbox.trash.size).to eq(0) expect(@user2.mailbox.inbox.size).to eq(0) expect(@user2.mailbox.sentbox.size).to eq(1) end end end
true
f8c635150adbdf9455879f51bcfc0252a4b91157
Ruby
frostmark/railway_ror
/app/models/station.rb
UTF-8
830
2.578125
3
[]
no_license
class Station < ApplicationRecord validates :name, presence: true has_many :routes_stations has_many :routes, through: :routes_stations has_many :trains, foreign_key: :current_station_id def update_position(route, position) station_route = station_route(route) station_route.update(position: position) if station_route end def position_in(route) station_route(route)&.position end def arrive_time_in(route) station_route(route)&.arrive_time end def departure_time_in(route) station_route(route)&.departure_time end def update_time(route, params) station_route(route)&.update(arrive_time: params[:arrive_time], departure_time: params[:departure_time]) end protected def station_route(route) @station_route ||= routes_stations.where(route: route).first end end
true
3041da1ec7630ed9a4b2ca523ad39da1a24bea65
Ruby
danielgrigg/sandbox
/langs/ruby/read_lines.rb
UTF-8
497
3.125
3
[ "WTFPL" ]
permissive
counter = 1 file = File.new("read_lines.rb", "r") while (line = file.gets) puts "#{counter}: #{line}" counter = counter + 1 end file.close File.open("read_lines.rb", "r") do |infile| while (line = infile.gets) puts "#{counter}: #{line}" counter = counter + 1 end end counter = 1 begin file = File.new("read_lines.rb", "r") while (line = file.gets) puts "#{counter}: #{line}" counter = counter + 1 end file.close rescue => err puts "Exception: #{err}" err end
true
d7d774ae3d337f5a5237c9bbfce4dc44f7b2b97e
Ruby
postazure/Ruby-Practice
/CH9/mooMethod.rb
UTF-8
84
2.515625
3
[]
no_license
def say_moo puts 'mooooo....' end say_moo say_moo puts 'coin-coin' say_moo say_moo
true
851eebb6c05102a250f34fa7a383375618fa26c1
Ruby
yazinsai/algorithms
/largest-number.rb
UTF-8
597
4.46875
4
[]
no_license
=begin Given a list of non negative integers, arrange them such that they form the largest number. For example: Given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. Source: https://www.interviewbit.com/problems/largest-number/ =end def largest_number(arr) special_sort = ->(a, b) { "#{b}#{a}".to_i <=> "#{a}#{b}".to_i } result = arr.sort(&special_sort).join("") result.sub!(/^0+/, "") # strip leading zeros result.empty? ? "0" : result end puts largest_number([3, 30, 34, 5, 9])
true
ec8db891f7d0e3743ffc34a1f35dcd68709cf990
Ruby
Coderdotnew/intro_web_apps_bs
/03_class/01_conditionals/code/01_math_conditionals/spec/math_conditionals_spec.rb
UTF-8
895
3.453125
3
[]
no_license
require_relative './spec_helper' require_relative '../math_conditionals.rb' describe "#less_than" do it "return the expected string if the input is not less than 100" do expect(how_big(100)).to eq("That's a large number.") end it "return the expected string if the input is less than 100" do expect(how_big(99)).to eq("That's a small number.") end end describe "#even?" do it "return true if even" do expect(even?(100)).to eq(true) end it "return false if not even" do expect(even?(99)).to eq(false) end end describe "#odd?" do it "return true if odd" do expect(odd?(99)).to eq(true) end it "return false if not odd" do expect(odd?(100)).to eq(false) end end describe "#zero?" do it "return true if input is 0" do expect(zero?(0)).to eq(true) end it "return false if input is not 0" do expect(zero?(1)).to eq(false) end end
true
0acb28e6e2af59d342b95913e17ceb8772203cf0
Ruby
tomoasleep/yoda
/lib/yoda/model/parameters/multiple.rb
UTF-8
1,269
2.828125
3
[ "MIT" ]
permissive
module Yoda module Model module Parameters class Multiple < Base # @return [Array<Base>] attr_reader :parameters, :post_parameters # @return [Array<Base>] attr_reader :keyword_parameters # @return [Base, nil] attr_reader :rest_parameter, :keyword_rest_parameter, :block_parameter, :forward_parameter # @param parameters [Array<Base>] # @param rest_parameter [Base, nil] # @param post_parameters [Array<Base>] # @param keyword_parameters [Array<(Base)>] # @param keyword_rest_parameter [Base, nil] # @param block_parameter [Base, nil] def initialize(parameters: [], rest_parameter: nil, post_parameters: [], keyword_parameters: [], keyword_rest_parameter: nil, block_parameter: nil, forward_parameter: nil) @parameters = parameters @keyword_parameters = keyword_parameters @rest_parameter = rest_parameter @post_parameters = post_parameters @keyword_rest_parameter = keyword_rest_parameter @block_parameter = block_parameter @forward_parameter = forward_parameter end # @return [Symbol] def kind :multiple end end end end end
true
f424c978551e996f604310e6abcedecd9fd0e351
Ruby
change/lita-totems
/lib/lita/handlers/stats.rb
UTF-8
1,862
2.53125
3
[ "MIT", "Apache-2.0" ]
permissive
require 'signalfx' module Stats module_function SIGNALFX_TOTEMS_METRICS_DASHBOARD = "https://app.signalfx.com/#/dashboard/FNSkEUVAYAA" def signalfx_client @signalfx_client ||= SignalFx.new ENV['LITA_SIGNALFX_TOKEN'] end def send_gauges_to_signalFX(metric, value) signalfx_client.send( gauges: [ { :metric => metric, :value => value, :timestamp => (Time.now.to_f * 1000).to_i } ] ) end def send_counter_to_signalFX(metric, value) signalfx_client.send( counters: [ { :metric => metric, :value => value, :timestamp => (Time.now.to_f * 1000).to_i } ] ) end # captures how many times a totem has being added def capture_totem_use(totem) send_counter_to_signalFX("totems:add:#{totem}", 1) end # captures how many people are waiting for a totem. def capture_people_waiting(totem,queue_size) send_gauges_to_signalFX("totems:people_waiting:#{totem}", queue_size) end # captures totem's holding time by user def capture_holding_time(totem, waiting_since_hash_user_id) user_holding_time_in_seconds = Time.now.to_i - waiting_since_hash_user_id.to_i user_holding_time_in_minutes = user_holding_time_in_seconds / 60 send_gauges_to_signalFX("totems:holding_time:#{totem}",user_holding_time_in_minutes) end # captures totem's waiting time by the next user def capture_waiting_time(totem, waiting_since_hash_next_user_id) user_waiting_time_in_seconds = Time.now.to_i - waiting_since_hash_next_user_id.to_i user_waiting_time_in_minutes = user_waiting_time_in_seconds / 60 send_gauges_to_signalFX("totems:waiting_time:#{totem}",user_waiting_time_in_minutes) end def signalfx_dashboard SIGNALFX_TOTEMS_METRICS_DASHBOARD end end
true
5800ec5405ef6dfd5bff57baf60a6e51b5e85122
Ruby
torpedo-t/recipe-book
/app/models/user.rb
UTF-8
1,292
2.78125
3
[]
no_license
class User < ApplicationRecord has_secure_password VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i.freeze has_many :recipes has_many :ratings has_many :rated_recipes, through: :ratings, source: :recipe validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :password_digest, presence: true end # validate :password_lower_case # validate :password_uppercase # validate :password_special_char # validate :password_contains_number # def password_uppercase # return if !!password.match(/\p{Upper}/) # errors.add :password, ' must contain at least 1 uppercase ' # end # def password_lower_case # return if !!password.match(/\p{Lower}/) # errors.add :password, ' must contain at least 1 lowercase ' # end # def password_special_char # special = "?<>',?[]}{=-)(*&^%$#`~{}!" # regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/ # return if password =~ regex # errors.add :password, ' must contain special character' # end # def password_contains_number # return if password.count("0-9") > 0 # errors.add :password, ' must contain at least one number' # end
true
87b1a6ecf2f579550c2ae399ad07ccd3e644951b
Ruby
TylerBrock/books
/Agile Web Development with Rails/work/depot/rake/ruby/1.9.1/gems/activesupport-3.0.10/lib/active_support/gzip.rb
UTF-8
695
2.6875
3
[ "MIT" ]
permissive
require 'zlib' require 'stringio' module ActiveSupport # A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip. module Gzip class Stream < StringIO def initialize(*) super set_encoding "BINARY" if "".encoding_aware? end def close; rewind; end end # Decompresses a gzipped string. def self.decompress(source) Zlib::GzipReader.new(StringIO.new(source)).read end # Compresses a string using gzip. def self.compress(source) output = Stream.new gz = Zlib::GzipWriter.new(output) gz.write(source) gz.close output.string end end end
true
6fe468765b3fc91f912cc702d80e6018fc5ef130
Ruby
bcarreno/blog
/test/models/message_test.rb
UTF-8
662
2.5625
3
[]
no_license
require 'test_helper' class MessageTest < ActiveSupport::TestCase test 'required attributes' do message = Message.new refute message.valid? assert_equal 'is invalid', message.errors[:email].first assert_equal "can't be blank", message.errors[:body].first message.email = 'dummy' refute message.valid? assert_equal 'is invalid', message.errors[:email].first end test 'create new message' do message = Message.new(email: 'stalker@example.com', body: 'Can we get together?') assert message.valid?, message.errors.full_messages.to_sentence assert_difference('Message.count', +1) do assert message.save! end end end
true
b57defb86ae21c1d21bf1afc38a9f3f333f1316c
Ruby
equivalentideas/westconnex_M4_East_Air_Quality_Monitoring
/lib/models/monitor.rb
UTF-8
752
2.75
3
[]
no_license
# frozen_string_literal: true # The Air Quality Monitor that readings belong to class Monitor attr_accessor :name def self.count AqmRecord.distinct(:location_name).count end def self.all AqmRecord.distinct(:location_name).select(:location_name).order(:location_name).collect do |record| new(name: record.values[:location_name]) end end def initialize(name: nil) @name = name end def display_name name.sub(/ AQM$/, '') end def percentage_of_pm2_5_readings_over_8 all_records = AqmRecord.where(location_name: name) with_pm25_over8 = all_records.where( Sequel.lit('pm2_5_concentration_ug_per_m3 > ?', 8) ) (with_pm25_over8.count.to_f / all_records.count * 100).round(2) end end
true
84ee180ab0f9b07151a679bf876d5b8a8a788992
Ruby
ekene966/hackerrank
/ruby/xor_and_sum.rb
UTF-8
274
3.796875
4
[ "MIT" ]
permissive
# Xor and Sum class XorAndSum UPPER_BOUND = 314_159 MODULO_VAL = (10**9) + 7 def self.calculate(a, b) sum = 0 (0..UPPER_BOUND).each { |i| sum += (a ^ (b << i)) } sum % MODULO_VAL end end a = gets.to_i(2) b = gets.to_i(2) puts XorAndSum.calculate(a, b)
true
a0475ae2ed867e35b928a4dad71ecd5939210fce
Ruby
colinyoung/mongoid_to_csv
/lib/mongoid_to_csv.rb
UTF-8
1,703
2.859375
3
[]
no_license
require 'mongoid' require 'csv' module MongoidToCSV # Return full CSV content with headers as string. # Defined as class method which will have chained scopes applied. def to_csv documents_to_csv all end module_function def documents_to_csv(documents, fields = nil) return documents.to_csv unless documents.first.class.respond_to? :fields fields ||= documents.first.class.fields.keys doc_class = documents.first.class csv_columns = fields - %w{_id created_at updated_at _type} header_row = csv_columns.to_csv records_rows = documents.map do |record| csv_columns.map do |column| value = if column.include? '.' column.split('.').reduce(record) {|r, method| r.send(method) } else record.send(column) end if value.respond_to?(:to_csv) value = value.to_csv value.gsub! /\n$/, '' if array_type_for_record(record, column) else value.to_s end value end.to_csv end.join header_row + records_rows end private def array_type_for_record record, column embed_list = column.split('.') field = embed_list.pop instance = embed_list.reduce(record) {|r, method| r.send(method) } instance.class.fields[field].type == Array end end module Mongoid::Document def self.included(target) target.extend MongoidToCSV end end # Define Relation#to_csv so that method_missing will not # delegate to array. class Mongoid::Relation def to_csv scoping do @klass.to_csv end end end class Array def mongoid_to_csv return self if empty? MongoidToCSV.documents_to_csv(self) end end
true
14086e38c2919a91789f1c2451346cadad19576b
Ruby
ShawnAukstak/problems
/elements_of_programming_interviews/16_1_tower_of_hanoi.rb
UTF-8
1,167
4.25
4
[]
no_license
=begin Have three pegs (stacks). Rings are on stack 0 in size order, with largest at the bottom. Only operation you can do it place one peg from top of on stack to another You cannot place a larger ring ontop of a smaller ring. input number of rings on stack[0] output - print sequence of moves. Create stacks + rings If stack 1 + 3 are empty, return See if we can move something from 1st to 2nd. See if we can move something from 3rd to 2nd see if we can something from from 1st to 3rd 2nd to first 2nd to 3rd 3rd to first 2nd to first 2nd to first print move. =end require 'pp' def towers_of_hanoi(number_of_rings) stacks = Array.new(3) { Array.new } number_of_rings.downto(1).each do |x| stacks[0].push x end pp stacks towers_of_hanoi_rec(number_of_rings, stacks, 0, 1, 2) pp stacks end def towers_of_hanoi_rec(rings_left, stacks, from, to, aux) if rings_left > 0 #move to aux towers_of_hanoi_rec(rings_left - 1, stacks, from, aux, to) puts "move #{stacks[from].last} from #{from} to #{to}" stacks[to].push stacks[from].pop towers_of_hanoi_rec(rings_left - 1, stacks, aux, to, from) end end towers_of_hanoi(3)
true
bc33a81f5d17ce09b94c6d91ef07c430119e2354
Ruby
garweim/Homuch
/app/services/detailed_estimate.rb
UTF-8
611
2.578125
3
[]
no_license
class DetailedEstimate def call(project) @project = project return unless market_price_estimate total_estimate end # private attr_reader :project def total_estimate market_price_estimate - renovation_price end def registration_fees market_price_estimate * 0.15 end def market_price_estimate @market_price ||= SimpleEstimate.new.market_price(@project) # SimpleEstimate.new.market_price(project) end def renovation_price @renovation_price ||= RenovationCalculator.new(@project).total_price end end # DetailedEstimate.new.call_detailed(Project.last)
true
7ab9f5efb8ac86e2e3238e229ac820404f46ec15
Ruby
batfrog/Ruby
/no_escape.rb
UTF-8
124
3.5625
4
[]
no_license
while 1 puts "Who are you?" user_name = gets.chomp puts "You'll NEVER ESCAPE, #{user_name}!! MUAHAHAHAHAHAHAHAHAHA!" end
true
0460f60bde140cb3835d5114d8e48132930d17c6
Ruby
sebglazebrook/dank
/spec/dank_spec.rb
UTF-8
1,822
2.984375
3
[ "MIT" ]
permissive
require 'spec_helper' describe Dank do describe '.parse' do subject { Dank } context 'when given a valid regular expression' do let(:regular_expression) { /[a-z]*/ } it 'converts it to dank' do expect(subject.parse(regular_expression)).to eq Dank.any_lowercase_letters end end end describe '.method_missing' do it 'sends the method name and args off to the evaluator for evaluation' do expect(Dank::Evaluator).to receive(:evaluate).with('some_method_that_doesnt_exist', ['arg1', 2, 'arg3']) subject.some_method_that_doesnt_exist('arg1', 2, 'arg3') end end describe 'evaluable expressions' do { 'any_letters' => /[a-zA-Z]*/, 'any_lowercase_letters' => /[a-z]*/, 'any_uppercase_letters' => /[A-Z]*/, 'any_numbers' => /\d*/, 'any_characters' => /\w*/, 'at_least_one_number' => /\d+/, 'at_least_one_letter' => /[a-zA-Z]+/, 'at_least_one_character' => /\w+/, 'at_least_one_lowercase_letter' => /[a-z]+/, 'at_least_one_uppercase_letter' => /[A-Z]+/ }.each do |expression, regex| it "evaluates '#{expression}' to: #{regex}" do expect(Dank.send(expression).regex).to eq regex end end end describe 'daisy chaining' do context 'given an evaluable expression' do let(:expression_one) { 'any_lowercase_letters' } context 'and another evaluable expression is chained on' do let(:expression_two) { 'any_numbers' } it 'combines them to build a new dank expression' do expected_dank = Dank::Models::Expression.new(regex: /[a-z]*\d*/, expression: ['any_lowercase_letters', 'any_numbers']) expect(subject.send(expression_one).send(expression_two)).to eq expected_dank end end end end end
true
78419672095b7d36e7b8cbfe0cac29578142118c
Ruby
RajaomalalaSendra/ruby_quiz
/test.rb
UTF-8
2,325
3.703125
4
[]
no_license
# Notre test score = 0 def run_test(questions,i) answer = "" score = 0 i = i.to_i for question in questions puts "The question ##{i + 1}" puts question.prompt enter() answer = gets.chomp() if answer == question.answer score += 1 end i += 1 end puts ("You got " + score.to_s + "/" + questions.length().to_s) end class Question attr_accessor :prompt, :answer def initialize(prompt, answer) @prompt = prompt @answer = answer end end def enter() print "> " end EASY_QUESTION_1 = "What is the first book in the bible?\n(a)Genesis\t(b)Exode\t(c)Psalm\t(d)Proverbs" EASY_QUESTION_2 = "Who is the first killer in the bible?\n(a)Adam\t(b)Abraham\t(c)Abel\t(d)Isaac" EASY_QUESTION_3 = "What is the true name of Israel?\n(a)Esau\t(b)Ephraim\t(c)Joseph\t(d)Jacob" EASY_QUESTION_4 = "What is the name of the father of King Solomon?\n(a)King David\t(b)King Saul\t(c)Daniel\t(d)Jese" EASY_QUESTION_5 = "Who is the dreamer that becomes a pharaon's right hand?\n(a)Benjamin\t(b)Simeon\t(c)Reuben\t(d)Joseph" EASY_QUESTION_6 = "Who deliever Israel from Egypt?\t(a)Abraham\t(b)David\t(c)Moses\(d)Aaron" EASY_QUESTION_7 = "What?\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_8 = "Who?\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_9 = "what?\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_10 = "where?\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_11 = "what?\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_12 = "when?\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_13 = "what\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_14 = "who?\n(a)\t(b)\t(c)\t(d)" EASY_QUESTION_15 = "what?\n(a)\t(b)\t(c)\t(d)" easy_questions = [ Question.new(EASY_QUESTION_1, "a"), Question.new(EASY_QUESTION_2, "c"), Question.new(EASY_QUESTION_3, "d"), Question.new(EASY_QUESTION_4, "a"), Question.new(EASY_QUESTION_5, "d"), Question.new(EASY_QUESTION_6, "c"), Question.new(EASY_QUESTION_7, "a"), Question.new(EASY_QUESTION_8, "c"), Question.new(EASY_QUESTION_9, "d"), Question.new(EASY_QUESTION_10, "a"), Question.new(EASY_QUESTION_11, "d"), Question.new(EASY_QUESTION_12, "c"), Question.new(EASY_QUESTION_13, "a"), Question.new(EASY_QUESTION_14, "c"), Question.new(EASY_QUESTION_15, "d") ] run_test(easy_questions, 0) puts "#{score}" run_test(easy_questions, 0)
true
6ad09915460b9070b68bf9bf497c13c27fde5830
Ruby
weyewe/scrap_avax
/scrap_animephile.rb
UTF-8
1,324
2.6875
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' require 'cgi' homepage = 'http://www.animephile.com/hentai' # 'http://www.animephile.com/hentai/birthday.html?ch=Volume+01' page = Nokogiri::HTML(open( homepage )) result_filename = "animephile_last.txt" results = page.css("#newesthentai div.boxhighlights-item a") file_content = [] results.each do |result| element = [] title = result.text link = "#{result.attributes['href'].value}" file_content << [ title, link ] end # puts file_content def download_image( title , url) page = Nokogiri::HTML(open( url )) results = page.css(".selectpage option") total_page = results.count images = [] (1.upto total_page).each do |page_number| page_url = url + "?ch=Volume+01" + "&page=#{page_number}" page = Nokogiri::HTML(open( page_url )) result = page.css("#mainimage") images << result.map {|x| x['src'] } .first end puts "Total images: #{images.count}" end download_image( file_content.first[0], file_content.first[1]) # http://webtunnel.org/browse.php?u=JKrSes%2BCnO%2B6CZVi08zZv9xAyY4WN%2BiuoG4UGw%3D%3D&b=29&f=norefer << tunnel from this # File.open(result_filename , 'w') {|f| f.write(file_content.first[1]) }
true
6d0ea87e9be1310338208389ac6d950b46505420
Ruby
gonyolac/ls_ruby_course
/OO_programming/lesson_4/easy_exercises.rb
UTF-8
5,676
4.1875
4
[]
no_license
module Speed def go_fast puts "I am a #{self.class} and going super fast!" end end class Car include Speed def go_slow puts "I am safe and driving slow." end end class Truck include Speed def go_very_slow puts "I am a heavy truck and like going very slow." end end test_car = Car.new("Aston Martin DBS") test_truck = Car.new("Durango") test_car.go_fast test_truck.go_fast ____________________________________ class AngryCat def hiss puts "Hisssss!!!" end end miko = AngryCat.new("Miko") ____________________________________ class Cube def initialize(volume) @volume = volume end # to access instance variable def get_volume @volume end end ____________________________________ class Cat attr_accessor :type, :age @@cats_count = 0 def initialize(type) @type = type @age = 0 @@cats_count += 1 end def make_one_year_older # self.age refers to the @age of a class object that called the method self.age += 1 end def self.cats_count @@cats_count end end # @@cats_count explanation =begin @@cats_count is a class variable; it increments each time a new object of the Cat class is initialized. To test the code, create a new object test_cat = Cat.new("Siamese"), then call Cat.cats_count to return current count =end ____________________________________ class Bag def initialize(color, material) @color = color @material = material end end test_bag = Bag.new("red", "leather") ____________________________________ class Oracle def predict_the_future "You will " + choices.sample end def choices ["eat a nice lunch", "take a nap soon", "stay at work late"] end end oracle = Oracle.new oracle.predict_the_future class RoadTrip < Oracle def choices ["visit Vegas", "fly to Fiji", "romp in Rome"] end end trip = RoadTrip.new # returns values under defined 'choices' under RoadTrip (see lookup chain) trip.predict_the_future ____________________________________ module Taste def flavor(flavor) puts "#{flavor}" end end class Orange include Taste end class HotSauce include Taste end test.ancestors ____________________________________ class BeesWax attr_accessor :type def initialize(type) @type = type end def describe_type puts "I am a #{type} of Bees Wax" end end ____________________________________ excited_dog # local variable @excited_dog # instance variable @@excited_dog # class variable ____________________________________ class Television def self.manufacturer # class method "test logic" end def model "test logic" end end Television.manufacturer ____________________________________ class Game def play "Start the game!" end end class Bingo < Game # make Game class the superclass for Bingo (to inherit play method) def rules_of_play #rules of play end def play # adding another play method will override the one under game (as per lookup chain) "Eyes Down" end end ____________________________________ =begin Q: What are the benefits of using Object Oriented Programming in Ruby? Create objects that allow programmers to think more abstractly about the code Objects are represented by nouns are easier to conceptualize Flexible method implementation and function; Reusable code Avoid redundand methods As the software becomes more complex, the code can easily be managed =end ____________________________________ class Greeting def greet(message) puts message end end class Hello < Greeting def hi greet("Hello") end def self.hi greeting = Greeting.new greeting.greet("Hello") end end class Goodbye < Greeting def bye greet("Goodbye") end end hello = Hello.new # case 1 hello.hi # => puts "Hello" # case 2 hello.bye # => undefined method error (since hello is an object of Hello class) # case 3 hello.greet # => 0 for 1 error (no message on greet method call) # case 4 hello.greet("Goodbye") # => puts "Goodbye" # case 5 Hello.hi # => undefined method error (since hi is an instance, NOT CLASS, method for Hello class) ____________________________________ class AngryCat def initialize(age, name) @age = age @name = name end def age puts @age end def name puts @name end def hiss puts "Hissssss!!!" end end mew = AngryCat.new(8, "Mew") mewtwo = AngryCat.new(5, "Mewtwo") ____________________________________ class Cat def initialize(type) @type = type end def display "I am a #{type} cat" end end tabby = Cat.new("tabby") ____________________________________ class Television def self.manufacturer # method logic end def model # method logic end end tv = Television.new tv.manufacturer # undefined method error (since manufacturer is a class method) tv.model # runs the method Television.manufacturer # runs the method Television.model # undefined method (since model is an instance method) ____________________________________ class Cat attr_accessor :type, :age def initialize(type) @type = type @age = 0 end def make_one_year_older @age += 1 # originally self.age (@ and self. are interchangeable, in this case) end end ____________________________________ class Light attr_accessor :brightness, :color def initialize(brightness, color) @brightness = brightness @color = color end def self.information return "I want to turn on the light with a brightness level of super high and a colour of green." # return is unecessary since Ruby automatically returns # the last line of any method end end
true
914b3295943946cee88a1e7e97e8c932b2835f55
Ruby
fluxfederation/squash_repeater
/lib/squash_repeater/exception_queue.rb
UTF-8
3,818
2.5625
3
[ "MIT" ]
permissive
require "time" require "timeout" require "backburner" module SquashRepeater WORKER_ERRORS = [ Beaneater::NotConnected, Beaneater::InvalidTubeName, Beaneater::JobNotReserved, Beaneater::UnexpectedResponse ] class CaptureTimeoutError < SquashRepeater::Error def to_s original_message = super "Capturing the exception timed-out#{" (#{original_message})" if original_message && !original_message.empty?}" end end WORKER_ERRORS << CaptureTimeoutError class << self def transmit_exceptions Backburner.work end alias :work :transmit_exceptions # Capture the HTTP data, and store it in the beanstalkd queue for later def capture_exception(url: nil, headers: nil, body: nil, squash_configuration: nil, no_proxy_env: nil) #FUTURE: Required keyword args, for Ruby 2.1+ #def capture_exception(url:, headers:, body:, squash_configuration:, no_proxy_env: nil) fail "Missing required keyword arg" unless url && headers && body && squash_configuration # If things fail, it's useful to know how long it caused the exception-capture to block the # calling process: start = Time.now begin Timeout::timeout(configuration.capture_timeout, CaptureTimeoutError) do #NB: Backburner doesn't seem able to #perform with keyword args: Backburner.enqueue(ExceptionQueue, url, headers, body, squash_configuration, no_proxy_env) end rescue *WORKER_ERRORS => e failsafe_handler( e, message: "whilst trying to connect to Beanstalk", time_start: start, args: { url: url, headers: headers, body: body, squash_configuration: squash_configuration, no_proxy_env: no_proxy_env } ) raise end end alias :enqueue :capture_exception def failsafe_handler(exception, message: nil, time_start: nil, args: {}) configuration.logger.error "Failed: #{exception}" + (message && !message.empty? ? ", #{message}." : ".") configuration.logger.error " : #{exception.inspect}" configuration.logger.error " (Took #{Time.now - time_start}s to fail)" if time_start configuration.logger.error ["*****"," original_args = #{args.inspect}", "*****"].join("\n") end end class ExceptionQueue include Backburner::Queue queue "exception" # Process one captured Squash notification; i.e. forward it to the Squash # server def self.perform(url, headers, body, squash_configuration, no_proxy_env=nil) #TODO: Change how Squash client deals with failures. # Normally it logs to a special log file, whereas what we really want # is for the job(s) to go back on the queue to be retried. # If things fail, it's useful to know how long it caused the exception-capture to block the # calling process: start = Time.now #NB: :timeout_protection is a Proc object: squash_configuration = squash_configuration.dup #NB: The JSON conversion turns symbol-keys --> strings #NB: Squash::Ruby.configure turns string-keys --> symbols squash_configuration.delete("timeout_protection") #NB: This relies on forking behaviour! # We do this, because the queue may be shared, therefore the config may have been different from # each client. Squash::Ruby.configure(squash_configuration) ENV['no_proxy'] = no_proxy_env begin # Transmit it to the Squash server: Squash::Ruby.http_transmit__original(url, headers, body) rescue Timeout::Error, SocketError => e SquashRepeater.failsafe_handler(e, message: "whilst trying to connect/transmit to Squash", time_start: start) raise end end end end
true
8ed8299f8962eeb9e9f2c256f560ddd2e69bc963
Ruby
singhanilk1959/rpl
/intro_1/bk/ex1.rb
UTF-8
260
2.6875
3
[]
no_license
#!/usr/bin/ruby out=`cat ex1.rb` puts out print "Press Enter:" out1 = gets ####################################################### hello = "hello world" print hello print hello,"\n" puts hello ########################################################
true
f1d1f8302d84474c91c7fb30eb28069f5b5cbe4f
Ruby
Jacobus-afk/ruby-linkedlist
/lib/linked_list.rb
UTF-8
1,954
3.96875
4
[]
no_license
# frozen_string_literal: true # https://commandercoriander.net/blog/2012/12/23/reversing-a-linked-list-in-ruby/ # ruby implementation of linked list class LinkedList include Enumerable attr_reader :head, :tail def initialize @head = nil @tail = nil end def append(value) node = Node.new(value) @tail.next_node = node unless @head.nil? @tail = node @head = node if @head.nil? end def prepend(value) node = Node.new(value) node.next_node = @head unless @head.nil? @head = node @tail = node if @head.nil? end def size size = 0 each_with_index { |_, _| size += 1 } size end def at(search_index) each_with_index do |entry, index| return entry if index == search_index end end def pop prev_node = nil each_with_index do |entry, _| if entry.next_node.nil? @tail = prev_node @tail.next_node = nil end prev_node = entry end end def contains?(value) return true if find(value) false end def find(value) each_with_index { |entry, index| return index if entry.value == value } end def to_s tmp_str = '' each_with_index do |entry, _| tmp_str += '( ' + entry.value + ' ) -> ' unless entry.nil? end tmp_str += 'nil' end private def each_with_index index = 0 return nil, index if @head.nil? entry = @head until entry.nil? yield entry, index entry = entry.next_node index += 1 end end end # node class class Node attr_accessor :value, :next_node def initialize(value = nil) @value = value @next_node = nil end end test = LinkedList.new test.append('a') test.prepend('b') test.append('c') test.append('d') puts test.head.value puts test.tail.value puts test.size puts test.at(1).value puts test test.pop puts test.tail.value puts test puts test.contains?('a') puts test.contains?('f') puts test.find('a')
true
59b90cea5b7d457ebb29913e1c717c59037f8336
Ruby
steve-alex/module-one-final-project-guidelines-london-web-082619
/app/search.rb
UTF-8
7,262
3
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Search attr_reader :origin_code, :destination_code, :outbound_date, :inbound_date, :cabin_class #Sets the maximum number of results returned by any search @@max_results = 5 ###### Instance methods ###### def initialize(origin_code:, destination_code:, outbound_date:, inbound_date: "", cabin_class:) @origin_code = origin_code @destination_code = destination_code @outbound_date = outbound_date @inbound_date = inbound_date @cabin_class = cabin_class end def run_search #Run the search and return an array of unique flight hashes, cheapest first #Establish a Skyscanner session begin @session = Timeout::timeout(10) { create_session } rescue Timeout::Error return nil end # Extracts the session key from the HTTP POST response get_key # Polls Skyscanner session until results status is "UpdatesCompleted" begin Timeout::timeout(60) { get_search_results } rescue Timeout::Error return nil end # Checks search results are valid return nil if !search_results_valid? # Return unique flights up to the Search class @@max_results limit flights = unique_flights(create_flights) flights.length > @@max_results ? flights.slice(0...@@max_results) : flights end private def create_session() # POST method: create a Skyscanner session with search parameters response = Unirest.post( "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0", headers:{ "X-RapidAPI-Host" => "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com", "X-RapidAPI-Key" => "c036ae2334msh6e52f9287ee7e7ap1fbff8jsnb8c6fa5b89b5", "Content-Type" => "application/x-www-form-urlencoded" }, parameters:{ "inboundDate" => self.inbound_date, "cabinClass" => self.cabin_class, "children" => 0, "infants" => 0, "country" => "UK", "currency" => "GBP", "locale" => "en-US", "originPlace" => self.origin_code, "destinationPlace" => self.destination_code, "outboundDate" => self.outbound_date, "adults" => 1 } ) # Attempts to create sessions until 201 response or function times out response.code == 201 ? response : create_session() end def get_key # Extract the session key (string) from the raw POST response session_url = @session.headers[:location] @session_key = session_url.split("/").last end def get_search_results # Poll the session results, converts them to a hash, and saves it to the search_results instance variable raw_results = Unirest.get("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/uk2/v1.0/#{@session_key}?sortType=price&sortOrder=asc&pageIndex=0&pageSize=10", headers:{ "X-RapidAPI-Host" => "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com", "X-RapidAPI-Key" => "c036ae2334msh6e52f9287ee7e7ap1fbff8jsnb8c6fa5b89b5" }) # Generate search_results hash from XML response @search_results = Hash.from_xml(raw_results.body) # Run get_search_results until Skyscanner response status is "UpdatesComplete" get_search_results if @search_results["PollSessionResponseDto"]["Status"] != "UpdatesComplete" end def search_results_valid? @search_results["PollSessionResponseDto"]["Itineraries"] end def create_flights # Creates an array of all the flights that are queried by the API flights = create_itineraries add_departure_and_arrival_time(flights) add_departure_and_arrival_airport(flights) flights end def create_itineraries # Creates a flight object hash for each flight queried by the API, then associates a flight_id and price with that flight object get_itineraries.each_with_object([]) do | itin, array | flight = {} flight["flight_id"] = itin["OutboundLegId"] # Check whether itinerary contains multiple pricing options before attempting to access them if itin["PricingOptions"]["PricingOptionApiDto"].is_a?(Array) flight["price"] = itin["PricingOptions"]["PricingOptionApiDto"][0]["Price"] else flight["price"] = itin["PricingOptions"]["PricingOptionApiDto"]["Price"] end array << flight end end def add_departure_and_arrival_time(flights) # Gives each flight an associated departure and arrival time using the Skyscanner "Legs" attribute flights.each do |flight| matching_leg = get_legs.find { | leg | leg["Id"] == flight["flight_id"] } flight["departure_time"] = matching_leg["Departure"] flight["arrival_time"] = matching_leg["Arrival"] end end def add_departure_and_arrival_airport(flights) # Adds in the departure and arrival airport codes and names using the Skyscanner "Places" attribute flights.each do |flight| matching_leg = get_legs.find { | leg | leg["Id"] == flight["flight_id"] } # Matches the leg to the relevant airport, and extracts their names and codes origin_airport = find_airport_details(matching_leg["OriginStation"]) destination_airport = find_airport_details(matching_leg["DestinationStation"]) flight["origin_code"] = origin_airport["Code"] flight["destination_code"] = destination_airport["Code"] flight["origin"] = origin_airport["Name"] flight["destination"] = destination_airport["Name"] end end def find_airport_details(airport_id) # Returns the information about an airport using its Skyscanner OriginStation ID get_airports.find { |airport| airport["Id"] == airport_id } end def get_itineraries # Extracts the array of itineraries from the search results @search_results["PollSessionResponseDto"]["Itineraries"]["ItineraryApiDto"] end def get_legs # Extracts the array of legs from the search results @search_results["PollSessionResponseDto"]["Legs"]["ItineraryLegApiDto"] end def get_airports # Extract the array of airports from the search results @search_results["PollSessionResponseDto"]["Places"]["PlaceApiDto"] end def unique_flights(flights) # Takes in a array of flights and returns a new array without the duplicates flights.uniq { | flight | flight["arrival_time"] && flight["departure_time"] } end ###### Class methods ###### def self.get_airport_from_city(city) # Return the first skyscanner airport code that matches the given city name places_hash = airport_names_api_request(city) if !places_hash["AutoSuggestServiceResponseApiDto"]["Places"] return nil elsif places_hash["AutoSuggestServiceResponseApiDto"]["Places"]["PlaceDto"].is_a?(Array) return places_hash["AutoSuggestServiceResponseApiDto"]["Places"]["PlaceDto"][0]["PlaceId"] else places_hash["AutoSuggestServiceResponseApiDto"]["Places"]["PlaceDto"]["PlaceId"] end end def self.airport_names_api_request(city) response = Unirest.get("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/UK/GBP/en-GB/?query=#{city}", headers:{ "X-RapidAPI-Host" => "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com", "X-RapidAPI-Key" => "407d1ed52amsh672332be486dc02p1be71fjsn7639b4ef4b82" }) Hash.from_xml(response.body) end end
true
65bdb62760adb0f1fe647e1936f0721dab943643
Ruby
gonecd/subsmgr
/vendor/bundle/ruby/1.8/gems/i18n-0.6.0/test/locale/tag/simple_test.rb
UTF-8
998
2.796875
3
[ "MIT" ]
permissive
# encoding: utf-8 require 'test_helper' class I18nLocaleTagSimpleTest < Test::Unit::TestCase include I18n::Locale test "returns 'de' as the language subtag in lowercase" do assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').subtags end test "returns a formatted tag string from #to_s" do assert_equal 'de-Latn-DE', Tag::Simple.new('de-Latn-DE').to_s end test "returns an array containing the formatted subtags from #to_a" do assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').to_a end # Tag inheritance test "#parent returns 'de-Latn' as the parent of 'de-Latn-DE'" do assert_equal 'de-Latn', Tag::Simple.new('de-Latn-DE').parent.to_s end test "#parent returns 'de' as the parent of 'de-Latn'" do assert_equal 'de', Tag::Simple.new('de-Latn').parent.to_s end test "#self_and_parents returns an array of 3 tags for 'de-Latn-DE'" do assert_equal %w(de-Latn-DE de-Latn de), Tag::Simple.new('de-Latn-DE').self_and_parents.map { |tag| tag.to_s} end end
true
0f71d13724d7e3689b2f67789dd8fb298dd118fb
Ruby
Muelletie/G16_Schuldata_TAM
/eup_fit4h/ruby/Code/AG_11.rb
UTF-8
3,362
3.765625
4
[]
no_license
# 1. Klasse Kunde class Kunde # 1a.Legen Sie eine Eigenschaft name und adresse in der Klasse Kunde an. Für die Eigenschaft # name gibt es einen Lese- und Schreibzugriff, fuer die Eigenschaft adresse einen Schreibzugriff. attr_accessor :name attr_accessor :gehalt attr_writer :adresse # b. Die Eigenschaft name enthält den Vor- und Zunamen des Kunden. Diese Eigenschaft wird beim # Anlegen des Objektes übergeben. Schreiben Sie den entsprechenden Konstruktor. def initialize(xname, xadresse="") @name = xname @adresse = xadresse end def to_s "Kunde: #{@name} /Wohnhaft in: #{@adresse} /mit einem Gehalt von #{gehalt}€" end end # c. Erzeugen Sie ein Objekt mit dem Namen 'kunde1' und dem Initialwert: 'Theo Sommer' kunde1 = Kunde.new('Theo Sommer') # d. Ändern Sie die Eigenschaft 'name' des Objektes in: 'Theo Sonnenschein' kunde1.name = 'Theo Sonnenschein' # e. Schreiben Sie den Befehl, der den Namen auf der Konsole ausgibt. puts kunde1 # f. Fügen Sie der Klasse Kunde die Eigenschaft gehalt hinzu, die sowohl gelesen als auch # geschrieben werden kann. Schreiben Sie den Befehl auf, der das Gehalt des Objektes als # Konsolenbefehl auf 2000 setzt. kunde1.gehalt = 2000 puts kunde1 # g. Die Eigenschaft adresse bekommt folgenden String uebergeben: Hermelinweg 11, 22159 Hamburg kunde1.adresse = "Hermelinweg 11, 22159 Hamburg" # h. Schreiben Sie eine Getter-Methode' für die Klasse Kunde, für die Eigenschaft adresse die # folgende Ausgabe produziert: 'Theo Sonnenschein, Hermelinweg 11, 22159 Hamburg.' und geben # sie das auf der Konsole aus. # i. Zusatz optional: Sichern Sie, dass im String Theo Sonnenschein sowohl Theo, als auch # Sonnenschein jeweils mit einem Grossbuchstaben beginnen # 2. Klasse Kredit class Kredit # a. Legen Sie eine Klasse Kredit an, mit der Eigenschaft kunde (ohne Setter und Getter) und # einem Konstruktor, der die Eigenschaft kunde füllt. Die Eigenschaft Kunde wird mit einem # Kunden-Objekt initialisiert. Erzeugen Sie ein Objekt kredit1, dem Sie das bereits # existierende Objekt kunde1 übergeben. # b. Legen Sie eine Eigenschaft jahresgehalt an, die sowohl les- als auch schreibbar sein soll. # Füllen Sie für das Objekt kredit1 die Eigenschaft mit einem Wert von 24000. # c. Legen Sie eine Getter-Methode für die Eigenschaft kunde an, die folgende Ausgabe # erzeugt: 'Theo Sonnenschein, Hermelinweg 11, 22159 Hamburg. Jahresgehalt: 24000 Euro.' # d. Fügen Sie eine Eigenschaft kreditsumme hinzu, auf die lesend und schreibend zugegriffen # werden kann. Speichern Sie für das bestehende Objekt in der Eigenschaft kredit den Wert 5000. # e. Fügen Sie eine Methode kreditvergabe hinzu. Diese Methode prüft, ob der Kredit vergeben # werden kann. Die Vergabe ist abhängig davon, ob das Jahresgehalt mehr als 6 mal so groß # ist, wie die kreditsumme. Falls der Kredit gewährt wird, erfolgt die Ausgabe: Der Kredit # in Hoehe von 5000 € kann gewaehrt werden. Anderfalls: Sorry: kein Kredit. Besseren Job suchen. # f. Ergänzen Sie die Klasse mit einer Methode abzahlung, der ein Parameter 'monate' mitgegeben # wird. Die Methode dividiert den Kreditbetrag durch die 'Monate' und gibt aus, wie groß # der abzuzahlende Betrag pro Monat ist. Die AUsgabe lautet: Bei einer Rückzahlung des Kredits # von 5000 € innerhalb von 10 Monaten ist pro Monat eine Zahlung von 500 € notwendig. end
true
af41c23bdf94c07bec38b40e5d4f425037147db8
Ruby
SpOOnman/puzzles
/stripectf3/level0/second
UTF-8
562
2.625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby # Our test cases will always use the same dictionary file (with SHA1 # 6b898d7c48630be05b72b3ae07c5be6617f90d8e). Running `test/harness` # will automatically download this dictionary for you if you don't # have it already. path = ARGV.length > 0 ? ARGV[0] : '/usr/share/dict/words' entries = File.read(path) contents = $stdin.read contents.each_line do |line| output = "" line.split.each do |word| if !entries.include?(word.downcase) output << "<#{word}> " else output << "#{word} " end end puts output end
true
f7615f5d5ab1447a4379ad2eb9cf8519c3d9dd1c
Ruby
w11th/ruby_scripts
/open_safely.rb
UTF-8
277
2.75
3
[]
no_license
require 'fileutils' require 'tempfile' class File def self.open_safely(path) result = nil temp_path = nil Tempfile.open("#{$0}-#{path.hash}") do |f| result = yield f temp_path = f.path end FileUtils.move(temp_path, path) result end end
true
b2b5c117d5c85a824ae142d474c2bf838f8cab19
Ruby
jonnymoore12/student-directory
/exercises/8-3count.rb
UTF-8
993
4.21875
4
[]
no_license
def input_students puts "Please enter the names of the students" puts "To finish, just hit return twice" students = [] name = gets.chomp while !name.empty? do students << {name: name, cohort: :november} puts "We now have #{students.count} students" name = gets.chomp end students end def print_header puts "The students of Villains Academy" puts "--------------" end def print(students) students.each_with_index do |student, index| # Or you can use student["name"] if your hash was set up like so: # "name" => "Darth Vader", etc. (Two ways of doing it) count = 0 if student[:name].length < 12 puts "#{index + 1}. #{student[:name]} (#{student[:cohort]} cohort)" count += 1 end end end def print_footer(names) puts "Overall, we have #{count} great students whose name is less than" puts "12 characters long." end students = input_students print_header print(students) print_footer(students)
true
e081492ba84b18247b7ef2d721a8c2ffbdcba582
Ruby
oscarlanca/fase1
/re.rb
UTF-8
1,223
3.40625
3
[]
no_license
class account def initialize (account) @string = account @match_account = /\(\d{4}\)-\d{3}-\d{4}/ end def account? @string =~ @match_account ? true : nil end def numero_valido @string =~ @match_account ? p "#{@match_account}" : nil end def array_account @empty_array = [] if @string.numero_valido == true @string.split(",").map { |s| s.to_i } else @empty_array end end def encoded_account counter = 0 if @string.numero_valido == true array = @string.split(%r{\s*}) end string = array.join while counter != 7 end end # Regresa true si encuentra un numero de cuenta. check # check Regresa un número de cuenta si existe dentro del string y nil en el caso contrario. # check Regresa un array con los números de cuenta que existen dentro del string y un array vacío en el caso contrario. # Regresa un string donde si existen números de cuenta estos tendran remplazados por "X" los primeros siete numeros. # Regresa un string formateado donde cualquier número de diez dígitos seguido o si tiene puntos en vez de guiones lo regresa a su formato original donde usa guiones para dividir los diez dígitos. Si encuentra un numero de menos dígitos no debería remplazarlo.
true
bb6b16bf91e08b870dcf4b60e570158d9b1e27a4
Ruby
antoniomachine/bigml-ruby
/test/test_22_source_args.rb
UTF-8
1,521
2.84375
3
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
require_relative "../lib/bigml/api" require "test/unit" class TestSourceArgs < Test::Unit::TestCase def setup @api = BigML::Api.new @test_name=File.basename(__FILE__).gsub('.rb','') @api.delete_all_project_by_name(@test_name) @project = @api.create_project({'name' => @test_name}) end def teardown @api.delete_all_project_by_name(@test_name) end # Scenario: Uploading source with structured args def test_scenario1 data = [{"filename" => File.dirname(__FILE__)+"/data/iris.csv", "params" => {"tags" => ["my tag", "my second tag"], "project" => @project["resource"]}}, {"filename" => "./data/iris.csv", "params" => {"name" => "Testing unicode names: áé", "project" => @project["resource"]}}] puts puts "Scenario: Uploading source with structured args" data.each do |item| puts puts "Given I create a data source uploading a " + item["filename"] + " file" source = @api.create_source(item["filename"], item["params"].clone) puts "And I wait until the source is ready" assert_equal(BigML::HTTP_CREATED, source["code"]) assert_equal(1, source["object"]["status"]["code"]) assert_equal(@api.ok(source), true) puts "Then the source exists and has args #{JSON.generate(item['params'])}" item['params'].each do |param, value| assert_equal(source["object"][param], value) end end end end
true
eabe0ed4045f880713c6256e1afacd905106f3ea
Ruby
depaolif/green_grocer-web-0217
/grocer.rb
UTF-8
1,580
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" def consolidate_cart(cart) # code here res = {} cart.each do |item| name = item.keys[0] if !res.keys.include?(name) res[name] = item[name] res[name][:count] = 1 else res[name][:count] += 1 end end res end def apply_coupons(cart, coupons) # code here # first create couponed items and subtract if !coupons.is_a?(Array) coupons = [coupons] end # for each coupon, coupons.each do |coupon| # only matters if the coupon can apply to the cart if cart.keys.include?(coupon[:item]) # check if there are enough items per coupons while cart[coupon[:item]][:count] >= coupon[:num] # then, subtract the number of coupons from the main item cart[coupon[:item]][:count] -= coupon[:num] # and create a new, couponed item that many times cart["#{coupon[:item]} W/COUPON"] = { :price => coupon[:cost], :clearance => cart[coupon[:item]][:clearance], :count => cart["#{coupon[:item]} W/COUPON"] ? cart["#{coupon[:item]} W/COUPON"][:count] + 1 : 1 } end end end cart end def apply_clearance(cart) # code here cart.each do |item,values| if values[:clearance] == true cart[item][:price] *= 0.8 cart[item][:price] = cart[item][:price].round(1) end end cart end def checkout(cart, coupons) # code here cart = consolidate_cart(cart) cart = apply_coupons(cart,coupons) cart = apply_clearance(cart) total = 0 cart.each do |item, values| total += values[:count] * values[:price] end return total > 100 ? total * 0.9 : total end
true
91cf7f8afbdbfb6f3febce3b6735d8ed49055d2e
Ruby
mgalibert/geonames
/parent_and_child.rb
UTF-8
1,016
2.84375
3
[]
no_license
require "csv" require "colorize" require_relative './lib/constants' require_relative './lib/utils' STATIONS = load_csv("stations2.csv") STATIONS_BY_ID = STATIONS.inject({}) { |hash, station| hash[station[:id]] = station; hash } CSV.open(POLISHED_STATIONS_FILE, 'w', CSV_PARAMS) do |csv| # Copy headers from original file headers = CSV.foreach(MODIFIED_STATIONS_FILE, {:col_sep => ";"}).first csv << headers # Importing rows from original file STATIONS.each do |row| parent = STATIONS_BY_ID[row[:parent_station_id]] if !parent.nil? && row[:is_suggestable] == "t" && parent[:is_suggestable] == "t" LOCALES.keys.each do |locale| if row[:"info#{locale}"].nil? && !parent[:"info#{locale}"].nil? row[:"info#{locale}"] = parent[:"info#{locale}"] puts "Station #{row[:name]} (#{row[:id]}) has a new localized info in “#{locale}”: #{row[:"info#{locale}"]}".green end end else print '.'.yellow end csv << row end end puts "Done"
true
8972db4476c6bf6b5d9c2d0c4155dd411e1dc117
Ruby
digital-fabric/polyphony
/examples/performance/thread_switch.rb
UTF-8
758
3.53125
4
[ "MIT" ]
permissive
# frozen_string_literal: true require 'fiber' class Fiber attr_accessor :next end # This program shows how the performance of Fiber.transfer degrades as the fiber # count increases def run(num_threads) count = 0 GC.start GC.disable threads = [] t0 = Time.now limit = 10_000_000 / num_threads num_threads.times do threads << Thread.new do individual_count = 0 loop do individual_count += 1 count += 1 break if individual_count == limit end end end threads.each(&:join) elapsed = Time.now - t0 puts "threads: #{num_threads} count: #{count} rate: #{count / elapsed}" rescue Exception => e puts "Stopped at #{count} threads" p e end run(100) run(1000) run(10000) run(100000)
true
788bf424208c35bec723492e175c1229f73862a0
Ruby
hquenin/mapel
/lib/mapel/engine/image_magick.rb
UTF-8
4,999
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Mapel class Engine class ImageMagick < Engine module ClassMethods def info(source) new.with_command("identify", source.inspect).run.to_info_hash end def exif(source) new.with_command("identify -format %[exif:*]", source.inspect).run.to_exif_hash end def render(source = nil) new.with_command("convert", source.nil? ? nil : source.inspect) end # http://www.imagemagick.org/script/command-line-options.php#list # ex: Mapel.list() # ex: Mapel.list('Orientation', true) # pass false as second argument, if you want an unparsed result def list(type = 'list', parse = true) new.with_command("convert -list", type).run.to_list(parse) end end extend ClassMethods # Crops an image to specified dimensions. # # More information on ImageMagick's crop option: # http://www.imagemagick.org/script/command-line-options.php#crop # def crop(*args) with_command %(-crop "#{Geometry.new(*args).to_s(true)}") end # Sets the current gravity suggestion to given type. # # Values for type incule: # NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast # # Call `convert -list gravity` to get a complete list of -gravity settings # available in your ImageMagick installation. # # More information on ImageMagick's gravity option: # http://www.imagemagick.org/script/command-line-options.php#gravity # def gravity(type = :center) with_command "-gravity #{type}" end # Grayscales an image # # More information on ImageMagick's type option: # http://www.imagemagick.org/script/command-line-options.php#type # def grayscale with_command "-type Grayscale" end # Automatically rotates an image with EXIF Orientation. # If the EXIF profile was previously stripped, orient will do nothing. # # More information on ImageMagick's auto-orient option: # http://www.imagemagick.org/script/command-line-options.php#auto-orient # def orient with_command "-auto-orient" end # Sets the quality level of the output image # # More information on ImageMagick's quality option: # http://www.imagemagick.org/script/command-line-options.php#quality # def quality(level) with_command "-quality #{level}" end # Resets the virtual canvas meta-data on the image. # # More information on ImageMagick's repage option: # http://www.imagemagick.org/script/command-line-options.php#repage # def repage with_command "+repage" end # Rotates in degree an image. # # More information on ImageMagick's repage option: # http://www.imagemagick.org/script/command-line-options.php#repage # def rotate(*args) with_command %(-rotate "#{Geometry.new(*args)}") end # Resizes an image to given geometry args. # # More information on ImageMagick's resize option: # http://www.imagemagick.org/script/command-line-options.php#resize # def resize(*args) with_command %(-resize "#{Geometry.new(*args)}") end # Resizes and crops an image to dimensions specified in geometry args. # Performs resize + crop + repage def resize!(*args) width, height = Geometry.new(*args).dimensions resize("#{width}x#{height}^").crop(width, height).repage end # Scales an image to given geometry args, which is faster than resizing. # # More information on ImageMagick's scale option: # http://www.imagemagick.org/script/command-line-options.php#scale # def scale(*args) with_command %(-scale "#{Geometry.new(*args)}") end # Removes any profiles or comments from the image, including EXIF meta-data. def strip with_command "-strip" end # Sets the output path. def to(path) with_command path.inspect end # Returns a hash of image informations def to_info_hash return {} if @output.empty? meta = @output.split(" ") # Count backwards as an image's path may contain a space { path: meta[0..-9].join(" "), format: meta[-8], dimensions: meta[-7].split("x").map(&:to_i), depth: meta[-5], size: meta[-3] } end # Converts EXIF data into a hash of values. def to_exif_hash return {} if @output.empty? meta = @output.scan(/exif:([^=]+)=([^\n]+)/) Hash[meta] end def to_list(parse = true) return self unless parse @output.split("\n") end end end end
true
b7fa9f963fe9ee6a78e55c7584fa5fde8603fe46
Ruby
mchmilar/squeeze-play
/lib/flipper.rb
UTF-8
6,017
3.125
3
[]
no_license
#! /usr/bin/ruby require_relative 'player_page' require 'byebug' require 'pry-byebug' class Flipper attr_reader :page, :starting_potential_profit, :starting_sellable, :starting_min_sell_price, :starting_max_buy_price class EmptyBuyOrdersError < StandardError; end class EmptySellOrdersError < StandardError; end class OrdersNotCancelledError < StandardError; end class NoSellableError < StandardError; end def initialize(player_id) @page = PlayerPage.new(player_id).load @starting_potential_profit = page.potential_profit @starting_sellable = page.sellable @starting_min_sell_price = page.min_sell_price @starting_max_buy_price = page.max_buy_price end def flip if page.sellable > 0 p "> You already own at least one of this player, would you like to buy another?" @should_buy = STDIN.gets.chomp p "> Would you like to sell all?" @should_sell_all = STDIN.gets.chomp end p @should_buy p @should_sell_all p "[#{timestamp}] ### Begin flipping #{page.name} ###" p "[#{timestamp}] Current sellable: #{starting_sellable}" p "[#{timestamp}] Buy price: #{starting_max_buy_price}" p "[#{timestamp}] Sell price: #{starting_min_sell_price}" p "[#{timestamp}] Starting potential profit: #{starting_potential_profit}" p "[#{timestamp}] Should buy first?: #{buy?}" p "[#{timestamp}] Should sell all?: #{sell_all?}" p "[#{timestamp}] #############################################\n" if buy? page.place_max_buy_order page.load binding.pry p "[#{timestamp}] place order result: #{page.toastr_result.result}, #{page.toastr_result.message}" until player_acquired? || profit_margin_too_thin? do raise EmptyBuyOrdersError if page.buy_order.nil? if buy_order_outbid? || buy_order_matched? || overbid? order_prices = page.buy_orders.map { |b| b.price } p "[#{timestamp}] #{reorder_reason}, cancelling orders of #{order_prices}" page.cancel_buy_orders page.load p "[#{timestamp}] cancel order result: #{page.toastr_result.result}, #{page.toastr_result.message}" raise OrdersNotCancelledError unless page.buy_order.nil? p "[#{timestamp}] Cancelled orders successfully" p "[#{timestamp}] Placing max buy order" page.place_max_buy_order page.load p "[#{timestamp}] place order result: #{page.toastr_result.result}, #{page.toastr_result.message}" end sleep(5) page.load p "[#{timestamp}] Refreshed buy orders. My order price: #{page.buy_order&.price}, max buy price: #{page.max_buy_price&.price}, min sell price: #{page.min_sell_price&.price}, profit: #{page.potential_profit}, sellable: #{page.sellable}" end p "Player acquired" if player_acquired? p "Margin too thin" if profit_margin_too_thin? end page.load pre_sale_sellable = page.sellable raise NoSellableError if pre_sale_sellable == 0 page.place_min_sell_order page.load p "[#{timestamp}] place order result: #{page.toastr_result.result}, #{page.toastr_result.message}" until sale_complete?(pre_sale_sellable) raise EmptySellOrdersError if page.sell_order.nil? if sell_order_outbid? || sell_order_matched? || underbid? order_prices = page.sell_orders.map { |s| s.price } p "[#{timestamp}] #{sell_reorder_reason}, cancelling orders of #{order_prices}" page.cancel_sell_orders page.load p "[#{timestamp}] cancel order result: #{page.toastr_result.result}, #{page.toastr_result.message}" raise OrdersNotCancelledError unless page.sell_order.nil? p "[#{timestamp}] Cancelled orders successfully" p "[#{timestamp}] Placing min sell order" page.place_min_sell_order page.load p "[#{timestamp}] place order result: #{page.toastr_result.result}, #{page.toastr_result.message}" end sleep(5) prev_sellable = page.sellable + page.sell_orders.size page.load current_sellable = page.sellable + page.sell_orders.size p "[#{timestamp}] Refreshed sell orders. My order price: #{page.sell_order&.price}, max buy price: #{page.max_buy_price&.price}, min sell price: #{page.min_sell_price&.price}, profit: #{page.potential_profit}, sellable: #{page.sellable}" p "[#{timestamp}] SOLD Card(s)! Quantity: #{prev_sellable - current_sellable}" if prev_sellable > current_sellable end end private def sale_complete?(pre_sale_sellable) if sell_all? (page.sellable + page.sell_orders.size) == 0 else (pre_sale_sellable - page.sellable) == 1 end end def sell_all? case @should_sell_all when 'n' false else true end end def buy? case @should_buy when 'n' false else true end end def reorder_reason if buy_order_outbid? 'outbid' elsif buy_order_matched? 'matched' elsif overbid? 'overbid' else 'unknown' end end def sell_reorder_reason if sell_order_outbid? 'outbid' elsif sell_order_matched? 'matched' elsif underbid? 'underbid' else 'unknown' end end def timestamp Time.now.strftime '%H:%M:%S' end def overbid? (page.buy_order.price - page.max_buy_price.price) > 1 end def underbid? (page.min_sell_price.price - page.sell_order.price) > 1 end def buy_order_matched? page.max_buy_price.quantity > 1 end def sell_order_matched? page.min_sell_price.quantity > 1 end def buy_order_outbid? page.buy_order.price < page.max_buy_price.price end def sell_order_outbid? page.min_sell_price.price < page.sell_order.price end def player_acquired? starting_sellable < page.sellable end def profit_margin_too_thin? (starting_potential_profit / 2) > page.potential_profit end end Flipper.new(ARGV[0]).flip
true
714384bcecef2b819fc201f12c13da9854d3bced
Ruby
mintona/flash_cards
/lib/card_generator.rb
UTF-8
712
3.25
3
[]
no_license
class CardGenerator attr_reader :filename def initialize(filename) @filename = filename end def cards lines = [] File.readlines(@filename).each do |line| lines << [line.chomp] end lines split_lines = [] lines.each do |line| split_lines << line.join.split(',') end split_lines question = nil answer = nil category = nil cards = split_lines.map do |element| question = element[0] answer = element[1] if element[2] == "STEM" || element[2] == "Geography" category = element[2].to_sym else category = element[2] end card = Card.new(question, answer, category) end cards end end
true
17c33d0206a430ac7721bdff71025e379bc89491
Ruby
jkappers/datetime_format_testing
/app/validators/date_or_time_validator.rb
UTF-8
370
2.53125
3
[]
no_license
# Validates an attribute to ensure the value is a Date, Time, or DateTime # TODO: Can we specify the friendly_x_format in the message? class DateOrTimeValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless [DateTime, Date, Time].any? { |kind| value.is_a? kind } record.errors[attribute] << 'invalid date' end end end
true
e891f276147da0b85e665bb13126717a1d801ff7
Ruby
MikeyC24/CSVtest
/upload_backed_up_tasks_with_new_ids.rb
UTF-8
580
2.640625
3
[ "MIT" ]
permissive
require 'csv' oldids_newids = {} CSV.foreach("livecsv/Oldidswithnewids.csv" ) do |row| oldid = row[1] newid = row[0] oldid_newid = { oldid => newid } oldids_newids.merge!( oldid_newid) end rows = [] CSV.foreach("livecsv/Task.csv" ) do |row| contactsoldid = row[1] task = [] task << row contactsnewid = oldids_newids[contactsoldid] task << contactsnewid if contactsnewid != nil rows << task end end File.open("livecsv/out.csv", "w") {|f| f.write(rows.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join(""))}
true
7f33b783c2a02e32a5b8640530847e01fa885612
Ruby
kandalf/funky-world-cup
/lib/map.rb
UTF-8
994
2.875
3
[ "MIT" ]
permissive
module FunkyWorldCup class Map COLORS_SCALE = ["#ff9059", "#7559ff", "#59ff90"].freeze SCALE = { "groups" => 1, "16_round" => 3, "quarter_finals" => 5, "semi_finals" => 7, "third_place" => 9, "final" => 12, "champion" => 20, }.freeze def initialize(cup_groups) @cup_groups = cup_groups end def series_data serie = { values: {}, scale: COLORS_SCALE, normalizeFunction: "linear", min: 1, max: 20, } @cup_groups.each do |group| group.teams.each do |team| next unless team serie[:values][team.iso_code] = SCALE[group.phase] end if group.phase == "final" champion = group.matches.first.winner serie[:values][champion.iso_code] = SCALE["champion"] if champion end end serie end end end
true
d8282838fa24826b1db67bbea5ddad7aca8a2805
Ruby
PurplePineapple123/connect-four
/lib/game.rb
UTF-8
1,109
3.484375
3
[]
no_license
# lib/connect_four.rb require_relative 'board.rb' class Game def initialize(game_board = Board.new) @game_board = game_board @player_turn = 1 @player = 0 end def player_selection loop do puts "Choose a column, Player #{@player_turn}:" @user_input = gets.chomp if @user_input.match?(/\b[1-7]\b/) return @player = @user_input.to_i else puts 'Error: Add number between 1-7' end end end def valid_vertical_move until @game_board.board[5][@player - 1] == '.' puts 'Please place piece in valid spot' player_selection end end def insert_circle valid_vertical_move @game_board.update_board(@player, @player_turn) @game_board.display_board @player_turn == 1 ? @player_turn = 2 : @player_turn = 1 end def play_game @game_board.display_board loop do player_selection insert_circle @game_board.winning_combo end end end # test = Game.new # puts test.valid_vertical_move # if test.valid_vertical_move == nil # puts "nil" # else # puts "not nil" # end
true
b4ddc3d1db89b755f7efe79cf74df57878b763fb
Ruby
1ulce/adventofcode2020
/day8/day8b.rb
UTF-8
1,509
3.09375
3
[]
no_license
f = File.open("day8_input") s = f.read # 全て読み込む f.close lines = s.split("\n") map = {} lines.each_with_index do |line, idx| words = line.split(" ") info = {nop: false, next: idx + 1, used: false, acc: 0} case words[0] when "acc" info[:acc] = words[1].to_i when "jmp" info[:next] = idx + words[1].to_i when "nop" info[:nop] = true if words[1].to_i == 0 info[:next] = idx + 1 else info[:next] = idx + words[1].to_i end end map[idx] = info end def saiki(answer, idx, map, ashiato) begin return answer if map[idx][:used] == true rescue => e p answer return true end map[idx][:used] = true ashiato << idx answer += map[idx][:acc] next_idx = map[idx][:next] next_idx = idx + 1 if map[idx][:nop] saiki(answer, next_idx, map, ashiato) end ashiato = [] answer = 0 answer = saiki(answer, 0, map, ashiato) original_ashiato = ashiato.dup original_answer = answer original_ashiato.reverse.each_with_index do |step, idx| if map[step][:acc] == 0 original_ashiato.pop map[step][:nop] = map[step][:nop] == false map[step][:used] = false ashiato = original_ashiato.dup answer = original_answer result = saiki(answer, step, map, ashiato) original_answer = answer return original_answer if result == true ashiato = original_ashiato.dup map[step][:nop] = map[step][:nop] == true else original_answer -= map[step][:acc] map[step][:used] = false original_ashiato.pop end end
true