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
ff06773650124ad068b851616fac8c8a2cf9580a
Ruby
caltonhill/dice_game
/code/print_dice.rb
UTF-8
732
3.390625
3
[]
no_license
def print_dice(num) resources_path = '../resources/' case num when 6 file_content = File.read(resources_path + '6.txt') print "#{file_content}" when 5 file_content = File.read(resources_path + '5.txt') print "#{file_content}" when 4 file_content = File.read(resources_path + '4.txt') print "#{file_content}" when 3 file_content = File.read(resources_path + '3.txt') print "#{file_content}" when 2 file_content = File.read(resources_path + '2.txt') print "#{file_content}" when 1 file_content = File.read(resources_path + '1.txt') print "#{file_content}" else puts "There was an error getting the number rolled" end end
true
2f1fa698d480a537241c088815d210e80f7e9600
Ruby
upper-hand/availability
/examples/scheduler.rb
UTF-8
3,291
3.40625
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
require_relative '../lib/availability' # # This is just an example of a scheduler that might be used with availabilities. It's a work in # progress that's helping to flesh out the design of availabilities. # class Scheduler attr_reader :availabilities, :scheduled # # availabilities: a list of Availability::AbstractAvailability instances defining when the resource is available # def initialize(availabilities) @availabilities = validate_availabilities availabilities @scheduled = Hash.new{|h, k| h[k] = []} end # # This method expects either an availability request or a start/end time pair. If the # start/end time pair is offered, this method acts the same as if an Availability::Once # request was offered with the given start_time and a duration going through the given # end_time. # # availability_request: an Availability instance # start_time: Time/DateTime representative of a single request starting at that time # end_time: Time/DateTime representative of a single request ending at that time # # Returns the first availability that corresponds to the availability request. If no # availability is found, returns nil. # def allow?(**args) availability_request = convert **args availability_for availability_request end # # This method expects either an availability request or a start/end time pair. If the # start/end time pair is offered, this method acts the same as if an Availability::Once # request was offered with the given start_time and a duration going through the given # end_time. # # availability_request: an Availability instance # start_time: Time/DateTime representative of a single request starting at that time # end_time: Time/DateTime representative of a single request ending at that time # # returns boolean indicating whether the availability request was scheduled. # def schedule(**args) request = convert **args availability = allow? availability_request: request return self unless availability scheduled[availability] << request unless scheduled[availability].size >= availability.capacity self end private def availability_for(request) @availabilities.detect do |some_availability| some_availability.corresponds_to? request end end def convert(availability_request: nil, start_time: nil, end_time: nil) validate_allow_params! availability_request, start_time, end_time if availability_request.nil? availability_request = Availability::Once.create( start_time: start_time, duration: (end_time.to_time - start_time.to_time).to_i) else availability_request end end def validate_availabilities(availabilities) list = Array(availabilities).flatten.compact return list if list.all? { |e| Availability.availability?(e) } raise ArgumentError, "expected a list of availabilities" end def validate_allow_params!(availability, start_time, end_time) return if Availability.availability?(availability) return if valid_time?(start_time) && valid_time?(end_time) raise ArgumentError, "must specify either availability_request or (start_time and end_time)" end def valid_time?(a_time) Time === a_time || DateTime === a_time || Date === a_time end end
true
c6a27050e46922f919292dd80f1a7d904c845577
Ruby
JayTeeSF/fortune_teller
/lib/fortune_teller/chooser.rb
UTF-8
2,318
2.90625
3
[ "MIT" ]
permissive
require_relative "list_renderer" require_relative "logger" module FortuneTeller class Chooser LOCATIONS = [ :tl, :tr, :bl, :br ] def self.subset(list, num=list.size) Logger.log("got list: #{list.inspect}, num: #{num.inspect}") choices = list.dup num.times.collect {|num| reduce_choices!(choices) } end def self.reduce_choices!( choices, by=random_choice(choices) ) choices.delete(by) end def self.random_choice(choices) choices[rand(choices.size)] end attr_reader :tl_panel, :tr_panel, :bl_panel, :br_panel attr_reader :list_renderer, :ui def initialize(_tl_panel, _tr_panel, options = {}) @ui = options[:ui] @tl_panel = _tl_panel Logger.log "tl_panel: #{@tl_panel}" @tr_panel = _tr_panel Logger.log "tr_panel: #{@tr_panel}" @bl_panel = options[:bl_panel] || NilPanel.new(@ui) Logger.log "bl_panel: #{@bl_panel}" @br_panel = options[:br_panel] || NilPanel.new(@ui) Logger.log "br_panel: #{@br_panel}" @list_renderer = options[:list_renderer] || ListRenderer.new define_selection_aliases end def selections_hash LOCATIONS.reduce({}) {|memo, location| if (value = send( "#{location}_panel" )).present? memo[location] = value end memo } end def selections selections_hash.values end def define_selection_aliases selections_hash.each_pair do |k,v| self.class.send(:alias_method, v.to_s.to_sym, k) end end def valid? choice respond_to? choice end def exit yield if block_given? Logger.log "exiting..." Kernel.exit end alias_method :Q, :exit alias_method :q, :exit def choose choice = nil begin ui.clear_screen choice = ui.prompt( list_renderer.render( selections | [:exit] ) ) Logger.log("got: #{choice.inspect}") end until( valid?( choice ) ) Logger.log("trying it...") ui.clear_screen(1) # need to unalias methods... send( choice ) end LOCATIONS.each do |location| define_method(location) { send( "#{location}_panel" ).tap do |panel| panel.pick end } end end end require_relative "panel"
true
9942c17abd23432e89e669f866b90c31e1377bc1
Ruby
banerjed/MyOnlinePractice
/test/unit/doctor_test.rb
UTF-8
2,270
2.5625
3
[]
no_license
require File.dirname(__FILE__) + '/../test_helper' class DoctorTest < Test::Unit::TestCase fixtures :doctors,:testimonials,:locations,:users,:practices def setup @doc = Doctor.find(1) @mydoctor_tst = doctors(:doctor_00001) end # Replace this with your real tests. def test_truth assert_kind_of Doctor, @doc assert_equal @mydoctor_tst.id, @doc.id assert_equal @mydoctor_tst.practice_id, @doc.practice_id assert_equal @mydoctor_tst.address, @doc.address assert_not_nil @mydoctor_tst.time_ranges assert_not_nil @mydoctor_tst.appointments assert_not_nil @mydoctor_tst.visits assert_not_nil @mydoctor_tst.testimonials end #This test case ensure that the validates_presence_of works... def test_invalid_with_empty_attributes doctor = Doctor.new assert !doctor.valid?, doctor.errors.full_messages assert doctor.errors.invalid?(:npi) assert doctor.errors.invalid?(:ssn) end #This test case ensure that the validates works fine with attributes def test_valid_with_attributes doctor = Doctor.new doctor.npi = @mydoctor_tst.npi doctor.ssn = @mydoctor_tst.ssn assert doctor.valid?, doctor.errors.full_messages end def test_for_written_testimonial @testimonial = Testimonial.find(:all, :conditions => ['testimonial != ?' , ""]) assert_not_nil @testimonial end def test_for_outstanding_testimonial @testimonial = Testimonial.find(:all, :conditions => [' testimonial = ?' , " "]) assert_equal 0,@testimonial.size end def test_for_locations assert_not_nil @doc.locations end #This test case ensure that the relation between doctor and practice works.. def test_belongs_to_practice assert_equal practices(:practice_00001).name, Doctor.find(1).practice.name assert !Doctor.find(1).practice.nil?, "Every doctor should have a Practice Details" end #This test case ensure that the relation between doctor and user works.. def test_belongs_to_user assert_equal users(:user_00001).first_name, Doctor.find(1).user.first_name assert !Doctor.find(1).user.nil?, "Every doctor should have a users Details" end end
true
3c4bf3113d933be71f3df48141d0fd0db6113807
Ruby
chrissiedunham/cycle_tracker
/app/models/cycle.rb
UTF-8
1,057
2.65625
3
[]
no_license
class Cycle < ActiveRecord::Base has_many :days, -> { order(number: :asc) } belongs_to :user def to_csv attributes = [ :bleeding, :sensation, :characteristics, :cervix, :temp, :created_at, :updated_at, :date, :number, :cycle_id, :weight, :cramps, :irritability, :sensitivity, :tenderness, :drinks, :hours_sleep, ] CSV.generate(headers: true) do |csv| csv << attributes days.each do |day| csv << attributes.map { |attr| day.send(attr) } end end end def populated_days last_populated_day = days.select(&:has_data?).last return [] unless last_populated_day.present? days.select {|day| day.number <= last_populated_day.number } end def cycle_day(num) days.where(:number => num).first end def populate_days (0...35).each do |day_num| days.create!( { date: start_date + day_num.days, number: day_num + 1, } ) end end end
true
3f3784a2e2aefbb4f7ba4525f6df552f6e591056
Ruby
RaulZhao/learning
/questions/leetcode_ruby/Remove_Duplicates_from_Sorted_Array.rb
UTF-8
1,566
4.15625
4
[]
no_license
# Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. # Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. # Return k after placing the final result in the first k slots of nums. # Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. # Custom Judge: # The judge will test your solution with the following code: # int[] nums = [...]; // Input array # int[] expectedNums = [...]; // The expected answer with correct length # int k = removeDuplicates(nums); // Calls your implementation # assert k == expectedNums.length; # for (int i = 0; i < k; i++) { # assert nums[i] == expectedNums[i]; # } # If all assertions pass, then your solution will be accepted. # @param {Integer[]} nums # @return {Integer} def remove_duplicates(nums) curr_index = 0 swap = -1 i = 1 while i < nums.length if nums[i] > nums[curr_index] swap = nums[curr_index+1] nums[curr_index+1] = nums[i] nums[i] = swap curr_index += 1 end i += 1 end curr_index + 1 end
true
27af3130af2e587ee1a9ca31bf4286e65e9102c3
Ruby
rutvij-pandya/twitter_app
/lib/twitter_lib/feed.rb
UTF-8
2,990
2.75
3
[]
no_license
module TwitterLib class Feed < Base DEFAULT_NO_OF_POST_LIMIT = 100 BATCH_SIZE = 100 def initialize super() end def export_posts_by_hashtag(hashtag, no_of_posts=DEFAULT_NO_OF_POST_LIMIT) begin return {success: false, error: "Invalid format of hastag. Sample - \'#ruby\'"} unless is_valid_hashtag?(hashtag) # append 'hashtag' with '-rt' to avoid fetching retweets @query = (hashtag.include?(" -rb") ? hashtag : "#{hashtag} -rt") # Search posts in batch result = find_in_batch(no_of_posts, {result_type: 'recent'}) # Export data into CSV file export_data(result) {success: true} rescue Exception => e Rails.logger.error "Error in Twitter::Feed download_posts_by_hashtag method - #{e.message}" end end private def is_valid_hashtag?(hashtag) (hashtag.present? && hashtag.is_a?(String) && hashtag[0] == "#") end def find_in_batch(no_of_posts, option_params={}) feeds_data = [] search_options = {result_type: option_params[:result_type]} while true break if no_of_posts <= 0 search_options[:count] = [no_of_posts, BATCH_SIZE].min response = search_feeds(@query, search_options) if response[:error].present? Rails.logger.error "Error in Twitter::Feed find_in_batch method - #{response[:error]}" return end parsed_data = parse_response(response[:result]) # Append feeds data of a batch feeds_data += parsed_data[:data] search_options[:max_id] = parsed_data[:max_id] no_of_posts -= BATCH_SIZE end # Twitter API returns Posts having Id <= max_id that we're passing # Which result into having duplicate entry of Last Post & First Post of the batches # Hence, return 'uniq' posts feeds_data.uniq end # parse response to fetch required details from posts. i.e, text def parse_response(response) # response.inject([]) {|res, feed| res << feed.attrs; res} response.inject({data: [], max_id: 0}) do |res, feed| Rails.logger.info "- Feed - #{[feed.id, feed.user.name, feed.text]}" res[:data] << [feed.id, feed.user.name, feed.text] res[:max_id]=feed.id res end end # Export data to csv def export_data(feeds_data) file_path = Rails.root.join("log","twitter_log","#{file_name}.csv") headers = ["ID, User Name, Tweet Text"] ExportCsv.new(file_path, headers, feeds_data).save Rails.logger.info "=================================================================" Rails.logger.info "Please open file - #{file_path} - to view result" Rails.logger.info "=================================================================" end # build file name def file_name # Append timestamp to prevent file from getting overwritten "#{@query.parameterize}_#{Time.now.to_i}" end end end
true
951cdfe16212f9e965d8751d0cacf4fafbc3601b
Ruby
kchasel/stub.born
/lib/stub_born.rb
UTF-8
1,408
2.59375
3
[]
no_license
module RSpec module Mocks module Methods def stub_return_of(message) ReturnStub.new(self, message) end end end end class ReturnStub def initialize(receiver, message) @receiver = receiver @message_sym = message.to_sym meth = @receiver.method(@message_sym) if @receiver.respond_to?("obfuscated_by_rspec_mocks__#{message.to_s}") @receiver.unstub(@message_sym) meth = @receiver.method(@message_sym) end @proc = meth.to_proc end def with(returns_message) @calls ||= [] @stub = nil @return_val = nil @exp = @receiver.stub(@message_sym) do val = @proc.call if val != @return_val || @stub.nil? @return_val = val @stub = @return_val.stub(returns_message) if !returns_message.is_a?(Hash) @calls.each { |call| @stub.send(call[:meth], *call[:args]) } end end @return_val end self end def method_missing(m, *args, &block) if method_of_expectations?(m) @calls << { meth: m, args: args, block: block } self else super end end def respond_to?(m) method_of_expectations?(m) || super end private def method_of_expectations?(meth) @allowed_methods ||= RSpec::Mocks::MessageExpectation.instance_methods @allowed_methods.include?(meth) end end
true
04a761a7232953b3ddbd87b61ddfdbbf300ad265
Ruby
molit-korea/main
/Pages/2017 국토교통 빅데이터 해커톤 참가작/molit_HAB-master/elastic/logstash-5.5.2/vendor/bundle/jruby/1.9/gems/sequel-4.49.0/lib/sequel/plugins/timestamps.rb
UTF-8
4,776
2.59375
3
[ "MIT", "Apache-2.0" ]
permissive
# frozen-string-literal: true module Sequel module Plugins # The timestamps plugin creates hooks that automatically set create and # update timestamp fields. Both field names used are configurable, and you # can also set whether to overwrite existing create timestamps (false # by default), or whether to set the update timestamp when creating (also # false by default). # # Usage: # # # Timestamp all model instances using +created_at+ and +updated_at+ # # (called before loading subclasses) # Sequel::Model.plugin :timestamps # # # Timestamp Album instances, with custom column names # Album.plugin :timestamps, :create=>:created_on, :update=>:updated_on # # # Timestamp Artist instances, forcing an overwrite of the create # # timestamp, and setting the update timestamp when creating # Album.plugin :timestamps, :force=>true, :update_on_create=>true module Timestamps # Configure the plugin by setting the available options. Note that # if this method is run more than once, previous settings are ignored, # and it will just use the settings given or the default settings. Options: # :allow_manual_update :: Whether to skip setting the update timestamp if it has been modified manually (default: false) # :create :: The field to hold the create timestamp (default: :created_at) # :force :: Whether to overwrite an existing create timestamp (default: false) # :update :: The field to hold the update timestamp (default: :updated_at) # :update_on_create :: Whether to set the update timestamp to the create timestamp when creating (default: false) def self.configure(model, opts=OPTS) model.instance_eval do @allow_manual_timestamp_update = opts[:allow_manual_update]||false @create_timestamp_field = opts[:create]||:created_at @update_timestamp_field = opts[:update]||:updated_at @create_timestamp_overwrite = opts[:force]||false @set_update_timestamp_on_create = opts[:update_on_create]||false end end module ClassMethods # The field to store the create timestamp attr_reader :create_timestamp_field # The field to store the update timestamp attr_reader :update_timestamp_field # Whether to overwrite the create timestamp if it already exists def create_timestamp_overwrite? @create_timestamp_overwrite end Plugins.inherited_instance_variables(self, :@allow_manual_timestamp_update=>nil, :@create_timestamp_field=>nil, :@create_timestamp_overwrite=>nil, :@set_update_timestamp_on_create=>nil, :@update_timestamp_field=>nil) # Whether to allow manual setting of the update timestamp when creating def allow_manual_timestamp_update? @allow_manual_timestamp_update end # Whether to set the update timestamp to the create timestamp when creating def set_update_timestamp_on_create? @set_update_timestamp_on_create end end module InstanceMethods # Set the update timestamp when updating def before_update set_update_timestamp super end private # Set the create timestamp when creating def _before_validation set_create_timestamp if new? super end # If the object has accessor methods for the create timestamp field, and # the create timestamp value is nil or overwriting it is allowed, set the # create timestamp field to the time given or the current time. If setting # the update timestamp on creation is configured, set the update timestamp # as well. def set_create_timestamp(time=nil) field = model.create_timestamp_field meth = :"#{field}=" set_column_value(meth, time||=model.dataset.current_datetime) if respond_to?(field) && respond_to?(meth) && (model.create_timestamp_overwrite? || get_column_value(field).nil?) set_update_timestamp(time) if model.set_update_timestamp_on_create? end # Set the update timestamp to the time given or the current time if the # object has a setter method for the update timestamp field. def set_update_timestamp(time=nil) return if model.allow_manual_timestamp_update? && modified?(model.update_timestamp_field) meth = :"#{model.update_timestamp_field}=" set_column_value(meth, time||model.dataset.current_datetime) if respond_to?(meth) end end end end end
true
dc7c32a8534c129a997f1f40b1bd7e37aeba5ab4
Ruby
MaximL1/Ruby_test
/Accaunts_class/accountClass.rb
UTF-8
813
2.90625
3
[]
no_license
require 'rubygems' require 'watir' require 'json' class Accounts def initialize(b) @b = b end def getAccount divs = @b.divs(class: "main-info") data = { Account: [] } divs.each do |div| str = div.html name = str[(str.index('class="name">')) + ('class="name">').size..str.index('</a>') - 1] currency = str[(str.index('"currency-icon">') + ('"currency-icon">').size)..str.index("</div>") - 1] balance = str[(str.index('class="amount">') + ('class="amount">').size)..str.index("</span>&nbsp") - 1] data[:Account].push({ :name => name, :balance => balance, :currency => currency, :nature => "check" }) end return data end end
true
0c8e6ffb7c9412f77347e0c7f22ee3b84c896eab
Ruby
case-iot/app_model
/lib/ontology/local_vocabulary.rb
UTF-8
452
2.65625
3
[]
no_license
require 'rdf' module Model class LocalVocabulary def self.method_missing(name, *arguments, &block) uri_for(name) end def self.name uri_for('name') end def self.question_type uri_for('question') end def self.answer_type uri_for('answer') end def self.uri_for(name) RDF::URI("http://matus.tomlein.org/case/#{name}") end end LV = LocalVocabulary QV = LocalVocabulary end
true
ac9ca1cfac2ed0f997718b380e77fc3d45fb44a6
Ruby
liefni/ruby_atbash
/atbash.rb
UTF-8
321
2.953125
3
[]
no_license
require './atbash_cypher.rb' ORIGINAL_CHARS = 'abcdefghijklmnopqrstuvwxyz' REPLACEMENT_CHARS = 'oephjizkxdawubnytvfglqsrcm' ENCRYPTED_TEXT = 'knlfgnb, sj koqj o yvnewju' cypher = AtbashCypher.new() cypher.original_chars = ORIGINAL_CHARS cypher.replacement_chars = REPLACEMENT_CHARS puts cypher.decrypt(ENCRYPTED_TEXT)
true
4d168e85c089aa2c93388b72d887a06a01e303a6
Ruby
gsisson/ruby_lib
/rename.add.suffix
UTF-8
838
3.046875
3
[]
no_license
#!/usr/bin/env ruby # require_relative 'lib/dir2' require_relative 'lib/string_colorize' def usage() STDERR.puts "usage: #{File.basename(__FILE__)} SUFFIX <files>" STDERR.puts " ex: #{File.basename(__FILE__)} \".avi\" *.mpg" abort end def main usage if ARGV.count < 2 suffix = ARGV[0] ARGV.shift ARGV.each do |f| abort "\nERROR: Cannot file file: \"#{f}\"\n\n" if ! File.exist? f end ARGV.each do |f| puts "File.rename \"#{f}\", \"#{f}#{suffix}\"" File.rename "#{f}", "#{f}#{suffix}" end end begin main rescue SystemExit => e raise # handle 'exit/abort' w/o stack trace; re-raise to pass return code to shell rescue Interrupt => e puts "\nCancelled by user." rescue Exception => e # shouldn't handle this, Kevin Skoglund says! puts "ERROR: #{e.message}".red_bold puts e.backtrace abort end
true
1362e02d8953bc532cadd1a16355ffee882ae85f
Ruby
lukew244/boris-bikes
/spec/docking_station_spec.rb
UTF-8
1,038
2.6875
3
[]
no_license
require 'docking_station.rb' describe DockingStation do let(:bike) { double :bike } it { is_expected.to respond_to :release_bike } it { is_expected.to respond_to :dock } it { is_expected.to respond_to :bikes } it { is_expected.to respond_to :capacity } it 'raises an error' do expect { subject.release_bike }.to raise_error 'No bike available' end it 'docks a bike' do subject.capacity.times { subject.dock(bike) } expect { subject.dock(bike) }.to raise_error 'Docking station full' end it 'releases working bikes' do bike = double(:working? => true) subject.capacity.times { subject.dock(bike) } subject.capacity.times { subject.release_bike } expect { subject.release_bike }.to raise_error 'No bike available' end it "doesn't release broken bikes" do bike = double(:report => false, :working? => false) bike.report subject.capacity.times { subject.dock(bike) } expect { subject.release_bike }.to raise_error 'No working bikes available' end end
true
c52ceaf5c5446a2e81f191136abf2b018d95e7ee
Ruby
davidyoung604/ProjectFIREBALL
/test/benchmarking/category_extensions_order_name.rb
UTF-8
407
2.5625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
ActiveRecord::Base.logger.level = 1 # Pre-benchmark fiddling showed a marginal improvement. puts '--- Sorting category extensions by name ---' Benchmark.ips do |bm| bm.report('original: ') do cat = Category.find(4) cat.extensions.sort_by(&:name).each { |e| e } end bm.report('updated: ') do cat = Category.find(4) cat.extensions.order(:name).each { |e| e } end bm.compare! end
true
39c14f2e20ab73f96d5260ef33bc8517a6d2f639
Ruby
gpcucb/ray-tracing-sergioKmoralesV
/tests/vector_test.rb
UTF-8
2,283
3.421875
3
[]
no_license
require 'minitest/autorun' require 'minitest/reporters' require './vector' class VectorTest < Minitest::Test def setup @a_vector = Vector.new(4,5,8) @another_vector = Vector.new(5,6,7) end def test_01_creates_an_object_vector_and_saves_values_as_floats @a_vector = Vector.new(4,5,8) assert_equal("(4.0, 5.0, 8.0)", @a_vector.as_string()) end def test_02_add_two_vectors_correctly result = @a_vector.add_vector(@another_vector) assert_equal(@a_vector.x+@another_vector.x, result.x) assert_equal(@a_vector.y+@another_vector.y, result.y) assert_equal(@a_vector.z+@another_vector.z, result.z) end def test_03_substract_two_vectors_correctly result = @a_vector.substract_vector(@another_vector) assert_equal(@a_vector.x-@another_vector.x, result.x) assert_equal(@a_vector.y-@another_vector.y, result.y) assert_equal(@a_vector.z-@another_vector.z, result.z) end def test_04_module_of_a_vector x,y,z = 4,5,8 a_expected_module = Math.sqrt((x**2) + (y**2) + (z**2)) assert_equal(a_expected_module, @a_vector.module) end def test_05_cross_product_calculated_correctly x1,y1,z1,x2,y2,z2 = @a_vector.x,@a_vector.y,@a_vector.z,@another_vector.x,@another_vector.y,@another_vector.z result = @a_vector.cross_product(@another_vector) assert_equal(y1*z2 - z1*y2, result.x) assert_equal(z1*x2 - x1*z2, result.y) assert_equal(x1*y2 - x2*y1, result.z) end def test_06_dot_product_calculated_correctly x1,y1,z1,x2,y2,z2 = @a_vector.x,@a_vector.y,@a_vector.z,@another_vector.x,@another_vector.y,@another_vector.z assert_equal(x1*x2+y1*y2+z1*z2,@a_vector.dot_product(@another_vector)) end def test_07_number_product_calculated_correctly a_number = 8 result = @a_vector.number_product(a_number) assert_equal(@a_vector.x * a_number,result.x) assert_equal(@a_vector.y * a_number,result.y) assert_equal(@a_vector.z * a_number,result.z) end def test_08_calculates_normalized_vector_correctly x,y,z = 4.0,5.0,8.0 a_expected_module = Math.sqrt((x**2) + (y**2) + (z**2)) result = @a_vector.normalize assert_equal(x/a_expected_module,result.x) assert_equal(y/a_expected_module,result.y) assert_equal(z/a_expected_module,result.z) end end
true
6cc77d147bb48119fa7e925d44e165471f42c5d3
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/combine_anagrams_latest/1711.rb
UTF-8
164
2.96875
3
[]
no_license
#!/usr/bin/env ruby # # HW 1: Ruby calisthenics # # Part 3: anagrams # def combine_anagrams(words) words.group_by { |word| word.downcase.chars.sort }.values end
true
6e0ae41c20b0f5b9d8ac5e71e2ab65a940bdba9f
Ruby
chetna1726/vinsol_campus_hiring
/app/models/mcq.rb
UTF-8
414
2.78125
3
[]
no_license
class MCQ < Question validate :ensure_only_one_answer validate :ensure_atleast_two_options def ensure_only_one_answer answers_count = options.select(&:answer?).length if answers_count != 1 errors.add(:answers, "Select one option as correct answer") end end def ensure_atleast_two_options if options.length < 2 errors.add(:options, 'Specify atleast two') end end end
true
999b16366be3c6d715ca8ab5b6c48992eeb92ea2
Ruby
aaaasmile/cup-sinatra
/middlewares/cup_srv/database/captcha_validator.rb
UTF-8
1,601
2.59375
3
[]
no_license
#file: captcha_validator.rb $:.unshift File.dirname(__FILE__) require 'rubygems' require 'log4r' require 'net/http' require 'openssl' include Log4r module MyGameServer class CaptchaValidator attr_reader :success, :last_error def initialize(secret) #verify captacha with an api call https://www.google.com/recaptcha/api/siteverify @log = Log4r::Logger["DbConnector"] @secret = secret @uri = URI('https://www.google.com/recaptcha/api/siteverify') end def validate(token) @success = false @last_error = '' @log.debug "Validate token using uri: #{@uri}" params = { 'secret' => @secret, 'response' => token } # Nota come vie usato https http = Net::HTTP.new(@uri.host, @uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE #p @secret #p @uri.request_uri #p @uri.path request = Net::HTTP::Post.new(@uri.request_uri) request.form_data = params #p request.body res = http.request(request) p resp_json = JSON.parse(res.body) @success = resp_json["success"] @last_error = resp_json["error-codes"].to_s @log.debug "token verification is #{@success}" # body is something like: #{ # "success": true, # "challenge_ts": "2018-02-24T19:12:53Z", # "hostname": "localhost" #} #in case of error: {"success"=>false, "challenge_ts"=>"2018-02-24T19:12:53Z", "hostname"=>"localhost", "error-codes"=>["timeout-or-duplicate"]} return @success end end end
true
953bd5abd570f49af47283ca3348e4d642bd151f
Ruby
qbart/handy_toolbox
/lib/handy_toolbox/tool_menu_item.rb
UTF-8
374
2.640625
3
[ "MIT" ]
permissive
module HandyToolbox class ToolMenuItem ICON = ' '.freeze attr_reader :id, :parent, :tool def initialize(parent, tool) @id = Ids.next @parent = parent @tool = tool end def to_s if @tool.desc.nil? @tool.name else [@tool.name, @tool.desc] end end def icon ICON end end end
true
638f444162ff798a25fe9596bf93de4e28adbfec
Ruby
mufid/rack-talk
/3-order/config.ru
UTF-8
498
3.03125
3
[]
no_license
require 'pry' class EaterBase def initialize(app) puts "Initialized with app name: #{app.name}" @app = app end end class Eater1 < EaterBase def call(env) puts 'CUMI DIGORENGGG' @app.call(env) end def name; 'Eater1'; end end class Eater2 < EaterBase def call(env) @app.call(env) end def name; 'Eater2'; end end class Meow def call(env) [200, {}, ['Miaw']] end def name 'Meower' end end use Eater1 use Eater2 run Meow.new $stdout.sync = true
true
8bec074fafb32005ecd485f19baa57715ab0764a
Ruby
burkhart-andrew/Launch_School
/101/lesson_3/exercise_3.rb
UTF-8
959
4.03125
4
[]
no_license
3.1 Show an easier way to write this array: flintstones = ["Fred", "Barney", "Wilma", "Betty", "BamBam", "Pebbles"] flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles) 3.2 How can we add the family pet "Dino" to our usual array: flintstones.push("Dino") flintstones << "Dino" 3.3 How can we add multiple items to our array? (Dino and Hoppy) flintstones.push("Dino", "Hoppy") flintstones.push("Dino").push("Hoppy") flintstones.concat(%w(Dino Hoppy)) 3.4 Review the String#slice! documentation, and use that method to make the return value "Few things in life are as important as ". But leave the advice variable as "house training your pet dinosaur.". advice.slice!(0, advice.index('house')) 3.5 Write a one-liner to count the number of lower-case 't' characters in the following string: statement = "The Flintstones Rock!" statement.scan('t').count # => 2 statement.count('t') # => 2 3.6 title = "Flintstone Family Members" title.center(40)
true
f02bff81e5703023f72fe2bd5a608c27cda74cde
Ruby
hlopezm/rails-week-2
/app/models/event.rb
UTF-8
1,142
2.671875
3
[]
no_license
class Event < ActiveRecord::Base # belongs_to :user validates :name, presence: true, length: { maximum: 60 } validates :description, length: { minimum: 100}, allow_blank: true validate :start_at_blank, :end_at_blank, :end_at_cannot_start_before_start_at validates :user, presence: true #scope :already_started, Lambda { # where(["start_at < ?", Time.now]) #} #scope :already_like, Lambda { # where(["name like ?", "%#{name}%"]) #} #scope :description_like, Lambda { # where(["description like ?", "%#{description}%"]) #} ###Aplicando Scope def self.for_today where(["DATE(start_at) = ? ", Date.today ]) end scope :name_like, lambda { |name| where (["name like ?", "%#{name}%"]) } private def start_at_blank if start_at.blank? errors.add(:start_at, "Start date can't be blank") end end def end_at_blank if end_at.blank? errors.add(:end_at, "Expiration date can't be blank") end end def end_at_cannot_start_before_start_at if end_at.present? && start_at.present? && end_at < start_at errors.add(:end_at, "Can't be minor than start at") end end end
true
03def7d0a6cf51566bf32ce426239dbb5e263816
Ruby
Sivard/flashcards
/app/services/words_parser.rb
UTF-8
946
2.796875
3
[]
no_license
require 'nokogiri' require 'open-uri' class WordsParser def initialize(*params) @user_id = params[0] @original_css = params[1] @translated_css = params[2] @url = params[3] @block_id = params[4] Log.create(user_id: @user_id, status: 0, msg: 'Начало загрузки') end def run doc = Nokogiri::HTML(open(@url)) original_list = doc.css(@original_css).map(&:content) translated_list = doc.css(@translated_css).map(&:content) count = original_list.count count.times do |i| Card.create(original_text: original_list[i], translated_text: translated_list[i], user_id: @user_id, block_id: @block_id) end Log.create(user_id: @user_id, status: 0, msg: "Успешно загружено #{count} карточек") rescue Log.create(user_id: @user_id, status: 1, msg: 'Перевод не загружен') end end
true
fabb3bf94956c82d7aa1728ad4b74c4116d4a5eb
Ruby
nicolaracco/simple_etl
/lib/simple_etl/source/parse_result.rb
UTF-8
707
2.640625
3
[]
no_license
require 'ostruct' module SimpleEtl module Source class ParseResult attr_reader :rows def initialize @rows = [] end def valid? # return false if at least one row is not valid !@rows.detect { |r| !r.valid? } end def errors @rows.inject([]) { |memo, row| memo.concat row.errors } end def append_row attributes @rows << Row.new(attributes) end def append_error row_index, message, e @errors << OpenStruct.new({ :row_index => row_index, :message => message, :exception => e }) @rows[row_index].valid = false if @rows end end end end
true
b7a0f1b65f3b28c00adc08ad0b3c2b8bce1185c9
Ruby
thuga-muffin/Development
/ruby/ruby the hard way/ex36.rb
UTF-8
2,738
3.859375
4
[]
no_license
# the beginning def beginning puts "You have the choice between right and left." print "Response: " choice = $stdin.gets.chomp choice.downcase! if choice == "left" the_left elsif choice == "right" the_right else puts "Only right or left" end end # beginning # choosing left def the_left puts "You walk to the left" puts "While walking through a tuft of bushes and leaves..." puts "You fall into a tiger pit" puts "Do you look around..." puts "...try to fall through the spikes" puts "...or try to climb up by grabbing \nthe cracks in the pit" secret_passage = false while true print "Response: " choice = $stdin.gets.chomp choice.downcase! if choice == "look" && !secret_passage puts "You don't really see anything" elsif choice == "fall" dead(""" you manage to fall through the spikes but as you're sliding down you're foot gets caught between the spikes. You're ankle is broken. You starve to death. """) elsif choice == "climb" puts """ As is tradition, the rocks come loose and you fall into the pit. Some how you surive What do you do now? """ secret_passage = true elsif choice == "look" && secret_passage puts "You see a secret passage" the_cave else puts "stick to the script" end end # while loop end # the_left def the_cave puts "You found a cave." puts """ It's unsettingly dark and silent. Silent except for a slow dripping noise in the distance. Slowly you feel your way through the cave. You move as quietly as possible. The silence is unnerving, but also safe. While creeping through, you bump into what feels like a face. You hear a low laugh that is so menacing, you can feel whatever creature this was smiling in the darkness. In a wispy but rich whisper, it says: \"There's a toll.\" """ puts """ Do you give him what's in your wallet? ...try to trick him by giving him pieces of paper? ...or offer him your soul? """ print "Response: " choice = $stdin.gets.chomp if choice.include? "wallet" puts "He bites into it, and spits it out." dead("He wasn't feeling it, he pounces on you and rips your trachea out.") elsif choice.include? "paper" puts "He's thirlled" puts "He lets you pass, you find the exit and survive." puts "Good job!" exit(0) elsif choice.include? "soul" dead(""" He laughs and says he doesn't know what a soul is. Then he hits you in the head with a rock. Good job! """) else puts "Not a lot of option bruh..." end end # choosing the right def the_right puts "walking to the right" end def dead(why) puts "It looks like things aren't really working out for you\n" puts why exit(0) end beginning
true
4713495ba96911f7ac9eadd20014d6dc843e3cfa
Ruby
Jhua96/Launchschool_exercises
/RB101_small_problems_exercises/easy_5/ASCII.rb
UTF-8
192
3.09375
3
[]
no_license
def ascii_value(str) str.chars.inject(0) {|sum, n| sum + n.ord} end p ascii_value('Four score') == 984 p ascii_value('Launch School') == 1251 p ascii_value('a') == 97 p ascii_value('') == 0
true
72f82844d48f74fcb840d86d1e3d76599a6ca9d8
Ruby
JeanPierreGrau/promo-2-challenges
/02-OOP/08-Cookbook/lib/cookbook.rb
UTF-8
963
3.703125
4
[]
no_license
require 'csv' class Cookbook attr_accessor :file, :recipe def initialize(file) # TODO: Retrieve the data from your CSV file and store it in an instance variable @file = file @recipes = csv_to_array(@file) end # TODO: Implement the methods to retrieve all recipes, create, or destroy recipes # TODO: Implement a save method that will write the data into the CSV # And don't forget to use this save method when you have to modify something in your recipes array. def all array = [] @recipes.each {|cookbook_recipe| array << cookbook_recipe.join} p array end def create(recipe) @recipes << [recipe] save end def destroy(index) @recipes.delete_at(index) save end def save CSV.open(@file, "wb") do |csv| @recipes.each {|recipe| csv << recipe} end end def csv_to_array(file_name) array = [] CSV.foreach(file_name) do |row| array << row end array end end
true
58ed1dce9c62739303ccee6c4c158877ca509e23
Ruby
stereocat/cisco_acl_intp
/lib/cisco_acl_intp/scanner.rb
UTF-8
4,642
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'strscan' require 'cisco_acl_intp/scanner_special_token_handler' module CiscoAclIntp # Lexical analyzer (Scanner) class Scanner # include special tokens data and its handlers include SpecialTokenHandler # Constructor # @return [Scanner] def initialize @arg_tokens = gen_arg_token_lists end # Scan ACL from file to parse # @param [File] file File IO object # @return [Array] Scanned tokens array (Queue) def scan_file(file) run_scaner(file) do # no-op end end # Scan ACL from variable # @param [String] str Access list string # @return [Array] Scanned tokens array (Queue) def scan_line(str) run_scaner(str) do |each| each.chomp! # add word separator at end of line each.concat(' ') end end private # Exec scanning # @param [File, String] acl_text ACL data text # @yield Pre-process of scanning a line # @yieldparam [String] each Each line of acl_text # (called by `each_line` methods) # @return [Array] Scanned tokens array (Queue) def run_scaner(acl_text) queue = [] acl_text.each_line do |each| yield(each) queue.concat(scan_one_line(each)) end queue.push [false, 'EOF'] end # Scan a line # @param [String] line ACL String # @return [Array] Scanned tokens array (Queue) def scan_one_line(line) @ss = StringScanner.new(line) @line_queue = [] scan_match_arg_tokens || scan_match_acl_header || scan_match_ipaddr || scan_match_common until @ss.eos? @line_queue.push [:EOS, nil] # Add end-of-string end # Numbered ACL header checker # @param [Integer] aclnum ACL number # @return [Array] Token list def check_numd_acl_type(aclnum) case aclnum when 1..99, 1300..1999 [:NUMD_STD_ACL, aclnum] when 100..199, 2000..2699 [:NUMD_EXT_ACL, aclnum] else [:UNKNOWN, "access-list #{aclnum}"] end end # Scanner of acl header # @return [Boolean] if line matched acl header def scan_match_acl_header if @ss.scan(/\s*!.*$/) || @ss.scan(/\s*#.*$/) ## "!/# comment" and whitespace line, NO-OP elsif @ss.scan(/\s+/) || @ss.scan(/\A\s*\Z/) ## whitespace, NO-OP # @line_queue.push [:WHITESPACE, ""] # for debug elsif @ss.scan(/(?:access-list)\s+(\d+)\s/) ## Numbered ACL Header ## numbered acl has no difference ## in format between Standard and Extended... @line_queue.push check_numd_acl_type(@ss[1].to_i) elsif @ss.scan(/(ip\s+access-list)\s/) ## Named ACL Header @line_queue.push [:NAMED_ACL, @ss[1]] end @ss.matched? end # Scanner of IP address # @return [Boolean] if line matched IP address def scan_match_ipaddr if @ss.scan(/(\d+\.\d+\.\d+\.\d+)\s/) ## IP Address @line_queue.push [:IPV4_ADDR, @ss[1]] elsif @ss.scan(%r{(\d+\.\d+\.\d+\.\d+)(/)(\d+)\s}) ## IP Address of 'ip/mask' notation @line_queue.push [:IPV4_ADDR, @ss[1]] @line_queue.push ['/', @ss[2]] @line_queue.push [:NUMBER, @ss[3].to_i] end @ss.matched? end # Scanner of common tokens # @return [Boolean] if line matched tokens def scan_match_common if @ss.scan(/(\d+)\s/) ## Number @line_queue.push [:NUMBER, @ss[1].to_i] elsif @ss.scan(/([+\-]?#{STR_REGEXP})/) ## Tokens (echo back) ## defined in module SpecialTokenHandler ## plus/minus used in tcp flag token e.g. +syn -ack @line_queue.push token_list(@ss[1]) else ## do not match any? ## then scanned whole line and ## put in @line_queue as unknown. @ss.scan(/(.*)$/) # match all @line_queue.push [:UNKNOWN, @ss[1]] end @ss.matched? end # Scanner of special tokens # @return [Boolean] if line matched tokens def scan_match_arg_tokens @arg_tokens.each do |(str, length)| next unless @ss.scan(/#{str}/) (1...length).each do |idx| @line_queue.push token_list(@ss[idx]) end @line_queue.push [:STRING, @ss[length]] # last element end @ss.matched? end # Generate echo-backed token array # @param [String] token Token # @return [Array] Token array for scanner queue def token_list(token) [token, token] end end end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
true
2e18161d5ad22475d5fb8c2f5472a02f7b930351
Ruby
zlindacz/codeeval
/easy/road_trip.rb
UTF-8
2,262
3.609375
4
[]
no_license
=begin ROAD TRIP CHALLENGE DESCRIPTION: You've decided to make a road trip across the country in a straight line. You have chosen the direction you'd like to travel and made a list of cities in that direction that have gas stations to stop at and fill up your tank. To make sure that this route is viable, you need to know the distances between the adjacent cities in order to be able to travel this distance on a single tank of gasoline, (No one likes running out of gas.) but you only know distances to each city from your starting point. INPUT SAMPLE: The first argument is a path to a filename. Each line in the file contains the list of cities and distances to them, comma delimited, from the starting point of your trip. You start your trip at point 0. The cities with their distances are separated by semicolon. E.g. Rkbs,5453; Wdqiz,1245; Rwds,3890; Ujma,5589; Tbzmo,1303; Vgdfz,70; Mgknxpi,3958; Nsptghk,2626; Wuzp,2559; Jcdwi,3761; Yvnzjwk,5363; Pkabj,5999; Xznvb,3584; Jfksvx,1240; Inwm,5720; Ramytdb,2683; Voclqmb,5236; OUTPUT SAMPLE: Print out the distance from the starting point to the nearest city, and the distances between two nearest cities separated by comma, in order they appear on the route. E.g. 1245,58,2587,1563,136 70,2489,67,1135,197 1240,2344,1779,357,279 2683,2553 Constrains: Cities are unique, and represented by randomly generated string containing latin characters [A-Z][a-z]. The route length is an integer in range [10000, 30000] The number of cities is in range [500, 600] =end File.open(ARGV[0]).each_line do |line| line = line.chomp.split('; ').map {|pair| pair.split(',')}.to_h differences = [] distances = line.values.map(&:to_i).sort.unshift(0) distances.each_with_index do |distance, idx| differences << (distance.to_i - distances[idx-1].to_i) if idx != 0 end puts differences.join(',') end =begin # old File.open(ARGV[0]).each_line do |line| line = line.chomp.split('; ').map {|pair| pair.split(',')}.to_h distances = line.sort_by { |town, distance| distance }.to_h.values byebug differences = [] distances.unshift('0').each_with_index do |distance, idx| if idx != 0 differences << (distance.to_i - distances[idx-1].to_i) end end puts differences.join(',') end =end
true
2badc1e80594e3023c7bda95dbba30a54f6c4763
Ruby
BWITS/card_game
/spec/unit/card_game/core_ext_spec.rb
UTF-8
1,916
2.640625
3
[]
no_license
require 'spec_helper' require 'card_game/core_ext' describe CardGame::CoreExt, aggregate_failures: true do describe 'String' do it 'points to the right things' do expected = CardGame::Card.from_string("AH") assert_equal expected, "A".hearts assert_equal expected, "A".♡ assert_equal expected, "A".♥︎ assert_equal expected, "A".♥️︎ expected = CardGame::Card.from_string("KD") assert_equal expected, "K".diamonds assert_equal expected, "K".♢ assert_equal expected, "K".♦︎ assert_equal expected, "K".♦️ expected = CardGame::Card.from_string("QC") assert_equal expected, "Q".clubs assert_equal expected, "Q".♧ assert_equal expected, "Q".♣︎ assert_equal expected, "Q".♣️ expected = CardGame::Card.from_string("JS") assert_equal expected, "J".spades assert_equal expected, "J".♤ assert_equal expected, "J".♠︎ assert_equal expected, "J".♠️︎ end end describe 'Integer' do it 'points to the right things' do expected = CardGame::Card.from_string("3H") assert_equal expected, 3.hearts assert_equal expected, 3.♡ assert_equal expected, 3.♥︎ assert_equal expected, 3.♥️︎ expected = CardGame::Card.from_string("5D") assert_equal expected, 5.diamonds assert_equal expected, 5.♢ assert_equal expected, 5.♦︎ assert_equal expected, 5.♦️ expected = CardGame::Card.from_string("7C") assert_equal expected, 7.clubs assert_equal expected, 7.♧ assert_equal expected, 7.♣︎ assert_equal expected, 7.♣️ expected = CardGame::Card.from_string("10S") assert_equal expected, 10.spades assert_equal expected, 10.♤ assert_equal expected, 10.♠︎ assert_equal expected, 10.♠️︎ end end end
true
12bbed19c701ae1dcddb6f8f50f8f15030d3ce10
Ruby
bodyshopbidsdotcom/shift_planning
/lib/shift_planning/client.rb
UTF-8
1,714
2.6875
3
[ "MIT" ]
permissive
require "http" require "json" require "base64" module ShiftPlanning class Client attr_accessor :strict def initialize(config = {}) raise ArgumentError.new('Missing username') unless config.key?(:username) @username = config[:username] raise ArgumentError.new('Missing password') unless config.key?(:password) @password = config[:password] raise ArgumentError.new('Missing api key') unless config.key?(:key) @key = config[:key] @strict = config.key?(:strict) ? config[:strict] : true @url = 'http://www.shiftplanning.com/api/' @headers = { "Content-Type" => "application/x-www-form-urlencoded" } end def authenticated? !@token.nil? end def authenticate body = body_formatter({ "key" => @key, "request" => { "module" => "staff.login", "method" => "GET", "username" => @username, "password" => @password } }) response = HTTP.headers(@headers).post(@url, body) @token = JSON.parse(response)["token"] end def request(method, api_module, request) authenticate unless authenticated? body = body_formatter({ "token" => @token, "method" => method, "module" => api_module, "request" => request }) response = HTTP.headers(@headers).post(@url, body) result = JSON.parse(response) raise ApiError.new(result) if @strict && is_error_response?(result) result end def is_error_response?(response) response["status"] != 1 end def body_formatter(body) { :body => "data=#{JSON.dump(body)}" } end end end
true
2a21fb9812497a7fa1cd21cf279e243b416a3f58
Ruby
BookingBug/bookingbug_yellowfin
/app/models/bookingbug_yellowfin/person_capacity_usage.rb
UTF-8
3,515
2.578125
3
[ "MIT" ]
permissive
module BookingbugYellowfin class PersonCapacityUsage < ActiveRecord::Base attr_accessible :person_id, :date, :total_time_hrs, :time_booked_hrs, :time_blocked_hrs, :yf_format_date def self.populate_all_capacity_usage failed_imports = [] p 'populate all historic capacity usage' $stdout.sync = true for company in Company.where("cancelled != ? and template is null or template = ?", true, false) print '.' (::Date.today - 4.weeks).to_date.upto(::Date.today) do |date| begin add_person_capacity_for_company company.id, date rescue failed_imports << [date, company.id] end end end p 'failed_imports **********' p failed_imports return true end def self.amend_yesterdays_capacity_usage failed_imports = [] p 'amend_yesterdays_capacity_usage' $stdout.sync = true Company.find_each() do |company| print '.' begin add_person_capacity_for_company company.id, 1.day.ago.to_date rescue failed_imports << company.id end end p 'failed_imports **********' p failed_imports if failed_imports.present? Airbrake.notify( :error_class => "BookingbugYellowfin", :error_message => "Failed Yellowfin Amend Yesterdays Capacity. Locale: #{LOCALE}" ) end return true end # BookingbugYellowfin::PersonCapacityUsage.add_person_capacity_for_company c, date def self.add_person_capacity_for_company company_id, date = ::Date.yesterday failed_people = [] for person in Person.where(company_id: company_id, deleted: false, disabled: false) begin booked_time = 0 blocked_time = 0 next if person.schedule.blank? total_time = person.schedule.total_time_available_for_date(date) total_time = total_time/60.0 #Convert to hours booked_slots = Slot.where(person_id: person.id, date: date, status: Slot::BOOKING_BOOKED) for slot in booked_slots booked_time += slot.ilen*5 end blocked_slots = Slot.where(person_id: person.id, date: date, status: Slot::BOOKING_BLOCKED) for slot in blocked_slots if slot.slot_type == Schedule::DAY && slot.ilen == 1 blocked_time += (total_time * 60) else blocked_time += slot.ilen*5 end end booked_time = booked_time/60.0 blocked_time = (total_time*60) if (total_time*60) < blocked_time blocked_time = blocked_time/60.0 capacity_record = self.where(person_id: person.id, date: date).first if capacity_record.present? capacity_record.update_attributes(person_id: person.id, date: date, yf_format_date: BookingbugYellowfin::FormatHelpers.to_yf_format(date), total_time_hrs: total_time, time_booked_hrs: booked_time, time_blocked_hrs: blocked_time) else self.create(person_id: person.id, date: date, yf_format_date: BookingbugYellowfin::FormatHelpers.to_yf_format(date), total_time_hrs: total_time, time_booked_hrs: booked_time, time_blocked_hrs: blocked_time) end rescue failed_people << person.id end end if failed_people.present? p 'failed for person(staff) **********' p failed_people raise "Failed Import" end return true end end end
true
4371bb58a364d866016f2492b38fe1697cc1d9dd
Ruby
chrisaugust/Launch-School-Intro-to-Programming
/basics/exercise_three.rb
UTF-8
426
4.1875
4
[]
no_license
# exercise 3: movie hash movies = {} still_inputting_movies = "yes" while still_inputting_movies == "yes" puts "Name of movie: " movie = gets.chomp.to_s puts "Year?" year = gets.chomp.to_i movies[movie] = year puts "Do you want to input another movie? (yes or no)" answer = gets.chomp if answer == "no" movies.each do |key, value| puts key + ": " + value.to_s end break end end
true
94c063c1cc81204a41a565fce0c333ec9de4407a
Ruby
jsonperl/boondoggle
/multicore_random.rb
UTF-8
1,225
3.25
3
[]
no_license
require "etc" class MulticoreRandom def initialize @dataset = File.readlines("data").map(&:to_i).freeze @pids = [] @readers = [] end # Brute force recursive def compute(goal, dataset) element = dataset.delete_at(rand(dataset.length)) if element < goal compute(goal - element, dataset).push(element) else [element] end end def run(goal) Etc.nprocessors.times do reader, writer = IO.pipe @readers << reader @pids << fork do Signal.trap("HUP") { exit } Signal.trap("INT") { } # let the parent process cleanup reader.close loop do answer = compute(goal, @dataset.dup) if answer.reduce(0, :+) == goal Marshal.dump(answer, writer) break end end end writer.close end ready, _, _ = IO.select(@readers) complete(ready[0].read) ensure cleanup end # For this excercise, we'll just write to stdout def complete(answer) puts Marshal.load(answer).sort end # Kill the sub-processes def cleanup @pids.each { |pid| Process.kill("HUP", pid) } rescue nil end end mr = MulticoreRandom.new mr.run(ARGV[0].to_i)
true
1c0b260f2eca7f8d0c5c4e0775a074b4c0c04ec2
Ruby
lishulongVI/leetcode
/ruby/58.Length of Last Word(最后一个单词的长度).rb
UTF-8
1,366
3.90625
4
[ "MIT" ]
permissive
=begin <p>Given a string <i>s</i> consists of upper/lower-case alphabets and empty space characters <code>' '</code>, return the length of last word in the string.</p> <p>If the last word does not exist, return 0.</p> <p><b>Note:</b> A word is defined as a character sequence consists of non-space characters only.</p> <p><b>Example:</b> <pre> <b>Input:</b> "Hello World" <b>Output:</b> 5 </pre> </p><p>给定一个仅包含大小写字母和空格&nbsp;<code>&#39; &#39;</code>&nbsp;的字符串,返回其最后一个单词的长度。</p> <p>如果不存在最后一个单词,请返回 0&nbsp;。</p> <p><strong>说明:</strong>一个单词是指由字母组成,但不包含任何空格的字符串。</p> <p><strong>示例:</strong></p> <pre><strong>输入:</strong> &quot;Hello World&quot; <strong>输出:</strong> 5 </pre> <p>给定一个仅包含大小写字母和空格&nbsp;<code>&#39; &#39;</code>&nbsp;的字符串,返回其最后一个单词的长度。</p> <p>如果不存在最后一个单词,请返回 0&nbsp;。</p> <p><strong>说明:</strong>一个单词是指由字母组成,但不包含任何空格的字符串。</p> <p><strong>示例:</strong></p> <pre><strong>输入:</strong> &quot;Hello World&quot; <strong>输出:</strong> 5 </pre> =end # @param {String} s # @return {Integer} def length_of_last_word(s) end
true
c35e87b4eea2a94012eaaf20e464cd5966e97aca
Ruby
emjose/ruby-oo-inheritance-modules-nyc04-seng-ft-071220
/lib/dancer.rb
UTF-8
502
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative './class_methods_module.rb' require_relative './dance_module.rb' require_relative './fancy_dance.rb' class Dancer extend FancyDance::ClassMethods include FancyDance::InstanceMethods # This is a module in dance_module.rb. include keyword allows us to use all of the methods of # the included module as instance methods (extend keyword allows module to be used as class methods) attr_accessor :name def initialize(name) @name = name end end
true
b35eccc385323371d99bf37fed5dfb22881630bb
Ruby
sad16/thinknetica-rails-advanced-qna
/app/services/search/base.rb
UTF-8
886
2.609375
3
[]
no_license
module Services module Search class Base < ApplicationService class Error < StandardError; end class EmptySearchError < Error; end def call(params) search(params.to_h.deep_symbolize_keys) end private def search(params) search_options = search_options(params) validate_search_options(search_options) search_klass.search(*search_options) end def search_options(params) [ params[:global].presence, { conditions: search_conditions(params).compact } ] end def validate_search_options(search_options) raise EmptySearchError if search_options[0].nil? && search_options[1][:conditions].blank? end def search_klass raise NotImplementedError end def search_conditions(params) {} end end end end
true
40896f4289c649d279f0c8266d037c2f8fb4f4c6
Ruby
GaryZCLau/programming-univbasics-4-square-array-nyc04-seng-ft-030920
/lib/square_array.rb
UTF-8
218
3.484375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(array) # your code here squared_array = [] counter = 0 while counter < array.length do squared = array[counter] ** 2 squared_array << squared counter += 1 end squared_array end
true
5e294fe73abeadab35bbe4518c7c1f873b886db4
Ruby
I-Mircheva/rsa-tp-hw
/spec/models/rsa_spec.rb
UTF-8
1,020
2.828125
3
[]
no_license
require 'rails_helper' require 'spec_helper' RSpec.describe RSA do let(:msg) { "The quick brown fox jumped over the lazy dog!" } let(:rsa) { RSA.new(217, 59, 119) } let(:new_keys) { rsa.new_key } let(:rsa_rand) { RSA.new(new_keys[0], new_keys[1], new_keys[2]) } it "Tries if return n works" do expect(rsa.n).to eq(217) end it "Tries if return e works" do expect(rsa.e).to eq(59) end it "Tries if return d works" do expect(rsa.d).to eq(119) end it "Tries if crypt changes message to right numbers" do expect(rsa.encrypt("abc")).to eq "132.56.57" end it "Tries if crypt/decrypt works" do expect(rsa.decrypt(rsa.encrypt(msg))).to eq(msg) end it "Tries if crypt/decrypt works with random keys" do expect(rsa_rand.decrypt(rsa_rand.encrypt(msg))).to eq(msg) end it "Tries if crypt/decrypt works with long message" do msg = "@#(SD(J!NC(@asdfomg.;51483lo lel {}:\" :))))2412561sdf" expect(rsa_rand.decrypt(rsa_rand.encrypt(msg))).to eq(msg) end end
true
a025d41a63c040eff723920e347b5c01178e35b9
Ruby
suguru03/leetcode
/algorithms/0172.Factorial Trailing Zeroes/solution.rb
UTF-8
154
3.390625
3
[]
no_license
# @param {Integer} n # @return {Integer} def trailing_zeroes(n) result = 0 while n > 0 do n = n / 5 | 0 result += n end return result end
true
3b1c9f28957ca930426e92a0e82fbd9f75434f2a
Ruby
anilsingh826/examplecrm
/app/models/dynamic_field.rb
UTF-8
757
2.515625
3
[]
no_license
class DynamicField < ActiveRecord::Base attr_accessible :roles, :model_name, :name, :type ROLES = %w[admin client tech] DATA_TYPES = [ ["Text","string_type"], ["Paragraph text","text_type"], ["Radio buttons", "radio_type"], ["Checkboxes", "check_boxes_type"], ["Integer", "integer_type"], ["Boolean", "boolean_type"], ["Float", "float_type"] ] def role?(base_role) ROLES.index(base_role.to_s) <= ROLES.index(role) end def roles=(roles) self.field_role = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+) end def roles ROLES.reject do |r| ((field_role || 0) & 2**ROLES.index(r)).zero? end end def is?(role) roles.include?(role.to_s) end end
true
272ce97bfbfe6f3afcf79f9b9d6d2f9c73089e27
Ruby
puttyplayer/fraction_calculator
/fraction.rb
UTF-8
2,982
4.34375
4
[]
no_license
#this is a fractions program that will add subtract multiply and reduce #it might also convert fraction into decimal require 'rational' #above require allows you acsess to two methods #the methods are lcm and gcd #use like this 12.gcd(4) or 12.lcm(3) #lcm is the number for common denominator #methods definition section #*************************************************************** #all methods should all reduce before reporting awnser def add_frac(a,b) lcm = a[1].lcm(b[1]) puts a.inspect puts b.inspect puts lcm if lcm == a[1] and b[1] then sum2 = a[0] + b[0] puts "Your sum is #{sum2}/#{lcm}" else sum1 = (a[0]*b[1]) + (b[0]*a[1]) puts sum1 puts "Your sum is #{sum1}/#{lcm}" end end def mult_frac(a,b) num= a[0]*b[0] denom=a[1]*b[1] frac = reduce_frac print_frac(frac) end def sub_frac(a,b) #sub should call addition method to do its legwork b[0] = b[0]*-1 add_frac(a,b) end def div_frac(a,b) #division should call invert and then multiply invert_frac(a,b) numeratorSum = $numerator1*$numerator2 denominatorSum = $den1 * $den2 puts "Your fraction is #{numeratorSum}/#{denominatorSum}" end def reduce_frac(a,b) redux = a[0].gcd(a[1]) numerator = a[0] / redux denom = a[1] / redux #now we do it for the 2nd frac redux1 = b[0].gcd(b[1]) numerator1 = b[0] / redux1 denom1 = b[1] / redux1 #numerator2 = b[0] / redixDenom puts "Your fractions are #{numerator}/#{denom} and #{numerator1}/#{denom1}" end def to_decimal(a,b) a.collect! {|x| x.to_f} b.collect! {|x| x.to_f} a = a[0] / a[1] b = b[0] / b[1] puts "Your first fraction into a decimal is #{a.inspect}" puts "Your second fraction into a decimal is #{b}" end def invert_frac(a,b) $numerator1 = a[1] $numerator2 = b[1] $den1 = a[0] $den2 = b[0] puts "The inverted fractions are #{$numerator1}/#{$den1} and #{$numerator2}/#{$den2}" end def print_frac(a,b) puts "Your fractions are: #{frac1[0]}/#{frac2[0]} and #{frac1[1]}/ #{frac2[1]}" #constuct a string w/ a frac #ex puts " #{frac1[1]}/ #frac{2} end #*************************************************************** #Procedural section of code #*************************************************************** puts "Welcome to my fraction calculator. Please enter the two fractions like this,one whole fraction at a time pressing enter inbetween the fraction. Example: a/b, enter, c/d then enter." frac1 = gets.chomp frac2 = gets.chomp frac1 = frac1.split("/") frac2 = frac2.split("/") #change into integers frac1.collect! {|x| x.to_i} frac2.collect! {|x| x.to_i} puts "Would you like to add (1), subtract (2), multiply (3), divide(4), reduce(5) invert (6), or turn to decimal(7) your fractions" choice = gets.to_i case choice when 1 add_frac(frac1,frac2) when 2 sub_frac(frac1,frac2) when 3 mult_frac(frac1,frac2) when 4 div_frac(frac1,frac2) when 5 reduce_frac(frac1,frac2) when 6 invert_frac(frac1,frac2) when 7 to_decimal(frac1, frac2) end #***************************************************************
true
0c966392a9ec6cd9e7b028a3755328fadb4d93a0
Ruby
ox/Angstrom
/bin/angstrom
UTF-8
3,346
2.875
3
[]
no_license
#!/usr/bin/env ruby require 'fileutils' include FileUtils # this is a cli tool to make getting running with angstrom easier. def inform puts """ Angstrom is an asynchronous ruby web framework that's fronted by mongrel2 and makes use of Actors in order to handle requests. It is preferred to use rubinius2.0.0dev in order to take advantage of true concurrency in Ruby. usage: angstrom <command> commands: create <name> [port] Creates an angstrom app with a sample mongrel2.conf and config.sqlite running on [port] or the default 6767. start [host] [db.sqlite] Starts a mongrel2 server in this directory and then runs the app called by the current directorys name. This is equivalent to: $m2sh start -host localhost -db config.sqlite >> /dev/null & $ruby app.rb stop [host] Kills the default running mongrel2 server or [host]. This is like: $m2sh stop -host localhost short commands: c = create s = start t = stop """ end mongrel2_conf = """ angstrom_handler = Handler( send_spec='tcp://127.0.0.1:9999', send_ident='34f9ceee-cd52-4b7f-b197-88bf2f0ec378', recv_spec='tcp://127.0.0.1:9998', recv_ident='') media_dir = Dir( base='media/', index_file='index.html', default_ctype='text/plain') angstrom_host = Host( name=\"localhost\", routes={ '/media/': media_dir, '/': angstrom_handler}) angstrom_serv = Server( uuid=\"%s\", access_log=\"/log/mongrel2.access.log\", error_log=\"/log/mongrel2.error.log\", chroot=\"./\", default_host=\"localhost\", name=\"angstrom test\", pid_file=\"/run/mongrel2.pid\", port=%i, hosts = [angstrom_host] ) settings = {\"zeromq.threads\": 2, \"limits.min_ping\": 15, \"limits.kill_limit\": 2} servers = [angstrom_serv] """ inform if ARGV.empty? case ARGV[0] when 'create', 'c' inform if ARGV[1].nil? port = (ARGV[2].nil? ? 6767 : ARGV[2]) mkdir ARGV[1] cd ARGV[1] %w[log run tmp].map(&method(:mkdir)) File.open("mongrel2.conf", 'w') {|file| file.puts(mongrel2_conf % [`m2sh uuid`.chomp, port]) } puts "loading in the mongrel2.conf config" puts `m2sh load -config mongrel2.conf -db config.sqlite` File.open("#{ARGV[1]}.rb", 'w') {|file| file.puts "require 'rubygems'\nrequire 'angstrom'\n\n"} puts "Created app #{ARGV[1]} that will run on port #{port}" when 'start', 's' host = (ARGV[1].nil? ? 'localhost' : ARGV[1]) db = (ARGV[2].nil? ? 'config.sqlite' : ARGV[2]) output = `m2sh start -host #{host} -config #{db} > /dev/null &` if output.match /Aborting/ puts "Error starting up mongrel2.\n\nTrace:\n#{output}" break end puts "Started #{host} using the #{db} db" file = Dir.pwd.split('/').last puts "now running #{file}.rb" puts `ruby #{file}.rb` when 'stop', 't' host = (ARGV[1].nil? ? 'localhost' : ARGV[1]) puts `m2sh stop -host #{host}` puts "Stopped #{host}, I think" else inform end
true
9cb7bb037034b15cbb47e7cb66ef49637f777967
Ruby
agussuparman/belajar-dasar-ruby
/9-hash/2-hash_default_value.rb
UTF-8
306
3.125
3
[]
no_license
hash = {nama: "Agus Suparman", "alamat" => "Gunungkidul"} puts hash puts hash.fetch(:nama, "Suparman Agus") puts hash[:salary] # nil puts hash.fetch(:salary, 50_000_000) puts "\n" # Cara lain membuat hash dan mendefinisikan nilai default hash hash = Hash.new("belum ada nilai") puts hash[:nilai] puts hash[:nilai_dua]
true
c6ffe0b603e5a241ac05edcd9df68689893af671
Ruby
OlegLazaryev/rubywarrior
/player.rb
UTF-8
1,294
3.296875
3
[]
no_license
require 'environment' require 'condition' class Player def initialize @condition = Condition.new @environment = nil end def play_turn(warrior) before_turn(warrior) process(warrior) after_turn end private def before_turn(warrior) @environment = Environment.new(warrior) condition.current_health = warrior.health end def after_turn condition.set_current_health end def process(warrior) warrior.pivot! and return if need_to_pivot? if environment.nothing_forward? chase_the_enemy(warrior) else save_the_captive(warrior) end end attr_reader :condition, :environment def need_to_pivot? environment.wall_forward? || environment.archer_backward? end def chase_the_enemy(warrior) if condition.injured? reinforce(warrior) else offense(warrior) end end def save_the_captive(warrior) warrior.rescue! if environment.captive_forward? end def reinforce(warrior) if environment.enemy_forward? warrior.shoot! elsif condition.not_injuring_now? warrior.rest! elsif condition.severe_injured? warrior.walk!(:backward) else warrior.walk! end end def offense(warrior) if environment.safe_attack? warrior.shoot! else warrior.walk! end end end
true
2ed6a6114936aeb02cd8ab36c611306abb632bb5
Ruby
ljorgens/triangles
/spec/triangle_spec.rb
UTF-8
1,092
3.234375
3
[]
no_license
require("rspec") require("triangle") require("pry") describe(Triangle) do describe("#is_triangle?") do it("takes 3 inputs from the user specifying side lengths and returns whether it's a triangle or not") do test_triangle = Triangle.new(3, 7, 2) expect(test_triangle.is_triangle?()).to eq(false) end end describe('#triangle_type') do it("takes 3 inputs from user and returns triangle type") do test_triangle = Triangle.new(5,5,5) expect(test_triangle.triangle_type()).to eq("equilateral") end it("takes 3 inputs from user and returns triangle type") do test_triangle = Triangle.new(3,5,5) expect(test_triangle.triangle_type()).to eq("iscosoles") end it("takes 3 inputs from user and returns triangle type") do test_triangle = Triangle.new(3,4,5) expect(test_triangle.triangle_type()).to eq("scalene") end it("takes 3 inputs from user and returns triangle type") do test_triangle = Triangle.new(1,2,5) expect(test_triangle.triangle_type()).to eq("not a triangle") end end end
true
95ec27551a05d543adcfe633680a24c04872d801
Ruby
stewartmatheson/The-AI-Server
/server/lib/rdai/lib/rdai/rule.rb
UTF-8
774
2.890625
3
[]
no_license
module RDAI module Rule def self.included(base) base.extend(ClassMethods) end module ClassMethods def acts_as_rule include InstanceMethods end end module InstanceMethods def fire eval <<-EOV #{camelize(name)}.fire EOV end private def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) if first_letter_in_uppercase lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } else lower_case_and_underscored_word.to_s[0].chr.downcase + camelize(lower_case_and_underscored_word)[1..-1] end end end end end
true
ddb1f814c9ea6c50cd8d61903db86d0bdc37b374
Ruby
flyeven/rSugar
/proxy.rb
UTF-8
507
3.1875
3
[]
no_license
#!/usr/bin/env ruby #-*- coding: utf-8 -*- Proxy = Class.new(BasicObject) do def initialize(subject) @subject = subject end def method_missing(message, *args, &block) ::STDOUT.puts "Before method called" ret = @subject.send(message, *args, &block) ::STDOUT.puts "After method called" ret end end Kkk = Class.new do def mmm puts "from #mmm" end end k = Kkk.new k.mmm # => MMM pk = Proxy.new k pk.mmm # => MMM puts "-----" puts pk.is_a? Kkk puts pk.class # => true
true
92be0abc197952ffcf54bee528b59a1886428859
Ruby
bsheehy9/ls-challanges
/medium/clock/clock.rb
UTF-8
1,740
4.375
4
[]
no_license
=begin problem: - create clock class - class method 'at' - mandatory hour parameter - optional minute parameter - '+' and '-' methods to add minutes - output string in 00:00 format - 24 hour day examples: given in tests data: - string output - integer inputs algorithm: - create constant for minutes in day - take integers and covert to total minutes - calculate hours and minutes - convert negative hours and more than 24 hours key rules: - need to make a new clock object if changing time =end class Clock HOURS_IN_DAY = 24 MINUTES_IN_HOUR = 60 MINUTES_IN_DAY = 1440 def initialize(hour, minute) @hour = hour @minute = minute @total_minutes = to_minutes(hour, minute) end def self.at(hour, minute = 0) new(hour, minute) end def to_minutes(hours, minutes) (hours * MINUTES_IN_HOUR) + minutes end def convert_time(minutes) hour, minute = minutes.divmod(60) hour %= HOURS_IN_DAY self.class.new(hour, minute) end def to_s format('%02d:%02d', hour, minute) end def +(add_minutes) new_minutes = total_minutes + add_minutes new_minutes -= MINUTES_IN_DAY if new_minutes > MINUTES_IN_DAY convert_time(new_minutes) end def -(sub_minutes) new_minutes = total_minutes - sub_minutes if new_minutes < -1440 new_minutes = new_minutes % 1440 elsif new_minutes < 0 new_minutes = MINUTES_IN_DAY + new_minutes end puts new_minutes convert_time(new_minutes) end def ==(other_time) hour == other_time.hour && minute == other_time.minute end private attr_accessor :total_minutes protected attr_accessor :hour, :minute end clock = Clock.at(0, 30) puts clock puts clock - 60
true
9a6332579fa1a653cac88cff9f9cf0d56d0afc21
Ruby
rajiv-g/devops-scripts
/influxdb-scripts/measurement-migration-script.rb
UTF-8
4,044
2.640625
3
[]
no_license
require 'influxdb' require 'json' require 'toml' require 'date' config = TOML.load_file('migrate.conf') $flag_after_rows = config['migrate']['flag_after_rows'] || 100 $start_from_previous_migration_date = config['migrate']['start_from_previous_migration_date'] $flag_rows_processed = 0 $total_rows_processed = 0 $influxdb = InfluxDB::Client.new config['connection']['database'], host: config['connection']['host'], port: config['connection']['port'], use_ssl: config['connection']['use_ssl'], verify_ssl: config['connection']['verify_ssl'], ssl_ca_cert: config['connection']['ssl_ca_cert'], retry: config['connection']['retry'], username: config['connection']['username'], password: config['connection']['password'] def get_start_date(measurement_name) # Store in Date filename return nil unless $start_from_previous_migration_date filename = "#{measurement_name}_Date" File.file?(filename) ? File.read(filename) : nil end def get_migration_json(filename) JSON.parse(File.read("#{filename}.json")) end def execute_query(query) $influxdb.query query end def extract_tags(measurement_name) # To extract tags query = "SHOW TAG KEYS FROM #{measurement_name}" result = execute_query(query) list = result.collect { |tags| tags['values'] }.flatten unless result.nil? tag_keys = list.collect { |t| t['tagKey'] }.compact.uniq unless list.nil? end def migrate(measurement_name) # Query results query = "select * from #{measurement_name}" start_date = get_start_date(measurement_name) query += " where time >= '#{start_date}'" unless start_date.nil? or start_date.empty? query += " ORDER BY time ASC" tags = extract_tags(measurement_name) # Format for writing migration_fields = get_migration_json(measurement_name) $influxdb.query query do |_, _, points| points.each do |row| point_set = generate_custom_measurement_hash(row, migration_fields, tags) p point_set send_to_influxdb(point_set) flag_date(row['time'], "#{measurement_name}_Date") end end rescue => e puts e.message end def generate_custom_measurement_hash(row, migration_fields, measurement_tags) point_set = {} # Used to store the tags & field set in the format point_set = {<measurement_name1>: { tags: {}, fields: {}, timestamp:<timestamp>}, <measurement_name2>: { tags: {}, fields: {}, timestamp: <timestamp>}, ... } row.each do |k,v| unless measurement_tags.include?(k) || k == 'time' || v.nil? # fields measurement_name = custom_measurement_of_field(k, migration_fields) if measurement_name point_set[measurement_name] ||= {} tags = {} measurement_tags.each do |t| tags[t] = row[t] if row.keys.include? t end point_set[measurement_name][:tags] ||= tags unless tags.empty? point_set[measurement_name][:values] ||= {} val = is_number?(v) ? v.to_f : v point_set[measurement_name][:values][k] = val point_set[measurement_name][:timestamp] = DateTime.parse(row['time']).strftime('%s') end end end point_set end def custom_measurement_of_field(f, migration_fields) measurement_name = nil migration_fields.each do |k,v| measurement_name = k if v.include? f end measurement_name end def send_to_influxdb(point_set) point_set.keys.each do |m| $influxdb.write_point(m, point_set[m]) end end def flag_date(timestamp, filename) $flag_rows_processed = $flag_rows_processed + 1 $total_rows_processed = $total_rows_processed + 1 if $flag_after_rows == $flag_rows_processed File.open(filename, 'w') { |file| file.write(timestamp) } puts "Flagged #{timestamp}" $flag_rows_processed = 0 end end def is_number?(input) true if Float(input) rescue false end migrate(config['migrate']['measurement'])
true
9f1460ac479cdc2d1098c4e0127f2703eeb3c149
Ruby
RameshC1993/collections_practice-onl01-seng-ft-012120
/collections_practice.rb
UTF-8
1,059
3.875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(array) array.sort do |a, b| a <=> b end end def sort_array_desc(array) array.sort do |a, b| b <=> a end end def sort_array_char_count(strings) strings.sort do |a, b| a.length <=> b.length end end def swap_elements(array) temp_item = array[1] array[1] = array[2] array[2] = temp_item return array end def reverse_array(array) new_arr = [] i = array.length - 1 while i >= 0 do new_arr << array[i] i -= 1 end return new_arr end def kesha_maker(array) new_arr = [] array.each do |str| temp_str = str temp_str[2] = "$" new_arr << temp_str end return new_arr end def find_a(array) new_arr = [] array.each do |string| if string[0] == "a" new_arr << string end end return new_arr end def sum_array(array) total = 0 array.each do |num| total += num end return total end def add_s(array) array.each_with_index do |element, index| if index != 1 array[index] = element + "s" end end return array end
true
7918bfaac7a5ae6b29e091f949d356a5ecb30753
Ruby
Bassmint123/Ruby-and-Rails-Projects
/script8.rb
UTF-8
7,260
4.75
5
[]
no_license
# 1. A block is just a bit of code between do..end or {}. It's not an object on its own, # but it can be passed to methods like .each or .select. # 2. A proc is a saved block we can use over and over. # 3. A lambda is just like a proc, only it cares about the number of arguments # it gets and it returns to its calling method rather than returning immediately. # Example of a code block 5.times do |x| puts "I'm a block!" end # Refactored another way 5.times {puts "I'm a block!"} # The collect method takes a block and applies the expression in the block to every element in an array. my_nums = [1, 2, 3] my_nums.collect { |num| num ** 2 } my_nums.each { |x| puts "#{x}" } # ==> [1, 4, 9] # However, # my_nums is still [1, 2, 3]. This is because .collect returns a copy of my_nums, # but doesn't change (or mutate) the original my_nums array. # If we want to do that, we can use .collect! with an exclamation point: my_nums = [1, 2, 3] my_nums.collect! { |num| num ** 2 } # ==> [1, 4, 9] my_nums.each { |x| puts "#{x}" } # ==> [1, 4, 9] # The map! method does the same thing as the collect! method my_nums = [1, 2, 3] my_nums.map! { |num| num ** 2 } # ==> [1, 4, 9] my_nums.each { |x| puts "#{x}" } # ==> [1, 4, 9] # An example using the yield method. # Here, yield isn't doing anything but passing an argument (in this case puts) to the block that is passed into the block_test method. def block_test puts "We're in the method!" puts "Yielding to the block..." yield puts "We're back in the method!" end block_test { puts ">>> We're in the block!" } # Using the yield method while passing Brad as the name parameter def yield_name(name) puts "In the method! Let's yield." yield("Kim") puts "In between the yields!" yield(name) puts "Block complete! Back in the method." end yield_name("Eric") { |n| puts "My name is #{n}." } # Calling the method with my name! yield_name("Brad") { |n| puts "My name is #{n}." } # Passing the yield parameter into the block from the double method def double(n) yield(4) end double(3) { |n| puts "My result is #{n * 2}." } # Prints out => My result is 8. # # procs help us do DRY code. Don't Repeat Yourself # Example of using a proc for multiples of 3 to 100 # multiples_of_3 = Proc.new do |n| n % 3 == 0 end (1..100).to_a.select(&multiples_of_3) # The & is used to convert the multiples_of_3 proc into a block # Another example of using a proc floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911] round_down = Proc.new {|x| x.floor} # The .floor method rounds a float (a number with a decimal) down to the nearest integer. ints = floats.collect(&round_down) ints.each {|x| puts "#{x}"} # Another example of using a proc # Here at the amusement park, you have to be four feet tall # or taller to ride the roller coaster. Let's use .select on # each group to get only the ones four feet tall or taller. group_1 = [4.1, 5.5, 3.2, 3.3, 6.1, 3.9, 4.7] group_2 = [7.0, 3.8, 6.2, 6.1, 4.4, 4.9, 3.0] group_3 = [5.5, 5.1, 3.9, 4.3, 4.9, 3.2, 3.2] # This is the Proc over_4_feet = Proc.new do |height| height >= 4 end # Changed these three so that they use the over_4_feet Proc can_ride_1 = group_1.select(&over_4_feet) can_ride_1.each {|x| puts "#{x}"} can_ride_2 = group_2.select(&over_4_feet) can_ride_2.each {|x| puts "#{x}"} can_ride_3 = group_3.select(&over_4_feet) can_ride_3.each {|x| puts "#{x}"} # Creates a method that calls a proc. Notice how the method takes no arguments to do this. def greeter yield end phrase = Proc.new {puts "Hello there!"} greeter(&phrase) # Outputs => Hello there! # Unlike blocks, we can call procs directly by using Ruby's .call method. # This is easier than using a method to call the proc. Check it out! test = Proc.new { puts "This does something" } test.call # executes the proc # Here we convert symbols to procs using that handy little "&" symbol numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] strings_array = numbers_array.map(&:to_s) strings_array.each {|x| puts "#{x}"} # Like procs, lambdas are objects. when we pass the lambda to lambda_demo, # the method calls the lambda and executes its code. def lambda_demo(a_lambda) puts "I'm the method!" a_lambda.call end lambda_demo(lambda { puts "I'm the lambda!" }) # Using more of the lambda syntax strings = ["leonardo", "donatello", "raphael", "michaelangelo"] symbolize = lambda { |x| x.to_sym } # Create the symbolize lambda symbols = strings.collect(&symbolize) # Convert array elements to symbols symbols.each {|y| puts "#{y}"} # Output => [:leonardo, :donatello, :raphael, :michaelangelo] # # Proc vs. lambda. Check out the difference. # # First, a lambda checks the number of arguments passed to it, while a proc does not. # This means that a lambda will throw an error if you pass it the wrong number of arguments, # whereas a proc will ignore unexpected arguments and assign nil to any that are missing. # # Second, when a lambda returns, it passes control back to the calling method; # when a proc returns, it does so immediately, without going back to the calling method. # # AT RUNTIME... # See how the proc says Batman will win? This is because it returns immediately, # without going back to the batman_ironman_proc method. # # Our lambda, however, goes back into the method after being called, # so the method returns the last code it evaluates: "Iron Man will win!" def batman_ironman_proc victor = Proc.new { return "Batman will win!" } victor.call "Iron Man will win!" end puts batman_ironman_proc def batman_ironman_lambda victor = lambda { return "Batman will win!" } victor.call "Iron Man will win!" end puts batman_ironman_lambda # Create a lambda, symbol_filter, that takes one parameter and checks to see if that parameter .is_a? Symbol. my_array = ["raindrops", :kettles, "whiskers", :mittens, :packages] symbol_filter = lambda { |x| x.is_a? Symbol } symbols = my_array.select(&symbol_filter) symbols.each {|y| puts "#{y}"} # Get the integers from odds_n_ends with a method that calls a block to check for integers odds_n_ends = [:weezard, 42, "Trady Blix", 3, true, 19, 12.345] ints = odds_n_ends.select {|x| x.is_a? Integer} # Outputs => 42, 3, 19 # Create a proc called under_100 that checks if a number it's passed is less than 100. ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44] under_100 = Proc.new { |x| if x < 100 x # return x end } ages.select(&under_100) # Create a lambda called first_half that checks if a hash value is # less than (that is, earlier in the alphabet than) "M". We are using # the |key, value| since this is a hash crew = { captain: "Picard", first_officer: "Riker", lt_cdr: "Data", lt: "Worf", ensign: "Ro", counselor: "Troi", chief_engineer: "LaForge", doctor: "Crusher" } # Create the lambda here first_half = lambda { |key, value| if value < "M" value end } a_to_m = crew.select(&first_half) # Pass lambda as the parameter here a_to_m.each {|x, y| puts "#{x}: #{y}"}
true
d255f38547cbfec207610981f913ea82e6f34a4d
Ruby
megamsys/nilavu
/lib/scheduler/schedule_info.rb
UTF-8
2,973
2.625
3
[ "MIT" ]
permissive
module Scheduler class ScheduleInfo attr_accessor :next_run, :prev_run, :prev_duration, :prev_result, :current_owner def initialize(klass, manager) @klass = klass @manager = manager data = nil if data = $redis.get(key) data = JSON.parse(data) end if data @next_run = data["next_run"] @prev_run = data["prev_run"] @prev_result = data["prev_result"] @prev_duration = data["prev_duration"] @current_owner = data["current_owner"] end rescue # corrupt redis @next_run = @prev_run = @prev_result = @prev_duration = @current_owner = nil end def valid? return false unless @next_run (!@prev_run && @next_run < Time.now.to_i + 5.minutes) || valid_every? || valid_daily? end def valid_every? return false unless @klass.every !!@prev_run && @prev_run <= Time.now.to_i && @next_run < @prev_run + @klass.every * (1 + @manager.random_ratio) end def valid_daily? return false unless @klass.daily !!@prev_run && @prev_run <= Time.now.to_i && @next_run < @prev_run + 1.day end def schedule_every! if !valid? && @prev_run mixup = @klass.every * @manager.random_ratio mixup = (mixup * Random.rand - mixup / 2).to_i @next_run = @prev_run + mixup + @klass.every end if !valid? @next_run = Time.now.to_i + 5.minutes * Random.rand end end def schedule_daily! return if valid? at = @klass.daily[:at] || 0 today_begin = Time.now.midnight.to_i today_offset = DateTime.now.seconds_since_midnight # If it's later today if at > today_offset @next_run = today_begin + at else # Otherwise do it tomorrow @next_run = today_begin + 1.day + at end end def schedule! if @klass.every schedule_every! elsif @klass.daily schedule_daily! end write! end def write! clear! redis.set key, { next_run: @next_run, prev_run: @prev_run, prev_duration: @prev_duration, prev_result: @prev_result, current_owner: @current_owner }.to_json redis.zadd queue_key, @next_run , @klass end def del! clear! @next_run = @prev_run = @prev_result = @prev_duration = @current_owner = nil end def key if @klass.is_per_host Manager.schedule_key(@klass, @manager.hostname) else Manager.schedule_key(@klass) end end def queue_key if @klass.is_per_host Manager.queue_key(@manager.hostname) else Manager.queue_key end end def redis @manager.redis end private def clear! redis.del key redis.zrem queue_key, @klass end end end
true
5a1b658aa066fff809db5bc8b8c02442fa438203
Ruby
trizen/sidef
/scripts/Tests/catalan_numbers_2.sf
UTF-8
134
2.921875
3
[ "Artistic-2.0" ]
permissive
#!/usr/bin/ruby func c(n) is cached { n == 0 ? 1 : (c(n-1) * (4 * n - 2) / (n + 1)) } 15.times { |i| say "#{i}\t#{c(i)}"; }
true
6d707d6c6fcfc11f75d558443811e17976e1cb04
Ruby
katymccloskey/phase-0-tracks
/ruby/hamsters.rb
UTF-8
1,139
3.984375
4
[]
no_license
# ask user hamster's name #name= gets.chomp puts "What is your hamster's name?" name = gets.chomp # ask user hamster's volume level on scale of 1-10 #volume= gets.chomp #volume= true if <=10, false if >10 puts "On a scale of 1-10, how loud is your hamster?" volume_level = gets.chomp volume_level.to_i puts #{volume_level} # ask user hamster's fur color # fur_color= gets.chomp puts "What color is your hamster?" fur_color = gets.chomp #while good_candidate!=true # ask user if hamster is a good candidate for adoption y/n # if input == "y" # good_candidate= true # elsif input =="n" # good_candidate= true # else puts "I didn't understand" #end puts "Is your hamster a good candidate for adoption? y/n" candidate_status = gets.chomp #ask user hamster's estimated age # age=gets.chomp # if age is blank, age=nil puts "What is your hamster's estimated age?" age = gets.chomp if age.empty? age = nil else age = age.to_i end puts "Hamster's name: #{name}. Hamster's volume: #{volume_level}. Hamster's fur color: #{fur_color}. Adoption candidate: #{candidate_status}. Hamster's age: #{age}."
true
fe0acad45b4d34d8e41aa106d78e2f3482d693c8
Ruby
huberb/eulerproblems
/euler39/euler39.rb
UTF-8
410
3.28125
3
[]
no_license
def solutions(p) sol = [] (1..500).each do |i| (1..500).each do |j| c = p - i - j next if c < 0 if c * c == i * i + j * j sol << [i, j, c].sort # puts "#{c}, #{i}, #{j}" end end end sol.uniq end max = [] max_index = 1 1000.times do |i| sol = solutions(i) if sol.length > max.length max = sol max_index = i end end puts max puts max_index
true
cb2797429e58eacfcabdabbbc9dc2c67604f16be
Ruby
MrMicrowaveOven/zadt
/spec/universe_specs/point_spec.rb
UTF-8
926
2.515625
3
[ "MIT" ]
permissive
require_relative "../spec_helper.rb" describe Point do RSpec::Expectations.configuration.on_potential_false_positives = :nothing before :each do @pointA = Point.new([5,4,3]) end it "stores coordinates" do expect(@pointA.coords).to eq([5,4,3]) end it "stores the dimensions of the coordinates" do expect(@pointA.dims).to eq(3) end it "is immutable" do expect{@pointA.coords=[0,0]}.to raise_error expect{@pointA.dims=4}.to raise_error end it "doesn't have default coordinates" do expect{@pointB = Point.new}.to raise_error end describe "#help_methods" do it "has valid help method: #help" do expect {@pointA.help}.to output(/Point/).to_stdout end it "has class help method" do expect {Point.help}.to output(/Point/).to_stdout end it "maintains standard Ruby Point #methods" do expect(@pointA.methods).to include(:coords) end end end
true
6a75ea1d83a665ac5dbeb0e5e6ce23194c1c2da8
Ruby
Jaywinebrenner/Code-Review-Week-11
/spec/models/product_spec.rb
UTF-8
1,409
2.640625
3
[ "MIT" ]
permissive
require 'rails_helper' describe Product do it("titleizes the name of an product") do product = Product.create({name: "rat milk", cost: "20", country_of_origin: "Bulgaria"}) expect(product.name()).to(eq("Rat Milk")) end it { should have_many(:reviews) } it { should validate_presence_of :name } it { should validate_presence_of :cost } it { should validate_presence_of :country_of_origin } it { should have_many :reviews } end describe Product do describe '#name' do it 'returns the product name' do product = Product.new({:name => 'Rat Milk', :cost => 50, :country_of_origin => 'USA', :id => nil}) expect(product.name).to eq 'Rat Milk' end end context '#id' do it 'returns the id of the product before saving product' do product = Product.new({:name => 'Rat Milk', :cost => 50, :country_of_origin => 'USA', :id => nil}) expect(product.id).to eq nil end end it 'returns the id of the product after saving product' do product = Product.new({:name => 'Rat Milk', :cost => 50, :country_of_origin => 'USA', :id => nil}) product.save expect(product.id).to be_an_instance_of Integer end end describe '#save' do it 'saves a product to the database' do product = Product.new({:name => 'Rat Milk', :cost => 50, :country_of_origin => 'USA', :id => nil}) product.save expect(Product.all).to eq [product] end end
true
a5908cd894d1d49e9fbc8881e6435193ac5986c0
Ruby
poorvashelke/aA-homework
/W1D3-recursion/W1D3_Recursion.rb
UTF-8
2,297
3.6875
4
[]
no_license
require 'byebug' def range(start, last) #base case return [] if last <= start [start] + range(start+ 1, last) end def exp_1(base, power) return 1 if power == 0 base * exp_1(base, power - 1) end def exp_2(base, power) puts " base: #{base} | power: #{power}" return 1 if power == 0 return base if power == 1 if power.even? exp_2(base, power / 2) ** 2 else base * (exp_2(base, (power - 1) / 2) ** 2) end end def deep_dup(a) # return [a] if a.length <=1 && !a.is_a?(Array) # if a[0].is_a?(Array) # a[0] + deep_dup[a[0][1..-1]] # else # a[0] # end #newarray = [] a.map do |el| if el.is_a?(Array) deep_dup(el) #newarray << deep_dup(el) else el #newarray << el end end # a.map {|el| el.is_a?(Array) ? deep_dup(el) : el } #newarray end # x = ['a',['b',['c']]] # y = deep_dup(x) # p x.object_id == y.object_id # p x[0].object_id == y[0].object_id # p x[1].object_id == y[1].object_id # p x[1][1].object_id == y[1][1].object_id def fibonacci(num) return 1 if num <= 2 fibonacci(num - 1) + fibonacci(num - 2) end def binary_search(array, target) binary_helper(array, target, 0, array.length) end def binary_helper(array, target, low, high) return nil if array.empty? mid = (low + high) / 2 return mid if array[mid] == target if array[mid] < target binary_helper(array, target, mid + 1, high) else binary_helper(array, target, low, mid - 1) end end def merge_sort(array) return array if array.length <= 1 mid = array.length / 2 left = merge_sort(array[0..mid-1]) right = merge_sort(array[mid..-1]) merge_helper(left, right) end def merge_helper(left, right) merged = [] i = 0 j = 0 # while i < left.length && j < right.length while !left.empty? && !right.empty? if left.first <= right.first merged << left.shift else merged << right.shift end end merged + left + right end #p merge_sort([3,4,1,6,2]) # p merge_helper([1,3],[2,4,8]) def subsets(array) return [[]] if array.length == 0 last = array.pop prev_subs = subsets(array) prev_subs + prev_subs.map {|el| el + [last]} end p subsets([]) # => [[]] p subsets([1]) # => [[], [1]] p subsets([1, 2]) # => [[], [1], [2], [1, 2]] p subsets([1, 2, 3])
true
0e72e4a77185db9c70d9987f4a52158200c55919
Ruby
iwpeifer/pokemon-scraper-web-040317
/lib/pokemon.rb
UTF-8
666
3.40625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Pokemon attr_reader :id, :name, :type, :db, :hp @@all = [] def initialize(id:, name:, type:, db:, hp: nil) @id = id @name = name @type = type @db = db @hp = hp @@all << self end def self.all @@all 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).flatten Pokemon.new(id: new_pokemon[0], name: new_pokemon[1], type: new_pokemon[2], db: db, hp: new_pokemon[3]) end def alter_hp(new_hp, db) db.execute("UPDATE pokemon SET hp = ? WHERE id = ?", new_hp, self.id) end end
true
118a36f1b6f3049165fa894282a233f28e9005dd
Ruby
frmichetti/websocket-tasks-app
/server.rb
UTF-8
2,048
2.921875
3
[]
no_license
require 'em/pure_ruby' require 'em-websocket' require 'rx' require 'rufus-scheduler' EM.run do @messages = [] @scheduler = Rufus::Scheduler.singleton @paused = false @times = 1 @amount = 1 EM::WebSocket.run(host: '0.0.0.0', port: 8080) do |ws| source = Rx::Observable.from_array(@messages) subscription = source.subscribe( lambda {|x| puts 'Next: ' + x.to_s }, lambda {|err| puts 'Error: ' + err.to_s }, lambda { puts 'Completed' }) ws.onopen do |handshake| puts 'WebSocket connection open' # Access properties on the EM::WebSocket::Handshake object, e.g. # path, query_string, origin, headers # Publish message to the client ws.send "Hello Client, you connected to #{handshake.path}" @ws = ws end ws.onclose do puts 'Connection closed' subscription.unsubscribe end ws.onmessage do |msg| puts "Received message: #{msg}" if msg.eql? 'reset' @times = 1 @amount = 1 ws.send "Pong: #{'ok - resetting count'}" elsif msg.eql? 'pause' @paused = !@paused puts 'Paused ? ', @paused ws.send @paused ? "Pong: #{'shhhhhhhhhh'}" : "Pong: #{'counting ...'}" else @messages << msg ws.send "Pong: #{msg}" end end @ws = ws end @scheduler.every '2s' do # @ws.send "scheduler message #{Time.now}" if @ws # if @ws unless @paused if @amount == 1 @ws.send("#{@amount} elefante incomoda muita gente!") else if @amount % 2 == 0 disturb = "" i = 0 for i in i..@times do disturb += "incomodam " end @ws.send("#{@amount} elefantes #{disturb}muito mais!") else @ws.send("#{@amount} elefantes incomodam muita gente!") end end @amount+=1 @times+=1 end end end puts 'Server Started' end
true
a04ce5b78f78c0fa8c7b2d6a6a1211ca3bf83041
Ruby
thatandyrose/vending_machine
/lib/change_calculator.rb
UTF-8
888
3.109375
3
[]
no_license
class ChangeCalculator attr_reader :change def initialize(change_required_in_pence, available_coins) @change_required_in_pence = change_required_in_pence @available_coins = available_coins calculate_change if enough_coins_value? end def calculate_change coins_collected = [] collected_amount = 0 CashMachine.new(@available_coins).order_by_large_coins.each do |coin| collected_amount += coin.amount_in_pence if collected_amount <= @change_required_in_pence coins_collected.push coin else collected_amount -= coin.amount_in_pence end break if collected_amount == @change_required_in_pence end @change = coins_collected if collected_amount == @change_required_in_pence end def enough_coins_value? CashMachine.new(@available_coins).value_in_pence >= @change_required_in_pence end end
true
e263034b01cc89c1cd988804582be70c2df5c352
Ruby
snailoff/knotz
/lib/knotz/template.rb
UTF-8
893
2.59375
3
[ "CC0-1.0" ]
permissive
module Knotz class Template def initialize config Knotz.logger.info "" Knotz.logger.info "=== Template ===" @config = config @tpl = File.read Knotz.mainConfig[:template_path] end def render knotFrom = !@config[:parsed][:knot_from].empty? ? "<p class=\"from\"><span class=\"glyphicon glyphicon-chevron-left\" aria-hidden=\"true\"></span> #{@config[:parsed][:knot_from]}</p>" : "" knotTo = !@config[:parsed][:knot_to].empty? ? "<div class=\"to\"><span class=\"glyphicon glyphicon-chevron-right\" aria-hidden=\"true\"></span>#{@config[:parsed][:knot_to]}</div>" : "" @tpl.sub! '__TITLE__', @config[:parsed][:title] @tpl.sub! '__BODY__', @config[:parsed][:body] @tpl.sub! '__KNOT_FROM__', knotFrom @tpl.sub! '__KNOT_TO__', knotTo @tpl.sub! '__PARSED_DATE__', DateTime.now.strftime("%Y%m%d %H%M%S").gsub(/0/, 'o') @config[:html] = @tpl end end end
true
b15a4d21e269746f9b43f9ba4cbfbf42db9d136e
Ruby
thestrauss3/black-1.1.1
/blackjack/lib/blackjack.rb
UTF-8
343
2.59375
3
[]
no_license
require_relative "card" require_relative "deck" require_relative "dealer" require_relative "player" require_relative "game" require 'pry' deck = Deck.new player = Player.new dealer = Dealer.new # Your code here... dealer.start_game(deck, player) game = Game.new(player, dealer, deck) game.get_action dealer.play(deck) game.announce_winner
true
4b75088b8a5f055e130cf7e96db862db02e5db3e
Ruby
dlee3427/ruby-oo-object-relationships-kickstarter-lab-yale-web-yss-052520
/lib/project.rb
UTF-8
362
3.0625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Project attr_accessor :title def initialize(title) @title = title end def add_backer(backer) ProjectBacker.new(self, backer) end def find_backer ProjectBacker.all.select { |project_backer| project_backer.project == self } end def backers self.find_backer.collect {|project_backer| project_backer.backer } end end
true
82aa4b8de0cf95213602744818997cce409b9b01
Ruby
maneeshacd/job_campaign
/lib/services/fetch_ads.rb
UTF-8
362
2.5625
3
[]
no_license
# frozen_string_literal: true require 'faraday' # fetch ads from external API class FetchAds def initialize(params) @url = params[:url] end def self.call(*args) new(*args).perform end def perform resp = Faraday.get(@url) JSON.parse(resp.body)['ads'] rescue => e warn "Error while fetching ads : #{e.message}" [] end end
true
14998316d856959492c39461c9d048bf252d6191
Ruby
CEsGutierrez/Hashmap-Questions
/lib/permutations.rb
UTF-8
608
3.484375
3
[ "MIT" ]
permissive
def permutations?(string1, string2) if string1.length != string2.length return false elsif string1.length == 0 return true end checking_hash = {} string1.each_char do |letter| if checking_hash.has_key?(letter) checking_hash[letter] += 1 else checking_hash[letter] = 1 end end string2.each_char do |letter| if checking_hash.has_key?(letter) checking_hash[letter] -= 1 else checking_hash[letter] = -1 end end eval = checking_hash.values eval.each do |value| if value != 0 return false end end return true end
true
9be9e3cff76415966ef72206fd0a67825808af45
Ruby
wishcastr/wishcastr
/app/models/wish.rb
UTF-8
482
2.578125
3
[]
no_license
class Wish < ActiveRecord::Base validates :name, presence: true has_many :products_wish has_many :products, through: :products_wish belongs_to :user accepts_nested_attributes_for :products def product_duplicate?(sku, type) self.products.any? { |p| p.sku == sku && p.type == type } end def find_catches catches = [] self.products.each do |product| catches << product if product.current_price <= self.threshold_price end catches end end
true
527d96bd210bbda32fd2f3c4dd9eb6b7af362fcb
Ruby
schacon/git-db
/lib/git-db/objects/tree.rb
UTF-8
845
2.90625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'stringio' class GitDB::Objects::Tree < GitDB::Objects::Base def entries @entries ||= begin entries = [] stream = StringIO.new(data) until stream.eof? perms = read_until(stream, ' ').to_i name = read_until(stream, 0.chr) sha = GitDB.sha1_to_hex(stream.read(20)) entries << GitDB::Objects::Entry.new(sha, perms, name) end entries end end def properties [:entries] end def raw "tree #{data.length}\000#{data}" end def type GitDB::OBJ_TREE end private ###################################################################### def read_until(stream, separator) data = "" char = "" loop do char = stream.read(1) break if char.nil? break if char == separator data << char end data end end
true
1e2fee56152025215b644738bffb42841ccffc83
Ruby
youssefbenlemlih/ruby-practice
/ptp7/examples/symbol.rb
UTF-8
162
2.921875
3
[]
no_license
# Author:: Youssef Benlemlih # Author:: Jonas Krukenberg # Definition of a symbol with interpolation var = "a#{1 + 1}".to_sym var2 = :"a#{2 + 2}" puts var.inspect puts var2.inspect
true
a4f6aa8b427f81b7badd4a8da5d19e1d19ad0bc2
Ruby
GavinThomas1192/rubyOnRailsBasics
/RubyBasics/widgets.rb
UTF-8
914
4.25
4
[]
no_license
def ask(question) # ask a question, that is a parameter print question + " " # implicit retun the value of the question after user types # https://ruby-doc.org/core-2.2.0/String.html link for chomp gets.chomp end def price(quantity) if quantity >= 100 price_per_unit = 8 puts "DISCOUNT!!!!" elsif quantity >= 50 && quantity <= 99 price_per_unit = 9 puts "NO DISCOUNT!!!" else quantity < 50 price_per_unit = 10 end quantity * price_per_unit end puts 'Welcome to the widgets store!' anwser = ask('How many widgets are you ordering?') puts "You entered #{anwser} widgets!" number = anwser.to_i total = price(number) # p anwser.class # above returns "5/n" without chomp, "5" with chomp # We need to convert the anwser to a number to do math because gets always returns a string. puts "Your total price is $#{total} "
true
2e2b815454f45462c8873f793978d208d6f21040
Ruby
Loft47/docusign_dtr
/lib/docusign_dtr/query_param_helper.rb
UTF-8
3,614
2.625
3
[ "MIT" ]
permissive
module DocusignDtr # rubocop:disable Metrics/ClassLength class QueryParamHelper # rubocop:disable Naming/PredicateName QUERY_PARAMS = { search: :search, count: :count, end_date: :endDate, start_position: :startPosition, room_status: :roomStatus, owned_only: :ownedOnly, transaction_side: :transactionSide, is_under_contract: :isUnderContract, region_id: :regionId, office_id: :officeId, has_submitted_task_list: :hasSubmittedTaskList, has_contract_amount: :hasContractAmount, sort: :sort, date_range_type: :dateRangeType, start_date: :startDate }.freeze class << self def call(options) @options = options QUERY_PARAMS.each_with_object({}) do |(key, value), memo| memo[value] = send(key) if @options.key? key end end def search @options[:search].to_s end def count @options[:count].to_i end def start_position @options[:start_position].to_i end def room_status unless acceptable_value?(:room_status, @options[:room_status]) raise DocusignDtr::InvalidParameter.new("value #{@options[:room_status]} is not valid for #{__method__}") end @options[:room_status].to_s end def owned_only to_boolean(@options[:owned_only], __method__) end def transaction_side unless acceptable_value?(:transaction_side, @options[:transaction_side]) raise DocusignDtr::InvalidParameter.new("value #{@options[:transaction_side]} is not valid for #{__method__}") end @options[:transaction_side].to_s end def is_under_contract to_boolean(@options[:is_under_contract], __method__) end def region_id @options[:region_id].to_i end def office_id @options[:office_id].to_i end def has_submitted_task_list to_boolean(@options[:has_submitted_task_list], __method__) end def has_contract_amount to_boolean(@options[:has_contract_amount], __method__) end def sort unless acceptable_value?(:sort, @options[:sort].to_s) raise DocusignDtr::InvalidParameter.new("value #{@options[:sort]} is not valid for #{__method__}") end @options[:sort].to_s end def date_range_type unless acceptable_value?(:date_range_type, @options[:date_range_type]) raise DocusignDtr::InvalidParameter.new( "value #{@options[:date_range_type]} is not valid for #{__method__}" ) end @options[:date_range_type].to_s end def start_date to_date(@options[:start_date].to_s, __method__) end def end_date to_date(@options[:end_date].to_s, __method__) end def to_boolean(value, key) unless value.is_a?(FalseClass) || value.is_a?(TrueClass) raise DocusignDtr::InvalidParameter.new("value #{value} is not valid for #{key}") end value end def to_date(value, key) date = Time.parse(value) date.iso8601 rescue ArgumentError raise DocusignDtr::InvalidParameter.new("#{value} is not a valid #{key}") end def acceptable_value?(key, value) query_acceptable_values[key].include?(value) end def query_acceptable_values DocusignDtr::Models::Room::ACCEPTABLE_VALUES end end end # rubocop:enable Naming/PredicateName # rubocop:enable Metrics/ClassLength end
true
1a91e206d32dc01c8227d673d29d05cfe66c2adc
Ruby
mwlang/tic-tac-toe
/run.rb
UTF-8
1,974
3.9375
4
[]
no_license
require_relative 'game' require_relative 'board' require_relative 'players/player' require_relative 'players/novice' require_relative 'players/skilled' module TicTacToe POSITIONS = 9 WINS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [1,4,8], [2,4,6] ] class Empty attr_reader :position def initialize position @position = position end def to_s " #{position} " end end class Move attr_reader :board attr_reader :turn def initialize board, turn @board = board @turn = turn end end class MoveSequence attr_reader :moves attr_reader :result def initialize board @moves = [] end def turns @moves.map(&:turn) end def play board, position @moves << Move.new(board, board.turn) end def won! @result = :won end def lost! @result = :lost end def draw! @result = :draw end def sequence @moves.map(&:turn) end def <=> other self.sequence <=> other.sequence end def next_turn turns_so_far, open_positions future_turns = Array sequence.slice(turns_so_far.size, POSITIONS) return if future_turns.empty? || (future_turns & open_positions) != future_turns turns = sequence.slice(0, turns_so_far.size) turn = future_turns.first if turns == turns_so_far && open_positions.include?(turn) puts "picking #{@result} turn #{turn} for #{turns_so_far.inspect}" return turn end return nil end end novice_computer = NovicePlayer.new("Novice") skilled_computer = SkilledPlayer.new("Skilled") 300.times do game = Game.new novice_computer, skilled_computer game.play! end novice_computer.print_results skilled_computer.print_results skilled_computer.past_sequences.sort.each do |moves| puts [moves.result, moves.turns].inspect end end
true
5664e184dbb49f606475b55c9445d1ecdf934681
Ruby
kumonopanya/hi
/refe/fsdbm.rb
UTF-8
2,388
2.734375
3
[]
no_license
# # fsdbm.rb # # Copyright (c) 2003 Minero Aoki <aamine@loveruby.net> # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2 or later. # require 'find' class FSDBM # turn on tracing only when used with refe begin require 'refe/traceutils' include ReFe::TraceUtils rescue LoadError def trace( msg ) end end def initialize( basedir ) @basedir = basedir @base_re = %r<\A#{@basedir}/> end def []( *keys ) path = keys_to_path(keys) if FileTest.file?(path) File.open(path) {|f| return f.read } elsif FileTest.directory?(path) return nil unless File.file?(path + '/-') File.open(path + '/-') {|f| return f.read } else nil end end def []=( *args ) val = args.pop setup_dirs args[0..-2] path = keys_to_path(args) begin # $stderr.puts "Warning: exist: #{path}" if File.file?(path) File.open(path, 'w') {|f| f.write val } rescue Errno::EISDIR # $stderr.puts "Warning: exist: #{path}/-" if File.file?(path + '/-') File.open(path + '/-', 'w') {|f| f.write val } end val end private def setup_dirs( dirs ) return if dirs.empty? dir = @basedir.dup while d = dirs.shift dir << '/' << encode(d) begin Dir.mkdir(dir) unless FileTest.directory?(dir) rescue Errno::EEXIST File.rename dir, File.dirname(dir) + "/tmp#{$$}" Dir.mkdir dir File.rename File.dirname(dir) + "/tmp#{$$}", dir + '/-' end end end def keys_to_path( keys ) @basedir + '/' + keys.map {|n| encode(n) }.join('/') end def encode( str ) str.gsub(/[^a-z0-9_]/n) {|ch| if ch == '#' '%23' # sprintf('%%%02x', '#') '#' is ASCII code 35 elsif ch == '.' '%2E' # sprintf('%%%02x', '.') '#' is ASCII code 2E elsif ch == ':' '%3A' # sprintf('%%%02x', ':') '#' is ASCII code 3A else (/[A-Z]/n === ch) ? "-#{ch}" : sprintf('%%%02x', ch[0]) end }.downcase end # def encode( str ) # str.gsub(/[^a-z0-9_]/n) {|ch| # (/[A-Z]/n === ch) ? "-#{ch}" : sprintf('%%%02x', ch[0]) # }.downcase # end def decode( str ) str.gsub(/%[\da-h]{2}|-[a-z]/i) {|s| (s[0] == ?-) ? s[1,1].upcase : s[1,2].hex.chr } end end
true
47ca89da6d291f011ada40d877d6e3b3bd10122c
Ruby
ministryofjustice/smartdown
/lib/smartdown/parser/scenario_sets_interpreter.rb
UTF-8
2,112
2.984375
3
[ "MIT" ]
permissive
require "smartdown/model/scenarios/scenario_set" require "smartdown/model/scenarios/scenario" require "smartdown/model/scenarios/question" module Smartdown module Parser class ScenarioSetsInterpreter def initialize(smartdown_input) @smartdown_input = smartdown_input end def interpret @smartdown_input.scenario_sets.map { |scenario_set| interpret_scenario_set(scenario_set) } end private def interpret_scenario_set(scenario_set) Smartdown::Model::Scenarios::ScenarioSet.new( scenario_set.name, scenario_set.read.split("\n\n").map { |scenario_string| interpret_scenario(scenario_string) } ) end def interpret_scenario(scenario_string) scenario_lines = scenario_string.split("\n") description_lines = scenario_lines.select{ |line| line.start_with?("#") } description = description_lines.map { |description_line| description_line[1..-1].strip }.join(";") scenario_lines = scenario_lines - description_lines outcome = scenario_lines.last question_pages = group_questions_by_page(scenario_lines[0..-2]) question_groups = question_pages.map { |question_page| interpret_question_page(question_page) } Smartdown::Model::Scenarios::Scenario.new( description, question_groups, outcome, ) end def group_questions_by_page(scenario_lines) result = [] scenario_lines.each do |scenario_line| if scenario_line.start_with?("-") result << [scenario_line[1..-1]] else result.last << scenario_line end end result end def interpret_question_page(question_page) question_page.map { |question| interpret_question(question) } end def interpret_question(question_string) name, answer = question_string.split(":").map(&:strip) Smartdown::Model::Scenarios::Question.new( name, answer, ) end end end end
true
3183bd8b8efdb74f38c1f6ead95fc04ca493db74
Ruby
geoiq/annotation_nation
/parrot.rb
UTF-8
850
2.71875
3
[]
no_license
%w{ pp rubygems eventmachine json geoiq-gem}.each {|gem| require gem} dataset_id = ARGV.shift puts "Fetching dataset #{dataset_id}..." dataset = Geoiq::Dataset.load(dataset_id) puts "Fetching features..." features = dataset.features puts "Creating a destination dataset..." target = Geoiq::Dataset.new() target.title = dataset.title first_feature = features.shift id = target.upload_data("#{first_feature.keys.join(',')}\n#{first_feature.values.join(',')}") puts "Saved Dataset #{id}" EventMachine::run { EventMachine.add_periodic_timer(5) { feature = features.shift feature['timestamp'] = feature['timestamp']['time'] feature['geometry'] = {:type => "Point", :coordinates => [feature['longitude'], feature['latitude']]} puts "Adding Feature: #{feature.to_json}" target.add( [feature] ) } } puts "Good day, sir!"
true
26d0746bc875ea82db8acbcfaae93f44ed4eaae1
Ruby
vincentpaca/clickinglabs_ruby
/chapter_01/code/arrays.rb
UTF-8
571
4.78125
5
[]
no_license
#anything goes inside arrays, numbers, strings, symbols. Anything array = [1, "two", :three] #we can use the 'each' method to iterate the values inside an array. array.each do |a| puts a end #this code simply multiplies each number inside the array numbers = [1, 2, 3] #lets initialize the numbers new_number_array = [] #initialize and empty array to store the new numbers to numbers.each { |number| new_number_array << (number * 2) } #notice that instead of each-do, we used a block of code to execute. puts new_number_array #=> shows us the numbers multiplied by 2
true
8ac09003a06a88ea9cb33275c0dda2077fc0733d
Ruby
EricRicketts/IntroductionToProgramming
/RubyBasics/Hashes/exercise_8_test.rb
UTF-8
342
2.78125
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' class Exercise7Test < Minitest::Test def setup @numbers = { high: 100, medium: 50, low: 10 } end def test_select_low_numbers expected = { low: 10 } @numbers.select! { |key, value| value < 25 } assert_equal(expected, @numbers) end end
true
a68fe31b87b0c79724496674817abbb54d14c972
Ruby
SpencerCDixon/SQL-Challenge
/import.rb
UTF-8
3,261
3.5
4
[]
no_license
# Use this file to import the sales information into the # the database. require "pg" require "csv" require "pry" ################ ### DB Conn ### ################ def db_connection begin connection = PG.connect(dbname: "korning") yield(connection) ensure connection.close end end ################ ### Employee ### ################ def parse_employee(employee) split = employee.split(' ') name = split[0] + ' ' + split[1] email = split[2].gsub(/[()]/, '') { name: name, email: email } end def insert_employee(employee) db_connection do |conn| result = conn.exec_params("SELECT id FROM employees WHERE name = $1", [employee[:name]]) if result.to_a.empty? result = conn.exec_params("INSERT INTO employees (name, email) VALUES ($1, $2) RETURNING id", [employee[:name], employee[:email]]) end result.first["id"] end end ################ ### Product ### ################ def insert_product(product) db_connection do |conn| result = conn.exec_params("SELECT id FROM products WHERE name = $1", [product[:name]]) if result.to_a.empty? result = conn.exec_params("INSERT INTO products (name) VALUES ($1) RETURNING id", [product[:name]]) end result.first["id"] end end ################ ### Customer ### ################ def parse_customer(customer) split = customer.split(' ') name = split[0] account_number = split[1].gsub(/[()]/, '') { name: name, account_number: account_number } end def insert_customer(customer) db_connection do |conn| result = conn.exec_params("SELECT id FROM customers WHERE name = $1", [customer[:name]]) if result.to_a.empty? sql = "INSERT INTO customers (name, account_number) VALUES ($1, $2) RETURNING id" result = conn.exec_params(sql, [customer[:name], customer[:account_number]]) end result.first["id"] end end ################ ### Invoice ### ################ def insert_invoice(transaction, foreign_keys) arguments = [ transaction[:sale_date], transaction[:sale_amount], transaction[:units_sold], transaction[:invoice_frequency], foreign_keys[:employee_id], foreign_keys[:product_id], foreign_keys[:customer_id] ] db_connection do |conn| sql = <<-eos INSERT INTO invoices (sale_date, sale_amount, units_sold, frequency, employee_id, product_id, customer_id) VALUES ($1, $2, $3, $4, $5, $6, $7) eos conn.exec_params(sql, arguments) end end ################ ### Seed DB ### ################ print "Loading." CSV.foreach("sales.csv", headers: true, header_converters: :symbol) do |row| print '.' transaction = row.to_hash # Insert normalized employee employee = parse_employee(transaction[:employee]) employee_id = insert_employee(employee) # Insert normalized product product = { name: transaction[:product_name] } product_id = insert_product(product) # Insert normalized customer customer = parse_customer(transaction[:customer_and_account_no]) customer_id = insert_customer(customer) # Create final invoice foreign_keys = { employee_id: employee_id, product_id: product_id, customer_id: customer_id } insert_invoice(transaction, foreign_keys) end puts "Import complete. You now have a normalized database!"
true
4061841df221ff315f5e3f1b5ca3eaaf36758f42
Ruby
mahtabnejad90/link-referral-web-application
/learning/playground-ruby/Intro_to_Numbers.rb
UTF-8
321
3.484375
3
[]
no_license
#following are integers: p 5.class p 0.class p 100.class p -866.class #following are floating point numbers. .next method cannot be used in floating point numbers: p 5.987.class p 2.71.class p -10.11.class #Big numbers are also classed as an integer: p 99999999999999999999999999999999999999999999999999999999999.class
true
f82fe2a5d120decd384f8944910cfb4c5c0407ad
Ruby
red-data-tools/red-chainer
/lib/chainer/functions/connection/convolution_2d.rb
UTF-8
5,488
3.078125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Chainer module Functions module Connection class Convolution2DFunction < Chainer::FunctionNode attr_reader :sy, :sx, :ph, :pw, :cover_all # Two-dimensional convolution function. # This is an implementation of two-dimensional convolution in ConvNets. # It takes three variables: the input image `x`, the filter weight `w`, and the bias vector `b`. # # a notation for dimensionalities. # # - :math:`n` is the batch size. # - :math:`c_I` and :math:`c_O` are the number of the input and output channels, respectively. # - :math:`h_I` and :math:`w_I` are the height and width of the input image, respectively. # - :math:`h_K` and :math:`w_K` are the height and width of the filters, respectively. # - :math:`h_P` and :math:`w_P` are the height and width of the spatial padding size, respectively. # # Then the `Convolution2D` function computes correlations between filters and patches of size :math:`(h_K, w_K)` in `x`. # Patches are extracted at positions shifted by multiples of `stride` from the first position `(-h_P, -w_P)` for each spatial axis. # The right-most (or bottom-most) patches do not run over the padded spatial size. # Let :math:`(s_Y, s_X)` be the stride of filter application. # Then, the output size :math:`(h_O, w_O)` is determined by the following equations: # # math: # h_O &= (h_I + 2h_P - h_K) / s_Y + 1,\\\\ # w_O &= (w_I + 2w_P - w_K) / s_X + 1. # If `cover_all` option is `true`, the filter will cover the all spatial locations. # So, if the last stride of filter does not cover the end of spatial locations, # an addtional stride will be applied to the end part of spatial locations. # In this case, the output size :math:`(h_O, w_O)` is determined by the following equations: # # math: # h_O &= (h_I + 2h_P - h_K + s_Y - 1) / s_Y + 1,\\\\ # w_O &= (w_I + 2w_P - w_K + s_X - 1) / s_X + 1. # If the bias vector is given, then it is added to all spatial locations of the output of convolution. # # @param [Chainer::Variable or Numo::NArray or Cumo::NArray] x Input variable of shape :math:`(n, c_I, h_I, w_I)`. # @param [Chainer::Variable or Numo::NArray or Cumo::NArray] w Weight variable of shape :math:`(c_O, c_I, h_K, w_K)`. # @param [Chainer::Variable or Numo::NArray or Cumo::NArray] b Bias variable of length :math:`c_O` # @param [Int or 2-D Array] stride Stride of filter applications. `stride=s` and `stride=(s, s)` are equivalent. # @param [Int or 2-D Array] pad Spatial padding width for input arrays. # @param [Boolean] cover_all If `true`, all spatial locations are convoluted into some output pixels. # @return [Chainer::Variable] Output variable of shape :math:`(n, c_O, h_O, w_O)`. def self.convolution_2d(x, w, b: nil, stride: 1, pad: 0, cover_all: false) func = self.new(stride: stride, pad: pad, cover_all: cover_all) if b.nil? args = [x, w] else args = [x, w, b] end func.apply(args).first end def initialize(stride: 1, pad: 0, cover_all: false) @sy, @sx = stride.is_a?(::Array) ? stride : [stride, stride] @ph, @pw = pad.is_a?(::Array) ? pad : [pad, pad] @cover_all = cover_all end def forward(inputs) retain_inputs([0, 1]) x = inputs[0] w = inputs[1] b = inputs.size == 3 ? inputs[2] : nil xm = Chainer.get_array_module(x) unless inputs.all? { |i| i.is_a?(xm::NArray) } if b.nil? raise TypeError, "#{xm}::NArray must not be used together w: #{w.class}, x: #{x.class}" else raise TypeError, "#{xm}::NArray must not be used together w: #{w.class}, x: #{x.class}, b: #{b.class}" end end if xm == Cumo and Chainer::CUDA.cudnn_enabled? and !@cover_all return _forward_cudnn(x, w, b) end kh, kw = w.shape[2..-1] col = Chainer::Utils::Conv.im2col(x, kh, kw, @sy, @sx, @ph, @pw, cover_all: @cover_all) y = Chainer::Utils::Math.tensordot(col, w, [[1, 2, 3], [1, 2, 3]]).cast_to(x.class) y = y.transpose(0, 3, 1, 2) # (N, oC, oH, oW) if !b.nil? y += b.reshape(1, b.size, 1, 1) end [y] end private def _forward_cudnn(x, w, b) w = w.cast_to(x.class) b = b.cast_to(x.class) if b [x.conv(w, b: b, stride: [@sy, @sx], pad: [@ph, @pw])] end def backward(indexes, grad_outputs) x, w = get_retained_inputs gy = grad_outputs.first ret = [] if indexes.include?(0) xh, xw = x.shape[2..-1] gx = Deconvolution2DFunction.deconvolution_2d(gy, w, stride: [@sy, @sx], pad: [@ph, @pw], outsize: [xh, xw]) ret << gx end if indexes.include?(1) gw = Chainer::Functions::Connection::Convolution2DGradW.new(self).apply([x, gy]).first ret << gw end if indexes.include?(2) gb = Chainer::Functions::Math::Sum.sum(gy, axis: [0, 2, 3]) ret << gb end ret end end end end end
true
941e3299c1559f7893caeade4aadba5627324639
Ruby
elasticstatic/mdslide
/lib/mdslide/creator.rb
UTF-8
1,543
2.734375
3
[ "MIT" ]
permissive
require 'rubygems' require 'kramdown' require 'erb' require 'kconv' module Mdslide class Creator attr_reader :stylesheets,:scripts,:theme_stylesheets,:theme_scripts attr_accessor :title def initialize @stylesheets = ['base.css'] @scripts = ['jquery.min.js','slides.js'] @theme_scripts = [] @theme_stylesheets = [] @page_template = File.open(File.dirname(__FILE__) + '/../../templates/page.html.erb','r'){|r| erb = ERB.new(r.read)} @slide_template = File.open(File.dirname(__FILE__) + '/../../templates/slide.html.erb','r'){|r| erb = ERB.new(r.read)} @title = 'Slides converted by Mdslide' end def set_theme name theme = Themes[name.to_sym] if theme theme[:css] && @theme_stylesheets.replace(theme[:css]) theme[:js] && @theme_scripts.replace(theme[:js]) end return theme end def get_binding binding end def convert_markdown md body = '' md.toutf8.gsub(/\r\n?/, "\n").split(/^\/\/+$/).map do |slide| if slide =~ /(^|\s)(https?:\/\/[^\s]+)($|\s)/ slide.gsub!(/(^|\s)(https?:\/\/[^\s]+)($|\s)/){"#{$1}[#{$2}](#{$2})#{$3}"} end if slide =~ /(^|\s)@([a-zA-Z0-9_]+)($|\s)/ slide.gsub!(/(^|\s)@([a-zA-Z0-9_]+)($|\s)/, "#{$1}[@#{$2}](https://twitter.com/#{$2})#{$3}") end body += @slide_template.result(self.get_binding{Kramdown::Document.new(slide).to_html}) end @page_template.result(self.get_binding{body}) end end end
true
528b2654cbcfc392426771042db10bab1353e462
Ruby
jli-hashrocket/ruby-algorithms
/node.rb
UTF-8
150
3.109375
3
[]
no_license
class Node attr_reader :val attr_accessor :left, :right def initialize(value=nil) @val = value @left = nil @right = nil end end
true
6ea3049b2e6b271f80707ab7b66a0ec38a28462c
Ruby
MSNCI17/Airfreighter-cargo-app
/app/models/shipment.rb
UTF-8
1,963
2.53125
3
[]
no_license
class Shipment < ActiveRecord::Base UNIT_CBM = 167 SL1_RATES = { 'Australia' => 30, 'Singapore/Taiwan/China' => 25, 'America' => 20, 'Europe' => 15, } SL2_RATES = { 'Australia' => 15, 'Singapore/Taiwan/China' => 12.50, 'America' => 10, 'Europe' => 7.5, } SL3_RATES = { 'Australia' => 15, 'Singapore/Taiwan/China' => 12.50, 'America' => 10, 'Europe' => 7.5, } belongs_to :user before_save :calculate_cbm def calculate_cbm self.tracking_code = SecureRandom.base64(8) len = length/100 wid = width/100 hei = height/100 volume = len*wid*hei total_volume = no_of_products * volume taxable_weight = total_volume * UNIT_CBM if taxable_weight > self.weight self.quotation = calculate_quotation(taxable_weight, self.origin, self.service_level) else self.quotation = calculate_quotation(self.weight, self.origin, self.service_level) end self.cbm = total_volume unless self.status.present? self.status = "pending" end end def calculate_quotation(weight, origin, service_level) quotation = 0 case origin when 'Australia' if service_level === "SL1" quotation = weight * SL1_RATES['Australia'] else quotation = weight * SL2_RATES['Australia'] end when 'Singapore/Taiwan/China' if service_level === "SL1" quotation = weight * SL1_RATES['Singapore/Taiwan/China'] else quotation = weight * SL2_RATES['Singapore/Taiwan/China'] end when 'America' if service_level === "SL1" quotation = weight * SL1_RATES['America'] else quotation = weight * SL2_RATES['America'] end when 'Europe' if service_level === "SL1" quotation = weight * SL1_RATES['Europe'] else quotation = weight * SL2_RATES['Europe'] end end quotation end end
true
569658f5ae02ac3aea2ac6de955e2801c0ddf9cb
Ruby
HISMalawi/eMastercard2Nart
/transformers/encounters/hiv_clinic_consultation.rb
UTF-8
3,120
2.53125
3
[]
no_license
# frozen_string_literal: true module Transformers module Encounters module HivClinicConsultation class << self def transform(patient, visit) observations = [side_effects(patient, visit), on_tb_treatment(patient, visit)] orders = [viral_load(patient, visit)] { encounter_type_id: Nart::Encounters::HIV_CLINIC_CONSULTATION, encounter_datetime: retro_date(visit[:encounter_datetime]), observations: observations.reject(&:nil?), orders: orders.reject(&:nil?) } end def side_effects(patient, visit) side_effects_present = case visit[:'side effects']&.upcase when 'Y' then Nart::Concepts::YES when 'N' then Nart::Concepts::NO end unless side_effects_present patient[:errors] << "Missing side effects on #{visit[:encounter_datetime]}" return nil end { concept_id: Nart::Concepts::ART_SIDE_EFFECTS, obs_datetime: retro_date(visit[:encounter_datetime]), value_coded: Nart::Concepts::UNKNOWN, children: [ { concept_id: Nart::Concepts::UNKNOWN, obs_datetime: retro_date(visit[:encounter_datetime]), value_coded: side_effects_present, comments: 'Migrated from eMastercard 1.0' } ] } end def on_tb_treatment(patient, visit) unless visit[:tb_tatus] # tb_tatus [sic] - that's how it's named in eMastercard] patient[:errors] << "Missing TB status on #{visit[:encounter_datetime]}" return nil end { concept_id: Nart::Concepts::TB_STATUS, obs_datetime: retro_date(visit[:encounter_datetime]), value_coded: case visit[:tb_tatus] when 'Rx' then Nart::Concepts::ON_TB_TREATMENT when 'Y' then Nart::Concepts::TB_SUSPECTED when 'N' then Nart::Concepts::TB_NOT_SUSPECTED when 'C' then Nart::Concepts::TB_CONFIRMED_BUT_NOT_ON_TREATMENT end } end def viral_load(_patient, visit) return nil unless visit[:viral_load_result] { order_type_id: Nart::Orders::LAB, concept_id: Nart::Concepts::VIRAL_LOAD, start_date: retro_date(visit[:encounter_datetime]), accession_number: "#{SITE_PREFIX}-#{next_accession_number}", observation: { concept_id: Nart::Concepts::VIRAL_LOAD, obs_datetime: retro_date(visit[:encounter_datetime]), value_numeric: visit[:viral_load_result], value_text: visit[:viral_load_result_symbol] || '=' } } end def next_accession_number @accession_number ||= 0 @accession_number += 1 end end end end end
true
6f2148be9a4e4b4d1cb2ea6e3479ed9291210542
Ruby
zarapeisker/want_to_know
/main.rb
UTF-8
661
2.515625
3
[]
no_license
require "sinatra" require "sinatra/reloader" require "movies" require "stock_quote" require "image_suckr" get "/" do erb :home end get "/movies" do unless params[:movie].nil? @movie = params[:movie] @result = Movies.find_by_title(@movie) end erb :movies end get "/stocks" do unless params[:symbol].nil? @symbol = params[:symbol] @result = StockQuote::Stock.quote(@symbol) unless @result.nil? @result = @result.last end @result end erb :stocks end get "/images" do unless params[:image].nil? @image = params[:image] suckr = ImageSuckr::GoogleSuckr.new @result = suckr.get_image_url({"q" => @image}) end erb :images end
true
a071bc310b7deeb2342d8212dd28e29ba806023b
Ruby
awslabs/cloud-templates-ruby
/lib/aws/templates/utils/parametrized/constraint/not_nil.rb
UTF-8
1,089
2.59375
3
[ "Apache-2.0" ]
permissive
require 'aws/templates/utils' module Aws module Templates module Utils module Parametrized class Constraint ## # Check if passed value is not nil # # === Example # # class Piece # include Aws::Templates::Utils::Parametrized # # parameter :param1, :constraint => not_nil # end # # i = Piece.new(:param1 => 3) # i.param1 # => 3 # i = Piece.new # i.param1 # throws ParameterValueInvalid class NotNil < self def initialize self.if(Constraint::Condition.any) end def transform_as(_transform, _instance) self end def satisfied_by?(other) other.is_a?(self.class) end protected def check(value, _) raise('required but was not found in input hash') if value.nil? end end end end end end end
true
c476cef40c0599958d757e18394be45d4d175b18
Ruby
nasa/mmt
/lib/cmr/util.rb
UTF-8
1,999
2.90625
3
[ "Apache-2.0" ]
permissive
module Cmr module Util # Times and logs execution of a block def self.time(logger, message, &block) start = Time.now result = yield ensure if message.is_a?(Proc) message.call(Time.now-start, result) else logger.info("#{message} [#{Time.now - start}s]") end end # checks if a token is an URS token def is_urs_token?(token) begin # this block is designed to check if the token is a URS JWT header = Base64.decode64(token.split('.').first) jwt_json = JSON.parse(header) jwt_json['typ'] == 'JWT' && jwt_json['origin'] == 'Earthdata Login' rescue # It is not a JWT token, so it must be a launchpad token return false # Deprecated below, so we can't use waiver anymore in EDL, as it causes # an issue with retrieving a provider token for SOAP requests. # The provider token length is <= 100, so it thinks the token is a # launchpad token but is really a provider token. # # this block allows proper function when URS token is not a JWT (waiver turned off), # because the parse or decode operations will raise an error if URS token isn't a JWT; # non-JWT URS token max length is 100, Launchpad token is much longer # token.length <= 100 end end def authorization_header(token) if is_urs_token?(token) { 'Authorization' => "Bearer #{token}" } else { 'Authorization' => "#{token}" } end end def truncate_token(token) return nil if token.nil? # the URS token should have the client id after the ':', but we don't care about outputting that token_part = token.split(':').first if is_urs_token?(token_part) token_part.truncate([token_part.length / 4, 8].max, omission: '') else # launchpad tokens should not have a client_id token_part.truncate(50, omission: '') end end end end
true
2fddba321433d15832a2ebb597ef624d70309d1b
Ruby
larrysass/reverse-each-word-dumbo-web-062419
/reverse_each_word.rb
UTF-8
153
3.390625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(string) words = string.split(" ") new_array = words.collect do |w| w = w.reverse end return new_array.join(" ") end
true
2b801bb57cfe177cd91750674c1731d7bf87ae78
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/binary-search-tree/427254fc67f841f896fd354dfbd8b801.rb
UTF-8
469
3.46875
3
[]
no_license
class Bst attr_reader :left, :right, :data def initialize(data) @data = data end def insert(new_data) new_data > data ? insert_on(:right, new_data) : insert_on(:left, new_data) end def each(&block) @left.each(&block) if @left yield data @right.each(&block) if @right end private def insert_on(side, new_data) send(side) ? send(side).insert(new_data) : instance_variable_set("@#{side}", self.class.new(new_data)) end end
true
a44008c3f415298dd58edb848ee85ae6ed0cee40
Ruby
John-Lin/kiwi-scraper
/bin/kiwicourse
UTF-8
1,274
2.734375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'digest' require 'thor' require 'fuzzy_match' require 'launchy' require 'coursesdesc' # for production # require '../lib/coursesdesc/courses.rb' # for cmd line testing purposes class KiwiCLI < Thor desc 'search COURSENAME', 'Search a course on ShareCourse' def search(coursename) sc = KiwiScraper::ShareCourse.new result = FuzzyMatch.new(sc.course_name).find(coursename) input_key = Digest::SHA256.digest result id = sc.courses_name_to_id_mapping[input_key] puts "#{id} - #{result}" end desc 'list', 'List all courses on ShareCourse' def list sc = KiwiScraper::ShareCourse.new sc.courses_id_mapping.each do |key, info| puts "#{key} - #{info['name']}" end end desc 'open ID', 'open the course page on browser with course id' def open(id) sc = KiwiScraper::ShareCourse.new course = sc.courses_id_mapping[id] Launchy.open(course['url']) end desc 'info ID', 'Display information about course.' def info(id) sc = KiwiScraper::ShareCourse.new course = sc.courses_id_mapping[id] puts "Course ID: #{course['id']}" puts "Course: #{course['name']}" puts "Course time: #{course['date']}" puts "Course webpage#{course['url']}" end end KiwiCLI.start(ARGV)
true
aae8a37c3397610d356102dc0f721b72da721f2e
Ruby
MsJennyGiraffe/mastermind
/lib/code_checker.rb
UTF-8
813
3.4375
3
[]
no_license
require 'pry' class CodeChecker def initialize guess_result = { "R" => 0, "G" => 0, "B" => 0, "Y" => 0} end def win?(user_guess, color_array) if user_guess == color_array true else false end end def check_guess(user_guess, color_array) check_colors(user_guess, color_array) check_postition(user_guess, color_array) end def check_colors(user_guess, color_array) guess_result = user_guess.group_by do |colors| colors end generated_result = color_array.group_by do |colors| colors end guess_result.each do |key, value| value = value.length end end def check_postition(user_guess, color_array) user_guess.each_with_index.count do |color, index| color == color_array[index] end end binding.pry end
true
0e291471b4e136306063f89413917cdbe76967a9
Ruby
SCPR/scripts
/SCPRv4/segments_by_show.rb
UTF-8
611
2.515625
3
[]
no_license
require "csv" shows = [ "brand-martinez", "take-two" ] low = Time.new(2012, 9, 10, 0, 0, 0) - 1 high = Time.new(2012, 12, 1, 0, 0, 0) - 1 rows = [] shows.each do |show| program = KpccProgram.find_by_slug(show) program.segments.where("published_at > :low and published_at <= :high", low: low, high: high).published.reorder("published_at").each do |segment| rows.push [segment.published_at, segment.to_title, "http://scpr.org#{segment.public_path}", segment.byline] end end CSV.open("/Users/bricker/Desktop/taketwo-segments.csv", "w+") do |csv| rows.each do |row| csv << row end end
true
1693aca8cbce39dc1801b98601cd757a727f6f80
Ruby
jackcusick95/Homework
/W3D5/stack.rb
UTF-8
307
3.75
4
[]
no_license
class Stack def initialize(array) @array = array end def push(el) @array.push(el) end def pop @array.pop end def peek @array.first end end stack = Stack.new([9,2,3,"hello", 5, "Jack"]) p stack.push("yoo") p stack.pop p stack.peek
true
e3ac38a31dab9ea0e02a441a382820f1cb4ce7cd
Ruby
AudTheCodeWitch/sql-library-lab-online-web-ft-071519
/lib/querying.rb
UTF-8
1,718
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def select_books_titles_and_years_in_first_series_order_by_year # I need book.title, book.year from books # where book.series_id = 1 # order by book.year "SELECT title, year FROM books WHERE series_id = 1 ORDER BY year;" end def select_name_and_motto_of_char_with_longest_motto # I need character.name, character.motto from characters # order by character.motto limit 1 "SELECT name, motto FROM characters ORDER BY motto LIMIT 1;" end def select_value_and_count_of_most_prolific_species # I need characters.species, COUNT(*) as count from Characters # group by characters.species "SELECT characters.species, COUNT(*) as count FROM characters GROUP BY characters.species ORDER BY count DESC LIMIT 1;" end def select_name_and_series_subgenres_of_authors # I need the authors.name and subgenres.name from series "SELECT authors.name, subgenres.name FROM series JOIN authors ON series.author_id = authors.id JOIN subgenres ON series.subgenre_id = subgenres.id;" end def select_series_title_with_most_human_characters # I need series.title from character_books # group by COUNT(character.species = human) limit 1 "SELECT series.title FROM series JOIN books ON books.series_id = series.id JOIN character_books on character_books.book_id = books.id JOIN characters on characters.id = character_books.character_id WHERE characters.species = 'human' GROUP BY series.title LIMIT 1;" end def select_character_names_and_number_of_books_they_are_in # I need the characters.names and COUNT(book_id) "SELECT characters.name, COUNT(*) AS book_count FROM characters JOIN character_books ON characters.id = character_books.character_id GROUP BY characters.id ORDER BY book_count DESC, name" end
true
028d239bee07013c04ddde2256407eff36117de2
Ruby
sisiyao/appacademy
/w2d1/chess/game.rb
UTF-8
521
2.53125
3
[]
no_license
require_relative 'board' require_relative 'piece' require_relative 'null_piece' require_relative 'display' require_relative 'sliders' require_relative 'steppers' require 'byebug' #require_relative 'pawns' class Game def initialize @board = Board.new; @display = Display.new(a); end def play b.render until valid_move(cursor_move) cursor_move = @display.get_input end end#class puts a.in_check?(:white) # p a.king_locator(:white) # # p a.king_locator(:black) # p a.in_check?(:white)
true
06f41b5b94f9b16ba4c5908c58f4e17287413dcf
Ruby
uniquehash/hardRuby
/ex37.rb
UTF-8
2,094
3.671875
4
[]
no_license
# ex37: Symbol Review learnrubythehardway.org/book/ex37.html BEGIN, run this block when the script starts, BEGIN { puts "hi" } END, run this block when the script is done, END { puts "hi" } alias, create another name for a function, alias X Y and, logical and, but lower priority than &&, puts "hello" and "Goodbye" begin, start a block, usually for expceptions, begin end break, break out of a loop right now, while true; break; end case, case style conditional, like an if, case X; when Y; else; end def, define a new function, def X(); end defined?, is this class/function/etc. defined already?, defined? Class == "constant" do, create a block that maybe takes a parameter, (0..5).each do |x| puts x end else, else conditional, if X; else; end elsif, else if conditional, if X; elsif Y; else; end end, ends blocks, functions, classes, everything, begin end # many others ensure, run this code whether an exception happens or not, begin ensure end for, for loop syntax. the .each syntax is preferred, for X in Y; end if, if conditional, if X; end in, in part of of for loops, for X in Y; end module, Define a new module, module X; end next, skip to the next element of a .each iterator, (0..5).each{|y| next} not, logical not. but use ! instead, not true == false or, logical or, puts "hello" or "goodbye" redo, rerun a code block exactly the same, (0..5).each{|i| redo if i > 2} rescue, run this code if an exception happens, begin rescure X; end retry, in a rescue clause, says to try the block again, (0..5).each{|i| retry if i > 2| return, returns a value from a function. mostly optional, return X self, The curren object, class, or module, defined? self == "self" super, the parent class of this class, super then, can be used with if optionally, if true then puts "hi" end undef, remove a function definition from a class, undef X unless, inverse of if, unless false then puts "not" end until, inverse of while, execute block as long as false, until false;end when, part of case conditionals, case X; when Y; else; end yield, pause and transfer control to the code block, yield
true
0250475f6f1ceb2d8224da3838bbad72b5d1af72
Ruby
fedeaux/brain_damage_1
/lib/generators/brain_damage/resource/helpers.rb
UTF-8
1,079
2.59375
3
[ "MIT" ]
permissive
module BrainDamage module ResourceHelpers attr_accessor :default_indentation def display_attributes(attributes, options = {}) options = { indentation: default_indentation, join: "\n" }.merge options attributes.map { |attribute| display_attribute(attribute, options[:indentation]) }.join options[:join] end def display_attribute(attribute, indentation = default_indentation) indent_or_die @resource.display_attribute(attribute), indentation end def input_for(attribute, indentation = default_indentation, &block) args = {} if block_given? args[:encapsulated_block] = encapsulate_block_in_view_context(&block) end indent_or_die @resource.input_for(attribute, args), indentation end def indent_or_die(html, indentation = default_indentation) return html.indent indentation if html false end def encapsulate_block_in_view_context(&block) Proc.new do |*args| self.send(:capture, *args, &block) end end end end
true
1e5a972b48e5fb096b5734d927bf5bd0b247a3fc
Ruby
tenfensw/dialogbind
/examples/alarmclock.rb
UTF-8
1,508
3.359375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # Simple reminders app written in Ruby and DialogBind. # # Copyright (C) Tim K 2018-2019. Licensed under MIT License. # This file is a DialogBind example. require 'dialogbind' require 'time' # Get the name of the reminder notification_name = guigets('What should I remind you?') if notification_name == '' || notification_name == nil then # If nil or empty, then exit guierror('You did not specify a valid name for a reminder. Exiting.') exit 1 end # Get the time of the reminder time_alert = guigets('When should I remind you? (type the time in the following format: HH:MM)') if not time_alert.to_s.include? ':' then # If there is no :, then the time was not specified at all guierror('You did not specify a valid time. Exiting.') exit 2 elsif time_alert.to_s.include? ' ' then # If there is a space, then the time was specified in a wrong format guierror('Please specify the date in the following format next time: HH:MM. For example: 22:30. Exiting for now.') exit 3 end # Convert our stringified time to Ruby's Time object time_real = Time.parse(time_alert) if time_real < Time.now then guierror('Late night/early morning appointments are not supported.') exit 3 end # Tell the user that we will remind him about his appointment guinotify('You will be notified about "' + notification_name + '" on ' + time_real.to_s, 'Reminder added') while Time.now < time_real do sleep 0.01 end guinotify('It\'s "' + notification_name + '" time.', 'Important!') exit 0 exit 1
true