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
676732f39826403c66f0d0ab84335b8e1432bf27
Ruby
ippei94da/gitan
/bin/gitan
UTF-8
3,955
3.171875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#! /usr/bin/env ruby # coding: utf-8 #gitan heads # Show hash value of every git repository. # #gitan status # Show status of every git working trees. # You should confirm the command 'git rev-parse FETCH_HEAD' # shows a hash value. # If not, you should execute 'git pull' # #gitan commit # Commit every working tree that has changes to be be commited. # #gitan push # Commit every working tree that has changes to be pushed. # #gitan pull # Pull every working tree that has updates on remote repository. require "optparse" require "yaml" require "pp" require "gitan" def show_usage puts <<-HERE USAGE gitan heads [path] gitan status [path] [--argument=str] [-r remote_dir] gitan commit [path] [--argument=str] gitan push [path] [--argument=str] gitan pull [path] [--argument=str] [-r remote_dir] Default value of 'path' is ~/git. Examples: gitan heads /home/git gitan status -r example.com:/home/git --argument="-s" gitan commit --argument='-am "commit message"' gitan push -a "origin master" gitan pull ~/git -r example.com:/home/git -a "origin master" HERE end def add_remote_option OPTION_PARSER.on("-r remote_dir", "--remote=dir", "with remote info"){ |remote_dir| server, path = remote_dir.split(":") OPTIONS[:remote] = Gitan.remote_heads(server, path) } end def add_argument_option OPTION_PARSER.on("-a str", "--arguments=str", "supply argument to command"){ |str| OPTIONS[:argument] = str } end def repositories(remote_heads = {}) git_dir = ENV["HOME"] + "/git" git_dir = File::expand_path(ARGV[0]) if ARGV[0] dirs = Dir.glob(git_dir + "/*").sort.map do |path| if File.directory? path remote_head = nil remote_head = OPTIONS[:remote][File.basename(path)] if OPTIONS[:remote] Gitan::Repo.new(path, remote_head) else nil end end dirs.select{|dir| dir} end def execute(path, command) print "#{path}: " Dir.chdir path puts command system command unless OPTIONS[:debug] end def status add_remote_option add_argument_option OPTION_PARSER.on("-A", "--all", "show all repositories."){ OPTIONS[:all] = true} OPTION_PARSER.on("-e", "--explain", "show explanation for abbreviation."){ OPTIONS[:explain] = true} OPTION_PARSER.parse!(ARGV) repos = repositories unless OPTIONS[:all] repos = repos.select do |repo| result = false result = true if repo.multiple_branch? result = true if repo.to_be_staged? result = true if repo.to_be_commited? result = true if repo.to_be_pushed? result = true if (OPTIONS[:remote] && repo.to_be_pulled?) result end end Gitan::Repo.show_abbreviation if OPTIONS[:explain] repos.each do |repo| puts repo.short_status #pp OPTION if OPTIONS[:argument] execute(repo.path, "git status #{OPTIONS[:argument]}") end end end def heads results = {} repositories.each do |repo| results[repo.path] = repo.head end YAML.dump(results, $stdout) end def commit add_argument_option OPTION_PARSER.parse!(ARGV) repositories.select {|repo| repo.to_be_commited?}.each do |repo| execute(repo.path, "git commit #{OPTIONS[:argument]}") end end def push add_argument_option OPTION_PARSER.parse!(ARGV) repositories.select {|repo| repo.to_be_pushed?}.each do |repo| execute(repo.path, "git push #{OPTIONS[:argument]}") end end def pull add_remote_option add_argument_option OPTION_PARSER.parse!(ARGV) repositories.select {|repo| repo.to_be_pulled?}.each do |repo| execute(repo.path, "git pull #{OPTIONS[:argument]}") end end ##main OPTIONS = {} OPTION_PARSER = OptionParser.new OPTION_PARSER.on("-d", "--debug", "debug mode."){OPTIONS[:debug] = true} command = ARGV.shift case command when "status" status when "heads" heads when "commit" commit when "push" push when "pull" pull when "--help" show_usage else puts "Unknown command: #{command}" show_usage end
true
132a65c7a183833d95f039b300261f6f109c4846
Ruby
wachin/Windows-WachiManuales
/Sketchup/Google_Sketchup/Plugins/Ruby_Scripts_de_sketchup.google.com/Windows_Tools/WindowTools/trim_tool.rb
UTF-8
1,268
2.921875
3
[]
no_license
=begin # Author tomot # Name: TrimTool # Description: Create a simple Exterior or Interior Window, Trim # Usage: click 3 points, on an EXISTING OPENING, creates a Window Trim # Date: 2008,09,17 # Type: Tool # Revised: 2008,09,20 Thanks to Jim Foltz for showing me how to Write methods in a way that they are re-usable #-------------------------------------------------------------------------------------------------------------------- =end require 'sketchup.rb' require 'windowtools/3PointTool' require 'windowtools/draw_trim' module WindowTools class TrimTool < ThreePointTool def initialize super # calls the initialize method in the ThreePointTool class # sets the default Window settings @etthick = 1.inch if not @etthick @etwidth = 4.inch if not @etwidth # Dialog box prompts = ["Exterior Trim Thickness ", "Exterior Trim Width"] values = [@etthick, @etwidth] results = inputbox prompts, values, "Window - Exterior Trim parameters" return if not results @etthick, @etwidth = results end def create_geometry WindowTools.draw_trim( @etthick, @etwidth, @pts ) reset end end # class TrimTool end
true
ae9a91fc7a0eff537a4c9697c85fda9bcf039507
Ruby
shibayu36/algorithms
/ruby/lib/hackerrank/one-week-again/palindrome-index.rb
UTF-8
781
3.390625
3
[]
no_license
#!/bin/ruby require 'json' require 'stringio' # # Complete the 'palindromeIndex' function below. # # The function is expected to return an INTEGER. # The function accepts STRING s as parameter. # def palindromeIndex(s) left = 0 right = s.length - 1 while left < right if s[left] == s[right] left += 1 right -= 1 next end if palindrome?(s[left + 1..right]) return left elsif palindrome?(s[left..right - 1]) return right else return -1 end end -1 end def palindrome?(s) s == s.reverse end # fptr = File.open(ENV.fetch('OUTPUT_PATH', nil), 'w') fptr = $stdout q = gets.strip.to_i q.times do |_q_itr| s = gets.chomp result = palindromeIndex s fptr.write result fptr.write "\n" end fptr.close
true
0c20480d9d912f75096117d3da8d1cf5a20e2571
Ruby
Overload119/active_record_uuid
/lib/active_record_uuid/extensions/association_methods.rb
UTF-8
1,606
2.546875
3
[ "MIT" ]
permissive
module ActiveRecordUuid module AssociationMethods def has_many(name, options = {}, &extension) options = uuid_assoc_options(:has_many, name, options) super end def has_one(name, options = {}) options = uuid_assoc_options(:has_one, name, options) super end def belongs_to(name, options = {}) options = uuid_assoc_options(:belongs_to, name, options) super end def has_and_belongs_to_many(name, options = {}, &extension) options = uuid_assoc_options(:has_and_belongs_to_many, name, options) super end private def uuid_assoc_options(macro, association_name, options) opts = {} # Set class_name only if not a has-through relation or poly relation if options[:through].blank? and options[:as].blank? and options[:class_name].blank? and !self.name.match(/::/) opts[:class_name] = "::#{association_name.to_s.singularize.camelize}" end # Set foreign_key only if not passed if options[:foreign_key].blank? case macro when :has_many, :has_one opts[:foreign_key] = uuid_foreign_key(self.name) when :belongs_to opts[:foreign_key] = uuid_foreign_key(association_name) when :has_and_belongs_to_many opts[:foreign_key] = uuid_foreign_key(self.name) opts[:association_foreign_key] = uuid_foreign_key(association_name) end end options.merge(opts) end def uuid_foreign_key(name) name.to_s.singularize.underscore.downcase + "_uuid" end end end
true
5e23a6e9bdd27db8fe5b382c3a5782981bf84328
Ruby
kristjan/adventofcode
/2017/4/valid.rb
UTF-8
147
2.890625
3
[]
no_license
phrases = File.readlines(ARGV[0]).map(&:strip) count = phrases.count do|p| words = p.split(' ') words.size == words.uniq.size end puts count
true
d24acb843720e554541464cd3f59842ab9c8f464
Ruby
sunsplat/tree_trie_tro_trum
/lib/letter_node.rb
UTF-8
301
3.109375
3
[]
no_license
Letter = Struct.new(:letter, :definition, :children, :parent, :depth) class LetterNode attr_accessor :letter, :definition, :children, :parent, :depth def new(word) @node = Letter.new @node.letter(word) @node.definition @node.children @node.parent @node.depth return @node end end
true
980223db9beb13c8aa5702b6b377c1a2e9e5f3b8
Ruby
yaozhen1979/RubyCookbook
/src/file/simple_write_file.rb
UTF-8
101
2.953125
3
[]
no_license
# open and write to a file with ruby open('myfile.out', 'w') { |f| f.puts "Hello, world !!!" }
true
ea8e8b6152bf956721024dadeb7a1c70bfacf1aa
Ruby
dmktel/ruby_basics
/part9/pass_train.rb
UTF-8
265
3.015625
3
[]
no_license
class PassTrain < Train def initialize(number) super(number, :pass) end def add_wagon(wagon) if wagon.instance_of?(PassWagon) super(wagon) else puts 'To passenger trains it is possible to add only passenger wagons!' end end end
true
03e485ae988205761d66c48e12426257e271c1f9
Ruby
sekharvajjhala/apisonator
/lib/3scale/backend/analytics/kinesis/adapter.rb
UTF-8
7,367
2.828125
3
[ "Apache-2.0", "LGPL-2.0-or-later", "BSD-3-Clause", "MIT", "Ruby", "BSD-2-Clause", "GPL-2.0-or-later", "Python-2.0", "Artistic-2.0" ]
permissive
require '3scale/backend/logging' module ThreeScale module Backend module Analytics module Kinesis class Adapter # Each Kinesis record is rounded to the nearest 5KB to calculate the # cost. Each of our events is a hash with a few keys: service, # metric, period, time, value, etc. This means that the size of one # of our events is nowhere near 5KB. For that reason, we need to make # sure that we send many events in each record. # The max size for each record is 1000KB. In each record batch, Kinesis # accepts a maximum of 4MB. # # We will try to optimize the batching process later. For now, I will # just put 1000 events in each record. And batches of 5 records max. # # When we receive a number of events not big enough to fill a record, # those events are marked as pending events. # Kinesis can return errors, when that happens, the events of the # records that failed are re-enqueued as pending events. # The list of pending events is stored in Redis, so we do not fail to # process any events in case of downtime or errors. include Logging EVENTS_PER_RECORD = 1000 private_constant :EVENTS_PER_RECORD MAX_RECORDS_PER_BATCH = 5 private_constant :MAX_RECORDS_PER_BATCH EVENTS_PER_BATCH = EVENTS_PER_RECORD*MAX_RECORDS_PER_BATCH private_constant :EVENTS_PER_BATCH KINESIS_PENDING_EVENTS_KEY = 'send_to_kinesis:pending_events' private_constant :KINESIS_PENDING_EVENTS_KEY # We need to limit the number of pending events stored in Redis. # The Redis database can grow very quickly if a few consecutive jobs # fail. I am going to limit the number of pending events to 600k # (10 jobs approx.). If that limit is reached, we will disable the # creation of buckets in the system, but we will continue trying to # send the failed events. We will lose data, but that is better than # collapsing the whole Redis. # We will try to find a better alternative once we cannot afford to # miss events. Right now, we are just deleting the stats keys with # period = minute, so we can restore everything else. MAX_PENDING_EVENTS = 600_000 private_constant :MAX_PENDING_EVENTS MAX_PENDING_EVENTS_REACHED_MSG = 'Bucket creation has been disabled. Max pending events reached'.freeze private_constant :MAX_PENDING_EVENTS_REACHED_MSG def initialize(stream_name, kinesis_client, storage) @stream_name = stream_name @kinesis_client = kinesis_client @storage = storage end def send_events(events) pending_events = stored_pending_events + events # Only disable indicating emergency if bucket storage is enabled. # We do not want to indicate emergency if it was disabled manually. if limit_pending_events_reached?(pending_events.size) && Stats::Storage.enabled? Stats::Storage.disable!(true) log_bucket_creation_disabled end # Batch events until we can fill at least one record if pending_events.size >= EVENTS_PER_RECORD failed_events = send_events_in_batches(pending_events) store_pending_events(failed_events) else store_pending_events(pending_events) end end # Sends the pending events to Kinesis, even if there are not enough of # them to fill 1 record. # Returns the number of events correctly sent to Kinesis def flush(limit = nil) pending_events = stored_pending_events events_to_flush = limit ? pending_events.take(limit) : pending_events failed_events = send_events_in_batches(events_to_flush) store_pending_events(pending_events - events_to_flush + failed_events) events_to_flush.size - failed_events.size end def num_pending_events storage.scard(KINESIS_PENDING_EVENTS_KEY) end private attr_reader :stream_name, :kinesis_client, :storage def stored_pending_events storage.smembers(KINESIS_PENDING_EVENTS_KEY).map do |pending_event| JSON.parse(pending_event, symbolize_names: true) end end def limit_pending_events_reached?(count) count > MAX_PENDING_EVENTS end def log_bucket_creation_disabled logger.info(MAX_PENDING_EVENTS_REACHED_MSG) end # Returns the failed events def send_events_in_batches(events) failed_events = [] events.each_slice(EVENTS_PER_BATCH) do |events_slice| begin kinesis_resp = kinesis_client.put_record_batch( { delivery_stream_name: stream_name, records: events_to_kinesis_records(events_slice) }) failed_events << failed_events_kinesis_resp( kinesis_resp[:request_responses], events_slice) rescue Aws::Firehose::Errors::ServiceError failed_events << events_slice end end failed_events.flatten end def events_to_kinesis_records(events) # Record format expected by Kinesis: # [{ data: "data_event_group_1" }, { data: "data_event_group_2" }] events.each_slice(EVENTS_PER_RECORD).map do |events_slice| { data: events_to_pseudo_json(events_slice) } end end # We want to send to Kinesis events that can be read by Redshift. # Redshift expects events in JSON format without the '[]' and # without separating them with commas. # We put each event in a separated line, that will make their parsing # easier, but it is not needed by Redshift. def events_to_pseudo_json(events) events.map { |event| event.to_json }.join("\n") + "\n" end def failed_events_kinesis_resp(request_responses, events) failed_records_indexes = failed_records_indexes(request_responses) failed_records_indexes.flat_map do |failed_record_index| events_index_start = failed_record_index*EVENTS_PER_RECORD events_index_end = events_index_start + EVENTS_PER_RECORD - 1 events[events_index_start..events_index_end] end end def failed_records_indexes(request_responses) result = [] request_responses.each_with_index do |response, index| result << index unless response[:error_code].nil? end result end def store_pending_events(events) storage.pipelined do storage.del(KINESIS_PENDING_EVENTS_KEY) events.each do |event| storage.sadd(KINESIS_PENDING_EVENTS_KEY, event.to_json) end end end end end end end end
true
3ba0b9848cbfedb4dc1cfb5cfb16f890b98a2736
Ruby
mscoutermarsh/exercism
/ruby/grade-school/school.rb
UTF-8
263
3.28125
3
[]
no_license
class School attr_reader :db def initialize @db = Hash.new{ |a,b| a[b] = Array.new } end def add(name, grade) @db[grade] << name end def sort @db.each_value(&:sort!) Hash[@db.sort] end def grade(grade) @db[grade] end end
true
a6b87acc0b6082ef8b99814ee7372e2cba292a54
Ruby
sorah/dqx_tools
/lib/dqx_tools/session.rb
UTF-8
2,341
2.640625
3
[ "MIT" ]
permissive
# coding: utf-8 require 'mechanize' require_relative './character' module DQXTools # 1. GET http://hiroba.dqx.jp/sc/login/ -> redirect # 2. GET https://secure.square-enix.com/account/app/svc/login?cont=... -> form # 3. POST https://secure.square-enix.com/account/app _pr_confData_sqexid, passwd -> redirect # 4. GET http://hiroba.dqx.jp/sc/public/welcome/ -> link # 5. GET http://hiroba.dqx.jp/sc/login/characterselect/ -> form # 6. POST http://hiroba.dqx.jp/sc/login/characterexec cid = button a[rel] class Session class LoginError < StandardError; end class MaintenanceError < Exception; end def initialize(username, password, cid=nil) @username, @password, @cid = username, password, cid @agent = Mechanize.new @agent.user_agent_alias = 'Mac Safari' @logined = false login end attr_reader :agent, :username, :cid def logined?; @logined; end def inspect "#<DQXTools::Session: #{@username}#{@cid && " (#{@cid})"}#{@logined ? ' logined' : ''}>" end def character Character.new(@cid, agent: self.agent) end private def login login_page = @agent.get("http://hiroba.dqx.jp/sc/login/") raise MaintenanceError, "seems in the maintenance" if login_page.at(".mainte_img") logined = login_page.form_with(action: "/account/app") do |form| form['_pr_confData_sqexid'] = @username form['_pr_confData_passwd'] = @password form['_event'] = "Submit" cushion = form.submit break cushion.forms[0].submit end raise LoginError, "Failed to login (Authentication failed?)" if logined.uri.to_s == "https://secure.square-enix.com/account/app" characterselect = @agent.get("http://hiroba.dqx.jp/sc/login/characterselect/") raise LoginError, "Failed to login (No Character exists or failed to get session)" if characterselect.at(".imgnochara") characterselect.form_with(action: "/sc/login/characterexec") do |form| form['cid'] = (@cid ||= characterselect.at("a.button.submitBtn.charselect.centering")['rel']) form.submit end mypage = @agent.get("http://hiroba.dqx.jp/sc/home/") raise LoginError, "Failed to login... (can't show mypage)" unless /マイページ/ === mypage.title @logined = true end end end
true
ab5f30970a6261cecf5583921cc28323cad0f471
Ruby
collabnix/dockerlabs
/vendor/bundle/ruby/2.6.0/gems/yell-2.2.2/examples/002.2-log-level-on-certain-severities-only.rb
UTF-8
729
3.34375
3
[ "Apache-2.0", "MIT" ]
permissive
# encoding: utf-8 require_relative '../lib/yell' puts <<-EOS # The Yell::Level parser allows you to exactly specify on which levels to log, # ignoring all the others. For instance: If we want to only log at the :debug # and :warn levels we simply providing an array: # * %i[] is a built-in for an array of symbols logger = Yell.new STDOUT, level: %i[debug warn] %i[debug info warn error fatal].each do |level| logger.send( level, level ) end #=> "2012-02-29T09:30:00+01:00 [DEBUG] 65784 : debug" #=> "2012-02-29T09:30:00+01:00 [ WARN] 65784 : warn" EOS puts "=== actual example ===" logger = Yell.new STDOUT, level: %i[debug warn] %i[debug info warn error fatal].each do |level| logger.send( level, level ) end
true
35c7ed53adac5a3b09097c30908335d2d9a9a7d0
Ruby
timothykim/hcsuzukiviolin.com
/app/models/session.rb
UTF-8
2,782
2.5625
3
[]
no_license
class Session < ActiveRecord::Base has_many :weekly_availablities, :dependent => :destroy has_many :session_days, :dependent => :destroy has_many :registration_options, :dependent => :destroy has_many :registrations, :order => "created_at DESC" has_many :registered_dates, :through => :registrations has_many :registered_days, :through => :registrations has_many :students, :through => :registrations, :order => "last_name ASC" has_many :lessons, :through => :registrations, :order => "time ASC" has_many :pricings DAY_TYPE = 0 DATE_TYPE = 1 def to_s self.name end def Session.current Session.find(:first, :conditions => ["is_active = ?", true], :order => "first DESC"); end def parents p = [] users = User.find(:all) users.each do |u| u.registrations.each do |r| if r.session_id == self.id p.push(u) break end end end return p.sort {|x,y| x.lastname <=> y.lastname } end def is_offday?(today) d = self.session_days.find_by_date(today) return true if d.nil? return d.offday end def is_groupday?(today) d = self.session_days.find_by_date(today) return false if d.nil? return d.group end def groups return self.session_days.select{|d| d.group}.sort{|a,b| a.date<=>b.date} end def get_note(day) d = self.session_days.find_by_date(day) return "" if d.nil? return d.note end def week(week_no) monday = (self.first.next_week - 7) + ((week_no - 1) * 7) saturday = monday + 6 return monday, saturday end def all_lessons_in_week(week_no) monday, saturday = self.week(week_no) self.lessons.find(:all, :conditions => { :time => monday..saturday }) end def find_all_registered_dates_in(start) done = start + (30 * 60) # 30 minute interval today = Date.parse(start.strftime("%Y/%m/%d")) return_array = [] self.registered_dates.find(:all, :conditions => ["start IS NOT NULL AND " + "'end' IS NOT NULL AND " + "start >= ? AND " + "start < ? AND " + "date = ?", start, done, today]) end def sanitize_data #get rid of duplicate lessons sql = <<SQL DELETE FROM lessons WHERE id NOT IN (SELECT MAX(dup.id) FROM lessons As dup GROUP BY dup.registration_id, dup.time, dup.is_recurring, dup.duration) SQL #get rid of out of scope lessons self.lessons.each do |l| if l.time.hour < 7 or l.time.hour > 21 l.destroy end if l.time < self.first or l.time > self.last l.destroy end end end end
true
d771b03476dc91ed0d3cc14e37d9d07711510850
Ruby
sushmasatish/handy_apn
/lib/handy_apn/apn_send_helper.rb
UTF-8
2,664
2.890625
3
[]
no_license
class ApnSendHelper attr_reader :device_token attr_reader :should_send_message_to_apn_prod attr_reader :apn_pem_file_path attr_reader :apn_pass_phrase attr_reader :message def initialize(apn_pem_file_path, apn_pass_phrase, device_token, should_send_message_to_apn_prod, message) @apn_pem_file_path = apn_pem_file_path @apn_pass_phrase = apn_pass_phrase @device_token = device_token @should_send_message_to_apn_prod = should_send_message_to_apn_prod @message = "Testing: #{Time.now}" if (message && message.strip.length > 0) @message = message.strip end end def send_push_notification result = false if !StringHelper.is_valid(apn_pem_file_path) ColouredLogger::CLogger.debug(__method__, "Cannot send push notification as no certificate file is provided.") return result end if !StringHelper.is_valid(apn_pass_phrase) ColouredLogger::CLogger.debug(__method__, "Cannot send push notification as pass-pharse is not provided for the certificate.") return result end if !StringHelper.is_valid(device_token) ColouredLogger::CLogger.debug(__method__, "Cannot send push notification as device_token is not provided.") return result end ColouredLogger::CLogger.debug(__method__, "Sending push notification to device_token #{@device_token} - #{@should_send_message_to_apn_prod}") reset_apn_configurations begin ApnConnection.open_for_delivery() do |conn, sock| conn.write(ApnSendHelper.data_to_send(@device_token, @message)) end result = true rescue Exception => err ColouredLogger::CLogger.debug(__method__, "Incurred while sending notifications [#{err.message}]") end result end def reset_apn_configurations configatron.apn.cert = @apn_pem_file_path configatron.apn.passphrase = @apn_pass_phrase if @should_send_message_to_apn_prod configatron.apn.host = configatron.apn.prod.host else configatron.apn.host = configatron.apn.dev.host end end def self.data_to_send(device_token, msg) json = self.to_apple_json(msg) message = "\0\0 #{self.to_hexa(device_token)}\0#{json.length.chr}#{json}" raise ApnErrorsHelper::ExceededMessageSizeError.new(message) if message.size.to_i > 256 message end def self.to_hexa(device_token) [device_token.delete(' ')].pack('H*') end def self.apple_hash(msg) result = {} result['aps'] = {} result['aps']['alert'] = msg result['aps']['badge'] = 1 result['aps']['sound'] = "1.aiff" ColouredLogger::CLogger.info(__method__, "Message: #{result}") result end def self.to_apple_json(msg) self.apple_hash(msg).to_json end end
true
ba16f5486928003bbc812eccaccabcfc7f5853ac
Ruby
jeffstienstra/ruby-practice
/show-me-the-money.rb
UTF-8
540
4.5
4
[]
no_license
# Given a string, write a function that returns true if the “$” character # is contained within the string or false if it is not. # Input: “i hate $ but i love money i know i know im crazy” # Output: true # Input: “abcdefghijklmnopqrstuvwxyz” # Output: false phrase1 = "i hate $ but i love money i know i know im crazy" phrase2 = "i hate money!@#%^&*(), but i love money i know i know im crazy" def find_money(string) if string[/\$/] then return true else return false end end p find_money(phrase1) p find_money(phrase2)
true
203e6f39ffd4e9ecae1a00c54d18d93ccdf9f6ad
Ruby
dylanrhodius/lrthw
/ex45.rb
UTF-8
6,702
3.796875
4
[]
no_license
class Scene def enter() puts "This scene is not yet configured. Subclass it and implement enter()." exit(1) end end class Engine def initialize(scene_map) @scene_map = scene_map end def play() current_scene = @scene_map.opening_scene() last_scene = @scene_map.next_scene('finished') while current_scene != last_scene next_scene_name = current_scene.enter() current_scene = @scene_map.next_scene(next_scene_name) end # be sure to print out the last scene current_scene.enter() end end class Death < Scene @@quips = [ "You did not make it this time.. Better luck next time!", "Man.. You suck!", "Learn from your mistakes, and try again!" ] def enter() puts @@quips[rand(0..(@@quips.length - 1))] exit(1) end end class DarkRoom < Scene def enter() puts "You are in a dark room. You have no idea how you got here" puts "and you don't remember anything at all. You are feeling uneasy, you" puts "need to get out of this room." puts "\n" puts "\n" puts "You see a small digital screen with a math equation and a little" puts "input board below it.." puts "\n" first_num = rand(1..20) second_num = rand(1..20) puts "#{first_num} * #{second_num} = " code = first_num * second_num print "[keypad]> " guess = Integer(gets) rescue nil if guess == code puts "You guessed, well done! A mechanical door slides open.." return 'corridor' elsif (guess.is_a? Integer) == false puts "Please input a valid answer." else puts "Wrong code, please try again." end end end class Corridor < Scene def enter() puts "You pass the door into a very dark and narrow corridor," puts "the corridor comes to a sudden end after 2 meters. " puts "You can't see anything at all, but you realise the corridor splits in two." puts "You can either go to the left, or turn to the right." print "> " action = $stdin.gets.chomp if action == "left" puts "You decide to take the route to the left, unfortunately, after" puts "taking a couple steps you fall into a huge trap and die!" return 'death' elsif action == "right" puts "You turn to your right and slowly start walking forwards." puts "So far, so good.. You carefully carry on walking. Suddenly, " puts "just before turning back to take the other route, you see a door" puts "in front of you. You look for its handle, anxious, you open the door." return 'gold_room' else puts "Please input a valid answer." return 'corridor' end end end class GoldRoom < Scene def enter() puts "You open the door into a very well lit room, Finally, some light." puts "The room is full of gold, it is amazing. You see many paintings" puts "on the wall with death related symbols. There is a note, would you" puts "like to pick it up?" print "> " choice = $stdin.gets.chomp if choice == "yes" puts "\n" puts "-------------" require "./ex45an.rb" puts "-------------" puts "\n" puts "The note dissolves in your hands..." elsif choice == "no" puts "\n" # carry on through journey else puts "Please input a valid answer." return 'gold_room' end puts "As you venture into the room you realise there is a bear in it." puts "The bear is in front of another door, and it slowly starts approaching you" puts "You notice there is a jar of honey next to you." puts "You think the smartest thing to do would be to put the jar of honey" puts "in the corridor, outside this room. Do you do that?" print "> " choice2 = $stdin.gets.chomp if choice2 == "yes" puts "You successfully locked the bear on the other side of the door." puts "You can now approach the door safely." return 'final_door' elsif choice2 == "no" puts "The bear is so hungry that confuses you for its jar of honey." puts "You are dead." return 'death' else puts "Please input a valid answer." return 'gold_room' end end end class FinalDoor < Scene def enter() puts "As you start approaching the door, you get tempted to get some of the gold." puts "It seems like it is worth a lot. Do you get some?" print "> " choice = $stdin.gets.chomp if choice == "yes" puts "You greedy bastard, you ignored the signs... The floor starts moving" puts "and the whole room comes falling down and crushes you to your death!!" return 'death' elsif choice == "no" return 'final_door_code' else puts "Please input a valid answer." return 'final_door' end end end class FinalDoorCode < Scene def enter() puts "You head towards the door. There is a keypad lock on it." puts "You need to get the code to open the door. If you get the code" puts "wrong 10 times then the lock closes forever." puts "The code is 2 digits long." code = "#{rand(1..3)}#{rand(1..3)}" print "[keypad]> " guess = $stdin.gets.chomp guesses = 0 while guess != code && guesses < 2 puts "BZZEEED!" guesses += 1 print "[keypad]> " guess = $stdin.gets.chomp end if guess == code puts "The door unlocks open into the wild. You escaped the maze." puts "You sigh with relief.." return 'finished' else puts "The lock buzzes one last time and the floor starts moving. The whole" puts "room comes falling down and crushes you to your death!!" return 'death' end end end class Finished < Scene def enter() puts "You are a free man!! You feel energised and ready to find your way" puts "back home. Go on then, to the next adventure!" puts "To be continued..." end end class Map @@scenes = { 'dark_room' => DarkRoom.new(), 'corridor' => Corridor.new(), 'gold_room' => GoldRoom.new(), 'final_door' => FinalDoor.new(), 'final_door_code' => FinalDoorCode.new(), 'death' => Death.new(), 'finished' => Finished.new(), } def initialize(start_scene) @start_scene = start_scene end def next_scene(scene_name) val = @@scenes[scene_name] return val end def opening_scene() return next_scene(@start_scene) end end a_map = Map.new('dark_room') a_game = Engine.new(a_map) a_game.play()#
true
3d321a32c3699f53223972c3e32eb614af227caa
Ruby
JenniferGrudi/practice_work
/hello_world/homework2.rb
UTF-8
528
4.09375
4
[]
no_license
# def create_array_of_numbers (num) # 100.times do # puts num # my_array = [] # my_array << num # num = num + 1 # end # end # create_array_of_numbers (1) def create_array_of_numbers (num) 100.times do #puts num my_array = [] my_array << num num = num + 1 if (num % 3 == 0 && num % 5 == 0) puts "Greene County" elsif (num % 3 == 0) #(num == 3) <this adds "greene to 3"> puts "Greene" elsif (num % 5 == 0) puts "County" else puts num end num = num + 1 end end create_array_of_numbers (1)
true
b714c266c51ff08099629ffcb2f2c5dd20b55a60
Ruby
ChantalDemissie/VideoStoreAPI
/app/models/movie.rb
UTF-8
381
2.65625
3
[]
no_license
class Movie < ApplicationRecord has_many :rentals validates :title, presence: true validates :inventory, presence: true, numericality: { greater_than_or_equal_to: 0 } def available_inventory inventory = self.inventory rentals = self.rentals.count{ |rental| rental.return_date.nil? } avail_inventory = inventory - rentals return avail_inventory end end
true
59120fa1deea5b48f2f8de4c2af3ab7fd259522e
Ruby
amatsukixgithub/atcoder
/ABC/ABC126/126A.rb
UTF-8
80
3.078125
3
[]
no_license
N,K=gets.chomp.split.map(&:to_i) S=gets.chomp.chars S[K-1].downcase! puts S.join
true
b88df5b66b01fa813af66c83697d05845922b528
Ruby
htll/swapfil.es
/server.rb
UTF-8
1,968
2.84375
3
[]
no_license
#!/usr/bin/ruby require "openssl" require "socket" require "timeout" require "thread" CHUNK_SIZE = 4 * 1024 PORT = ARGV.shift.to_i # ctx = OpenSSL::SSL::SSLContext.new # ctx.cert = OpenSSL::X509::Certificate.new File.open("cert.pem") # ctx.key = OpenSSL::PKey::RSA.new File.open("priv.pem") # server = OpenSSL::SSL::SSLServer.new TCPServer.new(PORT), ctx server = TCPServer.new PORT puts "Listening on port #{PORT}" connections = Hash.new class TCPSocket attr_accessor :name, :size, :scale def init @size, @name = self.gets.chomp.split ":", 2 if !/^\d+$/.match @size or @size.to_i == 0 self.puts "ERROR invalid filesize '#{@size}'" self.close throw "ERROR" end @size = @size.to_i @name = @name.gsub /[^0-9A-z.\-]/, '_' # no slashes etc. @scale = Math.log(@size).round @scale = 1 # @TODO: debug end end Thread.new { loop do before = Time.now # kek connections.each do |scale, conn| conn.puts "PING" begin timeout 2 do throw Timeout::Error unless conn.gets.chomp == "PONG" # wrong answer is like no answer end rescue Timeout::Error puts "Timed out!" conn.close connections.delete scale end end interval = 5 - (Time.now-before) sleep(interval) if interval > 0 end } loop do conn = server.accept conn.init if connections.has_key? conn.scale and not connections[conn.scale].closed? Thread.new { a = conn b = connections.delete a.scale a.puts "GO" b.puts "GO" b.puts "#{a.size}:#{a.name}" a.puts "#{b.size}:#{b.name}" loop do a.write b.read [CHUNK_SIZE, b.size].min b.write a.read [CHUNK_SIZE, a.size].min b.size -= [CHUNK_SIZE, b.size].min a.size -= [CHUNK_SIZE, a.size].min break if b.size == 0 and a.size == 0 end a.close b.close } else connections[conn.scale] = conn end end
true
4daee2470aea6d12e53cf2a440c5a2b80b2edc80
Ruby
fishbrain/administrate-field-belongs_to_search
/app/views/administrate/application/index.json.jbuilder
UTF-8
795
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# ## Index # # This view is the template for the index page. # # ## Local variables: # # - `page`: # An instance of [Administrate::Page::Collection][1]. # Contains helper methods to help display a table, # and knows which attributes should be displayed in the resource's table. # - `resources`: # An instance of `ActiveRecord::Relation` containing the resources # that match the user's search criteria. # By default, these resources are passed to the table partial to be displayed. # - `search_term`: # A string containing the term the user has searched for, if any. # # [1]: http://www.rubydoc.info/gems/administrate/Administrate/Page/Collection json.resources resources do |resource| json.id resource.id json.dashboard_display_name @dashboard.display_resource(resource) end
true
a0a58b76188e1b603a2093478f68c1eeb2ef86c0
Ruby
rossfoley/advent-of-code
/2015/day4.rb
UTF-8
554
3.453125
3
[]
no_license
require 'digest/md5' # Part 1: 5 Zeroes input = 'ckczppom' answer = 1 found_answer = false while not found_answer md5 = Digest::MD5.hexdigest(input + answer.to_s) if md5[0..4] == '00000' found_answer = true else answer += 1 end end puts "5 Zeroes Answer: #{answer}" # Part 2: 6 Zeroes input = 'ckczppom' answer = 1 found_answer = false while not found_answer md5 = Digest::MD5.hexdigest(input + answer.to_s) if md5[0..5] == '000000' found_answer = true else answer += 1 end end puts "6 Zeroes Answer: #{answer}"
true
93655f46cfffc6665fd94e548d35d8925fe9db00
Ruby
joshpencheon/tent
/lib/tent.rb
UTF-8
1,991
3.265625
3
[ "MIT" ]
permissive
require 'monitor' # Provides a way of deferring method calls to # an underlying object. class Tent include MonitorMixin # Yields a `Tent` over the given `underlying`. # By default, commits to the underlying when # the block closes. def self.cover(underlying, auto_commit = true, &block) new(underlying).tap do |instance| yield instance instance.commit! if auto_commit end end def initialize(underlying) # Maintain a reference to the underlying: @underlying = underlying # Collect calls for the underlying: @buffer = [] # Allow monitor mixin to initialise: super() end # Provide access to the underlying object. def direct @underlying end # Clears the buffer. Optionally, only clears # from the buffer. def discard!(*filters) process_buffer(false, filters) end # Commits the buffered calls to the underlying. def commit!(*filters) process_buffer(true, filters) end private # Wrap calls to the underlying. class BufferedCall attr_reader :name, :args, :block def initialize(name, *args, &block) @name = name @args = args @block = block end def apply_to(target) block ? target.send(name, *args, &block) : target.send(name, *args) end def matched_by?(filters) 0 == filters.length || filters.include?(name) end end # Clear from the buffer elements matching any # of the `filters`. Will commit those elements # to the underlying if `commit` is true. def process_buffer(commit, filters) synchronize do @buffer.reject! do |call| if call.matched_by?(filters) call.apply_to(direct) if commit true # Remove from buffer end end end end def method_missing(method, *args, &block) return super unless direct.respond_to?(method) synchronize do @buffer << BufferedCall.new(method, *args, &block) self # Make buffering chainable. end end end
true
d07fc4aa42f8e3cfc06d37714b54dba8ee3cb78a
Ruby
isatakebayashi/cargox-coding-challenge
/spec/models/position_spec.rb
UTF-8
751
2.796875
3
[ "Unlicense" ]
permissive
require 'spec_helper' require_relative '../../app/models/position' require_relative '../../app/models/surface' describe Position do describe '#move' do context 'when can move the robot' do let(:surface) { Surface.new('5 5') } let(:position) { described_class.new('1', '1', surface) } it 'updates the robot position' do position.move('N') expect(position.y).to eq(2) end end context 'when can not move the robot' do let(:surface) { Surface.new('5 5') } let(:position) { described_class.new('5', '5', surface) } it 'does not update the robot position' do expect { position.move('W') }.not_to change { position.y }.from(5) end end end end
true
50b5a7140ceed423abf30c8a1b0f30b5dba62520
Ruby
tpham-netprotections/sa_course
/Shimaya/module_oriented/user_module.rb
UTF-8
3,176
3.390625
3
[]
no_license
module User # ファンクションのためのモジュールで、データは持たない # require('./data.rb') def signup(members) a = {} puts "新規会員登録に必要な情報を入力してください。" puts "mail_address?" mail_address = gets.chomp a['mail_address'] = mail_address puts "phone_number?" phone_number = gets.chomp a['phone_number'] = phone_number puts "name_kanji?" name_kanji = gets.chomp a['name_kanji'] = name_kanji puts "name_kana?" name_kana = gets.chomp a['name_kana'] = name_kana puts "sex_division?" sex_division = gets.chomp a['sex_division'] = sex_division puts "birth_day?" birth_day = gets.chomp a['birth_day'] = birth_day puts "address?" address = gets.chomp a['address'] = address members[members.length] = a puts "会員登録を完了しました" return members end def search(members) puts "Enter memberID" @id = gets.chomp member = members[@id.to_i] puts member['mail_address'] puts member['phone_number'] puts member['name_kanji'] puts member['name_kana'] puts member['birth_day'] puts member['address'] end def edit(members) puts "Enter memberID" @id = gets.chomp member = members[@id.to_i] puts member['mail_address'] puts "=>1" puts member['phone_number'] puts "=>2" puts member['name_kanji'] puts "=>3" puts member['name_kana'] puts "=>4" puts member['birth_day'] puts "=>5" puts member['address'] puts "=>6" puts "Which to edit? Enter the number." @number = gets.chomp puts "Enter new content. " if @number == "1" puts "Enter new mail_address. " @content = gets.chomp member['mail_address'] = @content else if @number == "2" puts "Enter new phone_number. " @content = gets.chomp member['phone_number'] = @content else if @number == "3" puts "Enter new name_kanji. " @content = gets.chomp member['name_kanji'] = @content else if @number == "4" puts "Enter new name_kana. " @content = gets.chomp member['name_kana'] = @content else if @number == "5" puts "Enter new birth_day. " @content = gets.chomp member['birth_day'] = @content else if @number == "6" puts "Enter new address. " @content = gets.chomp member['address'] = @content end end end end end end puts "completed." puts member['mail_address'] puts member['phone_number'] puts member['name_kanji'] puts member['name_kana'] puts member['birth_day'] puts member['address'] return members end module_function :signup module_function :search module_function :edit end
true
598883ef08b3ae9a9967ad989f087060984c4a28
Ruby
tausvels/2_player_math_game
/main.rb
UTF-8
293
3.015625
3
[]
no_license
require "./Player.rb" require "./Question.rb" require "./Game.rb" #----- ENTER PLAYER NAME ------ # # p "Enter player1 name" # name1=gets.chomp # p "Enter player2 name" # name2=gets.chomp # player1 = Player.new(name1) # player2 = Player.new(name2) # player1.info game=Game.new game.run_game
true
8e5d8708c6783796c604f82525cb2a505ccf538a
Ruby
PaulDebevec/codewars
/string_ends_with/string_ends_with.rb
UTF-8
54
2.875
3
[ "MIT" ]
permissive
def solution(str, ending) str.end_with?(ending) end
true
0ac86c60bd53b01db3005aaa2b8be304ddc65119
Ruby
taw/paradox-tools
/analysis_eu4/list_countries
UTF-8
4,458
2.609375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require_relative "./eu4_analysis" class CountryHistory attr_reader :tag attr_accessor :government, :government_rank, :technology_group, :religion, :primary_culture def initialize(tag, node, date) @tag = tag @date = date add(node) end def add(node) node.each do |key, val| case key when Date next if key > @date add(val) when "government", "government_rank", "technology_group", "religion", "primary_culture" send(:"#{key}=", val) else # Ignore for now end end end end class ProvinceHistory attr_reader :id attr_accessor :base_tax, :base_production, :base_manpower, :culture, :religion, :hre attr_accessor :owner, :controller, :capital, :trade_goods attr_accessor :native_size, :native_ferocity, :native_hostileness def initialize(id, node, date) @id = id @date = date @base_tax = 0 @base_production = 0 @base_manpower = 0 @owner = nil @controller = nil @capital = nil @trade_goods = nil @hre = false add(node) end def add(node) node.each do |key, val| case key when Date next if key > @date add(val) when "base_tax", "base_production", "base_manpower", "culture", "religion", "hre", "controller", "capital", "trade_goods", "native_size", "native_ferocity", "native_hostileness", "owner" send(:"#{key}=", val) else # Ignore for now end end end def development @base_tax + @base_production + @base_manpower end end class ListCountries < EU4Analysis def date @date ||= Date.parse("1444.11.11") end def development_by_tag unless @development_by_tag @development_by_tag = Hash.new(0) history_provinces.each do |id, prov| next unless prov.owner @development_by_tag[prov.owner] += prov.development end end @development_by_tag end def history_countries unless @history_countries @history_countries = {} glob("history/countries/*.txt").each do |path| begin tag = File.basename(path)[0,3] node = parse(path) @history_countries[tag] = CountryHistory.new(tag, node, date) rescue warn "#{path} failed: #{$!}" end end end @history_countries end def history_provinces unless @history_provinces @history_provinces = {} glob("history/provinces/*.txt").each do |path| begin id = File.basename(path)[/\d+/].to_i node = parse(path) @history_provinces[id] = ProvinceHistory.new(id, node, date) rescue warn "#{path} failed: #{$!}" end end end @history_provinces end def culture_group unless @culture_group @culture_group = {} glob("common/cultures/*.txt").each do |path| parse(path).each do |group_name, group| group.each do |key, val| next unless val.is_a?(PropertyList) @culture_group[key] = group_name end end end end @culture_group end def religion_group unless @religion_group @religion_group = {} glob("common/religions/*.txt").each do |path| parse(path).each do |group_name, group| group.each do |key, val| next unless val.is_a?(PropertyList) @religion_group[key] = group_name end end end end @religion_group end def call headers = [ "tag", "name", "development", "religion", "religion group", "culture", "culture group", "government", "rank", "technology group", ] result = [] history_countries.each do |tag, country| dev = development_by_tag[tag] next if dev == 0 result << [ tag, localization(tag), dev, localization(country.religion), localization(religion_group[country.religion]), localization(country.primary_culture), localization(culture_group[country.primary_culture]), localization(country.government), country.government_rank, localization(country.technology_group), ] end result.sort_by!{|row| [-row[2], row[1]] } puts headers.join("\t") result.each do |row| puts row.join("\t") end end end ListCountries.new_from_argv.call
true
42d53a0a3e57ccc60a6c35e1b2226171fad02611
Ruby
Felipeandres11/desafioruby1
/DesafioArreglosII/desafio4.rb
UTF-8
179
2.9375
3
[]
no_license
recibir = ARGV numbers = recibir.to_a def chart(numbers, size=2) numbers.each do |dato| puts "| #{"*" * dato.to_i * size}" end end return chart(numbers,4)
true
df65c01abdc3c75676c28b857934844b5df8bf8e
Ruby
ygor/mt940
/test/mt940_triodos_test.rb
UTF-8
1,126
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'helper' class TestMt940Triodos < Test::Unit::TestCase def setup file_name = File.dirname(__FILE__) + '/fixtures/triodos.txt' @transactions = MT940::Base.transactions(file_name) @transaction = @transactions.first end should 'have the correct number of transactions' do assert_equal 2, @transactions.size end context 'Transaction' do should 'have a bank_account' do assert_equal '390123456', @transaction.bank_account end should 'have an amount' do assert_equal -15.7, @transaction.amount end should 'have a currency' do assert_equal 'EUR', @transaction.currency end should 'have a description' do assert_equal 'ALGEMENE TUSSENREKENING KOSTEN VAN 01-10-2010 TOT EN M ET 31-12-20100390123456', @transaction.description end should 'have a date' do assert_equal Date.new(2011,1,1), @transaction.date end should 'return its bank' do assert_equal 'Triodos', @transaction.bank end should 'return the contra_account' do assert_equal '987654321', @transaction.contra_account end end end
true
8b240e1099dfbe6f96f09da1973f3cdb48646191
Ruby
wilsonsilva/loqate
/spec/loqate/phone/phone_number_validation_spec.rb
UTF-8
3,095
2.734375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'loqate/phone/phone_number_validation' RSpec.describe Loqate::Phone::PhoneNumberValidation do let(:attributes) do { phone_number: '+447440019210', request_processed: true, is_valid: 'Yes', network_code: '26', network_name: 'Telefonica UK', network_country: 'GB', national_format: '07440 019210', country_prefix: 44, number_type: 'Mobile' } end let(:phone_number) { described_class.new(attributes) } describe '#phone_number' do it 'exposes the recipient phone number in international format' do expect(phone_number.phone_number).to eq('+447440019210') end end describe '#request_processed' do it 'exposes true if Loqate processed the request on the network' do expect(phone_number.request_processed).to eq(true) end end describe '#is_valid' do it 'exposes whether the number is valid or not' do expect(phone_number.is_valid).to eq('Yes') end end describe '#network_code' do it 'exposes the current operator serving the supplied number' do expect(phone_number.network_code).to eq('26') end end describe '#network_name' do it 'exposes the name of the current operator serving the supplied number' do expect(phone_number.network_name).to eq('Telefonica UK') end end describe '#network_country' do it 'exposes the country code of the operator' do expect(phone_number.network_country).to eq('GB') end end describe '#national_format' do it 'exposes the domestic network format' do expect(phone_number.national_format).to eq('07440 019210') end end describe '#country_prefix' do it 'exposes the country prefix that must be prepended to the number when dialling internationally' do expect(phone_number.country_prefix).to eq(44) end end describe '#number_type' do it 'exposes the number type' do expect(phone_number.number_type).to eq('Mobile') end end describe '#==' do context 'when the attributes are different' do it 'returns false' do number_validation1 = described_class.new(attributes) number_validation2 = described_class.new(attributes.merge(network_name: 'Giffgaff')) expect(number_validation1).not_to eq(number_validation2) end end context 'when the attributes are the same' do it 'returns true' do number_validation1 = described_class.new(attributes) number_validation2 = described_class.new(attributes) expect(number_validation1).to eq(number_validation2) end end end describe '#valid?' do %w[No Unknown Maybe].each do |validation_result| context "when the validation result is '#{validation_result}'" do subject { described_class.new(attributes.merge(is_valid: validation_result)) } it { is_expected.not_to be_valid } end end context 'when the validation result is Yes' do subject { described_class.new(attributes.merge(is_valid: 'Yes')) } it { is_expected.to be_valid } end end end
true
40348a9e02443be4414f8f98becc10fccc3371ed
Ruby
byoung1018/datastructures
/lib/graphs/edge.rb
UTF-8
157
2.875
3
[]
no_license
class Edge attr_accessor :start, :finish, :weight def initialize(start, finish, weight) @start, @finish, @weight = start, finish, weight end end
true
0d55bcc78704ec3bac62776de214f0e51aa9ae48
Ruby
piptcb/gemnasium-gem
/lib/gemnasium/configuration.rb
UTF-8
2,485
2.96875
3
[ "MIT" ]
permissive
require 'yaml' module Gemnasium class Configuration attr_accessor :site, :api_key, :use_ssl, :profile_name, :project_name, :api_version, :project_branch, :ignored_paths DEFAULT_CONFIG = { 'site' => 'gemnasium.com', 'use_ssl' => true, 'api_version' => 'v2', 'ignored_paths' => [] } # Initialize the configuration object from a YAML file # # @param config_file [String] path to the configuration file def initialize config_file raise Errno::ENOENT, "Configuration file (#{config_file}) does not exist.\nPlease run `gemnasium install`." unless File.file?(config_file) config_hash = DEFAULT_CONFIG.merge!(YAML.load_file(config_file)) config_hash.each do |k, v| writer_method = "#{k}=" if respond_to?(writer_method) v = convert_ignored_paths_to_regexp(v) if k.to_s == 'ignored_paths' send(writer_method, v) end end raise 'Your configuration file does not contain all mandatory parameters or contain invalid values. Please check the documentation.' unless is_valid? end private # Check that mandatory parameters are not nil and contain valid values # # @return [Boolean] if configuration is valid def is_valid? site_option_valid = !site.nil? && !site.empty? api_key_option_valid = !api_key.nil? && !api_key.empty? use_ssl_option_valid = !use_ssl.nil? && !!use_ssl == use_ssl # Check this is a boolean api_version_option_valid = !api_version.nil? && !api_version.empty? profile_name_option_valid = !profile_name.nil? && !profile_name.empty? project_name_option_valid = !project_name.nil? && !project_name.empty? ignored_paths_option_valid = ignored_paths.kind_of?(Array) site_option_valid && api_key_option_valid && use_ssl_option_valid && api_version_option_valid && profile_name_option_valid && project_name_option_valid && ignored_paths_option_valid end def convert_ignored_paths_to_regexp(paths) return [] unless paths.kind_of? Array paths.inject([]) do |regexp_array, path| path = path.insert(0,'^') # All path start from app root .gsub('*','[^/]+') # Replace `*` to whatever char except slash .gsub('.','\.') # Escape dots regexp_array << Regexp.new(path) end end end end
true
981704d133c617098437e47a9d964a202140e426
Ruby
SanderKleykens/improvise
/bin/improvise
UTF-8
2,963
2.96875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'gli' require 'json' require 'zlib' require 'improvise' include GLI::App program_desc 'Improvise generates random words by learning from existing text.' version Improvise::VERSION flag [:f, :format], :desc => 'The format of the dictionary (marshal or json)', :default_value => :marshal, :must_match => [ :marshal, :json ] switch [:g, :gzip], :desc => 'Indicates if the dictionary is in gzip format', :negatable => false desc 'Create or update a dictionary based on an input file' arg_name 'input dictionary' command :learn do |c| c.flag [:d, :depth], :desc => 'The depth to use when building the dictionary', :default_value => 2, :type => Integer c.switch [:r, :reverse], :desc => 'Build a reverse dictionary', :negatable => false c.action do |global_options, options, args| if args.length < 1 help_now!('Input argument missing.') elsif args.length < 2 help_now!('Dictionary argument missing.') end input_filename = args[0] dictionary_filename = args[1] depth = options[:depth] reverse = options[:reverse] format = global_options[:format] gzip = global_options[:gzip] input_file = File.open(input_filename, 'r') words = input_file.read.split(/\W+/) input_file.close() if File.exists?(dictionary_filename) dictionary = Improvise::IO::DictionaryReader.read(File.open(dictionary_filename, 'r'), format: format, gzip: gzip) else if reverse dictionary = Improvise::ReverseDictionary.new(depth) else dictionary = Improvise::ForwardDictionary.new(depth) end end dictionary.learn!(words) Improvise::IO::DictionaryWriter.write(File.open(dictionary_filename, 'w'), dictionary, format: format, gzip: gzip) end end desc 'Generate random words based on a dictionary' arg_name 'dictionary length' command :generate do |c| c.flag [:w, :words], :desc => 'The number of words to generate', :default_value => 1, :type => Integer c.flag [:r, :root], :desc => 'Root of the generated word', :type => String c.action do |global_options, options, args| if args.length < 1 help_now!('Dictionary argument missing.') elsif args.length < 2 help_now!('Length argument missing.') end dictionary_filename = args[0] words = options[:words] root = options[:root] format = global_options[:format] gzip = global_options[:gzip] begin length = Integer(args[1]) rescue ArgumentError exit_now!('Length argument is not an integer.') end dictionary = Improvise::IO::DictionaryReader.read(File.open(dictionary_filename, 'r'), format: format, gzip: gzip) words.times { puts dictionary.generate_word(length, root) } end end exit run(ARGV)
true
6b1d392109bb2f9db57b447864c24d25cc704e94
Ruby
Agkura/rspec_poker
/poker/lib/deck.rb
UTF-8
461
3.59375
4
[]
no_license
require_relative "card" class Deck def initialize @cards = [] fill_deck end def num_cards @cards.length end def draw(count = 1) raise "Not enough cards" if count > num_cards drawn = [] count.times {drawn << @cards.pop} drawn end def shuffle @cards.shuffle! end private def fill_deck Card::SUITS.each do |suit| Card::VALUES.each { |value| @cards << Card.new(value, suit) } end end end
true
3236cdf512034daacf349c376672d1ed9fc09564
Ruby
yamunanollu/MyTest
/median.rb
UTF-8
410
3.46875
3
[]
no_license
a=Array.new puts "enter number of elements:" n=gets.chomp.to_i puts "enter elements:" for j in 0..n-1 a[j]=gets.chomp.to_f end print "elements in sorted order is: " for i in 0...n for j in i+1...n if a[i]>a[j] a[i],a[j]=a[j],a[i] end end print "#{a[i]} " end puts "\nmedian is :" if a.length%2!=0 med=a.length+1/2 puts a[med] else me=a.length/2 f=me-1 mid=(a[me]+a[f])/2 puts "#{mid}" end
true
38fba7ab7c10693c59d918e36cb03da207ae40e1
Ruby
Mackdatascience007/MORPION
/lib/box.rb
UTF-8
177
2.5625
3
[]
no_license
class Box attr_accessor :content, :name # Création de la case qui servira à la création du tableau def initialize @content = " " end end
true
38764d3b3667a6cda3d47905d6076e27de209c6d
Ruby
Patarta/git-thp
/ruby/exo_16.rb
UTF-8
147
3.1875
3
[]
no_license
puts "quelle est votre age?" age = gets.chomp.to_i i = 0 until age == 0 do puts "il y a #{age} ans, tu avais #{i} ans" age-=1 i+=1 end
true
ebcf48a70def51dffab1222380937626a664c551
Ruby
Harry-KNIGHT/fire-test-2020
/anagramme.rb
UTF-8
350
2.953125
3
[]
no_license
value = ARGV[0] file_word_find = ARGV[1] word_on_array = [] position = 0 File.foreach(file_word_find) { |line| word_on_array[position] = line.chomp; position += 1} i = 0 while( i < word_on_array.length) if (word_on_array[i].split('').sort.join('') == value.split('').sort.join('')) puts word_on_array[i] end i += 1 end
true
ad3fb61df11f5385a25160848ac95b1037bb1764
Ruby
JuanDuran85/ejercicios_ruby_basico
/ejercicios_basicos/ejercicio6.rb
UTF-8
427
3.375
3
[ "Apache-2.0" ]
permissive
=begin Se pide crear el programa escape.rb donde el usuario ingrese la gravedad y el radio, y comoresultado obtenga la velocidad de escape del planeta (la velocidad mínima necesaria para poder salir de unplaneta) ). Fórmula Ve=(2gr)^1/2 =end puts "Calculando la velocidad de escape del planeta" g = ARGV[0].to_f r = ARGV[1].to_f Ve = Math.sqrt(2*g*r) puts "El resultado de la velocidad es: #{sprintf("%.2f",Ve)} mts/s"
true
03839e365543903798237734eb792d923792ae37
Ruby
LightLaboratories/tdg5_project_euler_2009
/pe_05.rb
UTF-8
862
3.28125
3
[]
no_license
#while def isPrime(r) for i in 2..Math.sqrt(r) if r%i == 0 then return false end i+=1 end return true end print "Enter the Upper Bound: " STDOUT.flush o = gets start = Time.now o=o.to_i @t= Array.new(o,0) @a= Array.new(o,0) for rr in 1..o @a[rr]=0 end for ii in 1..o for rr in 1..o @t[rr]=0 end n=ii while isPrime(n)==false for i in 2..n/2 if isPrime(i)==true if n%i == 0 @t[i]+=1 n=(n/i) break end end end end @t[n]+=1 for y in 1..o if @t[y] >@a[y] @a[y]=@t[y] end end end ty=1 for z in 1..o if @a[z] !=0 then ty=ty*(z**@a[z]) end end puts ty puts "#{Time.now - start}" #for i in 1..o #puts @a[i] #end
true
f1795dbc860e50c892bb3455d5f7127df631d41c
Ruby
satek/mitier
/lib/mitier/tokenizer.rb
UTF-8
572
2.703125
3
[ "MIT" ]
permissive
module Mitier class Tokenizer attr_accessor :tokens, :text def initialize(text) @text = text.to_s.strip end def process return [] if text.empty? tokens_ptr = tokenize process_token_elements tokens_ptr end private def tokenize Wrapper.mitie_tokenize text end def process_token_elements(ptr) @tokens = [].tap do |elements| until (element = ptr.read_pointer).null? elements << element.read_string ptr += FFI::Type::POINTER.size end end end end end
true
1535cdb647568a8b91fd449037514af5068e2b4b
Ruby
nurrutia/clase29
/ejercicio2connil.rb
UTF-8
544
3.859375
4
[]
no_license
a = [1,2,3,4,5] c = [1,12,3,45,21] ##uno #map b = a.select{ |x| x % 2 == 0 } puts "con select #{b}" puts #do a.each do |x| if x % 2 == 0 puts "con do #{x}" end end puts ## ##dos d = c.map{|e| e if e < 15} puts "con map #{d}" e = c.reject{ |x| x > 15} puts "con reject #{d}" puts ## ##tres nombres = ["Guillermo","Carlos","Rosario","Diego","Francisco","Joaquín","German"] #f = nombres.map{|e| e if e.byteslice(0) == "R"} f = nombres.map{|e| e if e[0] == "G"} g = nombres.reject{ |e| e if e[0] == "G"} puts "Con G#{f}" puts "sin G#{g}" ##
true
443b13c0e5b0dc383c16987f091951129023a5e1
Ruby
PaulineLabaisse/exo_ruby
/exo_10.rb
UTF-8
151
3.546875
4
[]
no_license
puts"Quelle est ton année de naissance ?" birthday = gets.chomp.to_i age_2017 = 2017 - birthday #user age in 2017 puts"Tu avais #{age_2017} en 2017"
true
afef49481c5584f6b9fc6bd2a092ea392bafb269
Ruby
kdbanman/ruby_four
/src/util/size_entry.rb
UTF-8
440
2.9375
3
[ "Apache-2.0" ]
permissive
require_relative '../util/text_entry.rb' class SizeEntry < TextEntry MINSIZE = 4 MAXSIZE = 10 def initialize(view, name) super(view, name) end def valid? if text.match(/^\d+$/) if text.to_i >= MINSIZE and text.to_i <= MAXSIZE return true end end raise_invalid_dialog "Sizes must be greater than #{MINSIZE} and less than #{MAXSIZE}" return false end def value text.to_i end end
true
da63df7073e7215011f8a119d0939cb9b4edd1fe
Ruby
oihiro/nokogiri
/pana_oss.rb
UTF-8
8,244
2.65625
3
[]
no_license
# -*- coding: utf-8 -*- # # pana_oss.rb # # scrape the Panasonic OSS site # require 'uri' require 'open-uri' require 'nokogiri' require 'optparse' require 'pg' # # カテゴリ、モデル、OSSを全て記録するクラス # class ProductOSS attr_accessor :last_ctg def initialize @h = {} @tv_h = {} end def set_ctg name @last_ctg = name if (name == 'TV') then @tv_h[name] = {} @tv_h[name] else @h[name] = {} @h[name] end end def set_area name, _h if (!_h[name]) then _h[name] = {} end _h[name] end def set_year name, _h if (!_h[name]) then _h[name] = {} end _h[name] end def set_osses_to_models _models, _osses, _h _models.each do |m| _h[m] = {} _osses.each do |o| _h[m][o] = true end end end def print_all @tv_h.keys.sort.each do |c| @tv_h[c].keys.sort.each do |a| @tv_h[c][a].keys.sort.each do |y| @tv_h[c][a][y].keys.sort.each do |m| @tv_h[c][a][y][m].keys.each do |o| puts "#{c}|#{a}|#{y}|#{m}|#{o['oss']}|#{o['package']}|#{o['ossurl']}" end end end end end @h.keys.sort.each do |c| @h[c].keys.sort.each do |m| @h[c][m].keys.each do |o| puts "#{c}|||#{m}|#{o['oss']}|#{o['package']}|#{o['ossurl']}" end end end end def create_tbl connection, tblname connection.exec(<<-"EOS") CREATE TABLE #{tblname} ( category VARCHAR(80), area VARCHAR(80), year VARCHAR(80), model VARCHAR(80), oss VARCHAR(256), package VARCHAR(256), ossurl VARCHAR(256) ); EOS end def insert_tbl connection, tbl i = 1 @tv_h.keys.sort.each do |c| @tv_h[c].keys.sort.each do |a| @tv_h[c][a].keys.sort.each do |y| @tv_h[c][a][y].keys.sort.each do |m| @tv_h[c][a][y][m].keys.each do |o| begin connection.exec(<<-EOS) INSERT INTO #{tbl} (category, area, year, model, oss, package, ossurl) VALUES(\'#{c}\', \'#{a}\', \'#{y}\', \'#{m}\', \'#{o['oss'].gsub(/'/, "''")}\', \'#{o['package']}\', \'#{o['ossurl']}\'); EOS # o['oss']にはシングルクォーテーションが入る場合があり、そのときはシングルクォーテーション2つへのエスケープ処理が必要になる rescue => e p e puts "#{c}|#{a}|#{y}|#{m}|#{o['oss']}|#{o['package']}|#{o['ossurl']}" raise e end if (i % 1000 == 0) then now "insert #{i}" end i = i + 1 end end end end end @h.keys.sort.each do |c| @h[c].keys.sort.each do |m| @h[c][m].keys.each do |o| begin connection.exec(<<-EOS) INSERT INTO #{tbl} (category, model, oss, package, ossurl) VALUES(\'#{c}\', \'#{m}\', \'#{o['oss']}\', \'#{o['package']}\', \'#{o['ossurl']}\'); EOS rescue => e p e puts "#{c}|||#{m}|#{o['oss']}|#{o['package']}|#{o['ossurl']}" raise e end if (i % 1000 == 0) then now "insert #{i}" end i = i + 1 end end end end end def dbgputs str if ($OPTS[:debug]) then STDERR.puts str end end # # 各モデルのページをスキャンする # def scan_model url, models, _h dbgputs "scan_model: url=#{url}" charset = nil a = [] html = open(url) do |f| charset = f.charset # 文字種別を取得 f.read # htmlを読み込んで変数htmlに渡す end doc = Nokogiri::HTML.parse(html, nil, charset) doc.xpath('//table[2]').each do |node| node.css('a').each do |anode| h = {} oss = anode.inner_text.strip ossurl = anode.attribute('href').value package = ossurl.sub(/^(.*\/)(.*)$/) {$2} if !(oss.include? 'Copyright') then h['oss'] = oss h['ossurl'] = ossurl h['package'] = package a.push h end end end $product_oss.set_osses_to_models models, a, _h a end # # 各年のページをスキャンする # def scan_year url, _h dbgputs "scan_year: url=#{url}" charset = nil h = {} html = open(url) do |f| charset = f.charset # 文字種別を取得 f.read # htmlを読み込んで変数htmlに渡す end doc = Nokogiri::HTML.parse(html, nil, charset) doc.xpath('//table[2]').each do |node| node.css('a').each do |anode| models = anode.inner_text.split(/\s*\/\s*/) uri = URI.join(url, anode.attribute('href').value) unless h[uri] then # 既にジャンプしたページならば飛ばない # 製品モデルのページにジャンプしてスキャン h[uri] = scan_model uri, models, _h # ossesを返す else $product_oss.set_osses_to_models models, h[uri], _h end end end end # # 各エリアのページをスキャンする # def scan_area url, _h dbgputs "scan_area: url=#{url}" charset = nil html = open(url) do |f| charset = f.charset # 文字種別を取得 f.read # htmlを読み込んで変数htmlに渡す end doc = Nokogiri::HTML.parse(html, nil, charset) doc.xpath('//table[2]').each do |node| node.css('a').each do |anode| _hh = $product_oss.set_year anode.inner_text, _h scan_year URI.join(url, anode.attribute('href').value), _hh end end end # # 各カテゴリのページをスキャンする # def scan_category url, _h dbgputs "scan_category: url=#{url}" charset = nil h = {} html = open(url) do |f| charset = f.charset # 文字種別を取得 f.read # htmlを読み込んで変数htmlに渡す end doc = Nokogiri::HTML.parse(html, nil, charset) doc.xpath('//table[2]').each do |node| node.css('a').each do |anode| if $product_oss.last_ctg == 'TV' _hh = $product_oss.set_area anode.inner_text, _h scan_area URI.join(url, anode.attribute('href').value), _hh else models = anode.inner_text.split(/\s*\/\s*/) uri = URI.join(url, anode.attribute('href').value) unless h[uri] then # 既にジャンプしたページならば飛ばない # 製品モデルのページにジャンプしてスキャン h[uri] = scan_model uri, models, _h # ossesを返す else $product_oss.set_osses_to_models models, h[uri], _h end end end end end def now msg STDERR.puts "#{msg}:#{Time.now}" end public :now # # main routine begin # now "start." # スクレイピング先のURL # トップカテゴリのリストが並ぶページ url = 'http://panasonic.net/avc/oss/' $OPTS = {} opt = OptionParser.new opt.on('--debug') {|v| $OPTS[:debug] = v} opt.on('--print') {|v| $OPTS[:print] = v} opt.on('--db') {|v| $OPTS[:db] = v} opt.on('--createtbl=TBL') {|v| $OPTS[:createtbl] = v} opt.parse!(ARGV) $product_oss = ProductOSS.new charset = nil html = open(url) do |f| charset = f.charset # 文字種別を取得 f.read # htmlを読み込んで変数htmlに渡す end # p html # htmlをパース(解析)してオブジェクトを作成 doc = Nokogiri::HTML.parse(html, nil, charset) # 2個目のTABLE doc.xpath('//table[2]').each do |node| # link node.css('a').each do |anode| h = $product_oss.set_ctg anode.inner_text # 各トップカテゴリのページに飛んでスキャン scan_category URI.join(url, anode.attribute('href').value), h end end now "site parsing finished." if ($OPTS[:print]) then $product_oss.print_all end if ($OPTS[:db]) then # connect to the PostgreSQL DB. # User, Password, Databaseはデフォルト設定 now "connecting to the DB." connection = PG::connect(:host => "localhost") begin if ($OPTS[:createtbl]) then connection.exec("drop table if exists #{$OPTS[:createtbl]};") $product_oss.create_tbl connection, $OPTS[:createtbl] $product_oss.insert_tbl connection, $OPTS[:createtbl] end ensure connection.finish end end
true
d586d0d3a18f89c88c011077535096376d9bdd1b
Ruby
ziptrade/kyc-admin
/lib/applications/single_sign_on.rb
UTF-8
680
2.625
3
[ "MIT" ]
permissive
module Applications class SingleSignOn def initialize(auth_application, jwt_config) @auth_application = auth_application @jwt_config = jwt_config end def authenticate_user_with(auth_token) user_auth_token, redirect_to_path = jwt_decoder.decode(auth_token) @auth_application.sign_in find_user_by(user_auth_token) redirect_to_path end private def find_user_by(user_auth_token) user = User.find_by(auth_token: user_auth_token) raise "Invalid User auth token [#{user_auth_token}]" unless user.present? user end def jwt_decoder JWTAuthentication::Decoder.new(@jwt_config) end end end
true
c093ebcebfe51b21b8a6b81db4094d6322b0a79e
Ruby
giangbimin/goodeats
/app/services/show_order_service.rb
UTF-8
659
3.03125
3
[ "Apache-2.0" ]
permissive
class ShowOrderService attr_reader :foods, :total def initialize(current_orders) @current_orders = current_orders prepare_data end private def prepare_data prepare_foods prepare_total end def prepare_foods @foods = FoodDecorator.decorate_collection(Food.find(id_quantity_hash.keys)) @foods.each { |food| food.order_quantity(id_quantity_hash["#{food.id}"]) } end def prepare_total @total = @foods.reduce(0) { |result, food| result + food.total_amount } end def id_quantity_hash @current_orders.inject(Hash.new(0)) { |result, id| result[id] += 1 result } end end
true
1f6746843b1395cb3b9a7c23d77a5d9475d97ce4
Ruby
gaborfoldes/originations
/lib/LOC/Lines.rb
UTF-8
2,728
2.65625
3
[]
no_license
require "date" module LOC class Lines SEPARATOR = "\t" attr_accessor :lines def initialize @lines = {} @exclusions = {} end def put(line) @lines[line.id] = line end # display info def print(ids=nil) puts LineOfCredit::HEADER + "\n" if ids.nil? then @lines.each do |id, line| puts line.to_s + "\n" end else ids = [ids] if ids.is_a? Fixnum ids.each do |id| puts lines[id].to_s + "\n" end end return "Done" end def print_csv(ids=nil) puts LineOfCredit::COL_NAMES.join(",") + "\n" if ids.nil? then @lines.each do |id, line| puts line.to_csv + "\n" end else ids = [ids] if ids.is_a? Fixnum ids.each do |id| puts lines[id].to_csv + "\n" end end return "Done" end def show(ids) build(ids) print(ids) # puts lines[id].ledger end # load data def by_email(email) return SmartLineDB.ids_by_email(email) end def by_app_number(app_number) return SmartLineDB.ids_by_app_number(app_number) end def build(ids=nil) if ids.nil? then SmartLineDB.get_line.each { |row| parse_line row } SmartLineDB.get_draws.each { |row| parse_draw row } SmartLineDB.get_payments.each { |row| parse_payment row } move_forward_to Date.today else ids = [ids] if ids.is_a? Fixnum ids.each do |id| SmartLineDB.get_line(id).each { |row| parse_line row } SmartLineDB.get_draws(id).each { |row| parse_draw row } SmartLineDB.get_payments(id).each { |row| parse_payment row } @lines[id].move_forward_to Date.today end end return "Done" end def parse_line(s) s[0] = Date.parse(s[0]) s[1] = s[1].to_i s[3] = s[3].to_i s[5] = s[5].to_f s[6] = Date.parse(s[6]) put(LineOfCredit.new(*s)) end def load_lines(file_name) File.open(file_name, "r").each_line do |row| parse_line row.strip.split(SEPARATOR) end end def parse_draw(s) l = @lines[s[0].to_i] l.draw(Date.parse(s[1]), s[2].to_f) if !l.nil? end def load_draws(file_name) File.open(file_name, "r").each_line do |row| parse_draw row.strip.split(SEPARATOR) end end def parse_payment(s) l = @lines[s[0].to_i] l.pay(Date.parse(s[1]), s[2].to_f) if !l.nil? end def load_payments(file_name) File.open(file_name, "r").each_line do |row| parse_payment row.strip.split(SEPARATOR) end end # get all lines in sync def move_forward_to(date) @lines.each do |id, line| line.move_forward_to date end end # queries def lines_due(date) ids = [] @lines.each do |id, line| ids.push id if line.next_due_date == date end return ids end end end
true
c4c99ee0968ec7aa60bc6f1c2b9ea27872303660
Ruby
tbeau5595/pokemon-scraper-houston-web-career-021819
/lib/pokemon.rb
UTF-8
913
3.359375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" require "sqlite3" db = SQLite3::Database.new('pokemon.db') class Pokemon # attr_reader :name, :db, :type attr_reader :db attr_accessor :id, :name, :type, :hp @@all = [] def initialize(id: nil, name: nil, type: nil, db: nil, hp: nil) @id = id @name = name @type = type @db = db @hp = hp @@all << self end def self.save(name, type, db) db.execute ("INSERT INTO pokemon (name, type) VALUES ('#{name}', '#{type}')") end def self.find(id, db) new_pokemon = db.execute ("SELECT * FROM pokemon WHERE id == '#{id}'") returned_pokemon = Pokemon.new(id: new_pokemon[0][0], name: new_pokemon[0][1], type: new_pokemon[0][2], hp: new_pokemon[0][3]) returned_pokemon end def alter_hp(hp, db) db.execute "UPDATE pokemon SET hp = '#{hp}' WHERE id == '#{id}'" end end
true
31a87feaf468ab917be266ba156a17217b5d548d
Ruby
whoojemaflip/aoc
/2017/12/part_2.rb
UTF-8
1,105
3.59375
4
[]
no_license
def assert_equal(a, b) raise unless a == b end data = File.read('input.txt').strip test_data = <<EOF 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5 EOF def parse(str) regex = %r{^(\d*) <-> (.*)$} strs = str.split("\n").map do |line| matches = regex.match line { from: matches[1].to_i, to: matches[2].split(', ').map(&:to_i) } end strs.reduce({}) { |acc, l| acc.tap { acc[l[:from]] = l[:to] } } end def explore_program_group(start, parsed_data) follow_up = [start] investigated = [] until follow_up.empty? current = follow_up.shift next_data = parsed_data[current] || [] follow_up.concat next_data.delete_if { |i| investigated.include? i } investigated << current end investigated.uniq end def count_programs(parsed_data) count = 0 until parsed_data.empty? result = explore_program_group(parsed_data.first[0], parsed_data) result.each do |i| parsed_data.delete(i) end count += 1 end count end assert_equal count_programs(parse test_data), 2 puts count_programs(parse data)
true
16020292bc1c64d90c9355779d465b94c46ef60c
Ruby
JustinStoddard/CasinoProject
/poker.rb
UTF-8
4,189
3.75
4
[]
no_license
require_relative 'customer' require_relative 'deck' #deck array should be hashes with three keys - number, suit, value class Poker attr_accessor :customer, :player_hand, :house_hand, :line_spread, :cash_pot, :hand_values def initialize (customer) @customer = customer @player_hand = [] @house_hand = [] @line_spread = [] @cash_pot = [] @hand_values = [ {name: 'one pair', value: 1} {name: 'two pair', value: 2} {name: 'three of a kind', value: 3} {name: 'straight', value: 4} {name: 'flush', value: 5} {name: 'full house', value: 6} {name: 'four of a kind', value: 7} {name: 'straight flush', value: 8} ] startup_deal end def startup_deal puts 'WELCOME TO TEXAS HOLD EM' puts "========================" puts 'Ante is $2' puts 'Enter D to deal new hand' first_input = gets.strip.downcase if first_input == 'd' @cash_pot << #take value of 2 from user wallet array @user_hand << #take two random cards from deck array @house_hand << #take two random cards from deck array bet_screen else startup_deal end end #need to add in a block if user tries to bet more than in their wallet def bet_screen puts 'Current cash pot = $' @cashpot.total x 2 puts 'Your hand:' print @player_hand puts 'Line spread:' print @line_spread puts 'Would you like to make a bet? Press Y or N' bet_ask = gets.strip.downcase if bet_ask == 'y' puts 'Enter bet dollar amount' bet_amt = input.strip.to_f #evaluate @house_hand to see if it should match or fold if yes puts 'Casino has decided to match your bet' @cash_pot << bet_amts << #from user wallet array else no puts 'Casino has folded.' you_win end elsif bet_ask == 'n' deal_next else bet_screen end end def deal_next if @line_spread.length == 0 @line_spread << #take three random cards from the deck array puts 'The line deal is:' print @line_spread bet_screen elsif @line_spread.length == 5 hand_eval else @line_spread << #take one random card from the deck array puts 'The next line card is:' puts @line_spread.last bet_screen end end def you_lose puts 'You lose!' puts @cash_pot.total x 2 puts 'Has been entered into Lot Lizard Casinos already filthy rich coffers' puts 'Press P to play again or any key to exit' play_again = gets.strip.downcase if play_again == 'p' startup_deal else exit end end def you_win 'You win!' puts 'The cash pot winnings of:' puts @cash_pot.value.total x 2 puts 'Has been added to your wallet.' #double the value of the cash pot array and deposit to user wallet array puts 'Press P to play again or any key to exit' play_again = gets.strip.downcase if play_again == 'p' startup_deal else exit end end #need to combine the hand with the line array first def hand_eval if array has 5 inputs with the same suit run eval_for_straight if yes hand_value = 8 (royal flush) else hand_value = 5 (flush) end elsif 4 array values all equal eachother? hand_value = 7 (4 of a kind) elsif run eval_for_straight if yes hand_value = 4 (straight) end elsif 3 array values all equal eachother? if the remaining array values have a pair? hand value = 6 else hand value = 3 end elsif 2 array values all equal eachother? if the remaining array values have a pair? hand value = 2 else hand value = 1 end elsif hand value = 0 end end def final_comparison if user hand value > than house hand value you_win elsif house hand value > user hand value you_lose else compares hands (i.e. which pair is higher) end end def eval_for_straight end def house_match_or_fold hand_eval if @house_hand.length + @line_spread.length = 0 end end
true
383fc5e4c69efb928666381f33eca8f7c103fa92
Ruby
rabble/rillow
/lib/rillow_helper.rb
UTF-8
847
3.25
3
[]
no_license
module RillowHelper # The find_attribute helper method is to provide a easy eay to find a attribute within the hash and array # Examples: # rillow = Rillow.new ('your-zillow-service identifier') # result = rillow.get_search_results('2114 Bigelow Ave','Seattle, WA') # valuationRange = result.find_attribute 'valuationRange' def find_attribute(key,obj=nil) if obj==nil then obj=self end if obj.is_a? Hash then obj.each { |k,v| if k==key then return v else result = find_attribute(key,v) if result != nil then return result end end } elsif obj.is_a? Array then obj.each {|o| result = find_attribute(key,o) if result != nil then return result end } end return nil end end
true
38949708c65103af3d0616d028d2210543b5dc97
Ruby
kat-siu/ruby-notes
/nil-false-evaluation.rb
UTF-8
1,381
4.625
5
[]
no_license
# if-else conditionals name = 'Xavier' if name == 'Javier' puts 'What a nice name!' elsif name == 'Xavier' puts 'Another nice name!' end # The only difference between or and || is their precedence. || has a higher precedence than or. if name == 'Javier' or name == 'Xavier' then puts 'Welcome ' + name + '!' end # You may be used to thinking that a false value may be represented as a zero, a null # string, a null character, or various other things. But in Ruby, all of these *values* # are true; in fact, everything is true except the reserved words false and nil. # In Ruby, nil and false evaluate to false, everything else (including true, 0) means true. puts nil || 2008 # 2008 puts false || 2008 # 2008 puts "ruby" || 2008 # ruby # nil and false are not the same things. Both have a false value and also remember # that everything in Ruby is an object. testValue = 0 if testValue then # 0 evaluates to true puts 'testValue is ' + testValue.to_s + ' and evaluates to true' end puts NIL.class # NilClass puts nil.class # NilClass # FALSE is synonym for false puts FALSE.class #FalseClass puts false.class #FalseClass puts false.object_id # 0 # A common idiom is to use || to assign a value to a variable only if that variable isn't already set. myVar = myVar || "default value" # or, more idiomatically, as: myVar ||= "default value"
true
3dfe961c574ad8f7a26e7cead9181cff5fc4b3a1
Ruby
404pnf/itest-find-similar-strings
/find_duplicate_records.rb
UTF-8
1,507
3.203125
3
[]
no_license
# ## 使用方法 # # USAGE: ruby script.rb inputfile # # ---- require 'csv' # require 'test/unit' require 'digest/md5' require 'pp' # ## 命名空间呗 module ItestFindDuplicateRecords # inputfile is a csv file with the format: # id, text # id, text # ... # # We process the records with following steps # 1. parse csv, make it an array of arrays # 2. make a hash of which each value is an array # 3. caclulate md5sum of each record's text, use the md5sum as key, and add the id to the value # 4. find those keys with multiple ids. Return the result in an array # HELPER FUNCTIONS # \W means charcaters not in range [a-zA-z0-9_] # dash '-' is removed, but underscore '_' is kept # whitespace is not part of \w so they are removed, too! def self.remove_non_words_and_downcase(str) str.downcase .gsub(/\W/, '') end # INPUT [id, text] # OUTPUT [md5sum(text), [id1, id10 ... ]] def self.find_duplicate_records(inputfile) db = CSV.read(inputfile).each_with_object(Hash.new { |h, key| h[key] = [] }) do |(id, text), a| key = Digest::MD5.hexdigest(text) a[key] << id end db.each_with_object([]) { |(_, ids), a| a << ids if ids.size > 1 } end end def main inputfile = ARGV[0] || 'records.csv' tmp_r = ItestFindDuplicateRecords.find_duplicate_records(inputfile) r = tmp_r.each_with_object('') { |e, a| a << e.to_csv } pp r File.write('duplicates.txt', r) end # RUN THE MAIN FUNCTION main if __FILE__ == $PROGRAM_NAME
true
ab4e1dceb0a6eefca4c48f1573b72b4e065550f2
Ruby
G07Watch/AA-Classwork
/W5D3/recursion.rb
UTF-8
2,527
4.09375
4
[]
no_license
#Warm up def range(start, endpt) #returns an array of all numbers from start to end excluding end #returns an empty array if end < start rarr = [] return rarr if endpt <= start rarr << start rarr += range(start+1,endpt) end # p range(1,10) #Sum an array recursive def re_sum(arr) return arr[0] if arr.length <=1 arr[0] + re_sum(arr[1..-1]) end # Examples re_sum # a = [] # p re_sum(a) # b = [1] # p re_sum(b) # c = [4,5,6] # p re_sum(c) # Sum an array iterative def it_sum(arr) arr.inject {|sum, n| sum+n} end # Examples it_sum # p it_sum([]) # p it_sum([1]) # p it_sum([4,5,6]) #Exponentiation def exp_1(b,n) return 1 if n == 0 b * exp_1(b,n-1) end # Examples exp_1 # p exp_1(0,1) # p exp_1(1,0) # p exp_1(2, 256) def exp_2(b,n) return 1 if n == 0 if n.even? m = n/2 return exp_2(b,m) * exp_2(b,m) else m = (n-1)/2 return b * exp_2(b,m) * exp_2(b,m) end end # Examples exp_2 # p exp_2(0,1) # p exp_2(1,0) # p exp_2(2,256) # p exp_2(3,4) def deep_dup(arr) dup = [] arr.each do |ele| if ele.is_a?(Array) dup << deep_dup(ele) else dup << ele end end dup end # Examples deep_dup # p deep_dup([1,['a'], [2], [3, [4]]]) def re_fib(n) return [0,1].take(n) if n <= 2 previous = re_fib(n-1) last = (previous[-1] + previous[-2]) previous << last end # p re_fib(18) def it_fib(n) return [0] if n == 0 return [0,1] if n == 1 fib_array = [0,1] i = 2 until i == n next_fib = fib_array[-1] + fib_array[-2] fib_array << next_fib i+=1 end fib_array end # Examples it_fib # p it_fib(18) def bsearch(array, target) return nil if array.empty? # if target isn't found mid = (array.length/2) lower = array[0...mid] upper = array[mid+1..-1] if target == array[mid] return mid elsif target < array[mid] bsearch(lower,target) else subsearch = bsearch(upper,target) if subsearch == nil return nil else return bsearch(upper,target) + (mid+1) end end end # p bsearch([1, 2, 3], 1) # => 0 # p bsearch([2, 3, 4, 5], 3) # => 1 # p bsearch([2, 4, 6, 8, 10], 6) # => 2 p bsearch([1, 3, 4, 5, 9], 5) # => 3 # p bsearch([1, 2, 3, 4, 5, 6], 6) # => 5 # p bsearch([1, 2, 3, 4, 5, 6], 0) # => nil # p bsearch([1, 2, 3, 4, 5, 7], 6) # => nil # p 1/2
true
5adbbd33a97fb0bad9f7392042b166dbe24da243
Ruby
zwaarty/project_euler
/ruby/problem_054.rb
UTF-8
2,614
3.796875
4
[]
no_license
class PokerHand def initialize hand @cards = my_cards hand @rank, @highest = decipher end attr_reader :cards, :rank, :highest def win? other if self.rank > other.rank true elsif self.rank == other.rank self.highest > other.highest else false end end private def decipher if a = royal_flush? [10, a] elsif b = straight_flush? [9, b] elsif c = four_of_a_kind? [8, c] elsif d = full_house? [7, d] elsif e = flush? [6, e] elsif f = straight? [5, f] elsif g = three_of_a_kind? [4, g] elsif h = two_pairs? [3, h] elsif i = one_pair? [2, i] else [1, highest_num] end end def to_num c case c.upcase when 'T' 10 when 'J' 11 when 'Q' 12 when 'K' 13 when 'A' 14 else c.to_i end end def my_cards hand hand.collect do |nm| n_and_m = nm.chars [to_num(n_and_m[0]), n_and_m[1]] end end def marks cards.collect { |c| c.last } end def nums cards.collect { |c| c.first } end def highest_num nums.max end def royal_flush? royal? and flush? ? highest_num : false end def straight_flush? straight? and flush? ? highest_num : false end def royal? nums == [*10..14] end def straight? nums.sort.each_cons(2) { |i, j| return false until (j - i) == 1 } nums.last end def flush? marks.uniq.length == 1 ? highest_num : false end def four_of_a_kind? maxnum = nums.group_by { |e| e }.max { |a, b| a[1].length <=> b[1].length } maxnum.last.length == 4 ? maxnum.first : false end def three_of_a_kind? maxnum = nums.group_by { |e| e }.max { |a, b| a[1].length <=> b[1].length } maxnum.last.length == 3 ? maxnum.first : false end def two_pairs? pairs = nums.group_by { |e| e }.select { |k, v| v.length == 2} pairs.length == 2 ? pairs.max[0] : false end def one_pair? pairs = nums.group_by { |e| e }.select { |k, v| v.length == 2} pairs.length == 1 ? pairs.max[0] : false end def full_house? a = three_of_a_kind? b = one_pair? a and b ? a : false end end win_count = 0 open('poker.txt') do |f| while line = f.gets arr = line.split player1, player2 = PokerHand.new(arr[0..4]), PokerHand.new(arr[5..9]) win_count += 1 if player1.win?(player2) puts "#{player1.cards}, #{player1.rank}, #{player1.highest}" puts "#{player2.cards}, #{player2.rank}, #{player2.highest}" puts player1.win?(player2) end end p win_count
true
084cae8d1f54d979f89c67ad9f0d791327cde361
Ruby
paulipayne/oo-email-parser-v-000
/lib/email_parser.rb
UTF-8
352
3.09375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class EmailParser attr_accessor :emails def initialize(emails) @emails = emails end def parse unique_emails_list = [] emails_list = self.emails.split(/( |\, )/) emails_list.each_with_index do |item, index| if index.even? && !(unique_emails_list.include?(item)) unique_emails_list << item end end unique_emails_list end end
true
9d112f606144ff0bf5cf25692779eb34ab03aca5
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz112_sols/solutions/Sander Land/str_eq.rb
UTF-8
320
3.203125
3
[ "MIT" ]
permissive
require 'matrix' class String def to_freq ('a'..'z').map{|c| Rational(count(c)) } # use Rational for stability in calculating rank end end def has_string_eqn(words) table = words.uniq.map{|w| w.downcase.gsub(/[^a-z]/,'').to_freq }.transpose nullity = words.length - Matrix[*table].rank return nullity > 0 end
true
199f575ff00e6f6a2d7a81118c601cf69588516c
Ruby
MikeSap/cli-applications-guessing-game-chi01-seng-ft-091420
/guessing_game_cli.rb
UTF-8
454
4.125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Code your solution here! def prompt puts"Guess a number from 1-6!" end def num_gen rand(6) + 1 end def capture_input gets.chomp end def goodbye puts "Goodbye!" end def run_guessing_game answer = num_gen puts"Guess a number from 1-6!" user_guess = capture_input if user_guess.to_i == answer puts "You guessed the correct number!" elsif user_guess == "exit" goodbye else puts "Sorry! the computer guessed #{answer}." end end
true
9db5ee8e61c2f57ed8f0e2c5c4d265b0558ee43c
Ruby
chrisstafford/learn-ruby
/ex15.rb
UTF-8
977
4.3125
4
[]
no_license
# Sets the variable filename to the first argument filename = ARGV.first # Sets the variable prompt to > prompt = "> " # Sets the variable to the file contained in the variable filename txt = File.open(filename) # Prints out the text "Here's your file" then the contents of the variable filename as a string puts "Here's your file: #{filename}" # Prints out the contents of the files opened in the variable txt puts txt.read() # Prints out the text "I'll also ask you to type it again:" puts "I'll also ask you to type it again:" # Prints out the contents of the variable prompt wihout a linebreak print prompt # Assings the variable file_again to what was captured at the command line and removes and trailing line breaks or spaces file_again = STDIN.gets.chomp() # Opens the file from the variable file_again and assigns it to the variable txt_again txt_again = File.open(file_again) # Prints out the contents of the file assigned to txt_again puts txt_again.read()
true
a689a8e3600311efe05ccf50ffbeead2052a845a
Ruby
maran/rlp-ruby
/lib/encode.rb
UTF-8
498
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module RLP module Encode; def to_rlp(is_array = false) return [0x80] if self == "" length = self.bytes.to_a.length offset = [0x80, 0xb7] offset = [0xc0, 0xf7] if is_array if length == 1 && !is_array && self.bytes.first <= 0x7f return [self.bytes.first] elsif length <= 55 return [(offset[0]+length), *self.bytes] elsif length > 55 return [(offset[1]+length.bytesize),*length.bytes, *self.bytes] end end end end
true
bd0070cdbad99402b67116174e8a5cc2b616b07b
Ruby
RaduMatees/TheOdinProject
/Ruby-basics/learn-ruby2.rb
UTF-8
221
2.796875
3
[]
no_license
# def grandfatherClock(&block) # todayHours = Time.now.hour # todayHours.times do # block.call # end # end # # grandfatherClock do # puts 'DONG!' # end def log(blockDescription, &block) block.call end log
true
daa21f0befcf491cc74118c2db1cab953e54a1d6
Ruby
MelnikovaK/rubyLab
/spec/unit/deposits_spec.rb
UTF-8
1,268
2.890625
3
[]
no_license
# frozen_string_literal: true require 'deposits' RSpec.describe Deposits do before do @deposits = Deposits.new @deposit = Deposit.new('Travel', 4, true) @deposit1 = Deposit.new('Super', 10, false) end describe '#delete_deposit' do it 'should delete deposit by index' do ped_list = Deposits.new ped_list.add(@deposit) ped_list.delete_deposit(0) expect(ped_list[0]).to eq(nil) end end describe '#get_deposit_by_type' do it 'should return the deposit which type is input' do ped_list = Deposits.new ped_list.add(@deposit1) ped_list.add(@deposit) expect(ped_list.get_deposit_by_type('Super')).to eq(@deposit1) end end describe '#add' do it 'should add deposit' do dep_list = Deposits.new dep_list.add(@deposit) expect(dep_list[0]).to eq(@deposit) end end describe '#by_index' do it 'should return deposit by index' do dep_list = Deposits.new index = 0 dep_list.add(@deposit) expect(dep_list.by_index(index)).to eq(@deposit) end end describe '#each' do it 'should return each deposit from deposit list' do @deposits.add(@deposit) @deposits.add(@deposit1) expect(@deposits.each.to_a).to eq([@deposits[0], @deposits[1]]) end end end
true
970eeb8bf98dfe4aa043dc3d73308d9705505f40
Ruby
zlschatz/phase-0
/week-5/die-class/my_solution.rb
UTF-8
2,320
4.53125
5
[ "MIT" ]
permissive
# Die Class 1: Numeric # I worked on this challenge [by myself, with: ] # I spent [] hours on this challenge. # 0. Pseudocode # Input: number of sides # Output: number of sides / random value within range # Steps: # Define class # initialize method passing the argument of sides # define variable sides # define method sides returning the variable of sides # define roll to return rand number # include if statement to return error for values less than 1 # 1. Initial Solution class Die def initialize(sides) @sides = sides if sides < 1 raise ArgumentError.new("What die have you rolled with a value of less than one?") end def sides return @sides end def roll return rand 1..sides end end # 3. Refactored Solution #Seems pretty solid in my opinion. # 4. Reflection =begin What is an ArgumentError and why would you use one? ArgumentErrors are notices that can be included in codes to notify users of class parameters. In this challenge, we set up the die class, but would not want a number less than 1 to be passed through the class. To solve this issue, we include an ArgumentError that returns an error message if the user inputs a value less than 1. What new Ruby methods did you implement? What challenges and successes did you have in implementing them? The ArgumentErrors.new method was pretty straight forward. The example provided in the challenge made it easy to implement. What is a Ruby class? A Ruby class is a collection of methods that create individual objects. The methods act as smaller parts to the whole class, which ultimately produces the desired object. Each method preserves a different function to be activitated in a given circumstance. Why would you use a Ruby class? We would use classes to execute similar methods with alike variables that may rely on one another. These methods can build upon each other, or result in separate object creation. What is the difference between a local variable and an instance variable? Local variables are not available outside the method while instance variables are available across methods within a particular class. Instance methods are preceded by the @ symbol. Where can an instance variable be used? Instance variables can be used within methods running inside a class. =end
true
e6513409cf953a4ddca9907bdf364df554b09ea7
Ruby
abowler2/small_problems
/medium1/rotation3.rb
UTF-8
661
4.0625
4
[]
no_license
def rotate_array(array) array.slice(1, array.size) << array[0] end def rotate_rightmost_digits(number, n) num_array = number.to_s.split('') right_side = num_array.slice(-n, n) left_side = num_array.slice(0, num_array.size - n) (left_side + rotate_array(right_side)).join.to_i end def max_rotation(number) number_size = number.to_s.size while number_size >= 2 number = rotate_rightmost_digits(number, number_size) number_size -= 1 end number end p max_rotation(735291) == 321579 p max_rotation(3) == 3 p max_rotation(35) == 53 p max_rotation(105) == 15 # the leading zero gets dropped p max_rotation(8_703_529_146) == 7_321_609_845
true
98cdb46065bec123faa5dece343d6dbf42b9a3fa
Ruby
deadelf79/Redenik
/code/module.Redenik.GameData.class.Person.rb
UTF-8
4,319
2.65625
3
[]
no_license
# encoding utf-8 class Redenik::Person < Redenik::Basic FEATURES___TOO_LOW = (1..3) FEATURES___LOW = (4..8) FEATURES___NORMAL = (9..11) FEATURES___HIGH = (12..16) FEATURES___SUPERB = (17..20) LEVEL___MAXIMUM = 100 attr_reader :appearance, :stats, :equips attr_reader :exp, :level, :skills, :sex, :gender attr_reader :hungriness, :max_hungriness attr_reader :drunkenness, :max_drunkenness attr_reader :feel_monsters, :feel_traps attr_reader :can_carry_weight def initialize(name,appearance,stats) @name, @appearance, @stats = name, appearance, stats @level = 1 @current_exp = 0 @surname, @secondname = "", "" @sex, @gender = :male, :getero @drunkenness, @max_drunkenness = 0, 100 @base_exp = rand(10..30) @divider = 3 @late_game_modifier = 1.2345 @exp_curve_storage = [] _generate_exp_curve _gen_actor_by_stats(stats) reset_exp super(0,0,[],0) end def reset_exp(level=:current) @level = 1 unless level==:current _reset_exp(@level) end def exp_curve(level) range = @exp_curve_storage[level] end def recover @health = @max_health @mana = @max_mana @hungriness = 0 end # Сильный? # Является ли характеристика ST выше нормальной (по умолчанию - от 13 и более) def strong? return false if stats[:st]<FEATURES___NORMAL.first return false if stats[:st]<=FEATURES___NORMAL.last true end # Слабый? def weak? return false if stats[:st]>=FEATURES___NORMAL.first true end # Проворный? # Является ли характеристика DX выше нормальной (по умолчанию - от 13 и более) def agile? return false if stats[:dx]<FEATURES___NORMAL.first return false if stats[:dx]<=FEATURES___NORMAL.last true end # Неуклюжий? def clumsy? return false if stats[:dx]>=FEATURES___NORMAL.first true end # Умный? # Является ли характеристика IQ выше нормальной (по умолчанию - от 13 и более) def smart? return false if stats[:iq]<FEATURES___NORMAL.first return false if stats[:iq]<=FEATURES___NORMAL.last true end # Глупый? def stupid? return false if stats[:iq]>=FEATURES___NORMAL.first true end # Живучий? # Является ли характеристика HT выше нормальной (по умолчанию - от 13 и более) def survivable? return false if stats[:ht]<FEATURES___NORMAL.first return false if stats[:ht]<=FEATURES___NORMAL.last true end # Нежизнеспособный? def unviable? return false if stats[:ht]>=FEATURES___NORMAL.first true end # Очаровательный? def charming? return false if stats[:cr]<FEATURES___NORMAL.first return false if stats[:cr]<=FEATURES___NORMAL.last true end # Грубый? def rough? return false if stats[:cr]>=FEATURES___NORMAL.first true end private def _check_hungry return :too_hungry if @hungriness>@max_hungriness*4/5 return :not_so_hungry if @hungriness<@max_hungriness*3 /5 return :hungry end def _gen_actor_by_stats(stats) @max_health = stats[:ht]*3+stats[:ht]*stats[:st]-stats[:cr]*3 @max_mana = stats[:iq]*3+stats[:ht]*3+stats[:cr]-stats[:dx] @max_melee = stats[:st]*3-stats[:ht]*2 @max_hungriness = (stats[:ht]*12-stats[:st]*6+stats[:dx]*4)*2 @atk_evade_chance = stats[:dx]*3-stats[:iq]*2 # in percent @can_carry_weight = stats[:st]*3+stats[:dx]/3 # in kg @feel_traps_chance = [stats[:iq]*3-stats[:dx]*2, 0].max # in percent @gold_modifier = (stats[:dx]*3-stats[:iq]*3).abs # in percent @gold_reward_modifier = [stats[:cr]-stats[:iq],0].max # in percent @shop_cost_modifier = [stats[:cr]*2-stats[:iq]*2,0].max # in percent @conviction_modifier = [stats[:ht]*2+stats[:iq]*3-stats[:cr]*3,0].max # in percent, шанс убеждения recover end def _reset_exp(level) @exp = exp_curve(level).first end def _generate_exp_curve value = @base_exp LEVEL___MAXIMUM.times{|i| value+=(i.to_f/@divider).to_i+(i*@late_game_modifier).to_i+@base_exp last = value + ((level+1).to_f/@divider).to_i+((level+1)*@late_game_modifier).to_i+@base_exp @exp_curve_storage[i] = (value...last) } @exp_curve_storage end end
true
18aafd89d2a8ea108300eac4aba9acac50b1e915
Ruby
braddeibert/learn_ruby
/05_book_titles/book.rb
UTF-8
1,408
3.609375
4
[]
no_license
class Book # write your code here def initialize end def title=(title) @title = title end def title words = @title.split(" ") formatted_title = "" conjunctions = ["for", "and", "nor", "but", "or", "yet", "so"] prepositions = ["about", "above", "across", "after", "against", "along", "amid", "among", "anti", "around", "as", "at", "before", "behind", "below", "beneath", "beside", "besides", "between", "beyond", "but", "by", "concerning", "considering", "despite", "down", "during", "except", "excepting", "excluding", "following", "for", "from", "in", "inside", "into", "like", "minus", "near", "of", "off", "on", "onto", "opposite", "outside", "over", "past", "per", "plus", "regarding", "round", "save", "since", "than", "through", "to", "toward", "towards", "under", "underneath", "unlike", "until", "up", "upon", "versus", "via", "with", "without", "within"] articles = ["the", "a", "an"] words.each do |word| if !(prepositions.include?(word) || conjunctions.include?(word) || articles.include?(word)) word = word.capitalize end if formatted_title == "" word = word.capitalize end formatted_title = formatted_title + word + " " end @title = formatted_title.chop end end
true
0cacd2d137f6b0dbbd53319befedaa78b875db8e
Ruby
DamonClark/introtoruby
/variables/example1a.rb
UTF-8
112
3.546875
4
[]
no_license
puts "Can you please type your name into the console?" name = gets.chomp puts "Hello " + name + ", how are you?"
true
69d45686aa29eb52138c49549861e66a6ccd46b1
Ruby
emilyjspencer/ruby-practice1
/dice_game.rb
UTF-8
944
3.921875
4
[]
no_license
puts 'Let\'s play a game! I have two die and I\'m going to roll them. You need to guess the total!' counters = 20 while counters > 0 puts 'Give me a total. You have ' + counters.to_s + ' counters left!' guess = gets.chomp while true if (counters.to_i - guess.to_i) < 0 puts 'You don\'t have that many counters! Try again.' guess = gets.chomp else break end end if guess.to_i > 5 puts guess.to_s + '?! Ahaha. Are you kidding me?' puts 'I\'ll roll two die. Guess the total' else puts guess.to_s + '?! Hmm WHAT How did you guess. Are you cheating?!' puts 'I\'ll roll two die. Guess the total' end total = gets.chomp dice_total = ((1 + rand(6))+(1 + rand(6))) print 'The total was ' + dice_total.to_s + '! ' if dice_total.to_i == total.to_i counters = counters.to_i + guess.to_i puts 'You win! !' else counters = counters.to_i - guess.to_i puts 'Not this time, I\'m afraid!' end end puts 'Yipee! I WON!'
true
44dfe6697703d62fa4f3c6f8d7a9bdf8509b778c
Ruby
Moniet/programming_languages-london-web-051319
/programming_languages.rb
UTF-8
401
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" def reformat_languages(languages) new_hash = {} languages.each do |type, data| data.each do |lang, val| # binding.pry if lang == :javascript new_hash[lang] = val new_hash[lang][:style] = [:oo, :functional] else new_hash[lang] = val new_hash[lang][:style] = [type] end end end new_hash end #reformat_languages(languages)
true
d4040d4251d5af13b0494fc21faee0191d039c60
Ruby
descala/b2b-utils
/peppol-id2ap/peppol-id2ap
UTF-8
2,252
3.078125
3
[]
no_license
#!/usr/bin/env ruby # == Synopsis # Given a Participant ID obtains its Access Point URL(s) # # == Examples # peppol-id2url 9906:05359681003 # # == Usage # peppol-id2url [options] participant_id [document_id] [process_id] # # For help use: peppol-id2url -h # # == Options # -h, --help Displays help message # -v, --verbose Show some additional output # # == Author # Ingent Grup Systems SL require 'optparse' require 'ostruct' require 'rdoc/usage' require "peppol_destination" class App VERSION = '0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin @options = OpenStruct.new @options.verbose = false end def run if parsed_options? && arguments_valid? process_arguments process_command else output_usage end end protected def parsed_options? # Specify options opts = OptionParser.new opts.on('-v', '--verbose') { @options.verbose = true } opts.on('-h', '--help') { output_help } opts.parse!(@arguments) rescue return false true end # True if required arguments were provided def arguments_valid? true if @arguments.length >= 1 end # Setup the arguments def process_arguments @participant_id = @arguments[0] @document_id = @arguments[1] @process_id = @arguments[2] end def output_help output_version RDoc::usage() end def output_usage RDoc::usage('usage') # gets usage from comments above end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command begin pd = PeppolDestination.new(@participant_id,@document_id,@process_id) pd.verbose = @options.verbose aps = pd.access_points puts "Can not find any matching AP" if aps.empty? aps.each do |ap| puts "AP = #{ap[:url]}" puts " accepts document_id #{ap[:document_id]}" unless @document_id puts " accepts process_id #{ap[:process_id]} " unless @process_id end rescue Exception => e puts "Error: #{e.message}" end end end # Create and run the application app = App.new(ARGV, STDIN) app.run
true
e889144ab3404724c47c69dfc69f0eb8b494dcee
Ruby
DouglasAllen/code-Programming_Ruby_3rd_ed
/Part_IV--Ruby_Library_Reference/ch27_Built-in_Classes_and_Modules/Alphabetical_Listing/Module/cdesc-Module.rb
UTF-8
1,795
3.46875
3
[]
no_license
=begin Module < Object (from ~/.rdoc) ------------------------------------------------------------------------------ A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not. Conversely, module methods may be called without creating an encapsulating object, while instancem ethods may not. (See Module#module_function) In the descriptions that follow, the parameter sym refers to a symbol, which is either a quoted string or a Symbol (such as :name). module Mod include Math CONST = 1 def meth # ... end end Mod.class #=> Module Mod.constants #=> [:CONST, :PI, :E] Mod.instance_methods #=> [:meth] ------------------------------------------------------------------------------ Class methods: constants nesting new Instance methods: < <= <=> == === > >= ancestors autoload autoload? class_eval class_exec class_variable_defined? class_variable_get class_variable_set class_variables const_defined? const_get const_set constants freeze include? included_modules instance_method instance_methods method_defined? module_eval module_exec name private_class_method private_instance_methods private_method_defined? protected_instance_methods protected_method_defined? public_class_method public_instance_method public_instance_methods public_method_defined? remove_class_variable to_s =end module Mod include Math CONST = 1 def meth # ... end end p Mod.class #=> Module p Mod.constants #=> [:CONST, :PI, :E] p Mod.instance_methods #=> [:meth]
true
452bfd8862765920f9b2d05886a821a58452a321
Ruby
NorbertLam/ruby-boating-school-dumbo-web-career-010719
/app/models/instructor.rb
UTF-8
998
3.3125
3
[]
no_license
class Instructor attr_reader :name @@all = [] def initialize(name) @name = name @@all << name end def pass_student(student_name, test_name) boat_test = BoatingTest.all.find{ |test| test.student.first_name == student_name and test.test_name == test_name } if boat_test == nil return BoatingTest.new(Student.new(student_name), test_name, "passed", self) else boat_test.test_status = "passed" end boat_test end def fail_student(student_name, test_name) boat_test = BoatingTest.all.find{ |test| test.student.first_name == student_name and test.test_name == test_name } if boat_test == nil return BoatingTest.new(Student.new(student_name), test_name, "failed", self) else boat_test.test_status = "failed" end boat_test end def self.all @@all end end
true
228bdbd044a9750617fc607a10591a93dad179fe
Ruby
RichardLW6/Tealeaf_Week1
/paper_rock_scissors/paper_rock_scissors.rb
UTF-8
2,095
4.15625
4
[]
no_license
#PAPER/ROCK/SCISSORS APPLICATION puts "Play Paper Rock Scissors!" choices = {'p' => 'Paper', 'r' => 'Rock', 's' => 'Scissors'} computer_score = 0 user_score = 0 while true begin puts "Choose one: (P/R/S)" user_answer = gets.chomp.downcase end until choices.keys.include?(user_answer) computer_answer = choices.keys.sample #Convert the choices into real words #Converting User Choice case user_answer when "p" user_answer = "Paper" when "r" user_answer = "Rock" when "s" user_answer = "Scissors" end #Converting Computer Choice case computer_answer when "p" computer_answer = "Paper" when "r" computer_answer = "Rock" when "s" computer_answer = "Scissors" end #Declaring who picked what puts "You picked #{user_answer} and the computer picked #{computer_answer}." #FIGURING OUT THE OUTCOMES #Both choices are equal if user_answer == computer_answer puts "Both sides have chosen the same thing. \nIt's a tie!" #User chooses Paper elsif user_answer == "Paper" if computer_answer == "Rock" puts "You wrap the Computer's Rock in wads of Paper. \nYou win!" user_score += 1 else puts "The Computer cuts your Paper into shreds. \nYou lose!" computer_score += 1 end #User chooses Scissors elsif user_answer == "Scissors" if computer_answer == "Rock" puts "The Computer smashes your Scissors to pieces. \nYou lose!" computer_score += 1 else puts "You cut the Computer's Paper to shreds. \nYou win!" user_score += 1 end #User chooses Rock elsif user_answer == "Rock" if computer_answer == "Scissors" puts "You smash the Computer's Scissors to pieces. \nYou win!" user_score += 1 else puts "The Computer wraps your Rock in wads of Paper. \nYou lose!" computer_score += 1 end end puts "Current Score: \n You: #{user_score}\n Computer: #{computer_score}" #Give option to Play Again, or Stop puts "Play again? (Y/N)" break if gets.chomp.downcase != 'y' end
true
4320f13d1dcf60fece13b819194dafab54d51e57
Ruby
Icicleta/practical_object_oriented_design_in_ruby
/05_Duck_Types/01.rb
UTF-8
1,101
4.5625
5
[]
no_license
# Duck type objects are chameleons that are defined more by their BEHAVIOUR than by their CLASS. This is how the technique gets it's name: # If it walks like a duck, and quacks like a duck, then its class is immaterial - it's a duck. # Duck typing is possible in Ruby, but not in, say, Java, because Ruby is dynamically typed and Java is statically typed. (Most) Static typed languages require the type of their variables and method parameters to be explicitly declared, whereas in dynamically typed languages, the type of the object does not have to be explicitly defined - you can put any value in any variable and pass any argument to any method, without further declaration. It is this very fact that allows duck typing to be possible. # Because - If it walks like a duck, and quacks like a duck, then for all intents and purposes, we can treat it like a duck. So long as it acts like one, we don't need to worry about what it *actually* is. # It's not what an object *is* that matters - it's what an object *does*. # So if it walks like a duck, and talks like a duck - treat it like a duck!
true
397fbf76762f91e8ca3226281a4dd9f871f9870f
Ruby
holderbaum-io/think-about-website
/test/event_test.rb
UTF-8
2,720
2.5625
3
[]
no_license
require 'minitest/autorun' require 'minitest/spec' require 'psych' require 'tmpdir' require 'fileutils' require_relative '../lib/event' REFERENCE_PERFORMANCE = { title: 'my title', track: 'keynote', lang: 'en', abstract: "my\nabstract", speakers: [ { name: 'Speaker 1', slug: 'speaker_1', bio: "I am\nSpeaker 1", position: 'Senior Speaker', company: { name: 'Speaking Company', link: 'https://example.org/company' }, links: [ { name: 'My Website 1', link: 'https://example.org/mywebsite1' } ] }, { name: 'Speaker 2', slug: 'speaker_2', bio: "I am\nSpeaker 2", position: 'Senior Speaker', company: { name: 'Speaking Company', link: 'https://example.org/company' }, links: [ { name: 'My Website 2', link: 'https://example.org/mywebsite2' } ] } ] }.freeze describe Event do before do @tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(@tmpdir, 'talks') end after do FileUtils.remove_entry @tmpdir end it 'has no performances for an empty event' do event = Event.new 'myevent', '/tmp' assert_empty event.keynotes assert_empty event.talks end it 'parses all keys of a yml performance definition' do file = File.join(@tmpdir, 'talks', 'my_slug.yml') File.write(file, Psych.dump(REFERENCE_PERFORMANCE)) event = Event.new 'myevent', @tmpdir assert_equal 1, event.keynotes.size assert_equal 0, event.talks.size keynote = event.keynotes.first assert_equal 'my_slug', keynote.slug assert_equal '/events/myevent/talks/my_slug.html', keynote.path assert_equal 'my title', keynote.title assert_equal "my\nabstract", keynote.abstract assert_equal 'EN', keynote.language assert_equal 2, keynote.speakers.size assert_equal 'Speaker 1 & Speaker 2', keynote.joined_speaker_names assert_equal 'Speaking Company', keynote.joined_company_names assert_equal ['https://example.org/company'], keynote.company_links speaker1 = keynote.speakers.first assert_equal 'speaker_1', speaker1.slug assert_equal( '/images/events/myevent/speakers/speaker_1.jpg', speaker1.image_path ) assert_equal( '/images/events/myevent/speakers/speaker_1_big.jpg', speaker1.big_image_path ) assert_equal 'Senior Speaker', speaker1.job_title assert_equal "I am\nSpeaker 1", speaker1.bio assert_equal 1, speaker1.links.size assert_equal 'My Website 1', speaker1.links.first.name assert_equal 'https://example.org/mywebsite1', speaker1.links.first.link end end
true
465dc8aaea904ba5844678610be0641400be98b6
Ruby
natey37/Black-Thursday
/black_thursday/lib/sales_engine.rb
UTF-8
1,398
2.78125
3
[]
no_license
require_relative './merchant_repository.rb' require_relative './item_repository.rb' require_relative './invoice_repository.rb' require_relative './invoice_item_repository.rb' require_relative './transaction_repository.rb' require_relative "./customer_repository.rb" require 'pry' class SalesEngine attr_reader :merchants, :items, :invoices, :invoice_items, :transactions, :customers def initialize(csv_files) @merchants = create_merchants(csv_files[:merchants]) @items = create_items(csv_files[:items]) @invoices = create_invoices(csv_files[:invoices]) @invoice_items = create_invoice_items(csv_files[:invoice_items]) @transactions = create_transctions(csv_files[:transactions]) @customers = create_customers(csv_files[:customers]) end def self.from_csv(csv_files) new(csv_files) end def create_merchants(file_name) MerchantRepository.new(file_name, self) end def create_items(file_name) ItemRepository.new(file_name, self) end def create_invoices(file_name) InvoiceRepository.new(file_name, self) end def create_invoice_items(file_name) InvoiceItemRepository.new(file_name) end def create_transctions(file_name) TransactionRepository.new(file_name, self) end def create_customers(file_name) CustomerRepository.new(file_name, self) end end
true
87cd03e4e0a5df8239eb851cc4745a9cfe5e73dd
Ruby
avdi/tick
/examples/fake-server.rb
UTF-8
584
2.890625
3
[]
no_license
$:.unshift(File.expand_path('../lib', File.dirname(__FILE__))) require 'rack/fake' fake = Rack::Fake.new("hello", :port => 8700) do get '/hello' do "Hello, world" end get '/goodbye' do "Goodbye, world" end end puts "Starting fake" fake.start puts "Fake started" host = fake.host port = fake.port puts "Host: #{host}; Port: #{port}" puts "Output: #{fake.output}" puts "Using Net::HTTP:" Net::HTTP.get_print(host, '/hello', port) puts url = "http://#{host}:#{port}/goodbye" puts "Using curl #{url}" puts `curl #{url}` puts "Press enter to stop" gets fake.stop
true
ad292a24fab24621b4f20e721e6853ed1c3de48d
Ruby
inem/hamdown
/lib/hamdown/engine.rb
UTF-8
502
2.8125
3
[ "MIT" ]
permissive
require 'hamdown_core' require_relative 'haml_handler' module Hamdown # Main module # Mahine to compile hamdown text to html module Engine # It takes string with hamdown text and compile it to html def self.perform(hd_text = '') return '' if hd_text.nil? || hd_text.size == 0 # step 1: hamdown to haml haml_text = HamdownCore::Engine.call(hd_text) # step 2: haml to html html_text = HamlHandler.perform(haml_text) return html_text end end end
true
14b07da80f615f0427ba41a59f1d23aa7674cb0e
Ruby
xincere-inc/jira_command
/lib/jira_command/prompt/base.rb
UTF-8
3,091
2.609375
3
[ "MIT" ]
permissive
require_relative '../config' require_relative '../jira/sprint' require_relative '../jira/user' require_relative '../jira/issue_type' require 'tty-prompt' module JiraCommand module Prompt class Base attr_writer :prompt, :config def initialize @prompt = TTY::Prompt.new @config = JiraCommand::Config.new.read end def select_board(message: 'Please select board', refresh: false) baord_list = if @config[:boards].nil? || refresh agile_board = JiraCommand::Jira::Board.new(@config) agile_board.list else @config[:boards] end @prompt.select(message) do |menu| baord_list.each do |item| menu.choice name: item[:name], value: item[:id] end end end def select_issue_type(message:, refresh: false) issue_types = if @config[:issue_types].nil? || refresh jira_issue_type = JiraCommand::Jira::IssueType.new(@config) jira_issue_type.list else @config[:issue_types] end @prompt.select(message) do |menu| issue_types.each do |item| menu.choice name: item[:name], value: { id: item[:id], name: item[:name] } end end end def select_project(message:, refresh: false) projects = if @config[:projects].nil? || refresh jira_project = JiraCommand::Jira::Project.new(@config) jira_project.list else @config[:projects] end @prompt.select(message) do |menu| projects.each do |item| menu.choice name: item[:name], value: { id: item[:id], key: item[:key] } end end end def select_user(message:, project_key: nil, refresh: false, additional: []) user_list = if @config[:users].nil? || refresh user_api = JiraCommand::Jira::User.new(@config) user_api.all_list(project: project_key) else @config[:users] end @prompt.select(message) do |menu| additional.each do |item| menu.choice name: item[:name], value: item[:account_id] end user_list.each do |item| menu.choice name: item[:name], value: item[:account_id] end end end def select_sprint(message: 'Please select sprint:', board_id:, state: 'active,future') jira_sprint = JiraCommand::Jira::Sprint.new(@config) res = jira_sprint.list( board_id: board_id, query: { state: state } ) @prompt.select(message) do |menu| res.each do |item| menu.choice name: item[:name], value: item[:id] end end end end end end
true
469f3d68bb61b8eedeab48bceb408db05d287f39
Ruby
kaiamz/Ruby
/ruby-exercise-1.rb
UTF-8
918
4.0625
4
[]
no_license
poem = File.read('the-man-from-snowy-river.txt') lines = poem.lines #/\W+/ is a "regular expression" - a text-searching pattern. # /\s+/ The slashes start and end the pattern. \W means "any non-alphabetic character" # and + means "repeated one or more times" words = poem.split(/\W+/) stanzas = poem.split(/\n\n/) #Example puts "There are #{words.count} words" puts "There are #{words.uniq.count} different words" #uniq removes duplicates #Exercises puts "The second through sixth words are #{words.slice(1..5)}" puts "The poem has #{lines.count} lines in it" puts "The first line has #{lines[0].split(/\W+/).count} words in it" puts "The poem has #{stanzas.count} number of stanzas" first_stanza_lines = stanzas[0].split(/\n/) first_stanza = stanzas[0] puts "The first stanza has #{stanzas[0].split(/\W+/).count} words in it" puts "Here is the poem with its lines randomly rearranged: #{lines.shuffle}"
true
c0c4cb33232280b1091d9ee4a2b5f431ffe3a400
Ruby
codereport/LeetCode
/0019_Problem_1.rb
UTF-8
242
2.953125
3
[]
no_license
# code_report Solution # Problem Link (Contest): https://leetcode.com/contest/leetcode-weekly-contest-19/problems/base-7/ # Problem Link (Practice): https://leetcode.com/problems/base-7/ def convert_to_base7(num) return num.to_s(7) end
true
0d1dff7085593ecb3605afa781910a381002f5b0
Ruby
FillanL/intro-to-tdd-rspec-and-learn-nyc-web-career-021819
/current_age_for_birth_year.rb
UTF-8
114
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def current_age_for_birth_year(birth_year) current_year = 2003 age_of_person = current_year - birth_year end
true
4e8e920a1743505ba7eff9ca39f41f048a4890d9
Ruby
Kmfisher13/Ruby-Basics
/hashes/low_medium_high.rb
UTF-8
340
4.375
4
[]
no_license
# Use Hash#select to iterate over numbers and return a hash containing only # key-value pairs where the value is less than 25. Assign the returned hash # to a variabe named low_numbers and print its value using #p. numbers = { high: 100, medium: 50, low: 10 } low_numbers = numbers.select { |key, value| value < 25 } p low_numbers
true
962e03698e0c3412704276dc40d83ea29694cebc
Ruby
arun-instructor/BEWD11-Arun
/week_10/day_1/book.rb
UTF-8
438
3.609375
4
[]
no_license
class Book attr_accessor :library def initialize @library = [] @book_count = 0 end def all return @library end def add(book) @library.push({ id: @book_count += 1, book: book }) end def show(id) @library.each do |book| if book[:id] == id return book end end end def remove(id) @library.each_with_index do |book, index| if book[:id] == id @library.slice!(index, 1) end end end end
true
ec8e53540055aabd02b89aa6d004e94fb2c7f8ee
Ruby
rymai/on_the_snow
/lib/on_the_snow/client/regions.rb
UTF-8
636
2.65625
3
[ "MIT" ]
permissive
module OnTheSnow class Client # Wrapper for the OnTheSnow REST API regions method. # class Regions module Helper # Gets a list of Region elements which contain all the State/Provinces # listed by OTS. The method can be used to retrieve the list of state # names and state abbrev to pull down information for the region # specific services. # # @see http://www.onthesnow.com/ots/webservice_tools/OTSWebService2009.html#getRegions # def regions @regions ||= get('regions', options: { type: :array }) end end end end end
true
cb523c269685b45ec1603608aa6d92d6a2fad181
Ruby
alexandradlg/THP_scrapping
/THP_scrapping/exo3.rb
UTF-8
2,161
3.296875
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' require 'HTTParty' def get_info_about_incubators(lien) page = Nokogiri::HTML(open(lien)) number_of_pages = page.css('div.nav-links > a.page-numbers:nth-last-child(-n+2)') # Pour connaitre la dernière page = récupération des deux dernier élément de la pagination (dernière page et suivant) last_page = [] number_of_pages.each { |info| page = info.text last_page.push(page) } # Ces deux élément sont pushé dans un array pour ne garder que le dernier numéro de page juste après. x = last_page[0] start = 1 stop = x.to_i # On garde le dernier numéro de page pour construire un range url = "" incubator_names = [] (start..stop).each { |a| if a == 1 url = lien else url = lien + "page/#{a}/" end # Pour la page 1, on garde la lien initial, pour les autres, on prend le lien initial auquel on ajoute page/a/ à chaque boucle pour réspecter le format des urls pages = HTTParty.get(url) website_pages = Nokogiri::HTML(pages) # On construit les nouveaux liens pour chaque page de l'annuaire et on ne garde que l'élément qui nous intéresse, les pages des incubateurs. incubator_pages = website_pages.css('h2.listing-row-title > a') incubator_pages.each { |page| incubator_name = page.text incubator_webpage = page['href'] incub_contact = Hash[incubator_name => incubator_webpage] incubator_names.push(incub_contact) # Ici on prend le nom de l'incubateur + sa webpage sur alloweb et on le met dans un hash. # On push chaque hash dans un array } print incubator_names # incubator_website = # et ici on essaye de récupérer le site internet de l'incubateur... à suivre! } end def perform lien = "http://www.alloweb.org/annuaire-startups/base-de-donnees-startups/annuaire-incubateurs-de-startups/" get_info_about_incubators(lien) end perform
true
26b05967e426acc71c0b21253c84682e0654195e
Ruby
senkadam/MI-RUB-Ukol2
/test/test_reader.rb
UTF-8
690
2.640625
3
[]
no_license
# To change this template, choose Tools | Templates # and open the template in the editor. $:.unshift File.join(File.dirname(__FILE__),'..','lib') require 'test/unit' require 'reader' class TestMain < Test::Unit::TestCase def test_is_number1 r=Reader.new assert_equal(r.is_number?(5),true) end def test_is_number2 r=Reader.new assert_equal(r.is_number?('a'),false) end def test_zero_up1 r=Reader.new assert_equal(r.zero_up?(10),true) end def test_zero_up2 r=Reader.new assert_equal(r.zero_up?(-10),false) end def test_raise r=Reader.new assert_raise StandardError do r.in_error(false) end end end
true
3694f8b5abc054004de3b9ca62e940268ac91989
Ruby
BenCmjn/THP_D_06
/trader_du_lundi.rb
UTF-8
3,601
3.515625
4
[]
no_license
# Lehman Brothers sont très fiers de ton travail. # Ils veulent maintenant te faire travailler sur plusieurs entreprises à la fois. # Ils vont te filer les stocks sous un format hash chaque jour, # et tu devras trouver les meilleurs moments pour acheter et vendre des actions # de chaque entreprise. Voici un exemple avec quelques jours : jour_1 = { :GOO => 15, :MMM => 14, :ADBE => 12, :EA=> 13, :BA => 8, :KO => 10, :XOM => 20, :GPS => 7, :MCD => 11, :DIS => 15, :CRM => 6, :JNJ => 10 } jour_2 = { :GOO => 8, :MMM => 20, :ADBE => 3, :EA=> 10, :BA => 5, :KO => 19, :XOM => 12, :GPS => 6, :MCD => 15, :DIS => 9, :CRM => 10, :JNJ => 17 } jour_3 = { :GOO => 3, :MMM => 8, :ADBE => 15, :EA=> 5, :BA => 10, :KO => 5, :XOM => 15, :GPS => 13, :MCD => 10, :DIS => 18, :CRM => 5, :JNJ => 14 } jour_4 = { :GOO => 17, :MMM => 3, :ADBE => 6, :EA=> 9, :BA => 15, :KO => 6, :XOM => 8, :GPS => 1, :MCD => 10, :DIS => 15, :CRM => 18, :JNJ => 3 } jour_5 = { :GOO => 8, :MMM => 18, :ADBE => 4, :EA=> 6, :BA => 15, :KO => 18, :XOM => 3, :GPS => 12, :MCD => 19, :DIS => 3, :CRM => 7, :JNJ => 9 } jour_6 = { :GOO => 10, :MMM => 12, :ADBE => 8, :EA=> 3, :BA => 18, :KO => 20, :XOM => 5, :GPS => 11, :MCD => 3, :DIS => 9, :CRM => 8, :JNJ => 15 } jour_7 = { :GOO => 17, :MMM => 14, :ADBE => 2, :EA=> 17, :BA => 7, :KO => 13, :XOM => 1, :GPS => 15, :MCD => 15, :DIS => 10, :CRM => 9, :JNJ => 17 } # Fais une fonction trader_du_lundi qui prend en entrée une array de hash # contenant des prix d'action, et qui sort pour chaque entreprise # le meilleur moment pour acheter, et le meilleur moment pour vendre. #------------------------------------------------------------------------------- def trader_du_lundi(jour) classement = jour.sort_by { |comp, rate| rate } puts classement end # trader_du_lundi(jour_1) #------------------------------------------------------------------------------- semaine = [jour_1,jour_2,jour_3,jour_4,jour_5,jour_6,jour_7] def trader_du_mardi(arr) cheap = arr.sort_by do |item| item[:GOO] end puts cheap end # trader_du_mardi(semaine) #------------------------------------------------------------------------------- def trader(jour, *companies) jour.each { |comp| puts "#{jour} \n\n #{comp}" } end trader(semaine) #--------------------------------------------- # [Par moi-même] : # frequencies.each { |word, frequency| puts word + " "+ frequency.to_s } # jour_1.each{|company,prix| puts company+" "+prix} #--------------------------------------------- # [VU SUR] http://www.informit.com/articles/article.aspx?p=1244471&seqNum=9 #--------------------------------------------- # my_hash.keys.sort_by { |key| my_hash[key] }.each do # |key| # puts my_hash[key] # end #--------------------------------------------- # #--------------------------------------------- # [VU SUR] http://www.rubyinside.com/how-to/ruby-sort-hash #--------------------------------------------- # people.sort_by { |name, age| age } # => [[:joan, 18], [:fred, 23], [:pete, 54]] # #--------------------------------------------- # [VU SUR] https://stackoverflow.com/questions/14113909/ruby-sort-by-method #--------------------------------------------- # res = array.sort_by do |item| # item[:name] # end # puts res #--------------------------------------------- # [VU SUR] https://www.codecademy.com/courses/learn-ruby/lessons/methods-blocks-sorting/exercises/splat?action=lesson_resume #--------------------------------------------- # def what_up(greeting, *friends) # friends.each { |friend| puts "#{greeting}, #{friend}!" } # end # what_up("What up", "Ian", "Zoe", "Zenas", "Eleanor")
true
9f54de1f595931468480c1d8c3fa3d7c15e2c14e
Ruby
thomasbeckett/sparta_stuff
/week-8/api_testing/rails_api_som/spec/philosopher_index_spec.rb
UTF-8
1,243
2.65625
3
[]
no_license
require_relative '../lib/philosopher.rb' describe Philosopher do context "getting all the philosophers" do before(:all) do @philosopher_index = Philosopher.new.philosopher_index_service @philosopher_index.get_philosophers end it "should get an array" do expect(@philosopher_index.get_philosophers).to be_an Array end it "should be hashes" do expect(@philosopher_index.get_philosophers).to all be_a Hash end it "should have a name" do expect(@philosopher_index.get_philosophers).to all have_key("name") end it "should have a nationality" do expect(@philosopher_index.get_philosophers).to all have_key("nationality") end it "should have a university" do expect(@philosopher_index.get_philosophers).to all have_key("university") end it "should have quotes" do expect(@philosopher_index.get_philosophers).to all have_key("quotes") end end context "getting quotes" do before(:all) do @philosopher_index = Philosopher.new.philosopher_index_service @philosopher_index.get_philosophers end it "should have a quote that is a string" do expect(@philosopher_index.get_quote).to eq true end end end
true
f2121c3297c1f645fc2651e76fbcce1074d60d8a
Ruby
bainewedlock/aoc2018ruby
/day9/solution1.rb
UTF-8
1,292
3.359375
3
[]
no_license
class Solver def initialize(players, marbles) @circle = [0] @current_marble = 0 @player = 0 @players = Array.new(players, 0) play marbles puts "solution for #{players}/#{marbles}: #{@players.max}" end def play(marbles) (1..marbles).each do |value| if (value % 23).zero? score value remove cycle(-7) else insert value, cycle(1) + 1 end # puts value if (value % 10_000).zero? next_player end end def next_player @player = (@player + 1) % @players.size end def score(value) @players[@player] += value end def remove(at) score @circle[at] @circle.delete_at(at) @current_marble = at end def insert(value, at) @circle.insert(at, value) @current_marble = at end def debug print "[#{@player + 1}] " @circle.each.with_index do |value, index| if index == @current_marble print "(#{value})" else print value end print ' ' end print "\n" end def cycle(offset) (@current_marble + offset) % @circle.size end end Solver.new(9, 25) Solver.new(10, 1618) Solver.new(13, 7999) Solver.new(17, 1104) Solver.new(21, 6111) Solver.new(30, 5807) Solver.new(423, 71_944) # Solver.new(423, 7_194_400)
true
f6f04527a53299cc0e866504bc5491f4b7f9f7af
Ruby
zvkemp/varese
/lib/varese/fips/state.rb
UTF-8
4,309
2.625
3
[ "MIT" ]
permissive
module Varese module FIPS class State ABBREVIATIONS = { "ak" => "alaska", "al" => "alabama", "ar" => "arkansas", "as" => "american samoa", "az" => "arizona", "ca" => "california", "co" => "colorado", "ct" => "connecticut", "dc" => "district of columbia", "de" => "delaware", "fl" => "florida", "ga" => "georgia", "gu" => "guam", "hi" => "hawaii", "ia" => "iowa", "id" => "idaho", "il" => "illinois", "in" => "indiana", "ks" => "kansas", "ky" => "kentucky", "la" => "louisiana", "ma" => "massachusetts", "md" => "maryland", "me" => "maine", "mi" => "michigan", "mn" => "minnesota", "mo" => "missouri", "ms" => "mississippi", "mt" => "montana", "nc" => "north carolina", "nd" => "north dakota", "ne" => "nebraska", "nh" => "new hampshire", "nj" => "new jersey", "nm" => "new mexico", "nv" => "nevada", "ny" => "new york", "oh" => "ohio", "ok" => "oklahoma", "or" => "oregon", "pa" => "pennsylvania", "pr" => "puerto rico", "ri" => "rhode island", "sc" => "south carolina", "sd" => "south dakota", "tn" => "tennessee", "tx" => "texas", "ut" => "utah", "va" => "virginia", "vi" => "virgin islands", "vt" => "vermont", "wa" => "washington", "wi" => "wisconsin", "wv" => "west virginia", "wy" => "wyoming" } CODES = { "alaska" => "02", "alabama" => "01", "arkansas" => "05", "american samoa" => "60", "arizona" => "04", "california" => "06", "colorado" => "08", "connecticut" => "09", "district of columbia" => "11", "delaware" => "10", "florida" => "12", "georgia" => "13", "guam" => "66", "hawaii" => "15", "iowa" => "19", "idaho" => "16", "illinois" => "17", "indiana" => "18", "kansas" => "20", "kentucky" => "21", "louisiana" => "22", "massachusetts" => "25", "maryland" => "24", "maine" => "23", "michigan" => "26", "minnesota" => "27", "missouri" => "29", "mississippi" => "28", "montana" => "30", "north carolina" => "37", "north dakota" => "38", "nebraska" => "31", "new hampshire" => "33", "new jersey" => "34", "new mexico" => "35", "nevada" => "32", "new york" => "36", "ohio" => "39", "oklahoma" => "40", "oregon" => "41", "pennsylvania" => "42", "puerto rico" => "72", "rhode island" => "44", "south carolina" => "45", "south dakota" => "46", "tennessee" => "47", "texas" => "48", "utah" => "49", "virginia" => "51", "virgin islands" => "78", "vermont" => "50", "washington" => "53", "wisconsin" => "55", "west virginia" => "54", "wyoming" => "56" } class << self def abbreviation(abbrev) state = ABBREVIATIONS.fetch("#{abbrev}".downcase){ raise UnknownAbbreviation } CODES.fetch(state) end def method_missing(name, *args, &block) str = ABBREVIATIONS.fetch("#{name}"){ "#{name}" } CODES.fetch(str){ super } end end end class UnknownAbbreviation < StandardError end end end
true
3e255b1eade97450aa6056be006c93f12d869252
Ruby
kenhys/drnbench
/lib/drnbench/shuttle/gradual-runner.rb
UTF-8
2,224
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# -*- coding: utf-8 -*- require "drnbench/shuttle/runner" require "csv" module Drnbench module Shuttle class GradualRunner attr_reader :start_n_clients, :end_n_clients, :step attr_reader :report_progressively, :result DEFAULT_START_N_CLIENTS = 1 DEFAULT_END_N_CLIENTS = 1 DEFAULT_STEP = 1 def initialize(params) @start_n_clients = params[:start_n_clients] || DEFAULT_START_N_CLIENTS @end_n_clients = params[:end_n_clients] || DEFAULT_END_N_CLIENTS @step = params[:step] || DEFAULT_STEP @report_progressively = params[:report_progressively] || false @params = params end def run run_benchmarks @result end private def run_benchmarks @result = Result.new @start_n_clients.step(@end_n_clients, @step) do |n_clients| benchmark = Runner.new(@params.merge(:n_clients => n_clients)) if @report_progressively puts "Running benchmark with #{n_clients} clients..." end benchmark.run if @report_progressively puts benchmark.result.to_s end @result << benchmark.result end end class Result def initialize @results = {} end def <<(result) @statuses = nil @results[result.n_clients] = result end def statuses @statuses ||= prepare_statuses end def to_csv ([csv_header] + csv_body).collect do |row| CSV.generate_line(row) end.join("") end private def prepare_statuses statuses = [] @results.each do |n_clients, result| statuses += result.statuses.keys end statuses.uniq! statuses.sort! statuses end def csv_header Drnbench::Result.keys + statuses end def csv_body @results.values.collect do |result| result.values + statuses.collect do |status| result.status_percentages[status] || 0 end end end end end end end
true
e83755dd8c9b6cc720a9bcb9d6febd25beb25802
Ruby
mrlhumphreys/just_chess
/lib/just_chess/pieces/knight.rb
UTF-8
564
3.328125
3
[ "MIT" ]
permissive
require 'just_chess/pieces/piece' module JustChess # = Knight # # The piece that jumps over pieces 1v2h or 2v1h class Knight < Piece # All the squares that the piece can move to and/or capture. # # @param [Square] square # the origin square. # # @param [GameState] game_state # the current game state. # # @return [SquareSet] def destinations(square, game_state) game_state.squares.not_orthogonal_or_diagonal(square).at_range(square,2).unoccupied_or_occupied_by_opponent(player_number) end end end
true
0f33556257a58512cc3de3a1e448014ed894812e
Ruby
usman-tahir/rubyeuler
/geometric_mean.rb
UTF-8
174
3.46875
3
[]
no_license
# http://rosettacode.org/wiki/Averages/Pythagorean_means def geometric_mean(low,high) (low..high).to_a.inject(:*) ** (1.0 / (low..high).count) end p geometric_mean(1,10)
true
926fc5bc0d65e1300df8dc912584d4a76475f050
Ruby
ruby/rbs
/test/stdlib/TSort_test.rb
UTF-8
5,174
2.734375
3
[ "BSD-2-Clause", "Ruby" ]
permissive
require_relative "test_helper" require "tsort" class TSortSingletonTest < Test::Unit::TestCase include TypeAssertions library 'tsort' testing "singleton(::TSort)" class EachNode def initialize(*nodes) @nodes = nodes end def call(&block) @nodes.each(&block) end end class EachChild def initialize(hash) @hash = hash end def call(node, &block) @hash[node].each(&block) end end def test_each_strongly_connected_component assert_send_type "(::TSortSingletonTest::EachNode, ::TSortSingletonTest::EachChild) { (Array[Integer]) -> void } -> void", TSort, :each_strongly_connected_component, EachNode.new(1, 2, 3, 4), EachChild.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }) do end assert_send_type "(::TSortSingletonTest::EachNode, ::TSortSingletonTest::EachChild) -> Enumerator[Array[Integer], void]", TSort, :each_strongly_connected_component, EachNode.new(1, 2, 3, 4), EachChild.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }) end def test_each_strongly_connected_component_from assert_send_type "(Integer, ::TSortSingletonTest::EachChild) { (Array[Integer]) -> void } -> void", TSort, :each_strongly_connected_component_from, 1, EachChild.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }) do end assert_send_type "(Integer, ::TSortSingletonTest::EachChild) -> Enumerator[Array[Integer], void]", TSort, :each_strongly_connected_component_from, 1, EachChild.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }) end def test_strongly_connected_components assert_send_type "(::TSortSingletonTest::EachNode, ::TSortSingletonTest::EachChild) -> Array[Array[Integer]]", TSort, :strongly_connected_components, EachNode.new(1, 2, 3, 4), EachChild.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }) end def test_tsort assert_send_type "(::TSortSingletonTest::EachNode, ::TSortSingletonTest::EachChild) -> Array[Integer]", TSort, :tsort, EachNode.new(1, 2, 3, 4), EachChild.new({ 1 => [2], 2 => [4], 3 => [2, 4], 4 => [] }) end def test_tsort_each assert_send_type "(::TSortSingletonTest::EachNode, ::TSortSingletonTest::EachChild) { (Integer) -> void } -> void", TSort, :tsort_each, EachNode.new(1, 2, 3, 4), EachChild.new({ 1 => [2], 2 => [4], 3 => [2, 4], 4 => [] }) do end assert_send_type "(::TSortSingletonTest::EachNode, ::TSortSingletonTest::EachChild) -> Enumerator[Integer, void]", TSort, :tsort_each, EachNode.new(1, 2, 3, 4), EachChild.new({ 1 => [2], 2 => [4], 3 => [2, 4], 4 => [] }) end end class TSortInstanceTest < Test::Unit::TestCase include TypeAssertions library 'tsort' testing "::TSort[::Integer]" class Sort def initialize(hash) @hash = hash end include TSort def tsort_each_node(&block) @hash.each_key(&block) end def tsort_each_child(node, &block) (@hash[node] || []).each(&block) end end def test_each_strongly_connected_component assert_send_type "() { (Array[Integer]) -> void } -> void", Sort.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }), :each_strongly_connected_component do end assert_send_type "() -> Enumerator[Array[Integer], void]", Sort.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }), :each_strongly_connected_component end def test_each_strongly_connected_component_from assert_send_type "(Integer) { (Array[Integer]) -> void } -> void", Sort.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }), :each_strongly_connected_component_from, 1 do end assert_send_type "(Integer) -> Enumerator[Array[Integer], void]", Sort.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }), :each_strongly_connected_component_from, 1 end def test_strongly_connected_components assert_send_type "() -> Array[Array[Integer]]", Sort.new({ 1 => [2], 2 => [3, 4], 3 => [2], 4 => [] }), :strongly_connected_components end def test_tsort assert_send_type "() -> Array[Integer]", Sort.new({ 1 => [2, 3], 2 => [4], 3 => [2, 4], 4 => [] }), :tsort end def test_tsort_each assert_send_type "() { (Integer) -> void } -> void", Sort.new({ 1 => [2, 3], 2 => [4], 3 => [2, 4], 4 => [] }), :tsort_each do end assert_send_type "() -> Enumerator[Integer, void]", Sort.new({ 1 => [2, 3], 2 => [4], 3 => [2, 4], 4 => [] }), :tsort_each end end
true
cdbf228880ed694b6950820bcf1311dbfe897447
Ruby
YOMOGItaro/rubyfuzzylib
/FuzzySet.rb
UTF-8
1,167
3.203125
3
[]
no_license
require 'MembershipFunction.rb' class FuzzySet @name @membership_functions def initialize(name, membership_functions) @name = name @membership_functions = membership_functions end def each @membership_functions.each{ |k,mf| yield mf } end def label @name end def to_gnuplot_data ret = "" @membership_functions.each{ |k, mf| ret += k + ' ' } ret += "\n" MembershipFunction::PARTITIONED_ELEMENT_NUMBER.times{ |iter| self.each{ |mf| ret += mf.call(iter).to_s + ' ' } ret += "\n" } return ret end def valued! @membership_functions.each{ |key, v| @membership_functions[key] = v.to_membership_function_valued } end def reference(label) @membership_functions[label] end end if __FILE__ == $0 mfs = Hash.new mfs["low"] = MembershipFunctionTrapezoid.new( 1, 50, 50,100, "low") mfs["mid"] = MembershipFunctionTrapezoid.new( 50,100,100,150, "mid") mfs["top"] = MembershipFunctionTrapezoid.new(100,150,150,200, "top") fs = FuzzySet.new("baribari", mfs) # p fs.reference("low") print fs.to_gnuplot_data end
true
14e75504d749ba02e83255b303b7340a9a0d898c
Ruby
kenta-s/algorithms
/ruby/quicksort.rb
UTF-8
869
3.578125
4
[]
no_license
require 'minitest/autorun' class TestQuicksort < Minitest::Test def test_quicksort_with_integers_returns_sorted_array array = (1..10).to_a.shuffle expected_array = [1,2,3,4,5,6,7,8,9,10] assert_equal expected_array, quicksort(array) array = (32..150).to_a.shuffle expected_array = (32..150).to_a assert_equal expected_array, quicksort(array) end def test_quicksort_with_alphabets_returns_sorted_array array = ('a'..'z').to_a.shuffle expected_array = ('a'..'z').to_a assert_equal expected_array, quicksort(array) end end def quicksort(array) left = [] right = [] pibot = array.shift array.each do |n| if n < pibot left << n else right << n end end if left.size > 1 left = quicksort(left) end if right.size > 1 right = quicksort(right) end left + [pibot] + right end
true
2e0603faaf0bfd51b1e772bf4f8c5f176e8eae8a
Ruby
c7devteam/baio_tracking_client
/lib/baio_tracking_client/client.rb
UTF-8
2,481
2.578125
3
[ "MIT" ]
permissive
require 'faraday' require 'typhoeus' require 'typhoeus/adapters/faraday' require 'faraday_middleware' require 'ostruct' module BaioTrackingClient class Client attr_reader(:base_url, :port, :username, :password) def initialize(config = {}) @base_url = "http://#{ config.fetch(:base_url, get_config_value(:base_url)) }" @port = config.fetch(:port, get_config_value(:port)) @username = config.fetch(:username, get_config_value(:username)) @password = config.fetch(:password, get_config_value(:password)) end def post_event(params:) post(path: '/api/v1/events', params: params) end def get_event(event:, params: ) path = { events: '/api/v1/events', owner_activities: '/api/v1/owners/owner_activities', online_list: '/api/v1/owners/online_list', onlines_users: '/api/v1/owners/onlines_users', online: "/api/v1/owners/#{params[:owner_id]}/online" }[event] || raise(NotImplementedError, "event not definite #{event}") get(path: path, params: params) end def in_parallel connection.in_parallel do yield end end def connection @connection ||= Faraday.new(url: "#{base_url}:#{port.to_s}", parallel_manager: Typhoeus::Hydra.new(max_concurrency: 10)) do |conn| conn.request :basic_auth, username, password conn.request :json conn.adapter :typhoeus end end class << self def clear BaioTrackingClient.http_client = nil end end private def post(path:, params: {}) connection.post do |req| req.url(path) req.params = params req.options.timeout = 2 req.options.open_timeout = 2 end rescue Faraday::TimeoutError failed_response('failed to conect tracking server') end def get(path:, params: {}) connection.get do |req| req.url(path) req.params = params req.options.timeout = 2 req.options.open_timeout = 2 end rescue Faraday::TimeoutError failed_response('failed to conect tracking server') end def get_config_value(key) BaioTrackingClient.send(key) || raise(BaioTrackingClient::NoConfigurationError, "Not set #{key}") end def failed_response(message) OpenStruct.new(success?: false, body: message, status: 0) end end end
true