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
bfa714f1961b17f96194fd2a96e97434c0c854d7
Ruby
eric-dowty/mythical_creatures
/medusa.rb
UTF-8
402
3.421875
3
[]
no_license
class Medusa attr_reader :name, :statues def initialize(name) @name = name @statues = [] end def empty? if @statues.length = 0 true else false end end def stare(victim) @statues << victim victim.stone = true end end class Person attr_reader :name attr_accessor :stone def initialize(name) @name = name @stone = false end def stoned? @stone end end
true
92780987922ff8d8b4d2d013a3f186dcf8f3f1e0
Ruby
car2323/w2
/day5/lib/post.rb
UTF-8
445
3.15625
3
[]
no_license
#Post class class Post attr_reader :created_at, :title attr_accessor :text, :updated_at def initialize(titlep, textp) @title = titlep @created_at = Time.now @text = textp @updated_at = nil end def test_atribute? value_return = false if ((@title != "" ) && (@created != nil) && (@text != "") && (updated_at == nil)) value_return = true end value_return end end
true
1c481f90ccde2633e240abfda70f392a781737d4
Ruby
nathanmeira/aws-autoscale-workers
/app/services/interval_service.rb
UTF-8
2,561
2.71875
3
[]
no_license
class IntervalService attr_reader :cycle, :work_manager def initialize(cycle) @cycle = cycle.is_a?(Cycle) ? cycle : Cycle.find(cycle) @work_manager = cycle.work_manager end def calculate intervals = build_array_from_array(last_cycle_intervals) total_intervals = intervals.size processed_jobs = cycle.processed_jobs intervals.each_with_index do |interval, i| pos = i+1 processed_jobs_interval = (work_manager.jobs_per_cycle / total_intervals * pos).to_i jobs_next_interval = intervals[pos].nil? ? 0 : intervals[pos][1] jobs_this_interval = intervals[i][1] num_jobs = if pos == total_intervals && cycle.new_jobs > 0 cycle.new_jobs elsif jobs_this_interval <= processed_jobs || (pos == 1 && jobs_this_interval > 0) jobs_next_interval + jobs_this_interval else jobs_next_interval end if num_jobs >= processed_jobs num_jobs = num_jobs - processed_jobs processed_jobs = 0 else processed_jobs = processed_jobs - num_jobs num_jobs = 0 end desired_workers_interval = (num_jobs.to_f / processed_jobs_interval.to_f).ceil interval[0] = pos interval[1] = num_jobs interval[2] = processed_jobs_interval interval[3] = desired_workers_interval end save_intervals!(intervals) intervals end def last_cycle_intervals build_array_from_intervals(cycle.previous.intervals) if cycle.previous.present? end private def save_intervals!(intervals) intervals.each do |interval| cycle.intervals.create!({ position: interval[0], jobs: interval[1], slice_jobs: interval[2], workers: interval[3] }) end end def build_blank_array(rows) Array.new(rows) { Array.new(4) { 0 } } end def build_array_from_intervals(intervals) intervals.map { |i| [i[:position], i[:jobs], i[:slice_jobs], i[:workers]] } end def build_array_from_array(source) new_array = build_blank_array(work_manager.total_intervals_period?) if source if source.size==new_array.size new_array = source else source.each do |i| item = new_array.min_by { |t| (t[1].to_f - i[1]).abs } new_array[new_array.index(item)][0] = i[0] end end end new_array end end
true
97f3d35f2733f93a2ab2a74f426b5530dc357e34
Ruby
Unayung/better_round
/lib/better_round/rounding_helper.rb
UTF-8
398
2.546875
3
[ "MIT" ]
permissive
# :nodoc: # require 'active_support/number_helper/rounding_helper' module BetterRound module RoundingHelper def better_round(number, symbol = nil, appendix = nil) s = '' s += "#{symbol} " if symbol s += round(number).to_s s += " #{appendix}" if appendix s end end end Integer.include(BetterRound::RoundingHelper) Float.include(BetterRound::RoundingHelper)
true
dce8ad89184b14143f39af2e77e38e56a771fdae
Ruby
janmilosh/advent_of_code
/spec/day_5/intcode2_spec.rb
UTF-8
714
2.9375
3
[]
no_license
require_relative '../../day_5/intcode2.rb' RSpec.describe Intcode2 do let(:file) { './day_5/data/test_data' } let(:intcode) { Intcode2.new(file) } describe '#initialize' do it 'initializes the data to an array of integers' do expect(intcode.data_array).to eq [1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50] end end describe '#instruction_array' do it 'returns a hash indicating opcode and modes' do expect(intcode.instruction_array(4)).to eq [1, 9, 10, 3] end end describe '#interpret' do it 'process the code to an opcode and parameters as a hash' do expect(intcode.interpret(1002)).to include ({ opcode: 2, p1: 0, p2: 1, p3: 0 }) end end end
true
64747fb53e06d34fbb9065dd8c08e8802291ffda
Ruby
guicharn/Quotes-CMS
/lib/directory.rb
UTF-8
316
3.15625
3
[]
no_license
require "proverb" require "quote" class Directory attr_reader :entries def initialize @entries = [] end def add_entry(entry) @entries.push(entry) end def get_entry_at(index) @entries[index] end def length @entries.length end def to_s @entries.join("\n") end end
true
812b598c17b98bf8daad25075171644699638f39
Ruby
jajapop-m/AtCoder
/過去問/ABC/ABC_161/D_5_calc_next.rb
UTF-8
781
3.75
4
[]
no_license
# 再帰関数を使わずに全列挙(BFS) K = gets.to_i # d桁のルンルン数が全列挙された配列を受け取り、 # d+1桁のルンルン数が全列挙された配列をreturnする関数(calc_next) def calc_next(ary) res=[] ary.each do |val| # 配列の要素全てに対して、 (-1..1).each do |i| # 次の桁を計算し、 add = (val % 10) + i # それが0..9の間なら、1桁目に挿入してresに入れる res << val*10 + add if add >= 0 && add <= 9 end end res end all = cur= [*1..9] # 1桁目の全列挙,cur=現在計算中の桁の全列挙,all=全ての値が入る配列 9.times do # 9回calc_nextを実行すれば10桁まで求まる cur = calc_next(cur) all.concat(cur) end puts all[K-1]
true
efe82aea114688854187413f6107c43a729f63e2
Ruby
brillantewang/Homework
/W2D5/lru_cache.rb
UTF-8
337
3.09375
3
[]
no_license
class LRUCache def initialize(max_num) @max_num = max_num @cache = [] end def count @cache.count end def add(el) delete(el) shift if count == @max_num @cache.push(el) end def show p @cache end private def shift @cache.shift end def delete(el) @cache.delete(el) end end
true
4ba29cc5f1b4fa2275177fb6a2154580eedd44ce
Ruby
PacktPublishing/RabbitMQ-Essentials-Second-Edition
/Chapter02/example_consumer.rb
UTF-8
896
3.125
3
[ "MIT" ]
permissive
# 1. Require client library require "bunny" # 2. Read RABBITMQ_URI from ENV connection = Bunny.new ENV["RABBITMQ_URI"] # 3. Start a communication session with RabbitMQ connection.start channel = connection.create_channel # Method for the processing def process_order(info) puts "Handling taxi order" puts info sleep 5.0 puts "Processing done" end def taxi_subscribe(channel, taxi) # 4. Declare a queue for a given taxi queue = channel.queue(taxi, durable: true) # 5. Declare a direct exchange, taxi-direct exchange = channel.direct("taxi-direct", durable: true, auto_delete: true) # 6. Bind the queue to the exchange queue.bind(exchange, routing_key: taxi) # 7. Subscribe from the queue queue.subscribe(block: true, manual_ack: false) do |delivery_info, properties, payload| process_order(payload) end end taxi = "taxi.1" taxi_subscribe(channel, taxi)
true
844d01a3756b3a5066f8b33983ab99cbd267c8bb
Ruby
lazyatom/media_organiser
/lib/downloaded_show.rb
UTF-8
1,643
3.078125
3
[]
no_license
require 'fileutils' require 'itunes_wrapper' class DownloadedShow attr_reader :filename, :show, :episode, :season, :name def initialize(filename) @filename = filename extract_details end def output_path(root="") File.join(root, show, "Season #{season}", output_filename) end def output_filename out = "#{show} S#{padded(season)}E#{padded(episode)}" out += " - #{name}" if name out += ".avi" out end def tv_show? @season && @episode end def import_to_itunes(movie_folder, itunes_add_folder) if tv_show? puts "Moving #{filename} to #{show.output_path}" sorted_show = output_path(movie_folder) FileUtils.mkdir_p(File.dirname(sorted_show)) FileUtils.mv(filename, sorted_show) ITunesWrapper.new(sorted_show).import(itunes_add_folder) end end private def extract_details separator_character = filename.match(/(.)S\d/)[1] bits = File.basename(filename, ".avi").split(separator_character) season_and_episode = bits.find { |x| x =~ /S\d/ } season_and_episode_index = bits.index(season_and_episode) @show = bits[0, season_and_episode_index].join(" ") m = season_and_episode.match(/(\d+)\w(\d+)/) @season = m[1].to_i @episode = m[2].to_i if bits.index("HDTV") @name = bits[(season_and_episode_index+1)...bits.index("HDTV")].join(" ") else name_bits = bits[(season_and_episode_index+1)..-1] name_bits.shift unless name_bits.first =~ /\w/ @name = name_bits.join(" ") end @name = nil if @name == "" rescue nil end def padded(value) value.to_s.rjust(2, "0") end end
true
4529a190756aa161225e7466e876dff34252bb3c
Ruby
chubbymaggie/chromium-history
/lib/scripts/OWNERSoutputParse (2).rb
UTF-8
3,423
3.203125
3
[]
no_license
def countCommits count = 0 counts = Array.new File.open("practiceOutput.txt").each do |line| if (line.include? "::::") puts "Over the course of one year, this file has had " + count.to_s + " commits" puts "" counts.push(count) count = 0 puts line.slice(5, line.length - 12) newFile = true elsif (line.index(",") == 3) puts "This file was created on " + line.slice(0, line.length - 15) elsif (line.include? "/") #if (newFile) # ary = Array.new # newFile = false #end #sum = 0 count += 1 #ary.push(line.split("\t")[1].to_i) #ary.each { |a| sum+=a } end end puts "Over the course of one year, this file has had " + count.to_s + " commits" counts.push(count) puts "" puts "The average number of commits on an OWNERS file per year is " + (counts.inject{ |sum, el| sum + el }.to_f / counts.size).to_s end def ownersAndAuthors list = Array.new File.open("AUTHORS").each do |line| line.chomp! if (line[0] != "#") if (line.index(">") != nil) list.push(line.slice(line.index("<") + 1, (line.index(">")-line.index("<") -1))) end end end puts list.sort end def getOwners list = Array.new File.open("search.txt").each do |line| line.chomp! File.open(line).each do |name| name.chomp! if (name[0] != "#") if (name.index("=") != nil) name = name.slice(name.index("=") + 1, name.length) end if (name[0] != "*") if (name.index("@") != nil) if (!list.include?(name)) list.push(name) end end end end end end puts list.sort end def compareLists list = Array.new count = 0 File.open("committersAlphabetical.txt").each do |author| own = false File.open("allTheOwners.txt").each do |owner| author.chomp! owner.chomp! if (owner === author) #list.push(owner + " has committed in the past year") own = true #else # if (!list.include? owner) # list.push(owner) # end end end if (!own) list.push(author) end count += 1 end puts "The total number of commiters in the last year that are not owners are: " + list.size.to_s puts "The total number of authors in general are: " + count.to_s puts list end def sortCommitters c = Array.new File.open("committers.txt").each do |line| line.chomp! if (!c.include? line) c.push(line) end end return c.sort end def totalCommitters c = sortCommitters counts = sortCommitters totals = Array.new(c.size) j = 0 totals.each do |t| totals[j] = 0 j += 1 end File.open("committers.txt").each do |line| c.each do |com| line.chomp! com.chomp! if (line === com) i = c.index(line) counts[i] << "*" totals[i] += 1 end end end k = 0 while k < c.size do puts c[k].to_s + ": " + totals[k].to_s k += 1 end end def compareListsTwo list = Array.new count = 0 File.open("allTheOwners.txt").each do |author| own = false File.open("committersAlphabetical.txt").each do |owner| author.chomp! owner.chomp! if (owner === author) #list.push(owner + " has committed in the past year") own = true #else # if (!list.include? owner) # list.push(owner) # end end end if (!own) list.push(author) end count += 1 end puts "The total number of commiters in the last year that are not owners are: " + list.size.to_s puts "The total number of authors in general are: " + count.to_s puts list end compareListsTwo
true
400489ce76d5bf3ef139c9daa07ad671ba6e902e
Ruby
omer-algreeb/Phoenix
/app/lib/voucher_consolidate_line_items.rb
UTF-8
1,319
2.65625
3
[ "Apache-2.0" ]
permissive
class VoucherConsolidateLineItems def initialize(attributes={}) # voucher, associated_collection = children that needs to be consolidated, attrib = column on which consolidation will be done eg. product_id, payment_mode_id, consolidate = field to be summed up (let me know if you can think of better term) voucher = attributes[:voucher] @associated_collection = voucher.send(attributes[:association_name]) @attrib_id = attributes[:attrib_id] @consolidate = attributes[:consolidate] end def consolidate_with_same_attribute # result_hash = line_items.group_by(&:product_id) result_hash = {} @associated_collection.reject(&:marked_for_destruction?).each do |record| if result_hash.key?(record.send(@attrib_id)) if record.new_record? result_hash[record.send(@attrib_id)][@consolidate] += record.send(@consolidate) @associated_collection.destroy(record) else record[@consolidate] += result_hash[record.send(@attrib_id)].send(@consolidate) @associated_collection.destroy(result_hash[record.send(@attrib_id)]) result_hash.delete[record.send(@attrib_id)] result_hash[record.send(@attrib_id)] = record end else result_hash[record.send(@attrib_id)] = record end end end end
true
651d23959e07d5a94f590dac795582911799eb99
Ruby
Tim-Feng/learn-ruby-the-hard-way
/ex14.rb
UTF-8
1,639
4
4
[]
no_license
# Argument variable with the 1st input parameter user = ARGV.first # this variable is not in the exercise, it's for reminding that ARGV calls from 0 reminder = ARGV[1] # this is just to unite the symbol so that you can change one code for all script prompt = '>' puts "Hi #{user}, I'm the #{$0} script." puts "I'd like to ask you a few questions." puts "Do you like me #{user}?" print prompt # STDIN means STanDard INput, there is also STDOUT, standard out and STDERR,standard error # OK, first thing, here's a change-up. gets.chomp() is represented as STDIN.gets.chomp(). # Why? Because ARGV is being used. # the default gets method will look in ARGV and try to read from the first variable as a # file but not data. # getting input straight from the keyboard (user input) is referred to in computer # parlance as STDIN. # So to read the users input as data, when ARGV is used, STDIN.gets is used. # after all, STDIN.gets.chomp() will receive user' input as data but not a file and print # without a new line, or to say, remove the white space likes = STDIN.gets.chomp() puts "Where do you live #{user}?" print prompt # here I didn't use .chomp and you will see the script include the return we press and # start a new line lives = STDIN.gets puts "What kind of computer do you have?" print prompt computer = STDIN.gets.chomp() puts <<MESSAGE Alright, so you said #{likes} about liking me. You live in #{lives}. Not sure where that is. And you have a #{computer} computer. Nice. MESSAGE # print here will include the return we press in the STDIN.gets so there will be a new # line for the next puts print lives puts lives
true
cc440267665391b47757c9e66261acf80cec24c9
Ruby
ndlib/curate_nd
/app/models/copyright.rb
UTF-8
1,042
2.6875
3
[ "Apache-2.0" ]
permissive
# Responsible for exposing means of looking up a list of copyrights from Locabulary module Copyright PREDICATE_NAME = 'copyright'.freeze # @api public # # Get a list of active copyright terms available for selection # # @return [Array<#term_label, #term_uri, #description>] def self.active ControlledVocabularyService.active_entries_for_predicate_name(name: PREDICATE_NAME) end # Returns a key/value pair of active items available for select # @return [Hash] def self.active_for_select active.each_with_object({}) do |item, hash| hash[item.term_label] = item.term_uri hash end end def self.default_persisted_value persisted_value_for!('All rights reserved') end def self.label_from_uri(uri) ControlledVocabularyService.label_from_uri(name: PREDICATE_NAME, uri: uri) end def self.persisted_value_for!(value) ControlledVocabularyService.item_for_predicate_name(name: PREDICATE_NAME, term_key: 'term_label', term_value: value, ignore_not_found: false).term_uri end end
true
d39eacf4733f2f1516ab4f97c88d43c4191dde40
Ruby
3014zhangshuo/refactoring-ruby
/inline_method.rb
UTF-8
193
2.9375
3
[]
no_license
def get_rating more_than_five_late_deliveries? 2 : 1 end def more_than_five_late_deliveries @number_of_late_deliveries > 5 end def get_rating @number_of_late_deliveries > 5 ? 2 : 1 end
true
7b18800c569c0530609191da53f76442863af6ae
Ruby
sergio-bobillier/g
/library/races.rb
UTF-8
776
3.1875
3
[]
no_license
# frozen_string_literal: true require_relative '../race' # This module contains a constant for each of the five races. Normally these # would be loaded from a database but since this is conceptual game I want to # keep it as simple as posible. # # @author Sergio Bobillier <[email protected]> module Races HUMAN = Race.new( Stats.new(con: 3, str: 3, dex: 3, int: 3, men: 3, wit: 3), [:light, :dark] ) ELF = Race.new( Stats.new(con: 2, str: 2, dex: 4, int: 4, men: 4, wit: 5), :water ) DARK_ELF = Race.new( Stats.new(con: 1, str: 2, dex: 5, int: 5, men: 1, wit: 4), :wind ) DWARF = Race.new( Stats.new(con: 5, str: 4, dex: 1, int: 2, men: 2, wit: 2), :earth ) ORC = Race.new( Stats.new(con: 4, str: 5, dex: 2, int: 1, men: 5, wit: 1), :fire ) end
true
0bdbc65ddae3275cdfca6d7b7eed8122323a4387
Ruby
thomas-boyer/ar-exercises
/exercises/exercise_7.rb
UTF-8
466
2.90625
3
[]
no_license
require_relative '../setup' require_relative './exercise_1' require_relative './exercise_2' require_relative './exercise_3' require_relative './exercise_4' require_relative './exercise_5' require_relative './exercise_6' puts "Exercise 7" puts "----------" # Your code goes here ... puts "Please type the name of the store you want to look up." name = gets.chomp error_store = Store.create(name: name) error_store.errors.messages.each do |error| puts error end
true
e8ad3b4648a65be9217ca369cd49ffff45683839
Ruby
DnailZ/ruby_make_script
/lib/ruby_make_script.rb
UTF-8
5,785
2.921875
3
[ "MIT" ]
permissive
# # Usage: # ``` # require "ruby_make_script" # make do # :run .from "a.out" do # ~ "./a.out" # end # "a.out" .from "test.c" do # ~ "gcc test.c" # end # end # ```` # # # if !system('gem list | grep pastel > /dev/null') puts "pastel not install automaticly, please 'gem install pastel'" end require 'pastel' require 'yaml' # all targets list $targetlist = [] # file -> target $file_target_dict = Hash[] # file -> mtime (last make) $file_time_dict = Hash[] # file -> mtime $cur_file_time_dict = Hash[] require 'ruby_make_script/utils' require 'ruby_make_script/target' # check a file (recursively) and run the commands of the target. def resolve(file, force_exec=false) if force_exec || file_modified?(file) t = $file_target_dict[file] # when t == nil, its a file not used for target if t != nil t.depend_each { |f| resolve(f) } t.run() # if File.exist?(file) # puts "#{file} modified #{$file_time_dict[file]} != #{File.mtime(file)}" # else # puts "#{file} modified not exist?" # end file_modified!(file) end end end # check if a file is modified or its dependency is modified def file_modified?(file) if $file_target_dict[file].class == FileTarget # 文件真正被修改:文件之前不存在,或文件现在已经不存在,或时间戳修改 real_modified = $file_time_dict[file] == nil || !File.exist?(file) || ($file_time_dict[file] != File.mtime(file)) # 文件依赖被修改 return real_modified || $file_target_dict[file].depend_modified? elsif $file_target_dict[file].class == PhonyTarget # 假目标被修改:依赖被修改或之前不存在 return $file_time_dict[file] == nil || $file_target_dict[file].depend_modified? elsif $file_target_dict[file] == nil # 对无目标的文件,判断其存在,存在则直接使用即可 if !File.exist?(file) raise "file not found #{file}" else $cur_file_time_dict[file] = File.mtime(file) return $file_time_dict[file] == nil || ($file_time_dict[file] != File.mtime(file)) end else raise "file type error #{$file_target_dict[file].class}" end end # mark a file is modified def file_modified!(file) if $file_target_dict[file].class == FileTarget $cur_file_time_dict[file] = File.mtime(file) elsif $file_target_dict[file].class == PhonyTarget $cur_file_time_dict[file] = true else raise "file type error #{file.class}" end end class Symbol # Usage: # # ``` # :app .from "file1" do # <your command here> # end # ``` def from(*dependlist) PhonyTarget.new(String(self)).from(*dependlist) { yield } end # Usage: # # ``` # :app .then do # <your command here> # end # ``` def then PhonyTarget.new(String(self)).from() { yield } end end class String # Usage: # # ``` # "file1" .from "file2" do # <your command here> # end # ``` def from(*dependlist) [self].from(*dependlist) { yield } end end class Array # Usage: # # ``` # ["file1", "file2"] .from "file3", "file4" do # <your command here> # end # ``` def from(*dependlist) tar = FileTarget.new(self) tar.from(*dependlist) { yield } end end # Usage: # # ``` # make do # <define target here> # end # ``` def make $targetlist = [] yield raise "at least a target" if $targetlist.length < 1 if File.exist?('./.make_script.yaml') $file_time_dict = YAML.load(File.read('./.make_script.yaml')) $cur_file_time_dict = $file_time_dict.clone() end puts Pastel.new.bright_cyan("make> ") + "start" begin if ARGV.length == 0 $targetlist[0].resolve_all else p ARGV[0] resolve(ARGV[0], true) end rescue StandardError => e puts Pastel.new.red.bold("make failed> ") + e.message if e.message != "make command failed" puts e.backtrace end else puts Pastel.new.bright_cyan("make> ") + "completed" end if !File.exist?('./.make_script.yaml') File.open('.gitignore', 'a') do |f| f << "\n.make_script.yaml\n" end end File.open('./.make_script.yaml', 'w') { |f| f.write(YAML.dump($cur_file_time_dict)) } end def dump_md(filename, thisfile="make.rb") puts Pastel.new.bright_cyan("make> ") + "dumping markdown file #{filename}" File.open(filename, 'w') do |f| f.puts "# #{thisfile} Documentation" f.puts "" if block_given? yield f f.puts "" end f.puts "## Usage" f.puts "" f.puts "Please install ruby and some package first:" f.puts "" f.puts "```sh" f.puts "$ apt instal ruby" f.puts "$ gem instal pastel ruby_make_script" f.puts "```" f.puts "" f.puts "then you can run these command below." $targetlist.each { |t| if t.class == PhonyTarget args = t.doc.arglist.map{ |a| a[0] }.join(' ') f.puts "### `./#{thisfile} #{t.target} #{args}`" f.puts "" f.puts "#{t.doc.descr}" f.puts "" t.doc.arglist.each { |a| f.puts "* `#{a[0]}` : #{a[1]}" } if t.doc.arglist != [] f.puts "" end end } end end
true
c7cd7ba1cb0927720eb8b2dd0c394f5b9a8625f7
Ruby
jalada/AutoQwert
/auto-qwert.rb
UTF-8
1,389
2.8125
3
[]
no_license
require 'bundler' Bundler.require require 'open-uri' # Fix for bug in AppConfig require 'erb' AppConfig.configure do |config| config.config_file = "config.yml" end class AutoQwert def state_file "current.txt" end def send_mail Pony.mail(subject: 'New Qwertee Tee!', html_body: "<h1>Hi!</h1> <p>There's a new Qwertee tshirt. Here it is:</p><img src='http://qwertee.com#{@current_image}'><p>Lots of love</p><br /><p>The Auto-Qwertee bot</p>") end def send_error(message="Problem!") Pony.mail(subject: 'Auto-Qwertee bot has a problem! :(', body: "The reported error was: #{message}. I'll try again later.") end def setup_pony Pony.options = { :from => AppConfig.from, :to => AppConfig.to } end def initialize @current_image = if File.exists? state_file File.read state_file end setup_pony end def run response = open("http://qwertee.com") if body = response.read html = Nokogiri::HTML.parse body image = html.at_css("#splash-picture-actual") send_error("No image found") and return unless image if image['src'] != @current_image @current_image = image['src'] send_mail File.open(state_file, "w") do |f| f.write @current_image f.close end end else send_error end end end AutoQwert.new.run
true
84804d4ecc13128a4287dd617fa2b67b54ac7e77
Ruby
errne/ruby_basics_functions
/part_a/part_a_spec/part_a_spec.rb
UTF-8
1,130
3.234375
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../part_a") class TestPart_A < MiniTest::Test def test_student_name student1 = Student.new("Jake", "E26") assert_equal("Jake", student1.name) end def test_student_cohort student1 = Student.new("Jake", "E26") assert_equal("E26", student1.cohort) end def test_set_student_name student2 = Student.new("Cat", "E26") student2.set_name("Fiona") assert_equal("Fiona", student2.name) end def test_set_student_cohort student3 = Student.new("Alex", "G9") student3.set_cohort("E26") assert_equal("E26", student3.cohort) end def test_make_student_talk student3 = Student.new("Alex", "G9") assert_equal("I can talk", student3.talk) end def test_favourite_language student3 = Student.new("Alex", "G9") assert_equal("I love Ruby", student3.say_favourite_language("Ruby")) end def test_say_everything student4 = Student.new("Ernest", "E26") assert_equal("My name is Ernest and I am in E26 cohort. My favourite language is Java.", student4.say_everything("Java")) end end
true
a493e1a988a1ede7c71fb13e41cbe5b1a0ce2885
Ruby
amy-l-hedges/parrot-ruby-dc-web-042318
/parrot.rb
UTF-8
62
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def parrot(hello = "Squawk!") puts hello return hello end
true
e3305c4f76507f9e222e75872aaae90e848d1669
Ruby
liamzebedee/learning-style-manager
/rails/app/models/ausidentities_test_result.rb
UTF-8
8,093
3.125
3
[]
no_license
class AusidentitiesTestResult < ActiveRecord::Base AUS_IDENTITIES = ['Eagle', 'Kangaroo', 'Dolphin', 'Wombat'] QUESTIONS = [["Do you enjoy having lots of friends, or just a few special friends?", ["Lots of friends.", "A few special friends."]], ["Do you prefer to talk about facts or possibilities?", ["Facts", "Possibilities"]], ["Do you sometimes consider other peoples' feelings before your own?", ["No, very rarely", "Yes, quite often."]], ["Do you like to make lists of things to do?", ["Yes, quite often.", "No, not very often."]], ["Do you ever speak before you think?", ["Yes, sometimes", "No, not usually"]], ["Is it better to work on projects that are well-organised, or new and exciting?", ["Well organised.", "New and exciting."]], ["Is it better to be respected or liked by students in your class?", ["Respected", "Liked"]], ["Do you prefer to make up your mind sooner or later?", ["Sooner", "Later"]], ["Does it take people a short or a long time to get to know you?", ["Short time", "Long time"]], ["Do you see yourself as practical with good common sense, or as insightful with a good imagination?", ["Practical, with a good common sense.", "Insightful, with a good imagination"]], ["If you disagree with what someone has said, are you more likely to argue with them, or keep quiet?", ["Argue with them", "Keep quiet"]], ["Which one would you usually do first?", ["What you have to do", "What you want to do"]], ["Do you enjoy talking a lot, or do you usually only talk when there is something to say?", ["Talk a lot", "Talk only when there is something to say"]], ["Would you describe yourself as more careful and thorough, or are you often in a hurry to finish?", ["Careful and thorough", "Often in a hurry to finish"]], ["Would you prefer to spend time solving problems, or helping people?", ["Solving problems", "Helping people"]], ["Are you better at finishing projects, or are you better at starting them?", ["Finishing projects", "Starting them"]], ["Do you find it easy to talk to people, or are you more quiet and reserved?", ["Easy to talk to people", "Quiet and reserved"]], ["Do you like to work on projects at a constant and steady pace, or do you work in bursts of energy?", ["Constant steady pace", "Bursts of energy"]], ["If you are having difficulty with a project, do you prefer people to leave you alone, or offer to help?", ["Leave me alone", "Offer to help"]], ["Are you happier with a plan of what you have to do, or no plan and just make things up as you go?", ["A plan", "No plan"]], ["Are you more outgoing and talkative, or quiet and reflective?", ["Outgoing and talkative", "Quiet and reflective"]], ["Would you rather do a task that involves your hands, or involves your mind?", ["Using my hands", "Using my mind"]], ["Is it more important for your teacher to be fair to students, or be kind to them?", ["To be fair", "To be kind"]], ["Do you ever get annoyed if you have to change your plans at the last minute?", ["Yes, usually.", "No, not really."]], ["Do you like big parties where you meet lots of people, or small parties where you know most people?", ["Big parties", "Small parties"]], ["Do you like stories where there is lots of action and adventure, or lots of fantasy and heroism?", ["Lots of action", "Lots of fantasy"]], ["I tend to avoid arguments and most forms of conflict?", ["False", "True"]], ["Are you usually quick to complete tasks, or do you have a habit of putting things off?", ["Quick to complete tasks", "Putting things off"]], ["Is it easy for you to speak to most people, even if you have not met them before?", ["Yes, usually", "No, not really"]], ["Do you prefer to know exactly how to do a project, or do you prefer to use your imagination?", ["Exactly how to do a project", "Use your imagination"]], ["Other people usually find it difficult to know what or how I am feeling?", ["False", "True"]], ["Is it important to keep your desk or workspace organised?", ["Yes, most of the time", "Not really"]], ["Are you happy to talk to most people, or do you prefer to talk to people with similar interests to you?", ["Most people", "Similar interests"]], ["Are you interested in finding the right way to do things, or doing things your own way?", ["Finding out the right way", "Doing things my own way"]], ["Which of the following occupation lists is more appealing to you?", ["Manager, Doctor or Pilot", "Nurse, Artist or Social Worker"]], ["Which of the following sounds more like you?", ["I like structure, routine and schedules.", "I like flexibility, freedom and spontaneity."]], ["At parties and social gatherings, who usually does most of the talking?", ["Usually you", "Usually other people"]], ["Is it more exciting when you build or make something, or design and invent something?", ["Build or make something", "Design and invent something"]], ["Do you spend more time dealing with your problems, or dwelling on your problems?", ["Dealing with them", "Dwelling on them"]], ["Do you prefer to work out how to do a project before starting it, or just figure things out as you go?", ["Work it out first", "Figure it out as I go"]], ["If you had to stay at home because you are unwell, would you prefer visitors, or prefer to be alone?", ["Visitors", "Left alone"]], ["Which of the following qualities do you think it is more valuable or important to have?", ["Good common sense", "Good imagination"]], ["Would you say that you are more of a firm minded type of person, or more of a soft hearted one?", ["Firm minded", "Soft hearted"]], ["Do you prefer to have things decided for you, or do you prefer to have choices?", ["Decided for me", "Choices"]], ["Do you usually the company of lots of people or the company of just one or two?", ["Lots of people", "Just one or two"]], ["I dislike projects that are very complicated or overly complex. True or false?", ["False", "True"]], ["Do you consider yourself to be quite patient and understanding with other people?", ["Not overly", "Yes, very"]], ["On school holidays, do you plan what you are going to do, or do you prefer to see what each day brings?", ["Plan what to do", "See what each day brings"]], ["Is it important for you to have lots of friends that you regularly catch up with?", ["Yes, quite important", "No, not really that important"]], ["Do you notice how things are, or how things could be?", ["How things are", "How things could be"]], ["Do you like to receive regular encouragement or praise when working on a project?", ["No, not really", "Yes"]], ["Are you happier knowing what you will be doing on the weekend?", ["Knowing", "Deciding on the day"]], ["Which set of words describes you best?", ["Talkative, outgoing and gregarious", "Quiet, shy and reserved"]], ["Which are the easiest to remember; facts about things you are interested in, or abstract theories and ideas?", ["Facts", "Theories"]], ["Do you ask for advice from other people before you make up your mind about most things?", ["No, not usually", "Yes, quite often"]], ["Do you like to work with timetables and deadlines?", ["Yes, usually", "No, not really"]], ["Would you say you are more of a people person, or a private person?", ["A people person", "A private person"]], ["Do you like stories about real people and real places, or about imaginary people and places?", ["Real people and real places", "Imaginary people and places"]], ["Would you prefer that other people see you as a clever person, or a caring person?", ["Clever", "Caring"]], ["Is it better to have a teacher that is well organised, or one that is a little more spontaneous?", ["Well organised", "More spontaneous"]]] serialize :answers, Array # letters: string # animal: integer def animal_name AUS_IDENTITIES[self.animal] end end
true
21e3de1bf1f69adee0e4c4619a736dcbbe63baed
Ruby
TheKaterTot/Battleship
/test/messages_test.rb
UTF-8
2,755
3.125
3
[]
no_license
require "./test/test_helper" require "./lib/messages" require "./lib/human_player" require "./lib/computer_player" require "stringio" class MessageTest < Minitest::Test def setup @player = HumanPlayer.new @computer = ComputerPlayer.new end def test_options with_stdio do |input, output| Message.options assert_includes output.gets, "Would you like" end end def test_computer_can_place_ships with_stdio do |input, output| Message.computer_place_ships assert_includes output.gets, "I've placed my ships" end end def test_place_small_ship with_stdio do |input, output| Message.place_small_ship assert_includes output.gets, "Place your" end end def test_place_large_ship with_stdio do |input, output| Message.place_large_ship assert_includes output.gets, "Place your large" end end def test_ship_overlap with_stdio do |input, output| Message.ship_overlap assert_includes output.gets, "You already" end end def test_ship_invalid with_stdio do |input, output| Message.ship_invalid assert_includes output.gets, "neighbors" end end def test_ship_overboard with_stdio do |input, output| Message.ship_overboard assert_includes output.gets, "Your ship is off" end end def test_fire_weapons with_stdio do |input, output| Message.fire_weapons assert_includes output.gets, "attack" end end def test_fire_again with_stdio do |input, output| Message.fire_weapons_again assert_includes output.gets, "Try again" end end def test_repeat_target with_stdio do |input, output| Message.target_is_repeat assert_includes output.gets, "Try to keep up" end end def test_hit with_stdio do |input, output| Message.hit(@player) assert_includes output.gets, "mankind" output.gets Message.hit(@computer) assert_includes output.gets, "singularity" end end def test_miss with_stdio do |input, output| Message.miss(@player) assert_includes output.gets, "failed" output.gets Message.miss(@computer) assert_includes output.gets, "capacity" end end def test_target with_stdio do |input, output| Message.report_target("A2") assert_includes output.gets, "A2" end end def test_total_shots with_stdio do |input, output| Message.total_shots(3) assert_includes output.gets, "3" end end def test_win with_stdio do |input, output| Message.win(@player) assert_includes output.gets, "victory" Message.win(@computer) assert_includes output.gets, "defeat" end end end
true
58abfe90093802a3a94e55fc32a28d7d057c4db2
Ruby
cooo/Emular
/instructions/ret.rb
UTF-8
425
3.265625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
# 00ee - RET # ------------------------- # Return from a subroutine.The interpreter sets the program counter to the # address at the top of the stack, then subtracts 1 from the stack pointer. class Ret def match?(opcode) @opcode = opcode opcode.eql?("00ee") end def execute(cpu) address = cpu.emular.stack.pop cpu.emular.pc = address end def to_s "#{@opcode}: RET\t\t\t\t => RET" end end
true
4d4e5bdf6ab788243803225e5d0f8f217e3aeaeb
Ruby
QWYNG/Echoes
/lib/spotify_track.rb
UTF-8
537
2.90625
3
[]
no_license
class SpotifyTrack attr_accessor :name, :popularity, :image_url def initialize(name, popularity, image_url) @name = name @popularity = popularity @image_url = image_url end def deconstruct_keys(keys) { name: name, popularity: popularity } end def popularity_comment case self in name: name, popularity: (90..100) "#{name} は内部スコア90点以上 すごい!!" in name: name, popularity: (80..89) "#{name} は内部スコア80点以上 すごい!!" end end end
true
04d131fa6b44796061b4376cedd85c0f02d9cb69
Ruby
javrodri42/discovery_piscine_ruby
/ruby05/ex06/upcase_it.rb
UTF-8
79
2.625
3
[]
no_license
#!/usr/bin/env ruby if ARGV[0] puts ARGV[0].upcase else puts "none" end
true
98fd954668355d9a62cefc47a874f6303b5148eb
Ruby
theinbetweens/cauldron
/lib/cauldron/operator/concat_operator.rb
UTF-8
1,507
2.625
3
[ "MIT" ]
permissive
# frozen_string_literal: true class ConcatOperator include Cauldron::Operator def initialize(indexes) @indexes = indexes @constant = 'bar' end def self.viable?(arguments, response) return false unless arguments.all? { |x| x.is_a?(String) } return false unless response.is_a?(String) # TODO: - Only accpets one argument true end def self.find_constants(problems) problems.examples.each_with_object([]) do |x, total| result = x.response.gsub(Regexp.new('^' + x.arguments.first), '') total << result unless result == x.response end.uniq end def self.uses_constants? true end def self.uses_block? false end def branch? false end # Operator for "x.concat("bar")" def successful?(problem) return true if (problem[:arguments].first + @constant) == problem[:response] false end def to_ruby(scope, operators) Sorcerer.source to_sexp(scope, operators) end def build(_operators, scope) to_sexp(scope) end def to_sexp(_scope, _operators) first_variable = 'var' + @indexes[0].to_s [:program, [:stmts_add, [:stmts_new], [:method_add_arg, [:call, [:vcall, [:@ident, first_variable]], :".", [:@ident, 'concat']], [:arg_paren, [:args_add_block, [:args_add, [:args_new], [:string_literal, [:string_add, [:string_content], [:@tstring_content, @constant]]]], false]]]]] end end
true
253acaec1a6e107ac08cc5fc9c2d5313eea043d8
Ruby
efueger/salama
/test/melon/fragments/test_itos.rb
UTF-8
437
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require_relative 'helper' class TestRubyItos < MiniTest::Test include MelonTests def test_ruby_itos @string_input = <<HERE 100000.to_s HERE @stdout = "Hello there" check end def pest_ruby_itos_looping @string_input = <<HERE counter = 100000 while(counter > 0) do str = counter.to_s counter = counter - 1 end str HERE @length = 37 @stdout = "Hello Raisa, I am salama" check end end
true
cf2576e3d85e1f0e158888378ec93b19f0483569
Ruby
yoshikig/ruby-cconv
/sjis2euc.rb
UTF-8
224
2.890625
3
[]
no_license
require 'jis2euc' require 'sjis2jis' class Sjis2euc def initialize @jis2euc = Jis2euc.new @sjis2jis = Sjis2jis.new end def conv(instr) jis = @sjis2jis.conv(instr) euc = @jis2euc.conv(jis) return euc end end
true
6471175216508f68ef9b12cdd2a09d7db45b3fb5
Ruby
WilliamAvHolmberg/AFS-Moped
/models/part_article.rb
UTF-8
1,209
2.59375
3
[]
no_license
class PartArticle include DataMapper::Resource property :id, Serial property :amount, Integer, :default => 1 property :status, Integer, :default => 0 #0 stands for "Not in stock", 1 stands for ordered but not recieved, 2 stands for "in stock" 3 stands for "dedicated to a specific construction" property :image_number, Integer property :list_figure, Float, :default => -10 property :location, String #tex i vilken låda, källaren, i borås.. etc! belongs_to :part belongs_to :article def get_list_figure return get_article_list_figure * amount end def get_article_list_figure if status == 3 return 0 elsif !list_figure.nil? && list_figure != -10 return list_figure end return article.list_price end def get_net_figure if !article.nil? return amount * article.net_price else return 0 end end def get_status if status == 3 return "Dedikerad" elsif status == 2 return "I lager" elsif status == 1 return "Beställd" end return "Behöver beställas" end def has_article if status == 2 return true end return false end end
true
86f272a8c73a452fb5a0a98f3ebacc94f13bc6b0
Ruby
howardbdev/flatiron-bnb-methods-v-000
/app/models/reservation.rb
UTF-8
987
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Reservation < ActiveRecord::Base belongs_to :listing belongs_to :guest, :class_name => "User" has_one :review validates :checkin, presence: true validates :checkout, presence: true validate :guest_and_host_not_the_same, :is_available, :chronological def duration (checkout - checkin).to_i end def total_price duration*listing.price end private def guest_and_host_not_the_same if guest_id == listing.host_id errors.add(:guest_id, "You can't book your own listing") end end def is_available Reservation.where(listing_id: listing.id).where.not(id: id).each do |res| busy = res.checkin..res.checkout if busy === checkin || busy === checkout errors.add(:guest_id, "Listing not available during requested dates") end end end def chronological if checkout == nil || checkin == nil || checkout <= checkin errors.add(:guest_id, "Check-out has to be after check-in") end end end
true
b453dc77ac8fc30376c0b50f45d771d0204a217b
Ruby
danrodz/cartoon-collections-houston-web-071618
/cartoon_collections.rb
UTF-8
457
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def roll_call_dwarves(array) array.each.with_index(1) do |name, index| puts "#{index}. #{name}" end end def summon_captain_planet(array) array.map do |word| word.capitalize << "!" end end def long_planeteer_calls(array) array.any? do |word| word.length > 4 end end def find_the_cheese(array) cheese_types = ["cheddar", "gouda", "camembert"] array.each do |word| return word if cheese_types.include?(word) end nil end
true
a2ba034fae3e9032eebfc1ad1380e85020da42b8
Ruby
bdimcheff/rag
/lib/rag/aggregator.rb
UTF-8
453
2.765625
3
[ "MIT" ]
permissive
module Rag class Aggregator attr_accessor :column, :start, :block def initialize(column) self.column = column end def inject(start, &block) self.start = start self.block = block end # TODO: make this work with streaming somehow # def all(&block) # self.start = [] # self.block = block # end def sum self.inject(0) {|acc, i| acc + i.to_i} end end end
true
8c7e323019a8080a984778875137f821809fd2c7
Ruby
yanap/learning
/ruby/meta/sorcery/open_class.rb
UTF-8
203
3.4375
3
[]
no_license
#encoding: utf-8 # 既存のクラスを拡張する class String def my_string_method "私のメソッド" end end "abc".my_string_method # => '私のメソッド' p "abc".my_string_method
true
5ae3fcbcc766e4454bb724a18e5eea9db282543e
Ruby
mengchenwang/Oystercard
/lib/station.rb
UTF-8
177
3.234375
3
[]
no_license
class Station def initialize(name, zone) @station = { :name => name, :zone => zone } end def name @station[:name] end def zone @station[:zone] end end
true
d773e82c810aef268aa1d30ff1f8ec4ef7465a08
Ruby
RomaneGreen/web_guesser
/web_guesser.rb
UTF-8
824
3.171875
3
[]
no_license
require 'sinatra' require 'sinatra/reloader' #rand number before get request established NUMBER = rand(100) get '/' do #erb :index, :locals => {:number => number,:message => 'Guess the number'} def check_guess(number) guess = params["guess"].to_i if guess - 5 > number erb :index, :locals => {:number => '_',:message => 'way too high'} elsif guess + 5 < number erb :index, :locals => {:number => '_',:message => 'way too low'} elsif guess > number erb :index, :locals => {:number => '_',:message => 'too high'} elsif guess < number erb :index, :locals => {:number => '_',:message => 'too low'} elsif guess == number erb :index, :locals => {:number => number,:message => 'You got it right'} end end check_guess(NUMBER) end #cheat mode get '/guess=56&cheat=true' do "The number is #{NUMBER}" end
true
87dce2981fc85c54555e1e2e499260e571d26659
Ruby
openstax/active_force
/lib/active_force/attribute.rb
UTF-8
664
2.5625
3
[ "MIT" ]
permissive
module ActiveForce class Attribute attr_accessor :local_name, :sfdc_name, :as def initialize name, options = {} self.local_name = name self.sfdc_name = options[:sfdc_name] || options[:from] || default_api_name self.as = options[:as] || :string end def value_for_hash value case as when :multi_picklist value.reject(&:empty?).join(';') else value end end private ### # Transforms +attribute+ to the conventional Salesforce API name. # def default_api_name local_name.to_s.split('_').map(&:capitalize).join('_') << '__c' end end end
true
fe6be5d12756c0a37dbd8db8829a5de8f4f0abc3
Ruby
puyo/exercises
/ruby/heartattack/Random.rb
UTF-8
228
3.453125
3
[]
no_license
def random(min, max) return rand(max - min + 1) + min end def rollDice(string) string =~ /([0-9]+)[dD]([0-9]+)/ num = $1.to_i sides = $2.to_i result = 0 (1..num).each { result += random(1, sides) } return result end
true
cc8688bcfa81ddb4b89a5c70243f8634a5722c24
Ruby
Guillaume954/lib
/00_hello.rb
UTF-8
171
3.21875
3
[]
no_license
def say_hello return "Hello" end def user_name puts " Quel est ton prénom ?" print "> " user_name = gets.chomp return user_name end puts say_hello puts user_name
true
60c8b836831566e861f09cbb863849310b12b327
Ruby
raegertay/exercises-ruby
/ttt_shirlaine.rb
UTF-8
1,612
4.09375
4
[]
no_license
def start welcome_message #welcomes player and shows empty board show_board(board) #gets input from player and reflects X on board end #Welcome Message def welcome_message puts "Welcome to Tic-Tac-Toe" new_board = ["0","1","2","3","4","5","6","7","8"] show_board(new_board) end def show_board(board) puts line_1= "#{board[0]} | #{board[1]} | #{board[2]} " puts line_separator="---------" puts line_2= "#{board[3]} | #{board[4]} | #{board[5]} " puts line_separator= "---------" puts line_3= "#{board[6]} | #{board[7]} | #{board[8]} " end def gets_input puts "Choose your position from 0-8 by typing it in." gets.chomp #string 9 end def board board_array=["0","1","2","3","4","5","6","7","8"] count=1 limit=10 ## while count<limit do if count.odd? p count count+=1 player1_input = gets_input puts "Player 1(X) chooses #{player1_input}" board_array.each do |string| if string == player1_input board_array[string.to_i]="X" # else # board_array[string.to_i]= string end end p board_array show_board(board_array) # #puts the updated board_array into show_board elsif count.even? p count count+=1 player2_input = gets_input puts "Player 2(0) chooses #{player2_input}" board_array.each do |string| if string == player2_input board_array[string.to_i]= "O" # else # board_array[string.to_i]= string end end p board_array show_board(board_array) end end puts "this is the final standing" board_array end start
true
32a293e59624440a30daff25d00735e18fd3d731
Ruby
stjordanis/ownership
/lib/ownership/global_methods.rb
UTF-8
842
2.6875
3
[ "MIT" ]
permissive
module Ownership module GlobalMethods private def owner(*args, &block) return super if is_a?(Method) # hack for pry owner = args[0] # same error message as Ruby raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 1)" if args.size != 1 raise ArgumentError, "Missing block" unless block_given? previous_value = Thread.current[:ownership_owner] begin Thread.current[:ownership_owner] = owner begin # callbacks if Ownership.around_change Ownership.around_change.call(owner, block) else block.call end rescue Exception => e e.owner = owner raise end ensure Thread.current[:ownership_owner] = previous_value end end end end
true
437a61f6349866b55d01d3c3d80fb4e35f76c159
Ruby
anhvu15/pruby
/ruby_month1.rb
UTF-8
589
3.421875
3
[]
no_license
# l = lambda {"do nothing"} # puts l.call # t = lambda do |string| # if string == "try" # return "There is no such thing" # else # return "Do or do not" # end # end # puts t.call("try") # addition = lambda { |a,b| a + b} # subtraction = lambda {|a,b| a - b} # multiplicaiton = lambda {|a,b| a*b} # division = lambda {|a,b| a/b} # Modulus = lambda {|a,b| a % b} # puts addition.call(2,3) # puts subtraction.call(3,2) # puts multiplicaiton.call(4,5) # puts division.call(8,4) # puts Modulus.call(4,3) short = ->(a,b) { a +b} puts short.call(1,2)
true
612777e7d34c655c4a5718bd6f438da7daf2814d
Ruby
PiotrAleksander/Ruby
/WickedCoolRubyScripts/fileSecurity.rb
UTF-8
2,114
3.328125
3
[]
no_license
# == Opis programu # # fileSecurity.rb: szyfruje i odszyfrowuje pliki; ilustruje działanie Blowfish: bardzo szybkiego symetrycznego szyfru blokowego # # # == Sposób użycia # # szyfrowanie [OPCJE] ... PLIK # # -h, --help: # Wyświetla pomoc # # --encrypt klucz, -d klucz # Szyfruje plik przy użyciu hasła # # --decrypt klucz, -d klucz # Odszyfrowuje plik przy użyciu hasła # # PLIK: Plik, który chcesz zaszyfrować lub odszyfrować require 'getoptlong' require 'rdoc/ri/paths' require 'rdoc/rdoc' require 'crypt/blowfish' def encrypt(file, pass) c = "Z_#{file}" if File.exists?(c) puts "\nPlik już istnieje." exit end begin # Inicjowanie metody szyfrującej przy użyciu klucza podanego przez użytkownika. blowfish = Crypt::Blowfish.new(pass) blowfish.encrypt_file(file.to_s, c) # Szyfrowanie pliku. puts "\nSzyfrowanie zakończone sukcesem!" rescue Exception => e puts "W czasie szyfrowania wystąpił błąd: \n #{e}" end end def decrypt(file, pass) p = "O_#{file}" if File.exists?(p) puts "\nPlik już istnieje" end begin # Inicjowanie metody odszyfrowującej przy użyciu klucza podanego przez użytkownika. blowfish = Crypt::Blowfish.new(pass) blowfish.decrypt_file(file.to_s, p) # Odszyfrowywanie pliku. puts "\nOdszyfrowywanie zakończone sukcesem!" rescue Exception => e puts "W czasie odszyfrowywania wystąpił błąd: \n #{e}" end end opts = GetoptLong.new( [ '--help', '-h', GetoptLong::NO_ARGUMENT ], [ '--szyfruj', '-s', GetoptLong::REQUIRED_ARGUMENT ], [ '--odszyfruj', '-o', GetoptLong::REQUIRED_ARGUMENT] ) unless ARGV[0] puts "\nNie podano nazwy pliku (wypróbuj: ruby fileSecurity.rb --help)" exit end filename = ARGV[-1].chomp opts.each do |opt, arg| case opt when '--help' options = RDoc::Options.new rdoc = RDoc::RDoc.new rdoc.document options.formatter when '--szyfruj' encrypt(filename, arg) when '--odszyfruj' decrypt(filename, arg) else options = RDoc::Options.new rdoc = RDoc::RDoc.new rdoc.document options.formatter end end
true
6b2502cb6cd4ff9d697ca9c8ee422467d5bc0756
Ruby
eregon/image-demo.rb
/lib/noborder.rb
UTF-8
2,622
3.453125
3
[ "MIT" ]
permissive
# An image class for people who dont care about border effects class NoBorderImage attr_reader :width, :height, :data def initialize(w, h) @width = w @height = h @data = Array.new(w*h, 0) end def from_io(io) @data = io.read(@width*@height).bytes self end def initialize_copy(from) @data = from.data.dup end def index(p, y = nil) if p.is_a?(Pixel) p.idx else y * @width + p end end private :index def [](*p) @data[index(*p)] end def []=(*p, val) idx = index(*p) raise "invalid index: #{idx}" if idx < 0 or idx >= @data.size @data[index(*p)] = val end def pixel_range (0...@width * @height) end def each_pixel pixel_range.each { |i| yield Pixel.new(i, self) } end def map img = self.class.new(@width, @height) each_pixel { |p| img[p] = yield(p) } img end def setup(data) @height.times { |y| @width.times { |x| self[x, y] = data[y][x] } } self end def tofile(f) f.write @data.pack('C*') end end class NoBorderImagePadded < NoBorderImage def initialize(w, h) @width = w @height = h @data = Array.new(w*(h+2)+2, 0) end def from_io(io) w, h = @width, @height @data[(w+1)...-(w+1)] = io.read(w*h).bytes self end def index(p, y = nil) if p.is_a? Pixel p.idx else (y+1) * @width + p + 1 end end private :index def pixel_range (@width + 1 ... (@width+1) * @height + 1) end def tofile(f) f.write @data[(@width+1)...(-@width-1)].pack('C*') end end class Pixel attr_reader :idx, :image def initialize(idx, image) @idx = idx @image = image end def + other x, y = other Pixel.new(@idx + y*@image.width + x, @image) end end def conv3x3(img, k) img.map { |p| k[2,2]*img[p + [-1,-1]] + k[1,2]*img[p + [0,-1]] + k[0,2]*img[p + [1,-1]] + k[2,1]*img[p + [-1, 0]] + k[1,1]*img[p + [0, 0]] + k[0,1]*img[p + [1, 0]] + k[2,0]*img[p + [-1, 1]] + k[1,0]*img[p + [0, 1]] + k[0,0]*img[p + [1, 1]] } end def main image_class = Object.const_get(ARGV.first) n = 1000 10.times do conv3x3(image_class.new(n, n), image_class.new(3, 3)) end 'conv3x3(%s(%dx%d))' % [image_class, n, n] end if $0 == __FILE__ require 'benchmark' image_class = Object.const_get(ARGV.first) n = 1000 a = Time.now 100.times { p Benchmark.realtime { 10.times { conv3x3(image_class.new(n, n), image_class.new(3,3)) } } } b = Time.now puts 'conv3x3(%s(%dx%d)):' % [image_class, n, n], b - a end
true
7e66ef9eb1068303162cdba63852398578e07fa9
Ruby
marltu/basketball
/spec/objects/throw_spec.rb
UTF-8
4,503
2.859375
3
[]
no_license
require "./objects/throw" describe Throw do before(:each) do @match = get_empty_match() @home_member = @match.members_home.first @away_member = @match.members_away.first end it "should increase count of throws after creating throw" do expect { Throw.new(@home_member, 3) }.to change(Throw, :count).by(1) end it "should set points to registered throw" do Throw.new(@home_member, 3).points.should == 3 end it "should set member to registered throw" do Throw.new(@home_member, 3).match_member.should == @home_member end it "should set accurate flag to registered throw" do Throw.new(@home_member, 3, false).accurate = false end it "should increase home match member points by 3 after registering 3 points" do expect { Throw.new(@home_member, 3) }.to change(@home_member, :points).by(3) end it "should decrease home match member points by 3 after deleting 3 points throw" do thr = Throw.new(@home_member, 3) expect { thr.delete }.to change(@home_member, :points).by(-3) end it "should increase away match member points by 3 after registering 3 points" do expect { Throw.new(@away_member, 3) }.to change(@away_member, :points).by(3) end it "should decrease away match member points by 3 after deleting 3 points throw" do thr = Throw.new(@away_member, 3) expect { thr.delete }.to change(@away_member, :points).by(-3) end it "should increase match home points by 3 after registering 3 points" do expect { Throw.new(@home_member, 3) }.to change(@match, :points_home).by(3) end it "should decrease match home points by 3 after deleting 3 points throw" do thr = Throw.new(@home_member, 3) expect { thr.delete }.to change(@match, :points_home).by(-3) end it "should increase match away points by 3 after registering 3 points" do expect { Throw.new(@away_member, 3) }.to change(@match, :points_away).by(3) end it "should decrease match away points by 3 after deleting 3 points throw" do thr = Throw.new(@away_member, 3) expect { thr.delete }.to change(@match, :points_away).by(-3) end it "should not increase home match member points when throw is missed" do lambda { Throw.new(@home_member, 3, false) }.should_not change(@home_member, :points) end it "should increase total throws after accurate throw" do expect { Throw.new(@home_member, 3, true) }.to change(@home_member, :throws_total).by(1) end it "should increase total throws after inaccurate throw" do expect { Throw.new(@home_member, 3, false) }.to change(@home_member, :throws_total).by(1) end it "should increase accurate throws after accurate throw" do expect { Throw.new(@home_member, 3, true) }.to change(@home_member, :throws_accurate).by(1) end it "should not increase accurate throws after inaccurate throw" do lambda { Throw.new(@home_member, 3, false) }.should_not change(@home_member, :throws_accurate) end it "should increase number of throws from 2 points by 1" do expect { Throw.new(@home_member, 2, true) }.to change {@home_member.throws_total(2)}.by(1) end it "should not increase number of throws from 2 points after registering 3 point throw" do lambda { Throw.new(@home_member, 3, true) }.should_not change {@home_member.throws_total(2)} end it "should increase number of accurate throws from 2 points after registering 2 point throw" do expect { Throw.new(@home_member, 2, true) }.to change {@home_member.throws_accurate(2)}.by(1) end it "should not increase number of accurate throws from 2 points after registering 3 point throw" do lambda { Throw.new(@home_member, 3, true) }.should_not change {@home_member.throws_accurate(2)} end it "should have 0.33 accuracy after 1 accurate throw and 2 inaccurates" do Throw.new(@home_member, 3, true) Throw.new(@home_member, 3, false) Throw.new(@home_member, 3, false) @home_member.accuracy.should == 1/3.0 end it "should have 0.5 accuracy from 2 points after 1 accurate and one inaccurate from 2 points and one accurate 3 point" do Throw.new(@home_member, 2, true) Throw.new(@home_member, 2, false) Throw.new(@home_member, 3, true) @home_member.accuracy(2).should == 0.5 end end
true
f37b11e4a1fbd0f55b537754d25ec4c96ebaf715
Ruby
ca33dang/close-but-no-cigar
/close_ntdd.rb
UTF-8
909
2.625
3
[]
no_license
require "minitest/autorun" require_relative "close_no.rb" class Test_close_no < Minitest::Test def test_1_equals_1 assert_equal(1, 1) end def test_for_empty_array my_n = "1234" bash_n = [] assert_equal([], grand_bash(my_n, bash_n)) end def test_1234 my_n = "1234" bash_n = ["1234"] assert_equal(["1234"], grand_bash(my_n, bash_n)) end def test_array_3_numbers my_n = "1234" bash_n = ["1233", "1345", "3445"] assert_equal([], grand_bash(my_n, bash_n)) end def test_array_4_n my_n = "3456" bash_n = ["1123", "3456", "6543", "1342"] assert_equal(["3456"], grand_bash(my_n, bash_n)) end def test_array_5_n my_n = "3345" bash_n = ["1234", "2345", "3455", "5673", "3345"] assert_equal(["3345"], grand_bash(my_n, bash_n)) end def test_array_6 my_n = "6565" bash_n = ["2345", "1234", "2345", "4567", "5656", "2112"] assert_equal([], grand_bash(my_n, bash_n)) end end
true
6ead42cf29c3b8dfac35810d4a722edf1a8c3322
Ruby
virajs/aws-sdk-core-ruby
/vendor/seahorse/spec/seahorse/model/shapes/shape_spec.rb
UTF-8
3,209
2.6875
3
[ "Apache-2.0" ]
permissive
require 'spec_helper' module Seahorse module Model module Shapes describe Shape do describe 'from_hash_class' do it 'fails if shape is not registered' do expect do Shape.from_hash_class('type' => 'invalid') end.to raise_error(/Unregistered shape type invalid/) end end end describe ListShape do it 'deserializes members property' do shape = Shape.from_hash 'members' => { 'type' => 'structure', 'members' => { 'property' => { 'type' => 'string' } } }, 'type' => 'list' expect(shape).to be_instance_of ListShape expect(shape.members).to be_instance_of StructureShape expect(shape.members.members[:property]).to be_instance_of StringShape end end describe MapShape do it 'deserializes keys and members properties' do shape = Shape.from_hash 'keys' => { 'type' => 'string' }, 'members' => { 'type' => 'structure', 'members' => { 'property' => { 'type' => 'string' } } }, 'type' => 'map' expect(shape).to be_instance_of MapShape expect(shape.keys).to be_instance_of StringShape expect(shape.members).to be_instance_of StructureShape expect(shape.members.members[:property]).to be_instance_of StringShape end end describe StructureShape do it 'defaults to an empty members hash' do shape = StructureShape.new expect(shape.members).to eq({}) end it 'populates the #member_name attribute' do shape = Shape.from_hash( 'type' => 'structure', 'members' => { 'abc' => { 'type' => 'string' }, 'xyz' => { 'type' => 'string' } } ) expect(shape.members[:abc].member_name).to eq(:abc) expect(shape.members[:xyz].member_name).to eq(:xyz) end it 'provides a hash of members by their serialized names' do shape = Shape.from_hash( 'type' => 'structure', 'members' => { 'abc' => { 'type' => 'string', 'serialized_name' => 'AbC' }, 'xyz' => { 'type' => 'string', 'serialized_name' => 'xYz' }, } ) expect(shape.members[:abc]).to be(shape.serialized_members['AbC']) expect(shape.members[:xyz]).to be(shape.serialized_members['xYz']) end it 'defaults the #serialized_name value to the member_name' do shape = Shape.from_hash( 'type' => 'structure', 'members' => { 'abc' => { 'type' => 'string' }, 'xyz' => { 'type' => 'string' } } ) expect(shape.members[:abc].serialized_name).to eq('abc') expect(shape.members[:xyz].serialized_name).to eq('xyz') expect(shape.members[:abc]).to be(shape.serialized_members['abc']) expect(shape.members[:xyz]).to be(shape.serialized_members['xyz']) end end end end end
true
71dc4a9dae87f5e1378ed0d1ac18a5b0add693fb
Ruby
sjezewski/dotfiles
/scripts/travis_build.rb
UTF-8
1,247
2.78125
3
[]
no_license
#!/usr/bin/env ruby require "http" require "json" $latest = false raw = %x`pwd` $org_and_project = raw.strip.split("/")[-2..-1].join("/") if ARGV.size == 1 && ARGV.last == "latest" $latest = true end def repos_url(org_and_project) org_and_project.gsub("/", "%2F") "https://api.travis-ci.org/repos?slug=#{org_and_project}" end def builds_url(repo_id) "https://api.travis-ci.org/builds?event_type%5B%5D=push&event_type%5B%5D=api&repository_id=#{repo_id}" end def build_view_url(org_and_project, build_id) "https://travis-ci.org/#{org_and_project}/builds/#{build_id}" end def match?(build) if $latest # assume you just want the latest build, so return return true end branch = %x`git branch | grep "\*"` branch = branch.split("* ").last.strip return true if branch == build["branch"] commit = %x`git log | head -n 1 | cut -f 2 -d " "` return true if commit == build["commit"] return false end resp = HTTP.get(repos_url($org_and_project)) repos = JSON.parse(resp.body) resp = HTTP.get(builds_url(repos.first["id"])) builds = JSON.parse(resp) builds.each do |build| if match?(build) puts build_view_url($org_and_project, build["id"]) exit 0 end end puts "No matching builds found" exit 1
true
71953302b97fcbe21cc529f725a8a1b6e51ced26
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/kindergarten-garden/9070b234c44e41cc9245cb472e5f6ab8.rb
UTF-8
885
3.65625
4
[]
no_license
class Garden def initialize(diagram, students = DEFAULT_STUDENTS) @diagram, @students = diagram, students.sort define_student_accessors end private DEFAULT_STUDENTS = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"] PLANTS = { "G" => :grass, "C" => :clover, "R" => :radishes, "V" => :violets } STUDENT_PLANTS_PER_ROW = 2 def define_student_accessors @students.each do |student| define_singleton_method(student.downcase) { translate letters_for(student) } end end def letters_for(student) @diagram.split.map { |line| line[index_of(student),STUDENT_PLANTS_PER_ROW] }.join end def index_of(student) @students.find_index(student) * STUDENT_PLANTS_PER_ROW end def translate(letters) letters.chars.map { |letter| PLANTS[letter] } end end
true
927de8d496c1486a16398d931899a206dcf58b37
Ruby
Lawrenccee/w1d5
/skeleton/lib/00_tree_node.rb
UTF-8
1,069
3.703125
4
[]
no_license
class PolyTreeNode def initialize(value) @value = value @parent = nil @children = [] end def parent @parent end def children @children end def value @value end def parent=(node) if node != parent parent.children.delete(self) if parent @parent = node node.children << self if node end end def add_child(child_node) child_node.parent = self end def remove_child(child_node) raise "Not a child" unless children.include?(child_node) child_node.parent = nil end def dfs(target_value) result = nil return self if value == target_value return nil if children.empty? children.each do |child| result = child.dfs(target_value) return result if result && result.value == target_value end result end def bfs(target_value) queue = [] queue << self until queue.empty? node = queue.shift return node if node.value == target_value node.children.each { |child| queue << child } end nil end end
true
b95000f7d58d4e01a13fa092119bf9cc6f525664
Ruby
isabellassobral/nivelamento-aluno
/avaliacao/03-avaliacao.rb
UTF-8
1,034
4.40625
4
[]
no_license
# 3) Defina uma função “altura_escada” que deve receber um número inteiro para representar a altura da escada e deve retornar um array de strings para representar graficamente a escada. # Valide o parâmetro da altura da escada, que deve ser um número maior ou igual a 1. Caso contrário, a função deve retornar um array vazio. def altura_escada(altura) array_strings = [] if altura >= 1 for linhas in (1..altura) for colunas in (1..linhas) array_strings[linhas] = "_"*(altura-linhas) + "#"*linhas end end return array_strings end array_vazio = [] return array_vazio end # Ex.: puts(altura_escada(1)) # deve imprimir # puts(altura_escada(2)) # # # deve imprimir # # _# # # ## puts(altura_escada(3)) # # # deve imprimir # # __# # # _## # # ### puts(altura_escada(5)) # # deve imprimir # ____# # ___## # __### # _#### # ##### puts(altura_escada(0)) # # deve imprimir nada, pois tem que retornar um array vazio puts(altura_escada(20))
true
7c5fe396d6c4b3e93c6be0a02ddd16645dc732ef
Ruby
enogrob/ebook-effective-testing-with-rspec-3
/src/code/09-configuring-rspec/04/configuring_rspec/mocha_spec.rb
UTF-8
837
2.703125
3
[]
no_license
#--- # Excerpted from "Effective Testing with RSpec 3", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/rspec3 for more book information. #--- class PointOfSale def self.purchase(item, with: nil) with.charge(item.cost) end end RSpec.configure do |config| config.mock_with :mocha end RSpec.describe 'config.mock_with :mocha' do it 'allows you to use mocha instead of rspec-mocks' do item = stub('Book', cost: 17.50) credit_card = mock('CreditCard') credit_card.expects(:charge).with(17.50) PointOfSale.purchase(item, with: credit_card) end end
true
76f72dc7f8f678dcbd2a96484bbc52e269d40795
Ruby
zocoi/codefights
/challenges/antWalking.rb
UTF-8
1,047
3.78125
4
[ "MIT" ]
permissive
# An ant starts at (0, 0) on an xy-coordinate plane and makes a sequence of n steps. Each step is of 1 unit length, and is directed left, right, up, or down. The direction is chosen randomly from these four options. # # Find the probability that after n steps the ant ends up back at (0, 0). Return this probability as an irreducible fraction as an array [numerator, denominator]. # # Example # # For n = 2, the output should be # antWalking(2) = [1, 4]. # # Let L, R, U and D stand stand for a step to the left, right, up and down respectively. # Thus, the possible paths the ant can travel are: # LL, LR, LU, LD, RL, RR, RU, RD, UL, UR, UU, UD, DL, DR, DU, and DD. # Only LR, RL, UD, and DU bring the ant back to (0, 0). # Thus, the probability is (4 choices)/(16 total) = 1/4. def antWalking(n) r = Rational((1..n).to_a.combination(n/2).to_a.size ** 2, 4**n) [r.numerator, r.denominator] end # Shortest solution possible in ruby # def antWalking(n) # ((1..n).to_a.combination(n/2).count.to_r ** 2/ 4**n).to_s.split('/').map &:to_i # end
true
dab416d479318a098f74cdea3818f07422997316
Ruby
GovWizely/endpointme
/app/models/ingest_pipeline.rb
UTF-8
3,782
2.5625
3
[]
no_license
class IngestPipeline def initialize(name, metadata) @name = name @metadata = metadata @array_context = false end def pipeline Jbuilder.new do |json| generate_description(json) generate_pipeline(json) end.attributes!.with_indifferent_access end private def generate_description(json) json.description "Pipeline for #{@name}" end def generate_pipeline(json) json.processors do processors = generate_processors(json) json.array! [] unless processors.any? end end def generate_processors(json) @metadata.entries.map do |field, meta| generate_all_processors_for_field(json, field, meta.with_indifferent_access) @array_context = false end end def generate_all_processors_for_field(json, target_field, meta) @array_context = true if meta[:array] return unless meta[:transformations].present? meta[:transformations].each do |transformation_entry| target_field = generate_processor_for_transformation(json, meta, target_field, transformation_entry) coalesce(json, target_field) if array_contains_multi_value_external_mapping(transformation_entry) end end def generate_processor_for_transformation(json, meta, target_field, transformation_entry) json.child! do target_field = choose_processor_for_transformation(json, meta, target_field, transformation_entry) end target_field end def choose_processor_for_transformation(json, meta, target_field, transformation_entry) if meta[:search_path].present? target_field, nested_field = meta[:search_path].split('.') foreach(json, target_field, transformation_entry, nested_field) elsif @array_context foreach(json, target_field, transformation_entry) else generate_processor_for_target_field(target_field, json, transformation_entry) end target_field end def array_contains_multi_value_external_mapping(transformation_entry) @array_context && transformation_entry.dig(:external_mapping, :multi_value) end def coalesce(json, target_field) source = "ctx.#{target_field}=ctx.#{target_field}.stream().flatMap(l -> l.stream())."\ 'distinct().sorted().collect(Collectors.toList())' json.child! do json.script do json.source source end end end def foreach(json, target_field, transformation_entry, nested_field = nil) json.foreach do json.field target_field.to_s json.processor do ingest_value_field = '_ingest._value' ingest_value_field = [ingest_value_field, nested_field].join('.') if nested_field.present? generate_processor_for_target_field(ingest_value_field, json, transformation_entry) end json.ignore_failure true end end def generate_processor_for_target_field(field, json, transformation_entry) if transformation_entry.instance_of?(String) DataSources::StringTransformation.generate_processor(json, field, transformation_entry) else process_hash(json, field, transformation_entry) end end def process_hash(json, field, transformation_entry_hash) transformation_klass_name = "DataSources::#{transformation_entry_hash.keys.first.to_s.camelize}Transformation" if class_exists?(transformation_klass_name) klass = transformation_klass_name.constantize klass.generate_processor(json, field, transformation_entry_hash.values.first) else array = transformation_entry_hash.to_a.flatten DataSources::StringTransformation.generate_processor(json, field, array.first, array.from(1)) @array_context = 'split' == array.first end end def class_exists?(class_name) Module.const_get(class_name).is_a?(Class) rescue NameError false end end
true
069a159cc1bedf550abe8ac5aa4622a4e683302b
Ruby
krismac/course_notes
/week_02/day_4/pry/pry_end_point/specs/cake_shop_specs.rb
UTF-8
759
2.671875
3
[]
no_license
require( 'minitest/autorun' ) require( 'minitest/rg' ) require_relative( '../cake_shop' ) require_relative( '../cake' ) class TestCakeShop < MiniTest::Test def setup ingredients1 = ["chocolate", "cocoa powder", "flour", "eggs", "sugar", "butter"] cake1 = Cake.new("brownie", ingredients1, 5) ingredients2 = ["carrots", "raisins", "cinnamon", "flour", "eggs", "sugar", "butter"] cake2 = Cake.new("carrot cake", ingredients2, 4) ingredients3 = ["lemon juice", "flour", "eggs", "sugar", "butter"] cake3 = Cake.new("lemon drizzle", ingredients3, 3) @cakes = [ cake1, cake2, cake3] @kates_cakes = CakeShop.new(@cakes) end def test_average_cake_rating assert_equal(4.0, @kates_cakes.average_cake_rating()) end end
true
976f4c93155aac6069124d878a0e36e6190b90ff
Ruby
thoughtbot/factory_bot
/spec/acceptance/initialize_with_spec.rb
UTF-8
6,037
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
describe "initialize_with with non-FG attributes" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string, age: :integer) do def self.construct(name, age) new(name: name, age: age) end end FactoryBot.define do factory :user do initialize_with { User.construct("John Doe", 21) } end end end subject { build(:user) } its(:name) { should eq "John Doe" } its(:age) { should eq 21 } end describe "initialize_with with FG attributes that are transient" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string) do def self.construct(name) new(name: "#{name} from .construct") end end FactoryBot.define do factory :user do transient do name { "Handsome Chap" } end initialize_with { User.construct(name) } end end end subject { build(:user) } its(:name) { should eq "Handsome Chap from .construct" } end describe "initialize_with non-ORM-backed objects" do include FactoryBot::Syntax::Methods before do define_class("ReportGenerator") do attr_reader :name, :data def initialize(name, data) @name = name @data = data end end FactoryBot.define do sequence(:random_data) { Array.new(5) { Kernel.rand(200) } } factory :report_generator do transient do name { "My Awesome Report" } end initialize_with { ReportGenerator.new(name, FactoryBot.generate(:random_data)) } end end end it "allows for overrides" do expect(build(:report_generator, name: "Overridden").name).to eq "Overridden" end it "generates random data" do expect(build(:report_generator).data.length).to eq 5 end end describe "initialize_with parent and child factories" do before do define_class("Awesome") do attr_reader :name def initialize(name) @name = name end end FactoryBot.define do factory :awesome do transient do name { "Great" } end initialize_with { Awesome.new(name) } factory :sub_awesome do transient do name { "Sub" } end end factory :super_awesome do initialize_with { Awesome.new("Super") } end end end end it "uses the parent's constructor when the child factory doesn't assign it" do expect(FactoryBot.build(:sub_awesome).name).to eq "Sub" end it "allows child factories to override initialize_with" do expect(FactoryBot.build(:super_awesome).name).to eq "Super" end end describe "initialize_with implicit constructor" do before do define_class("Awesome") do attr_reader :name def initialize(name) @name = name end end FactoryBot.define do factory :awesome do transient do name { "Great" } end initialize_with { new(name) } end end end it "instantiates the correct object" do expect(FactoryBot.build(:awesome, name: "Awesome name").name).to eq "Awesome name" end end describe "initialize_with doesn't duplicate assignment on attributes accessed from initialize_with" do before do define_class("User") do attr_reader :name attr_accessor :email def initialize(name) @name = name end end FactoryBot.define do sequence(:email) { |n| "person#{n}@example.com" } factory :user do email name { email.gsub(/@.+/, "") } initialize_with { new(name) } end end end it "instantiates the correct object" do built_user = FactoryBot.build(:user) expect(built_user.name).to eq "person1" expect(built_user.email).to eq "[email protected]" end end describe "initialize_with has access to all attributes for construction" do it "assigns attributes correctly" do define_class("User") do attr_reader :name, :email, :ignored def initialize(attributes = {}) @name = attributes[:name] @email = attributes[:email] @ignored = attributes[:ignored] end end FactoryBot.define do sequence(:email) { |n| "person#{n}@example.com" } factory :user do transient do ignored { "of course!" } end email name { email.gsub(/@.+/, "") } initialize_with { new(**attributes) } end end user_with_attributes = FactoryBot.build(:user) expect(user_with_attributes.email).to eq "[email protected]" expect(user_with_attributes.name).to eq "person1" expect(user_with_attributes.ignored).to be_nil end end describe "initialize_with with an 'attributes' attribute" do it "assigns attributes correctly" do define_class("User") do attr_reader :name def initialize(attributes:) @name = attributes[:name] end end FactoryBot.define do factory :user do attributes { {name: "Daniel"} } initialize_with { new(**attributes) } end end user = FactoryBot.build(:user) expect(user.name).to eq("Daniel") end end describe "initialize_with for a constructor that requires a block" do it "executes the block correctly" do define_class("Awesome") do attr_reader :output def initialize(&block) @output = instance_exec(&block) end end FactoryBot.define do factory :awesome do initialize_with { new { "Output" } } end end expect(FactoryBot.build(:awesome).output).to eq "Output" end end describe "initialize_with with a hash argument" do it "builds the object correctly" do define_class("Container") do attr_reader :contents def initialize(contents) @contents = contents end end FactoryBot.define do factory :container do initialize_with { new({key: :value}) } end end expect(FactoryBot.build(:container).contents).to eq({key: :value}) end end
true
7f7d157f4c8ca34e6829a8420fabe0ddd01ffab6
Ruby
dcere/LearnRubyTheHardWay
/ex17-3.rb
UTF-8
111
2.640625
3
[]
no_license
#from_file, to_file = ARGV File.open(ARGV[1], 'w').write(File.open(ARGV[0]).read()) puts "Alright, all done."
true
97e3fa96afb438f8793d0f3898943afd65e4274a
Ruby
austinfromboston/projectmonitor
/app/models/dashboard_grid.rb
UTF-8
2,019
2.5625
3
[ "MIT" ]
permissive
class DashboardGrid DEFAULT_LOCATION_GRID_SIZE = 63 class << self def generate(request_params={}) new(request_params).generate end end def initialize(request_params) @request_params = request_params @tags = request_params[:tags] @locations = request_params[:view] @projects = find_projects.sort_by { |p| p.name.to_s.downcase } end def generate if @locations generate_with_locations else generate_without_locations end end private def generate_with_locations locations = [] @projects.group_by(&:location).keys.sort{ |l1,l2| group_sort(l1,l2) }.each do |location| location_projects = location_groups[location] locations << SubGridCollection.new([Location.new(location(location_projects))] + location_projects) end GridCollection.new(locations.flatten, DEFAULT_LOCATION_GRID_SIZE).each_slice(9).to_a.transpose.flatten end def generate_without_locations GridCollection.new @projects, @request_params[:tiles_count].try(:to_i) end def find_projects if @tags generate_with_tags else generate_projects end end def generate_projects Project.standalone + AggregateProject.all end def generate_with_tags aggregate_projects = AggregateProject.all_with_tags(@tags) projects_with_aggregates = aggregate_projects.collect(&:projects).flatten.uniq Project.find_tagged_with(@tags, match_all: true) - projects_with_aggregates + aggregate_projects end def group_sort(l1, l2) return -1 if ["San Francisco", "SF"].include?(l1) return 1 if ["San Francisco", "SF"].include?(l2) return 1 if l1.blank? return -1 if l2.blank? l1 <=> l2 end def location(location_projects) location = location_projects.first.try(:location) return location if location_projects.all? { |e| e.blank? || e.location == location } end def location_groups @projects.group_by(&:location) end def sort(projects) projects.sort_by(&:name) end end
true
3e3996efd654c2eb3d227a9db341f437488a053c
Ruby
leemachine/ruby-installer
/Hash.rb
UTF-8
552
2.828125
3
[]
no_license
#This is not used! module Hash def hash_check require 'digest/md5' require 'yaml' config = YAML.load_file('config/hash.yaml') #Loads the config.yaml file $hash = config['PyHash'] #read the config file and turn the PyHash fact into a variable puts "Checking MD5 checksums " #puts @hash $md5 = Digest::MD5.file('/home/e58496/workspace/ruby/gnuradio-install/src/Python-2.7.8.tgz').hexdigest #puts @md5 if $hash == $md5 then puts "Hashes match :)" else abort("Hashes don't match!") end end end
true
555e4bfcdf3a1c7d7567b48efdb084f995b7b2bc
Ruby
crondaemon/sciformbot
/lib/xinfei_bot.rb
UTF-8
2,919
2.75
3
[]
no_license
require 'telegram/bot' $commands = Telegram::Bot::Types::ReplyKeyboardMarkup.new(one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['cos\'è la XinFei?', 'dove sono i corsi'], %w(orari costi promo), %w(sito contatti) ]) def sanitize(text) text.gsub!('\'', '') text.gsub!('è', 'e') text.gsub!('é', 'e') text.gsub!('à', 'a') text.gsub!('ì', 'i') text.gsub!('ò', 'o') text.gsub!('ù', 'u') return text.downcase end def key(message) ret = :unknown clean_msg = sanitize(message) ret = :general if clean_msg == 'corsi' ret = :where if clean_msg.include?('dove') ret = :about if clean_msg == 'chi' ret = :about if clean_msg.include?('cose') && clean_msg.include?('xinfei') ret = :about if clean_msg.include?('chi') && clean_msg.include?('siete') ret = :costs if clean_msg.include?('cost') ret = :site if clean_msg.include?('sito') ret = :site if clean_msg.include?('web') ret = :contacts if clean_msg == 'contatti' ret = :contacts if clean_msg.include?('facebook') ret = :contacts if clean_msg.include?('telefono') ret = :contacts if clean_msg.include?('mail') ret = :contacts if clean_msg.include?('contattar') ret = :hours if clean_msg.include?('orar') ret = :hours if clean_msg.include?('quando') ret = :thanks if clean_msg.include?('grazie') ret = :promo if clean_msg.include?('promo') return ret end def send_additional(key, bot, chat_id) case key when :where bot.api.send_location(chat_id: chat_id, latitude: 45.068717, longitude: 7.670221, disable_notification: true, reply_markup: $commands) end end def answer(bot, message, key) filename = key.to_s + ".msg" begin content = File.read(filename) bot.api.send_message(chat_id: message.chat.id, text: content, parse_mode: 'Markdown', reply_markup: $commands) send_additional(key, bot, message.chat.id) rescue => e bot.logger.debug(e.inspect) bot.api.send_message(chat_id: message.chat.id, text: "Temo di avere qualche problema...", reply_markup: $commands) end end # MAIN token = '246996184:AAEm-HCWLJLpHlNd-tAUuVz5vamwo9Yv3Dw' while true begin bot = Telegram::Bot::Client.new(token, logger: Logger.new('xinfei-bot.log')) bot.options[:timeout] = 3 bot.listen do |message| next if !message.text if message.text == '/start' bot.logger.info("#{message.from.first_name} #{message.from.last_name} (#{message.from.username}) entered chat") bot.api.send_message(chat_id: message.chat.id, reply_markup: $commands, text: "Ciao #{message.from.first_name}, io sono il bot della XinFei, dimmi cosa vuoi sapere.") next end bot.logger.info("[#{message.from.first_name} #{message.from.last_name}]: #{message.text}") key, additional = key(message.text) bot.logger.debug("key: #{key}") if key == :unknown bot.api.send_message(chat_id: message.chat.id, text: "Non capisco. Dimmi cosa vuoi sapere.") else answer(bot, message, key) end end rescue => e end end
true
5c417c9e74991d5c7d6f2b3aa5d6e8d97fa9f62f
Ruby
jcoglan/oyster
/lib/oyster/options/glob.rb
UTF-8
244
2.515625
3
[ "MIT" ]
permissive
module Oyster class GlobOption < Option def consume(list) Dir.glob(list.shift) end def default_value super([]) end def help_names super.map { |name| name + ' ARG' } end end end
true
6dee94aba6f1d93fa5463c5ddfc230fcbe5cda07
Ruby
Kisamict/ruby
/homework8/2.rb
UTF-8
100
3.09375
3
[]
no_license
def average(array) return puts 0 unless array.all?(Integer) p array.inject(:+) / array.size end
true
8b1c7aca32146c4d387ad664c10242cf9ce1e918
Ruby
robertoplancarte/rapier
/rapier_lang/compilador/CUA.rb
UTF-8
741
2.984375
3
[]
no_license
#clase cuadruplo que junta strings. los operandos son arreglos de strings donde [0]:nombre, [1]:tipo y [2]:dir_mem class Cuadruplo attr_accessor :operador, :operando1, :operando2, :respuesta def initialize(operador, operando2, operando1, respuesta='resp') @operador = operador @operando1 = operando1 @operando2 = operando2 @respuesta = respuesta end def human_prt [operador, operando1[0], operando2[0], respuesta[0]] end def debug_prt "[#{operador}, #{operando1}, #{operando2}, #{respuesta}]" end def compiler_prt if operador == "GoF" || operador == "Go" [operador, operando1[2], operando2[2], respuesta] else [operador, operando1[2], operando2[2], respuesta[2]] end end end
true
8ab0d838427b7247f1e6dfa9ffd8cd1af2d36bd6
Ruby
gudata/manga-downloadr-test-performance-mode
/simple-chapters-processor.rb
UTF-8
279
2.546875
3
[]
no_license
require 'nokogiri' require 'singleton' class SimpleChaptersProcessor include Singleton def get_page_paths(chapter_page) Nokogiri::HTML(chapter_page). xpath("//div[@id='selectpage']//select[@id='pageMenu']//option"). map{|option| option['value'] } end end
true
87547c1cd07ab7b5de4186c82f1aa3c2f62f6ea2
Ruby
beastie87/everypolitician-data
/rakefile_common.rb
UTF-8
3,765
2.9375
3
[]
no_license
# We take various steps to convert all the incoming data into the output # formats. Each of these steps uses a different rake_helper: # # Step 1: combine_sources # This takes all the incoming data (mostly as CSVs) and joins them # together into 'sources/merged.csv' # Step 2: verify_source_data # Make sure that the merged data has everything we need and is # well-formed # Step 3: turn_csv_to_popolo # This turns the 'merged.csv' into a 'sources/merged.json' # Step 4: generate_ep_popolo # This turns the generic 'merged.json' into the EP-specific # 'ep-popolo.json' # Step 5: generate_final_csvs # Generates term-by-term CSVs from the ep-popolo # Step 6: generate_stats # Generates statistics about the data we have require 'colorize' require 'csv' require 'csv_to_popolo' require 'erb' require 'fileutils' require 'fuzzy_match' require 'json' require 'open-uri' require 'pry' require 'rake/clean' require 'set' require 'yajl/json_gem' Numeric.class_eval { def empty?; false; end } def deep_sort(element) if element.is_a?(Hash) element.keys.sort.each_with_object({}) { |k, newhash| newhash[k] = deep_sort(element[k]) } elsif element.is_a?(Array) element.map { |v| deep_sort(v) } else element end end def json_load(file) raise "No such file #{file}" unless File.exist? file JSON.parse(File.read(file), symbolize_names: true) end def json_write(file, json) File.write(file, JSON.pretty_generate(json)) end def popolo_write(file, json) # TODO remove the need for the .to_s here, by ensuring all People and Orgs have names json[:persons].sort_by! { |p| [ p[:name].to_s, p[:id] ] } json[:persons].each do |p| p[:identifiers].sort_by! { |i| [ i[:scheme], i[:identifier] ] } if p.key?(:identifiers) p[:contact_details].sort_by! { |d| [ d[:type] ] } if p.key?(:contact_details) p[:links].sort_by! { |l| [ l[:note] ] } if p.key?(:links) p[:other_names].sort_by! { |n| [ n[:lang].to_s, n[:name] ] } if p.key?(:other_names) end json[:organizations].sort_by! { |o| [ o[:name].to_s, o[:id] ] } json[:memberships].sort_by! { |m| [ m[:person_id], m[:organization_id], m[:legislative_period_id], m[:start_date].to_s, m[:on_behalf_of_id].to_s, m[:area_id].to_s ] } json[:events].sort_by! { |e| [ e[:start_date].to_s || '', e[:id].to_s ] } if json.key? :events json[:areas].sort_by! { |a| [ a[:id] ] } if json.key? :areas final = Hash[deep_sort(json).sort_by { |k, _| k }.reverse] File.write(file, JSON.pretty_generate(final)) end @SOURCE_DIR = 'sources/manual' @DATA_FILE = @SOURCE_DIR + '/members.csv' @INSTRUCTIONS_FILE = 'sources/instructions.json' def clean_instructions_file json_load(@INSTRUCTIONS_FILE) || raise("Can't read #{@INSTRUCTIONS_FILE}") end def write_instructions(instr) File.write(@INSTRUCTIONS_FILE, JSON.pretty_generate(instr)) end def load_instructions_file json = clean_instructions_file json[:sources].each do |s| s[:file] = "sources/%s" % s[:file] unless s[:file][/sources/] end json end def instructions(key) @instructions ||= load_instructions_file @instructions[key] end desc "Rebuild from source data" task :rebuild => [ :clobber, 'ep-popolo-v1.0.json' ] task :default => [ :csvs, 'stats:regenerate' ] require_relative 'rake_build/combine_sources.rb' require_relative 'rake_build/verify_source_data.rb' require_relative 'rake_build/turn_csv_to_popolo.rb' require_relative 'rake_build/generate_ep_popolo.rb' require_relative 'rake_build/generate_final_csvs.rb' require_relative 'rake_build/generate_stats.rb' require_relative 'rake_generate/election_info.rb' require_relative 'rake_generate/position_info.rb' require_relative 'rake_generate/groups_info.rb'
true
0d6b412773362c09e3efe1dda10af1acbc463ca7
Ruby
MarilenaRoque/CodeChallenges
/jewels_and_stones.rb
UTF-8
424
3.25
3
[]
no_license
# @param {String} j # @param {String} s # @return {Integer} def num_jewels_in_stones(j, s) s = s.split('') hash = {}; counter = 0 s.each do |el| if hash[el] hash[el] = hash[el] + 1 else hash[el] = 1 end end j = j.split('') j.each do |el| if hash[el] counter = counter + hash[el] end end return counter end
true
5ec6bfc69916d089e91a4a3d0e0d0a1aaf681cf8
Ruby
codemargaret/contact
/lib/contact.rb
UTF-8
892
3.0625
3
[ "MIT" ]
permissive
class Contact @@list = [] attr_accessor :first_name, :last_name, :address, :phone_number attr_reader :id def initialize(attributes) @first_name = attributes.fetch("first_name") @last_name = attributes.fetch("last_name") @address = attributes.fetch("address") @phone_number = attributes.fetch("phone_number") @id = @@list.length + 1 end def self.all @@list end def self.find(id) contact_id = id.to_i() @@list.each do |contact| if contact.id == contact_id return contact end end end def save @@list.push(self) end def self.clear() @@list = [] end def self.sort @@list.sort_by! {|contact| contact.last_name} end def self.remove_contact(id) @@list.map do |contact| if contact.id == id contact.first_name = "" contact.last_name = "" end end end end
true
c973bb313b06cd5842ff65bfc6c16fcd8614da60
Ruby
MarcoBgn/bolt-template
/app/models/kpis/base.rb
UTF-8
3,272
2.71875
3
[]
no_license
# frozen_string_literal: true # Abstract base class inherited by all the widgets class Kpis::Base < ApplicationModel attr_accessor :title, :settings, :hist_parameters, :currency, :watchables, :alerts # Constants to be defined in child class # BASE_ENTITIES = [String] - List of entities on which the KPI calculation is based # WATCHABLES = [Symbol] -- List of watchables available for the KPI # ATTACHABLES = [String] -- List of widgets that can have the KPI attached to # TODO: dynamic? KPIS_LIST = {}.freeze def initialize(attrs = {}) options = attrs.deep_symbolize_keys self.title = self.class.name.demodulize.titleize self.settings = options[:settings].to_h self.hist_parameters = Utility::HistParameters.new(settings[:hist_parameters]) self.currency = settings[:currency] self.watchables = options[:targets].to_h.map do |watchable, targets_array| valid_watchable = self.class::WATCHABLES.find { |w| w == watchable } next unless valid_watchable.present? targets = targets_array.map { |t_hash| Utility::Kpis::Target.new(t_hash) } Utility::Kpis::Watchable.new(title: valid_watchable, targets: targets) end.to_a.compact self.alerts = options[:alerts].to_a.map do |alert_hash| Utility::Kpis::Alert.new(alert_hash.merge(title: title)) end block_given? ? yield : self end # def self.based_on_any?(entities_names) # entities_names.any? { |entity_name| BASE_ENTITIES.include?(entity_name) } # end def compute if valid? watchables.each do |watchable| watchable.targets.each do |target| next unless target.currency.present? target.min = convert(target.min, target.currency).round(2) if target.min target.max = convert(target.max, target.currency).round(2) if target.max end send("assess_#{watchable.title}!", watchable) end end self end # Render KPI results # Returns: # ---------------- # { # triggered: true, # watchables: [{ # title: 'threshold', # "targets": [{ # "min": 13700, # "messages": [ ... ], # "triggered_interval_index": 1, # "trigger_state": true # }], # "trigger_state": true # }] # } def render compute { triggered: triggered?, watchables: watchables.as_json } end # The KPI is considered triggered if any target of any watchable is met def triggered? @trigger_state ||= watchables.any?(&:triggered?) end # Dispatch alert if: # - alert not sent and watchable triggered # OR - alert sent and watchable not triggered ("back to normal") def dispatch_alerts compute alerts.each do |alert| watchables.select { |watchable| alert.sent != watchable.triggered? }.each do |watchable| send("format_alert_for_#{watchable.title}!", alert, watchable) alert.dispatch end end end def self.can_watch?(watchable) self::WATCHABLES.include?(watchable.to_sym) end protected def convert(amount_f, from_currency, at_date = Time.zone.today) return amount_f if from_currency == currency date = Chronic.parse(at_date) || Time.zone.today amount_f * Money.default_bank.get_rate(date, from_currency, currency) end end
true
edf3366b0dc4a60b810f3305f36dc6467eaceb03
Ruby
samtalks/sam-personal
/1011-dogstr/dogstr-original/generator.rb
UTF-8
583
2.921875
3
[]
no_license
require_relative './environment' # 100.times do # Dog.new.tap do |d| # d.name = Faker::Name.name # d.color = Faker::Lorem.word # d.bio = Faker::Lorem.paragraph # d.save # end # end index = ERB.new(File.open('lib/templates/index.erb').read) dogs = Dog.all File.open('_site/index.html', 'w+') do |f| f << index.result(binding) end show = ERB.new(File.open('lib/templates/show.erb').read) # For each dog, first, cast the dog into instance var dogs.each do |dog| File.open("_site/dogs/#{dog.url}.html", 'w+') do |f| f << show.result(binding) end end
true
32b577601657532f3116e2cba9736e6c058b45d3
Ruby
pincsolutions/rosruby
/test/test_msg.rb
UTF-8
1,127
2.546875
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env ruby require 'ros' require 'rosgraph_msgs/Log' require 'std_msgs/UInt8MultiArray' require 'test/unit' class TestMessageInitialization < Test::Unit::TestCase def test_message now = ROS::Time.now log = Rosgraph_msgs::Log.new(:header => Std_msgs::Header.new(:seq => 1, :stamp => now, :frame_id => 'aa'), :level => Rosgraph_msgs::Log::DEBUG, :topics => ["/a", "/b"]) assert_equal(1, log.header.seq) assert_equal(now, log.header.stamp) assert_equal('aa', log.header.frame_id) assert_equal(Rosgraph_msgs::Log::DEBUG, log.level) assert_equal(["/a", "/b"], log.topics) assert_equal("", log.name) assert_equal("", log.function) end def test_message_invalid now = ROS::Time.now log = Rosgraph_msgs::Log.new(:aaa => '', :bbbb => '') assert_equal(0, log.level) assert_equal("", log.name) assert_equal("", log.function) end end
true
7434a3d5943be5c89de2b06319258b9d6607eb68
Ruby
johslarsen/dotfiles
/test/bin/nrandfile_test.rb
UTF-8
789
2.640625
3
[ "Unlicense" ]
permissive
#!/usr/bin/env ruby require 'minitest/autorun' require 'set' require_relative '../test_helper' class NrandfileTest < Minitest::Test def test_that_2_runs_gives_different_result files = Set.new(1.upto(100).map{|n| n.to_s}) tmpdir_with(*files) do |root| a = nrandfile(4, root) assert_equal 4, a.length assert a.subset? files b = nrandfile(4, root) assert_equal 4, b.length assert b.subset? files if a == b # possible, but very unlike skip "Two 4/100 draws happens to return the same set of files" end end end private def nrandfile(n, dir) files = pipe(File.join(DOTFILES, "bin", "nrandfile"), n.to_s, dir) .split("\n") .map{|p|p[(dir.length+1)..-1]} Set.new files end end
true
e4b233a56bae9fd96ba4462aef1111c5a8ea72b2
Ruby
ffloyd/flows
/lib/flows/shared_context_pipeline/track_list.rb
UTF-8
1,125
2.703125
3
[ "MIT" ]
permissive
module Flows class SharedContextPipeline # @api private class TrackList attr_reader :current_track def initialize @tracks = { main: Track.new(:main) } @current_track = :main end def initialize_dup(_other) @tracks = @tracks.transform_values(&:dup) end def switch_track(track_name) @tracks[track_name] ||= Track.new(track_name) @current_track = track_name end def add_step(step) @tracks[@current_track].add_step(step) end def first_step_name @tracks[:main].first_step_name end def main_track_empty? @tracks[:main].empty? end def to_node_map(method_source) @tracks.reduce({}) do |node_map, (_, track)| node_map.merge!( track.to_node_map(method_source) ) end end def to_flow(method_source) raise NoStepsError, method_source if main_track_empty? Flows::Flow.new( start_node: first_step_name, node_map: to_node_map(method_source) ) end end end end
true
deb62e8e3b0176283418584cfe3526761dab0da7
Ruby
maRce10/marce10.github.com
/vendor/bundle/ruby/2.5.0/gems/jekyll-github-metadata-2.2.0/lib/jekyll-github-metadata/value.rb
UTF-8
1,538
2.75
3
[ "MIT" ]
permissive
require "json" module Jekyll module GitHubMetadata class Value attr_reader :key, :value def initialize(*args) case args.size when 1 @key = "{anonymous}" @value = args.first when 2 @key = args.first.to_s @value = args.last else raise ArgumentError, "#{args.size} args given but expected 1 or 2" end end def render @value = if @value.respond_to?(:call) case @value.arity when 0 @value.call when 1 @value.call(GitHubMetadata.client) when 2 @value.call(GitHubMetadata.client, GitHubMetadata.repository) else raise ArgumentError, "Whoa, arity of 0, 1, or 2 please in your procs." end else @value end @value = Sanitizer.sanitize(@value) rescue RuntimeError, NameError => e Jekyll::GitHubMetadata.log :error, "Error processing value '#{key}':" raise e end def to_s render.to_s end def to_json(*) render.to_json end def to_liquid case render when nil nil when true, false value when Hash value when String, Numeric, Array value else to_json end end end end end
true
008e2c6ce64b29a6272cf0dba976a6221a695e86
Ruby
tynmarket/coffeehub
/app/models/coffee.rb
UTF-8
522
2.53125
3
[ "MIT" ]
permissive
class Coffee < ApplicationRecord PER_PAGE = 10 belongs_to :site enum roast: { unknown: 0, light: 1, cinnamon: 2, medium: 3, high: 4, city: 5, fullcity: 6, french: 7, italian: 8 } enum_text :roast class << self def for_api(page) eager_load(:site).order(created_at: :desc, id: :desc).page(page) end def page(page) page = page.to_i if page >= 2 limit(PER_PAGE + 1).offset(PER_PAGE * (page - 1)) else limit(PER_PAGE + 1) end end end end
true
4b37ab167d5bfa4495387ea8c14501b1ba23c5d7
Ruby
csilva1/phase-0-tracks
/ruby/list/list.rb
UTF-8
235
3.203125
3
[]
no_license
class TodoList def initialize(list_array) @list = list_array end def get_items @list end def add_item(item) @list << item end def delete_item(item) @list.delete(item) end def get_item(index) @list[index] end end
true
fc5ed3d2295b3b7122e07559e5c75af05959d366
Ruby
Eractus/CWRK-W3D2
/aa_questions/reply.rb
UTF-8
2,274
2.71875
3
[]
no_license
require 'sqlite3' require 'singleton' require 'byebug' class QuestionsDatabase < SQLite3::Database include Singleton def initialize super('questions.db') self.type_translation = true self.results_as_hash = true end end class Reply def self.find_by_id(id) reply = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM replies WHERE id = ? SQL return nil if reply.empty? Reply.new(reply.first) end def self.find_by_user_id(user_id) user = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM replies WHERE user_id = ? SQL return nil if user.empty? user.map { |hash| Reply.new(hash) } end def self.find_by_question_id(question_id) reply = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM replies WHERE question_id = ? SQL return nil if reply.empty? reply.map { |hash| Reply.new(hash) } end attr_accessor :body attr_reader :id, :top_reply_id, :question_id, :user_id def initialize(options) @id = options['id'] @body = options['body'] @top_reply_id = options['top_reply_id'] @question_id = options['question_id'] @user_id = options['user_id'] end def author reply = QuestionsDatabase.instance.execute(<<-SQL, self.user_id) SELECT * FROM users WHERE id = ? SQL return nil if reply.empty? User.new(reply.first) end def question question = QuestionsDatabase.instance.execute(<<-SQL, self.question_id) SELECT * FROM questions WHERE id = ? SQL Question.new(question.first) end def parent_reply par_reply = QuestionsDatabase.instance.execute(<<-SQL, self.top_reply_id) SELECT * FROM replies WHERE id = ? SQL Reply.new(par_reply.first) end def child_replies c_reply = QuestionsDatabase.instance.execute(<<-SQL, self.id) SELECT * FROM replies WHERE top_reply_id = ? SQL return nil if c_reply.empty? c_reply.map { |hash| Reply.new(hash) } end end
true
d2b86c79cfd0a8043f0745d167ebbd9cd1cc52ba
Ruby
thedoritos/resheet
/src/resheet/sheet.rb
UTF-8
1,283
2.78125
3
[]
no_license
module Resheet class Sheet attr_reader :error attr_reader :header, :rows, :records def initialize(sheets_service, spreadsheet_id, resource) @sheets_service = sheets_service @spreadsheet_id = spreadsheet_id @resource = resource end def fetch begin values = @sheets_service.get_spreadsheet_values(@spreadsheet_id, "#{@resource}!A:Z").values @header = values[0] @rows = values.drop(1) @records = @rows.map do |row| @header.each_with_index.map { |key, i| [key, row[i]] }.to_h end rescue Google::Apis::ClientError => error @error = error end end def new_record(params) record = @header.map { |key| [key, params[key]] }.to_h record['id'] = (@records.map { |item| item['id'].to_i }.max || 0) + 1 record end def updated_record(params) record = find_record(params['id']) return nil if record.nil? safe_params = params.select do |key, value| next false if key == 'id' @header.include?(key) end record.merge(safe_params) end def find_record(id) @records.find { |item| item['id'] == id } end def row_number_of(record) @records.index(record) + 2 end end end
true
b709594518600f1f5c823ce9a6bc862edbc2f02a
Ruby
leahhuyghe/codecore-fundamentals
/week_2/hash_looping.rb
UTF-8
314
4.25
4
[]
no_license
# Write a hash that three contains Canadian provinces # as keys and their capital as values then loop # through it and print each province and its capital canadian_cities = {"BC" => "Victoria", "ON" => "Ottawa", "Nova Scotia" => "Halifax"} canadian_cities.each do |k, v| puts "The Capital of #{k} is #{v}" end
true
7c434f170a012f38ce6597fbe25857e77d5bd8f9
Ruby
marcinszydelko/week2_day4_lab
/star_system.rb
UTF-8
1,593
3.421875
3
[]
no_license
class StarSystem attr_reader :name, :planets def initialize(name, planets) @name = name @planets = planets end def planet_names @planets.map { |planet| planet.name } end def get_planet_by_name(name) @planets.find { |planet| planet.name == name } end def get_largest_planet result = 0 biggest_diameter = 0 @planets.each do |planet| if planet.diameter > biggest_diameter result = planet biggest_diameter = planet.diameter end end return result end def get_smallest_planet smallest_planet = @planets[0] @planets.each do |planet| if planet.diameter < smallest_planet.diameter smallest_planet = planet end end return smallest_planet end def get_planets_with_no_moons planet_no_moons = [] @planets.each do |planet| if planet.number_of_moons == 0 planet_no_moons << planet end end return planet_no_moons end def get_planets_with_more_moons(number) result = [] @planets.each do |planet| if planet.number_of_moons > number result << planet.name end end return result end def get_number_of_planets_closer_than(distance) number_of_planets = 0 @planets.each do |planet| if planet.distance_from_sun < distance number_of_planets += 1 end end return number_of_planets end def get_total_number_of_moons number_of_moons = 0 @planets.each do |planet| number_of_moons += planet.number_of_moons end return number_of_moons end end
true
0a81ef89fe671220d82b45691c9b246d4c7e2257
Ruby
calacademy-research/antcat
/app/services/markdowns/bolton_keys_to_ref_tags.rb
UTF-8
914
2.515625
3
[]
no_license
# frozen_string_literal: true module Markdowns class BoltonKeysToRefTags include Service attr_private_initialize :bolton_content def call replace_with_ref_tags end private def replace_with_ref_tags split_by_semicolon.map do |part| part.gsub(/(?<bolton_key>.*?):/) do reference = find_reference $LAST_MATCH_INFO[:bolton_key] if reference "#{Taxt.ref(reference.id)}:" else "#{Regexp.last_match(1)}: " end end end.join("; ").gsub(" ", " ") end def split_by_semicolon bolton_content.split("; ") end def find_reference bolton_key Reference.find_by(bolton_key: normalize_bolton_key(bolton_key)) end def normalize_bolton_key bolton_key bolton_key.remove(",", "&").gsub(" ", " ").strip end end end
true
99e882dc794a0b438718c5e262880f5bba3f060e
Ruby
rubysoftwaredev/EmailAlerter
/email_sender.rb
UTF-8
791
2.765625
3
[]
no_license
# This program reads email addresses from a table # constructs personalized emails and sends the email require 'rubygems' require 'gmail_sender' class EmailSender attr_accessor :senderEmailer def initialize(sender_addr,ppw) @senderEmailer = GmailSender.new(sender_addr,ppw) end public def send_email(to_email_addr,subj,email_text,*attach_filename) #puts("sending email", to_email_addr, subj, email_text,attach_filename) attach_filename.each do |i| #print i @senderEmailer.attach(i) end # @senderEmailer.send( :to => to_email_addr, # :subject => subj, # :content => email_text) end end #Test #g=EmailSender.new("h","b") # #arr=["file1", "file2" ] # #g.send_email("a","b","c",*arr)
true
c8f0c39ce71a5e5798c10b323e7d08d845e027f8
Ruby
d3r3k6/Ruby_Praxy
/localvar.rb
UTF-8
293
3.765625
4
[]
no_license
#Simple program to illustrate local variable in programs def doubleThis num numTimes2 = num * 2 puts num.to_s + ' doubled is ' + numTimes2.to_s end doubleThis 44 #The below will throw an error because numTimes2 is a local variable and doesnt exist outside of the method puts numTimes2.to_s
true
352f81819f7156eabe2ceb95627b37ad09450502
Ruby
BilboAtBagEnd/pocket-battlelizer
/calculate-army-points.rb
UTF-8
1,186
3.65625
4
[]
no_license
#!/usr/bin/ruby require 'yaml' require 'optparse' require 'pocket-battles-1.0.rb' OptionParser.new do |opts| opts.banner = <<-END Given input army units, calculates how much your army is worth. Available armies: - #{PocketBattles.armies.join("\n - ")} Input your units with separate lines per army as: ARMY1 n1 n2 n3... ARMY2 n1 n2 n3... Example: Celts 1 02 23 28 Romans 1 2 04 17 30 Press Control-d when you're done. END end.parse! points = 0 STDIN.each do |line| line.strip! next if line.empty? fields = line.split(/[ ,]+/) army_name = fields.shift unless PocketBattles.has_army? army_name puts "Unknown army #{army_name}; please try again." next end army = PocketBattles.army(army_name) fields.each do |n| begin unit = army.unit n puts "#{unit.name} [#{unit.reference}] is worth #{unit.points}" points += unit.points rescue => e puts "Couldn't find unit #{n}, skipping" next end end puts end puts <<END Your army is worth #{points} points. Your opponent needs to collect #{(points.to_f/2).round} points to win. END
true
6637d7f2f96f3a676cbda029510fc52b0ba9d321
Ruby
kftwotwo/update_contacts
/spec/user_spec.rb
UTF-8
1,577
3
3
[]
no_license
require('rspec') require('user') describe(User) do before :each do User.clear end describe('#initialize') do it "will fetch the name" do test_user = User.new(:name => 'Kevin') expect(test_user.name()).to(eq('Kevin')) end end describe('#save') do it "will save the user into an array" do test_user = User.new(:name => 'Kevin') expect(test_user.save()).to(eq([test_user])) end end describe('.clear') do it "will clear the array" do test_user = User.new(:name => 'Kevin').save() expect(User.clear()).to(eq([])) end end describe(".all") do it "will display all users" do test_user = User.new(:name => 'John') test_user.save() test_user2 = User.new(:name => 'Kevin') test_user2.save() expect(User.all()).to(eq([test_user, test_user2])) end end describe("#id") do it "will return the users id" do test_user = User.new(:name => 'John') test_user.save() expect(test_user.id_user()).to(eq(1)) end end describe(".find") do it "will find the users by id" do test_user = User.new(:name => 'John') test_user.save() test_user2 = User.new(:name => 'Kevin') test_user2.save() expect(User.find(test_user.id_user())).to(eq(test_user)) end end describe("#add_contact") do it "will add contact to user" do test_user = User.new(:name => "Ron") test_user.save() contact = Contact.new(:name => "Logan") expect(test_user.add_contact(contact)).to(eq([contact])) end end end
true
d8cdd2c5907b07704ade22d8d3d7ad88d89b4b00
Ruby
smarbaf/2airport-challenge
/spec/airport_spec.rb
UTF-8
893
3.078125
3
[]
no_license
require 'airport' ## Note these are just some guidelines! ## Feel free to write more tests!! # A plane currently in the airport can be requested to take off. # # No more planes can be added to the airport, if it's full. # It is up to you how many planes can land in the airport # and how that is implemented. # # If the airport is full then no planes can land describe Airport do it 'should accept a plane once landed' do airport = Airport.new # plane = double(:plane) plane = Plane.new airport.land(plane) allow(plane).to receive(:flying=).with(false) expect(airport.count_planes).to eq(1) end it 'should release a plane' do airport = Airport.new # plane = double(:plane) plane = Plane.new # airport.land(plane) allow(plane).to receive(:flying=).with(false) airport.release(plane) expect(airport.count_planes).to eq(0) end end
true
ee9d14c96953dc0f2e24b021702413df7a3d8f93
Ruby
leoprananta/ruby-basic-syntax
/logic.rb
UTF-8
218
3.265625
3
[]
no_license
#logic || boolean == "saya" == "anda" -> false != "saya" != "anda" -> true > , >= 3 >= 2 -> false < , <= 3 <= 2 -> false && 1==1 && 2==3 true && false -> false || 1==1 || 2==3 true || false -> true
true
8195c0f5430dea553920342c912235df5e9f33be
Ruby
gwright/acts_as_bitemporal
/test/acts_as_bitemporal/range_test.rb
UTF-8
5,636
2.75
3
[ "MIT" ]
permissive
# encodsng: utf-8 require 'test_helper' class ActsAsBitemporal::RangeTest < ActiveSupport::TestCase ARange = ActsAsBitemporal::Range RangeCases = [ # expected, start, end, visual [false, 6, 7], # ---o -o [false, 5, 6], # ---o-o [false, 4, 5], # ---*o [true, 3, 4], # --=O [true, 2, 3], # -=*o [true, 1, 2], # =*-o [false, 0, 1], # -*--o [false, -1, 0], # -o---o [false, -1, -2], # -o ---o [true, 1, 5], # -==*o [true, 1, 4], # ===O [true, 0, 3], # -==*o [true, 0, 4], # -===O [true, 1, 5], # ===*o [true, 0, 5], # -===*o ] def test_with_integer_range first_range = ARange.new(1,4) RangeCases.each do |expected, b, e| assert_equal expected, first_range.intersects?(b...e), "1...4 vs #{b}...#{e}" assert_equal !expected, first_range.disjoint?(b...e), "1...4 vs #{b}...#{e}" end end def test_with_integer_arange first_range = ARange.new(1,4) RangeCases.each do |expected, b, e| assert_equal expected, first_range.intersects?(ARange.new(b, e)), "1...4 vs #{b}...#{e}" assert_equal !expected, first_range.disjoint?(ARange.new(b, e)), "1...4 vs #{b}...#{e}" end end def test_with_integer_range_two_args first_range = ARange.new(1,4) RangeCases.each do |expected, b, e| assert_equal expected, first_range.intersects?(b, e), "1...4 vs #{b}...#{e}" assert_equal !expected, first_range.disjoint?(b, e), "1...4 vs #{b}...#{e}" end end def test_with_date_arange base_date = Time.zone.now d1_range = ARange.new((base_date+1), (base_date+4)) RangeCases.each do |expected, b, e| d2_range = ARange.new(base_date+b, base_date+e) assert_equal expected, d1_range.intersects?(d2_range), "#{d1_range} vs #{b}...#{e}" assert_equal !expected, d1_range.disjoint?(d2_range), "#{d1_range} vs #{b}...#{e}" end end EventRangeCases = [ # expected, start, end, visual [false, 6], # ---o -o [false, 5], # ---o-o [false, 4], # ---*o [true, 3], # --=O [true, 2], # -=*o [true, 1], # =*-o [false, 0], # -*--o [false, -1], # -o---o [false, -1], # -o ---o ] def test_with_integer_event first_range = ARange.new(1,4) EventRangeCases.each do |expected, event| assert_equal expected, first_range.intersects?(event), "#{first_range} vs #{event}" assert_equal !expected, first_range.disjoint?(event), "#{first_range} vs #{event}" end end def test_with_time_event base_date = Time.zone.now first_range = ARange.new(base_date + 1, base_date + 4) EventRangeCases.each do |expected, event| event = base_date + event assert_equal expected, first_range.intersects?(event), "#{first_range} vs #{event}" assert_equal !expected, first_range.disjoint?(event), "#{first_range} vs #{event}" end end def test_with_invalid_argument assert_raises ArgumentError do ARange.new(1,4).intersects?(Object.new) end assert_raises ArgumentError do ARange.new(1,4).intersects?(Date.today, Date.today + 1) end end def test_convenience_construction assert_equal ARange.new(1,4), ARange[1,4] end CoverCases = [ # Exepected First Second [true, 1, 2, 1, 2], [true, 1, 10, 1, 2], [true, 1, 10, 2, 4], [true, 1, 10, 8, 10], [false, 1, 10, 8, 15], [false, 1, 10, 0, 2], ] def test_cover CoverCases.each do |expected, a_start, a_end, b_start, b_end| assert_equal expected, ARange[a_start, a_end].covers?(b_start, b_end) assert_equal expected, ARange[a_start, a_end].covers?(ARange[b_start, b_end]) assert_equal expected, ARange[a_start, a_end].covers?(b_start...b_end) end end XorCases = [ # First Second Expected Result [ [10,20], [0,15], [[0,10], [15,20] ]], [ [10,20], [10,15], [[15,20] ]], [ [10,20], [12,15], [[10,12], [15,20] ]], [ [10,20], [15,20], [[10,15] ]], [ [10,20], [15,25], [[10,15], [20,25] ]], [ [10,20], [20,25], [[10,20], [20,25] ]], ] def test_xor XorCases.each do |first, second, result| assert_equal(result.map { |pair| ARange[*pair] }, ARange[*first].xor(*second)) end end MeetsCases = [ # First Second Expected Result [ [10,20], [0,15], false], [ [10,20], [0,10], true], [ [10,20], [10,15], false], [ [10,20], [10,20], false], [ [10,20], [15,20], false], [ [10,20], [15,25], false], [ [10,20], [20,25], true] ] def test_meets MeetsCases.each do |first, second, expected| assert_equal(expected, ARange[*first].meets?(*second)) end end def test_infinity now = Time.zone.now range = ARange[now, 'infinity'] assert range.include?(now) assert range.include?(now + 1.day) assert range.include?(now + 1_000.days) assert range.include?(now + 1_000_000.days) assert !range.include?(now - 1.day) assert !range.include?(now - 1_000.days) end def test_negative_infinity now = Time.zone.now range = ARange['-infinity', now] assert !range.include?(now) assert !range.include?(now + 1.day) assert !range.include?(now + 1_000.days) assert !range.include?(now + 350_000.days) assert range.include?(now - 1.day) assert range.include?(now - 1_000.days) assert range.include?(now - 350_000.days) end end
true
d9b8f7e2eece0f4ae9ccf564a644729d45a6de9e
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/800/feature_try/method_source/24054.rb
UTF-8
325
3.265625
3
[]
no_license
def combine_anagrams(words = []) uniq_alphabetized_words = alphabetize(words) grouped_anagrams = [] uniq_alphabetized_words.each do |uaw| group = [] words.each do |w| (group << w) if (w.downcase.split("").sort.join == uaw) (grouped_anagrams << group) end end return grouped_anagrams.uniq end
true
b03a2bb94deb540a825e09c784f97b1ee4c9fe59
Ruby
coreymartella/project_euler
/p030.rb
UTF-8
537
3.765625
4
[]
no_license
load 'common.rb' def p30(n=5) (2..10**(n+1)-1).reduce(0) do |r,i| r + (i.to_s.chars.reduce(0){|s,d| s + d.to_i**5} == i ? i : 0) end end # Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: # 1634 = 14 + 64 + 34 + 44 # 8208 = 84 + 24 + 04 + 84 # 9474 = 94 + 44 + 74 + 44 # As 1 = 14 is not a sum it is not included. # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
true
3077819478068a2f5cb8ed2fd0d8529662ac7c30
Ruby
ganmacs/playground
/ruby/sinatra_test/utils/loader.rb
UTF-8
386
2.640625
3
[]
no_license
module Utils class Loader def initialize(klass, file_path = '') @klass = Models.const_get(klass) @file_path = file_path end def all @all ||= load_file.map do |o| @klass.new(o) end end def find(&block) all.find(&block) end private def load_file @load_file ||= YAML.load_file(@file_path) end end end
true
3f1e0f85db928741cbae4ae3f4821d895dfc5ba0
Ruby
bfagundez/rubygoalcoach
/martiancoach.rb
UTF-8
8,325
3.015625
3
[]
no_license
# RubyGoal - Fútbol para Rubistas # # Este documento contiene varias implementaciones mínimas de un entrenador de RubyGoal.# # # Esta clase debe implementar, como mínimo, los métodos `name` y `formation(match)` # Esta clase debe ser implementada dentro del módulo Rubygoal module Rubygoal class Martiancoach < Coach # Indica el nombre del equipo # Debe retornar un string def name "Martians FC" end def formation(match) formation = Formation.new # # ------------------------------ # | N N N N N | # | | # | N N N N N | # A | | A # R | N N N N N | R # C | | C # O | N N N N N | O # | | # | N N N N N | # ------------------------------ # # Los tipos de jugadores válidos son :average, :fast, :captain # Restricciones: # Exactamente un :captain # Exactamente tres :fast # Exactamente seis :average # :captain -> Este jugador es el más rápido y preciso del equipo # :fast -> Estos jugadores son más rápidos que los demás (aunque más lentos que # el capitán del equipo) # :average -> Estos jugadores completan el equipo # #formation.defenders = [:none, :average, :average, :average, :none] #formation.midfielders = [:average, :fast, :none, :none, :average] #formation.attackers = [:none, :fast, :captain, :fast, :average] baselineup = [ [:none, :average, :none, :none, :none ], [:average, :none, :none, :average, :fast ], [:none, :none, :captain, :none, :fast ], [:average, :none, :none, :average, :none ], [:none, :average, :none, :none, :fast ], ] aggressive = [ [:none, :none, :average, :none, :none ], [:average, :none, :none, :average, :fast ], [:none, :none, :none, :captain, :fast ], [:average, :none, :none, :average, :none ], [:none, :none, :average, :none, :fast ], ] conservative = [ [:none, :average, :none, :fast, :none ], [:average, :none, :none, :none, :average], [:none, :none, :captain, :fast, :none ], [:average, :none, :none, :none, :average ], [:none, :average, :none, :fast, :none ], ] uruguayan = [ [:average, :average, :none, :none, :none ], [:average, :fast, :none, :none, :none ], [:fast, :captain, :none, :none, :none ], [:average, :fast, :none, :none, :none ], [:average, :average, :none, :none, :none ], ] formation.lineup = baselineup # me.winning? indica si estoy ganando # me.losing? y me.draw? son análogos al anterior :) # me.score me indica la cantidad exacta de goles que marcó mi equipo if match.me.winning? formation.lineup = aggressive end if match.me.draw? formation.lineup = conservative end if match.me.winning? and ( match.time < 20 ) formation.lineup = uruguayan end if match.me.losing? formation.lineup = baselineup end if match.me.losing? and ( match.me.score - match.other.score ) == 1 formation.lineup = baselineup end if match.me.losing? and ( match.me.score - match.other.score ) > 2 formation.lineup = aggressive end # if match.me.winning? and ( match.other.score - match.me.score ) > 2 # formation.lineup = uruguayan # end # elsif match.time < 10 # formation.defenders = [:none, :average, :average, :average, :none] # formation.midfielders = [:average, :average, :captain, :none, :average] # formation.attackers = [:fast, :fast, :none, :fast, :average] # else # # # # El método `other` devuelve información básica del rival. Tiene los mismos # # métodos que `me`. # # # # En particular, se puede acceder a la formación definida por el equipo # # contrario. En la siguiente linea, a modo de ejemplo, se estableció # # una táctica `espejo` con respecto al rival (posiciono mis jugadores en forma # # simétrica) # formation.lineup = match.other.formation.lineup # end formation end end # Lo siguiente es otra implementación posible de una instancia de Coach # class AnotherCoach < Coach # def name # "Maeso FC" # end # # El método formation debe devolver una instancia de Formation # # El siguiten ejemplo muestra como controlar la posición de los jugadores # # de una forma más fina, usando el método `lineup` # # # def formation(match) # formation = Formation.new # # Por defecto el valor de formation.lineup es # # # # [ # # [:none, :none, :none, :none, :none], # # [:none, :none, :none, :none, :none], # # [:none, :none, :none, :none, :none], # # [:none, :none, :none, :none, :none], # # [:none, :none, :none, :none, :none], # # ] # # # # Este valor DEBE sobreescribirse con una formación que incluya las # # cantidades correctas de :average, :fast y :captain # # # # Para este tipo de estrategias es importante siempre considerar que el arco # # que atacas es el de la derecha. # # # # En el siguiente ejemplo, la formación 4322 puede interpretarse # # de la siguiente manera # # | | # # defensa | medio campo | delantera # # [ | | # # [ :average, | :none, :average, :none, | :none ], # # [ :fast, | :none, :none, :average, | :none ], # # [ :none, | :none, :captain, :none, | :fast ], # # [ :fast, | :none, :none, :average, | :average ], # # [ :average, | :none, :average, :none, | :none ], # # ] | | # # | | # # # # Usando `lineup`, la línea mas defensiva son los primeros elementos de # # cada uno de los arrays (:average, :fast, :none, :fast, :average) # # # # La segunda línea (entre la defensa y los mediocampistas) no tiene jugadores # # (son todos :none) # # # # La tercer línea, la que corresponde a los mediocampistas, son el tercer # # elemento de cada array (:average, :none, :captain, :none, :average) # # # # La cuarta línea está ubicada entre los mediocampistas y delanteros # # (:none, :average, :none, :average, :none) # # # # Los últimos elementos de los arrays corresponden a la línea de # # delanteros (:none, :none, :fast, :average, :none) # formation.lineup = [ # [:average, :none, :average, :none, :none], # [:fast, :none, :none, :average, :none], # [:none, :none, :captain, :none, :fast], # [:fast, :none, :none, :average, :average], # [:average, :none, :average, :none, :none], # ] # formation # end # end # Otra implementación posible de una instancia de Coach # Gran parte de la gracia de este juego está en hacer cambios en la formación # a medida que va transcurriendo el partido # # La instancia de `match` que recibe el método `formation` contiene información # sobre el partido y el rival de turno # # Veamos un ejemplo # class MyCoach < Coach # def name # "Villa Pancha" # end # def formation(match) # formation = Formation.new # formation # end # end end
true
256b4343d09c5aeeea217a93404a9bd9739196f1
Ruby
m-lowen/-matthew-lowen-m-lowen-
/exercises/d3/exercises/fizzbuzz.rb
UTF-8
157
3.046875
3
[]
no_license
i = 1 while i <=100 if (i%3==0 && i%5==0) puts "fizzbuzz" elsif i%3==0 puts "fizz" elsif i%5==0 puts "buzz" else puts i end i +=1 end
true
0626b0bfd39edf9b180e2befdf034a6ca7f9bca3
Ruby
eddie/benji
/server.rb
UTF-8
1,579
2.859375
3
[]
no_license
require 'em-websocket' require 'json' client_count = 0 browsers = [] def handle_command(data,command,&block) begin parsed_data = JSON.parse(data) if parsed_data["command"] == command yield parsed_data if block.arity > 0 end puts parsed_data rescue puts 'JSON malformed:',$1 end end EventMachine.run { EventMachine::WebSocket.start(:host => "127.0.0.1", :port => 8080) do |ws| ws.onopen do client_count = client_count + 1 end ws.onclose do client_count = client_count - 1 if client_count > 0 end ws.onmessage do |msg| handle_command msg,'get_visitors' do |params| ws.send JSON.generate({ :command=>'visitors', :data=>{ :time=>Time.now.to_i, :visitors=>client_count.to_s } }); end handle_command msg,'set_browser' do |params| browsers.push({ :id=>params["id"], :name=>params["browser"], :time=>params["time"] }) end handle_command msg,'get_browsers' do |params| browser_count = browsers.group_by{|browser| browser[:name]}.map{|browser,value| {:browser=>browser,:users=>value.length} } ws.send JSON.generate({ :command=>'get_browsers', :data=>JSON.generate(browser_count) }); end handle_command msg,'byebye' do |params| client = params[:id] index = browsers.index{|browser| browser["id"] == client} browsers.delete_at(index) end end end }
true
8fb2d426bca94196e866675bae83fd04ec8faeae
Ruby
jockofcode/NetworkService
/bin/network_server.rb
UTF-8
3,517
2.59375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#!/usr/bin/env ruby require 'rubygems' require 'time' require 'digest/md5' require 'base64' require 'eventmachine' require 'network_message' require 'http_message' require 'gzip' if ARGV.length == 0 then port = 8888 else port = ARGV[0].to_i if port == 0 then port = 8888 end #should probably test for < 1024 end STDOUT.sync = true $interface = [] $clients = [] class String def to_base27 text=self; alph=[];('a'..'z').each_with_index{|c,i| alph<<c }; result = "" text.split(//).each{|c|i = c[0]; while i != 0 tmp_result = "" r = i%27 print alph[r] tmp_result += alph[r] i = i/27 end puts result += (tmp_result.ljust(4,"a")) } end end module NetworkServer MessageTypes = "GET|HEAD|POST|DELETE|PUT|TRACE|OPTIONS|CONNECT|RUN|SET_VAR|GET_VAR" def post_init puts "post_init called" #send_data "welcome to my custom server\n" @data = '' end def send_data(data,unprocessed = false) if unprocessed then super(data) else super(NetworkMessage.encode(data)) end end def receive_data(incomming_data) @data << incomming_data Thread.new{ #puts "\tpre_process buffer is: #{@data.gsub("\n",'\n').gsub("\r",'\r')}" while NetworkMessage::decode(@data) || HttpMessage::decode(@data) if HttpMessage::is_message?(@data) then @data,http_message = HttpMessage::decode(@data) puts http_message.to_yaml if HttpMessage::is_request?(http_message.options["id"]) then request_type,resource,args = http_message.request_info case request_type.upcase when "GET" puts "getting #{resource}" if File.file?(resource) then response = HttpMessage.encode(File.read(resource),"id" => "HTTP/1.1 200 OK","Content-Encoding" => "gzip","Content-MD5" => "","Last-Modified" => File.mtime(resource).httpdate,"Expires" => (Time.now + 3600).httpdate,"Cache-Control" => "max-age") elsif File.file?(resource + ".cgi") then response = HttpMessage.encode(`#{resource + ".cgi"} "#{args.join("&")}"`,"id" => "HTTP/1.1 200 OK","Content-Encoding" => "gzip","Content-MD5" => "","Last-Modified" => Time.now.httpdate,"Expires" => (Time.now + 3600).httpdate,"Cache-Control" => "max-age") elsif File.file?("404.html") response = HttpMessage.encode(File.read("404.html"),"id" => "HTTP/1.1 404 OK","Content-Encoding" => "gzip","Content-MD5" => "","Last-Modified" => File.mtime("404.html").httpdate,"Expires" => (Time.now + 3600).httpdate,"Cache-Control" => "max-age") else response = HttpMessage.encode("Yeah, hmmm, wow, really dropped the ball here, not even a 404 page, gadzukes","id" => "HTTP/1.1 404 OK","Content-Encoding" => "gzip","Content-MD5" => "","Last-Modified" => Time.now.httpdate,"Expires" => (Time.now + 3600).httpdate,"Cache-Control" => "max-age") end send_data(response,true) else response = HttpMessage.encode("<HTML><HEAD><TITLE>404</TITLE></HEAD><BODY><H1>Niner Niner, thats a Four Oh Four</H1><BR><H5>the request of #{request_type} is not supported</H5></BODY></HTML>","id" => "HTTP/1.1 404 OK","Content-Encoding" => "gzip") send_data(response,true) end end else message,@data = NetworkMessage::decode(@data) puts "message decoded to: #{message}" puts " : #{message.split(//).collect{|c| c[0].to_s }.join(",")}" end end #@data = @data.gsub(/^[^0-9]*(.*)$/m,"\\1") puts "\tbuffer is: #{@data.gsub("\n",'\n').gsub("\r",'\r')}" } end end EM.run{ EM.start_server('0.0.0.0',port,NetworkServer) }
true
5971e6d200fdd3ade9337b3601b3445ae959203b
Ruby
l-jdavies/ruby_small_problems
/ruby_foundations_problems/medium_2/test_prompt_for_payment_method_transaction.rb
UTF-8
524
3
3
[]
no_license
# Write a test that verifies that Transaction#prompt_for_payment sets the amount_paid correctly. require 'stringio' require 'minitest/autorun' require_relative 'cash_register' require_relative 'transaction' class TestCashRegister < MiniTest::Test def setup @register = CashRegister.new(100) @transaction = Transaction.new(50) end def test_prompt_for_payment amount = StringIO.new("60\n") @transaction.prompt_for_payment(input: amount) assert_equal(60, @transaction.amount_paid) end end
true
66a08fe27661144c92f5d7542c1adb7d250d3d85
Ruby
satoshi-takano/hataraki
/app/models/guest.rb
UTF-8
770
2.609375
3
[]
no_license
# coding: utf-8 class Guest < ActiveRecord::Base belongs_to :user attr_accessible :login_id, :login_password, :user_id, :memo validates_presence_of :login_id, :login_password, :user_id, :message=>"は入力が必須です" validates_format_of :login_id, :with=> /^[0-9A-Za-z]/, :message=>"は半角英数字で入力してください" validates_format_of :login_password, :with=> /^[0-9A-Za-z]/, :message=>"は半角英数字で入力してください" validates_numericality_of :user_id validates_length_of :login_id, :in => 1..32, :message=>"は32字以下で入力してください" validates_length_of :login_password, :in => 6..32, :message=>"は6〜32字で入力してください" validates :memo, :length => { :maximum => 140} end
true
4e67a6804c33e04f635c780adce66d1ab571513e
Ruby
aerodame/sampler
/Algorithms/PairsSearch/Ruby/main.rb
UTF-8
590
3.546875
4
[]
no_license
# https://github.com/aerodame/sampler require './pairs_search' puts "ENTER number of integers to pair[3-100]:" n=gets.chomp.to_i if (n < 3) || (n > 100) puts "Illegal number of values" abort end puts "ENTER sum value to search[4-200]:" k=gets.chomp.to_i if (k < 4) || (k > 200) puts "Illegal sum value" abort end p = PairsSearch.new(n) # might get nil from no matches, so catch that error if it occurs begin puts "Result: #{p.report(k).size} sums found" p.report(k).each do |x| puts "(#{x})" end rescue puts "no matches found" end
true
858b7d29650e4ebcc651397928f106448ad5b191
Ruby
lastobelus/rudelo
/lib/rudelo/parsers/set_value_parser.rb
UTF-8
1,798
2.84375
3
[ "MIT" ]
permissive
require 'parslet' module Rudelo module Parsers module Space include Parslet rule(:space) { match["\t "].repeat(1) } rule(:space?) { space.maybe } def spaced_op(s) space >> str(s).as(:op) >> space end def spaced_op?(s, protect=nil) if protect # this is necessary when some ops are substrings of # other ops. if you have '>' and '>=', use # spaced_op?('>', '=') for '>' space? >> str(protect).absent? >> str(s).as(:op) >> space? >> str(protect).absent? else space? >> str(s).as(:op) >> space? end end end module Set include Parslet rule(:comma) { str(',') } rule(:comma?) { str(',').maybe } rule(:quote) { match '"' } rule(:open_set) { str('$(') } rule(:close_set) { str(')') } rule(:unquoted_element) { (close_set.absent? >> comma.absent? >> any). repeat(1).as(:element) } rule(:quoted_element) { (quote >> (quote.absent? >> any).repeat. as(:element) >> quote)} rule(:element) { quoted_element | unquoted_element } rule(:element_delimiter) { (comma) >> space? } rule(:bare_element_list) { (element >> (element_delimiter >> element).repeat). as(:element_list) } rule(:explicit_set) { open_set >> space? >> bare_element_list >> space? >> close_set } end class SetValueParser < Parslet::Parser include Space include Set rule(:set_value) { explicit_set | bare_element_list } root(:set_value) end end end
true
eca746efe9b3247822273864296bbb07038e2556
Ruby
rinapratama335/belajar-ruby
/1.Dasar Banget/11.upto_dan_downto.rb
UTF-8
140
3.046875
3
[]
no_license
5.upto(10).each do |no| puts "Perulangan naik ke-#{no}" end puts puts 10.downto(3).each do |x| puts "Perulangan turun ke-#{x}" end
true
f962f2b39e062ccd66ced0966eb3e1d1d7ac236f
Ruby
tcopeland/occams-record
/lib/occams-record/query.rb
UTF-8
3,840
2.84375
3
[]
no_license
require 'occams-record/batches' module OccamsRecord # # Starts building a OccamsRecord::Query. Pass it a scope from any of ActiveRecord's query builder # methods or associations. If you want to eager loaded associations, do NOT us ActiveRecord for it. # Instead, use OccamsRecord::Query#eager_load. Finally, call `run` to run the query and get back an # array of objects. # # results = OccamsRecord. # query(Widget.order("name")). # eager_load(:category). # eager_load(:order_items, ->(q) { q.select("widget_id, order_id") }) { # eager_load(:orders) { # eager_load(:customer, ->(q) { q.select("name") }) # } # }. # run # # @param query [ActiveRecord::Relation] # @param use [Module] optional Module to include in the result class # @param query_logger [Array] (optional) an array into which all queries will be inserted for logging/debug purposes # @return [OccamsRecord::Query] # def self.query(scope, use: nil, query_logger: nil) Query.new(scope, use: use, query_logger: query_logger) end # # Represents a query to be run and eager associations to be loaded. Use OccamsRecord.query to create your queries # instead of instantiating objects directly. # class Query # @return [ActiveRecord::Base] attr_reader :model # @return [ActiveRecord::Relation] scope for building the main SQL query attr_reader :scope # @return [ActiveRecord::Connection] attr_reader :conn include Batches # # Initialize a new query. # # @param scope [ActiveRecord::Relation] # @param use [Module] optional Module to include in the result class # @param query_logger [Array] (optional) an array into which all queries will be inserted for logging/debug purposes # @param eager_loaders [OccamsRecord::EagerLoaders::Base] # @param eval_block [Proc] block that will be eval'd on this instance. Can be used for eager loading. (optional) # def initialize(scope, use: nil, query_logger: nil, eager_loaders: [], &eval_block) @model = scope.klass @scope = scope @eager_loaders = eager_loaders @conn = model.connection @use = use @query_logger = query_logger instance_eval(&eval_block) if eval_block end # # Specify an association to be eager-loaded. You may optionally pass a block that accepts a scope # which you may modify to customize the query. For maximum memory savings, always `select` only # the colums you actually need. # # @param assoc [Symbol] name of association # @param scope [Proc] a scope to apply to the query (optional) # @param use [Module] optional Module to include in the result class # @param eval_block [Proc] a block where you may perform eager loading on *this* association (optional) # @return [OccamsRecord::Query] returns self # def eager_load(assoc, scope = nil, use: nil, &eval_block) ref = model.reflections[assoc.to_s] raise "OccamsRecord: No assocation `:#{assoc}` on `#{model.name}`" if ref.nil? @eager_loaders << EagerLoaders.fetch!(ref).new(ref, scope, use, &eval_block) self end # # Run the query and return the results. # # @return [Array<OccamsRecord::ResultRow>] # def run sql = scope.to_sql @query_logger << sql if @query_logger result = conn.exec_query sql row_class = OccamsRecord.build_result_row_class(model, result.columns, @eager_loaders.map(&:name), @use) rows = result.rows.map { |row| row_class.new row } @eager_loaders.each { |loader| loader.query(rows) { |scope| assoc_rows = Query.new(scope, use: loader.use, query_logger: @query_logger, &loader.eval_block).run loader.merge! assoc_rows, rows } } rows end end end
true