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
4e6719d84792aa7185c65443cf69c36f152d6b53
Ruby
nagano564/tv_app
/app/services/movie_api.rb
UTF-8
1,634
2.984375
3
[]
no_license
require 'httparty' require_relative '../models/movie' class MovieAPI def initialize @api_key = ENV['MY_API_ENV'] @api_base = 'https://api.themoviedb.org/3/' end def get_popular_shows params = '&sort_by=popularity.desc' response = http_get('discover/tv', params) response['results'].map { |movie| Movie.new(movie) } end def get_recommended_tv(id) params = '&language=en-US&page=1' recommended = http_get("tv/#{id}/recommendations", params ) recommended['results'].map { |movie| Movie.new(movie) } end def search(query) response = http_get('search/tv', "&language=en-US&query=#{URI.encode(query)}") response['code'] = response.code response end def get_show(id) response = http_get("tv/#{id}", '&language=en-US') # TODO: need to switch to raising an exception instead response['code'] = response.code Movie.new(response) end def get_popular_movies params = '&language=en-US&page=1' response = http_get('movie/popular', params) response['results'].map { |movie| Movie.new(movie) } end def get_movie(id) response = http_get("movie/#{id}", '&language=en-US') # TODO: need to switch to raising an exception instead response['code'] = response.code Movie.new(response) end def get_recommended_movies(id) params = '&language=en-US&page=1' recommended = http_get("movie/#{id}/recommendations", params ) recommended['results'].map { |movie| Movie.new(movie) } end private def http_get(resource, query_params) HTTParty.get(@api_base + resource + "?api_key=#{@api_key}" + query_params) end end
true
c5ef1cf4d94989e476b778c9c3f2963492aca231
Ruby
a-velasquez/collections_practice-online-web-pt-051319
/collections_practice.rb
UTF-8
818
3.84375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(array) array.sort end def sort_array_desc(array) array.sort do |a, b| b <=> a end end def sort_array_char_count(array) array.sort do |a, b| a.length <=> b.length end end def swap_elements(array) array[1], array[2] = array[2], array[1] array end def reverse_array(array) array.reverse end def kesha_maker(array) new_array = [] array.each do |string| string_array = string.split("") string_array.insert(2, "$").delete_at(3) new_array << string_array.join("") end new_array end def find_a(array) array.select do |word| word.start_with?("a") end end def sum_array(array) sum = 0 array.each { |num| sum += num} sum end def add_s(array) array.each_with_index do |word, index| unless index == 1 word << "s" end end end
true
2c01b7d3f7a6cb13e5ee2acc3f6e6b375afb3383
Ruby
anshulverma/bin
/scripts/xdu
UTF-8
2,876
3.171875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'cliqr' require 'filesize' require 'pty' cli = Cliqr.interface do name 'xdu' description <<-EOS A extended disk usage facility. Currently supports: - Get list of top files sorted by size EOS version '0.1.0' shell :disable action :list do description 'print list of top n files sorted by size' option :depth do short 'd' description 'Depth until which you want to search for files.' type :numeric default 0 end option 'min-size' do short 'm' description 'Minimum size of the file you are looking to find (use B for bytes, K for kilobytes, M for megabytes, G for gigabytes and T for terabytes).' default '0B' end option :header do description 'Turn off printing of header line.' type :boolean default true end option :limit do short 'l' description 'Limit output to N lines.' type :numeric default -1 end handler do basedir = File.expand_path(File.dirname(File.dirname(__FILE__))) min_size_bytes = to_bytes(option('min-size').to_s) line_count = limit.value format="%-10s%s\n" if header.value printf(format, "Size", "Name") printf(format, "----", "------------") end cmd = """ find #{Dir.pwd} -maxdepth #{depth} \ -exec stat \ --printf=\"%s %n\\n\" \"{}\" \\; | awk -f #{basedir}/lib/xdu.awk """ execute(cmd) do |line| file = FileInfo.new(line) unless (file.is_dir || file.size < min_size_bytes) printf(format, file.size_str, file.name) line_count -= 1 if line_count > 0 end exit 0 if line_count == 0 end end end end SIZE_CONSTANTS = { 'B' => 1024, 'K' => 1024 * 1024, 'M' => 1024 * 1024 * 1024, 'G' => 1024 * 1024 * 1024 * 1024, 'T' => 1024 * 1024 * 1024 * 1024 * 1024 } def to_size_str(bytes) SIZE_CONSTANTS.each_pair { |e, s| return "#{(bytes.to_f / (s / 1024)).round(2)}#{e}" if bytes < s } end def to_bytes(size) multiplier = SIZE_CONSTANTS[size[-1, 1]] / 1024 size.to_i * multiplier end def execute(cmd, &block) begin PTY.spawn(cmd) do |stdout, stdin, pid| begin stdout.each(&block) rescue Errno::EIO puts "Errno:EIO error" end end rescue PTY::ChildExited puts "The child process exited!" end end class FileInfo include Comparable attr_accessor :size attr_accessor :size_str attr_accessor :name attr_accessor :is_dir def initialize(str) line = str.split @size = line[0].to_i @size_str = to_size_str(size) @name = line[1] @is_dir = File.directory?(name) end def to_s "#{size} #{name}" end def <=>(other) size <=> other.size end end cli.execute(ARGV)
true
c81e65b1eafa641f4a4f0ae2ce75c6da840a9e9c
Ruby
kopz9999/directory-scanner
/lib/directory_scanner/scanner/base.rb
UTF-8
2,191
2.59375
3
[]
no_license
module DirectoryScanner module Scanner class Base attr_accessor :settings, :directory public # @param [String] scanner_path # @param [DirectoryScanner::Directory] directory def initialize(scanner_path, directory) conf = YAML::load_file(scanner_path).deep_symbolize_keys! self.settings = conf[:settings] || {} self.directory = directory end # @param [BusinessLocal] business_local # @return [BusinessLocal] def search_business_local(business_local) mapping_hash = self.mapping build_url = query_url(business_local) result_hash = Wombat.crawl do base_url build_url path "/" mapping_hash.each do |k,v| opt = v.delete(:options) if opt.blank? self.send k, v else self.send k, v, opt.to_sym end end end business_name = result_hash['name'] if !business_name.blank? && business_name == business_local.name result = BusinessLocal.new result_hash result.apply_settings self.settings result else nil end end # @param [BusinessLocal] business_local # @return [BusinessLocal] def query_url(business_local) hash = {} uri = URI.parse(self.base_url) self.parameters.each do |param_hash| properties = Array.wrap(param_hash[:property]) param_key = param_hash[:key] values = [] properties.each { |prop| values << business_local.send(prop) } hash[param_key] = values.join(' ') end if uri.query.nil? uri.query = hash.to_query else uri.query += "&#{hash.to_query}" end uri.to_s end # @return [String] def base_url @base_url||= self.settings[:base_url] end # @return [Array<Hash<Symbol,Object>>] def parameters @parameters||= self.settings[:parameters] end # @return [Hash<Symbol,Object>] def mapping @mapping||= self.settings[:mapping] end end end end
true
f5022c6b341eed76cc36a7a4fa2a31d783828e40
Ruby
muyscully/ruby_challenges
/bobby_class_02.rb
UTF-8
842
3.96875
4
[]
no_license
class Baby def set_name (name) @baby_name = name end def get_name return @baby_name end def set_birthdate (birthdate) @baby_birthdate = birthdate end def get_birthdate return @baby_birthdate end def favorite_songs @songs= [] end def get_favorite_songs return @songs end def add_favorite_song_to_list (song) @songs.push(song) end def make_sound return "ooooooooo" end end baby_bobby = Baby.new baby_bobby.set_name ("Bobby") baby_bobby.set_birthdate ("September 11, 2015") baby_bobby.favorite_songs baby_bobby.add_favorite_song_to_list ("Snuggle Puppy") baby_bobby.add_favorite_song_to_list ("Pout Pout Fish") puts "My name is #{baby_bobby.get_name} and I was born on #{baby_bobby.get_birthdate} and here are my favorite songs: #{baby_bobby.get_favorite_songs}" puts "#{baby_bobby.make_sound}"
true
a7718a357f6bbc1ade6202add84eacb9bdaa2c37
Ruby
georgebrock/greeter
/lib/greeter.rb
UTF-8
432
3.796875
4
[]
no_license
class Greeter class BadNameError < StandardError; end VALID_NAME_REGEXP = /^\w+$/.freeze def self.greeting(name) new(name).greeting end def initialize(name) @name = name end def greeting if valid_name? "Hello #{name}" else raise BadNameError, "#{name.inspect} is not a valid name" end end private attr_reader :name def valid_name? name =~ VALID_NAME_REGEXP end end
true
b6cd081a369c625b7c9989888c774268eaa1f9f6
Ruby
pravosleva/ocrsdk.com
/Ruby/abbyy_ruby_example.rb
UTF-8
5,032
2.59375
3
[ "Apache-2.0" ]
permissive
# OCR SDK Ruby sample # Documentation available on https://ocrsdk.com/documentation/ require "rubygems" # IMPORTANT! # Make sure you have rest-client (see https://github.com/archiloque/rest-client for detaile) gem installed or install it: # gem install rest-client require "rest_client" require "rexml/document" # IMPORTANT! !!! Please provide your application id and password and remove this line !!! # To create an application and obtain a password, # register at https://cloud.ocrsdk.com/Account/Register # More info on getting your application id and password at # https://ocrsdk.com/documentation/faq/#faq3 # CGI.escape is needed to escape whitespaces, slashes and other symbols # that could invalidate the URI if any # Name of application you created APPLICATION_ID = CGI.escape("my_application_id") # Password should be sent to your e-mail after application was created PASSWORD = CGI.escape("my_password") # OCR SDK base url with application id and password # Change to cloud-eu.ocrsdk.com if the application was created in US location BASE_URL = "http://#{APPLICATION_ID}:#{PASSWORD}@cloud-eu.ocrsdk.com" # IMPORTANT! # Specify path to image file you want to recognize FILE_NAME = "/path/to/my/image.jpg" # IMPORTANT! # Specify recognition languages of document. For full list of available languaes see # https://ocrsdk.com/documentation/apireference/processImage/ # Examples: # English # English,German # English,German,Spanish LANGUAGE = "English" # Routine for OCR SDK error output def output_response_error(response) # Parse response xml (see https://ocrsdk.com/documentation/specifications/status-codes) xml_data = REXML::Document.new(response) error_message = xml_data.elements["error/message"] puts "Error: #{error_message.text}" if error_message end # Upload and process the image (see https://ocrsdk.com/documentation/apireference/processImage) puts "Image will be recognized with #{LANGUAGE} language." puts "Uploading file.." begin response = RestClient.post("#{BASE_URL}/processImage?language=#{LANGUAGE}&exportFormat=txt", :upload => { :file => File.new(FILE_NAME, 'rb') }) rescue RestClient::ExceptionWithResponse => e # Show processImage errors output_response_error(e.response) raise else # Get task id from response xml to check task status later xml_data = REXML::Document.new(response) task_element = xml_data.elements["response/task"] task_id = task_element.attributes["id"] # Obtain the task status here so that the loop below is not started # if your application account has not enough credits task_status = task_element.attributes["status"] end # Get task information in a loop until task processing finishes puts "Waiting till image is processed.." while task_status == "InProgress" or task_status == "Queued" do begin # Note: it's recommended that your application waits # at least 2 seconds before making the first getTaskStatus request # and also between such requests for the same task. # Making requests more often will not improve your application performance. # Note: if your application queues several files and waits for them # it's recommended that you use listFinishedTasks instead (which is described # at https://ocrsdk.com/documentation/apireference/listFinishedTasks/). # Wait a bit sleep(5) # Call the getTaskStatus function (see https://ocrsdk.com/documentation/apireference/getTaskStatus) # Note: a logical error in more complex surrounding code can cause # a situation where the code below tries to prepare for getTaskStatus request # while not having a valid task id. Such request would fail anyway. # It's highly recommended that you have an explicit task id validity check # right before preparing a getTaskStatus request. raise "Invalid task id used when preparing getTaskStatus request"\ if ((!(defined? task_id)) || task_id.nil? ||task_id.empty?|| (task_id.include? "00000000-0")) response = RestClient.get("#{BASE_URL}/getTaskStatus?taskid=#{task_id}") rescue RestClient::ExceptionWithResponse => e # Show getTaskStatus errors output_response_error(e.response) raise else # Get the task status from response xml xml_data = REXML::Document.new(response) task_element = xml_data.elements["response/task"] task_status = task_element.attributes["status"] end end # Check if there were errors .. raise "The task hasn't been processed because an error occurred" if task_status == "ProcessingFailed" # .. or you don't have enough credits (see https://ocrsdk.com/documentation/specifications/task-statuses for other statuses) raise "You don't have enough money on your account to process the task" if task_status == "NotEnoughCredits" # Get the result download link download_url = xml_data.elements["response/task"].attributes["resultUrl"] # Download the result puts "Downloading result.." recognized_text = RestClient.get(download_url) # We have the recognized text - output it! puts recognized_text
true
015246d969d588fb7cfd6ce294e5215da4346413
Ruby
i3zhe/sample_rails_app
/spec/models/user_spec.rb
UTF-8
2,738
2.578125
3
[]
no_license
require 'spec_helper' describe User do # pending "add some examples to (or delete) #{__FILE__}" before(:each) do @attr = {:name => "Example User", :email => "[email protected]", :password => "foobar", :password_confirm => "foobar" } end it "should create a new instance given valid attributes" do User.create!(@attr) end it "should require a name" do no_name_user = User.new(@attr.merge(:name => "")) no_name_user.should_not be_valid end it "should reject names that are too long" do long_name = "a" * 51 long_name_user = User.new(@attr.merge(:name => long_name)) long_name_user.should_not be_valid end it "should accept valid emails" do addresses = %w[[email protected] [email protected]] addresses.each do |addr| user = User.new(@attr.merge(:email => addr)) # puts addr user.should be_valid end end it "should reject duplicate email addresses" do User.create!(@attr) duplicate_user = User.new(@attr) duplicate_user.should_not be_valid end it "should require a password" do User.new(@attr.merge(:password => "", :password_confirm => "")).should_not be_valid end it "should require a matching password confirmation" do User.new(@attr.merge(:password_confirm => "123123")).should_not be_valid end it "should reject short passwords" do short = "a" * 5 User.new(@attr.merge(:password => short, :password_confirm => short)).should_not be_valid end describe "password validation" do before (:each) do @user = User.create!(@attr) end it "should have an encrypted password attribute" do @user.should respond_to(:encrypted_password) end end describe "password encryption" do before(:each) do @user = User.create!(@attr) end describe "has_password method" do it "should be true if passwords match" do @user.has_password?(@attr[:password]).should be_true end it "should be false if passwords don't match" do @user.has_password?( "foobar").should be_false end end end describe "user microposts assosiation" do before(:each) do @user = User.create!(@attr) @mp1 = Factory(:micropost, :user => @user, :created_at => 1.day.ago) @mp2 = Factory(:micropost, :user => @user, :created_at => 1.hour.ago) end it "should have a micropost attribute" do @user.should respond_to(:microposts) end it "should have the right microposts in the right orders" do @user.microposts.should == [@mp2, @mp1] end it "should remove associated microposts when user is destroyed" do @user.destroy [@mp2, @mp1].each do |mp| Micropost.find(mp).should be_nil end end end end
true
4b6d1b39b0498c64b1478bfde224599dc70813cc
Ruby
jtmaclachlan/diff_json
/ruby/lib/diff_json/diff.rb
UTF-8
2,680
2.640625
3
[]
no_license
require_rel './diff' module DiffJson def self.diff(old_json, new_json, return_type, diff_opts = {}, output_opts = {}) completed_diff = Diff.new(old_json, new_json, **diff_opts) return case return_type when :raw completed_diff when :patch patch_operations = [] completed_diff.diff.each do |path, operations| operations.each do |op| patch_operations << op if [:add, :replace, :remove].include?(op[:op]) or (op[:op] == :move and path == op[:from]) end end return patch_operations when :html HtmlOutput.new(completed_diff, **output_opts) end end class Diff include JsonMapping include JsonDiffing def initialize(old_json, new_json, **opts) # Set config options @opts = { count_operations: { '/**' => [:add, :replace, :remove, :move, :update] }, ignore_paths: [], path_sort: :sorted, sub_diffs: {}, track_array_moves: true, track_structure_updates: false, replace_primitives_arrays: false, logger: ::Logger.new(STDOUT), log_level: :warn }.merge(opts) # Create map of both JSON objects @old_map = map_json(old_json, '', 0) @new_map = map_json(new_json, '', 0) # Gather the full list of all paths in both JSON objects in a consistent order @all_paths = gather_paths(@old_map.keys, @new_map.keys, @opts[:path_sort] == :sorted) # Generate diff operations list @diff = diff_check(old_json, new_json) # Find difference counts @counts = find_counts(@diff) # Gather sub-diffs @sub_diffs = generate_sub_diffs end def count(count_type = :all) return case count_type when :ignore, :add, :replace, :remove, :move, :update @counts[count_type] || 0 when :total @counts.values.sum else @counts end end def diff return @diff end def json_map(version = :old) return (version == :old ? @old_map : @new_map) end def paths(version = :joint) return case version when :old json_map(:old).keys when :new json_map(:new).keys else @all_paths end end def sub_diffs return @sub_diffs end def log_message(log_level, message) log_levels = [ :debug, :info, :warn, :error ] if (log_levels.index(log_level) || -1) >= (log_levels.index(@opts[:log_level]) || 0) @opts[:logger].method(log_level).call((is_structure?(message) ? JSON.pretty_generate(message) : message)) end end end end
true
dd99fecbe894a7de8b44170ee8dc9f64720b5f3d
Ruby
simi/ruby-sentiments
/jankubr/events/app/services/leave_event.rb
UTF-8
164
2.71875
3
[]
no_license
class LeaveEvent attr_accessor :event def initialize(event) self.event = event end def leave(user) event.users -= [user] event.save end end
true
2a34f26c550a398543bc7081ad85b8a07e2517b8
Ruby
voydz/souyuz
/lib/souyuz/msbuild/project.rb
UTF-8
938
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Souyuz module Msbuild class Project attr_accessor :options def initialize(options) @options = options end def project_name @options[:project_name] end def project_path @options[:project_path] end def ios? is_platform? Souyuz::Platform::IOS end def osx? is_platform? Souyuz::Platform::OSX end def android? is_platform? Souyuz::Platform::ANDROID end def is_platform?(platform) return case platform when Souyuz::Platform::IOS then self.project_name.downcase.include? 'ios' when Souyuz::Platform::OSX then self.project_name.downcase.include? 'mac' when Souyuz::Platform::ANDROID then self.project_name.downcase.include? 'droid' else false end end end end end
true
686e83aa6b4dfee3c08ba688938937c08f10dc97
Ruby
UzmaKR/todo-rspec
/list_spec.rb
UTF-8
1,963
3.03125
3
[]
no_license
require "rspec" require_relative "list" describe List do let(:title) { "todo at the serengeti" } let(:task1) { mock(:task, :description => "walk the lion", :complete => false) } let(:task2) { mock(:task, :descripttion => "go on safari", :complete => true) } let(:task3) { mock(:task, :descripttion => "watch the rhinos", :complete => false) } let(:wrong_argument) { mock(:task) } let(:list) { List.new(title, [task1,task2]) } describe "#initialize" do it "should take 2 arguments" do expect { List.new }.to raise_error(ArgumentError) end it "should have a title" do expect(list.title).to_not be_nil end context "checking task inputs" do it "should have an array of tasks" do expect(list.tasks).to eq([task1,task2]) end it "raises error when input is not an array" do expect { List.new(title, wrong_argument) }.to raise_error(TypeError) end end end describe "#add_task" do it "increases the task list by 1" do expect(list.add_task(task3)).to eq([task1,task2,task3]) end end describe "#complete_task" do it "changes complete from false to true" do task1.should_receive(:complete!) list.complete_task(0) end end describe "#delete_task" do it "delete task from list" do list.tasks.should_receive(:delete_at) list.delete_task(0) end end describe "#completed_tasks" do it "should return 1 completed task from the 2 tasks" do task1.should_receive(:complete?).and_return(false) task2.should_receive(:complete?).and_return(true) expect(list.completed_tasks).to eq([task2]) end end describe "#incomplete_tasks" do it "should return 1 incomplete task from the 2 tasks" do task1.should_receive(:complete?).and_return(false) task2.should_receive(:complete?).and_return(true) expect(list.incomplete_tasks).to eq([task1]) end end end
true
0d968566e06d1994f08cf86db138910043e7cbba
Ruby
CSavi/ruby-music-library-cli-v-000
/lib/concerns/findable.rb
UTF-8
264
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
module Concerns::Findable def find_by_name(name) all.detect {|song| song.name == name} end def find_or_create_by_name(name) find_by_name(name) || create(name) end #helper method def sorted all.sort {|a,b| a.name <=> b.name} end end
true
fb6f759ef64f0adf08fd81097ae49a4b1a5df609
Ruby
JMazzy/assignment_rspec_ruby_tdd
/spec/dice_thrower_spec.rb
UTF-8
1,902
3.140625
3
[]
no_license
require 'dice_thrower' require 'human' require 'computer' describe DiceThrower do let(:dice_thrower) { DiceThrower.new(human_double,computer_double) } let(:human_double) { instance_double("Human") } let(:computer_double) { instance_double("Computer") } describe '#play' do it 'asks the player for their number' do allow(dice_thrower).to receive(:quit?).and_return(true) expect(human_double).to receive(:roll) dice_thrower.play end end describe '#quit?' do it 'returns true when the game has been quit' do dice_thrower.quit! expect(dice_thrower.quit?).to eq(true) end it 'returns false when the game has not been quit' do expect(dice_thrower.quit?).to eq(false) end end describe "#last_player_number" do it "should return the number of the last player's selection" do dice_thrower.last_player_number = 5 expect(dice_thrower.last_player_number).to eq(5) end end describe '#compare_rolls' do it 'adds to the players score if their roll is greater' do expect(human_double).to receive(:score!) allow(human_double).to receive(:last_roll).and_return(38) allow(computer_double).to receive(:last_roll).and_return(18) dice_thrower.compare_rolls end it 'adds to the computers score if their roll is greater' do expect(computer_double).to receive(:score!) allow(human_double).to receive(:last_roll).and_return(8) allow(computer_double).to receive(:last_roll).and_return(18) dice_thrower.compare_rolls end it 'adds half a point if there is a draw' do expect(computer_double).to receive(:half_score!) expect(human_double).to receive(:half_score!) allow(human_double).to receive(:last_roll).and_return(8) allow(computer_double).to receive(:last_roll).and_return(8) dice_thrower.compare_rolls end end end
true
3898266e55c3dce641bd040d801b5ce698e13d4c
Ruby
brad72287/project-euler-solutions
/23 - Non-abundant sums.rb
UTF-8
684
3.65625
4
[]
no_license
def divisors(x) arr=Array.new (1..(x**0.5)).each do |number| arr << number if x%number==0 arr << x/number if x%number==0 unless x / number == x end arr.sort.uniq end def perfect?(x) return false if x != divisors(x).reduce(:+) return true end def abundant?(x) return true if x < divisors(x).reduce(:+) return false end abundant_arr = (12..28123).select {|x| abundant?(x)} hola = [] abundant_arr.each do |y| abundant_arr.each do |z| hola << y+z end end hola = hola.sort.uniq.select {|x| x < 28123} p divisors(18) #final_arr=[] #(1..28123).each do |x| # final_arr << x unless hola[0,x].include?(x) #end #p final_arr.reduce(:+)
true
fdf10b0ecbf66a071a8aac53de37c4f63a3d2fdc
Ruby
brucewu/exmail
/lib/exmail.rb
UTF-8
6,281
2.578125
3
[ "MIT" ]
permissive
require 'exmail/version' require 'restclient' module Exmail class Server attr_accessor :key, :account_name, :access_token #主要用于获取token DOMAIN_TOKEN = 'exmail.qq.com' #主要是调用API DOMAIN_API = 'openapi.exmail.qq.com:12211' def initialize(account_name, key) @account_name, @key=account_name, key end #获取具体的邮箱的信息 #返回数据: {"PartyList"=>{"Count"=>1, "List"=>[{"Value"=>"IT部"}]}, # "OpenType"=>1, "Name"=>"bruce", "Mobile"=>"18612345678", "Status"=>1, "Tel"=>"", # "Position"=>"IT技术", "Gender"=>1, "SlaveList"=>"", "Alias"=>"[email protected]", "ExtId"=>""} def user_get(email) api_path = '/openapi/user/get' result = post_api(api_path, {:alias => email}) result['error'].nil? ? result : {} end #检查邮件帐号是否可用,多个邮箱用数组形式传入 # user_check(['[email protected]','[email protected]']) # 返回 {"Count"=>2, "List"=>[{"Email"=>"[email protected]", "Type"=>1}, {"Email"=>"[email protected]", "Type"=>1}]} # Type说明: -1:帐号名无效 0: 帐号名没被占用 1:主帐号名 2:别名帐号 3:邮件群组帐 号 def user_check(emails) emails=[emails] if emails.class!=Array api_path = '/openapi/user/check' post_api(api_path, 'email='+emails.join('&email=')) end # 创建用户 # slave别名列表 # 1. 如果多个别名,传多个 Slave 2. Slave 上限为 5 个 3. Slave 为邮箱格式 # user_add('[email protected]',{:slave=>"", :position=>"", :partypath=>"北京/IT技术部", :gender=>1, # :password=>"123123", :extid=>1, :mobile=>"", :md5=>0, :tel=>"", :name=>"dede", :opentype=>1}) def user_add(email, user_attr) params = user_attr.merge(:action => 2, :alias => email) result = user_sync(params) if !result.nil? && result['error']=='party_not_found' partypath = user_attr[:partypath]||user_attr['partypath'] party_add_p(partypath) sleep(1) #添加完部门要等一会才会有 user_sync(params) end end # 修改用户,调用方法参考 user_add def user_mod(email, user_attr) params = user_attr.merge(:action => 3, :alias => email) user_sync(params) end # 修改密码 # new_pass为新密码 def change_pass(email, new_pass) user_sync({:alias => email, :password => new_pass, :md5 => 0, :action => 3}) end #删除用户 def user_delete(email) user_sync(:action => 1, :alias => email) end # 同步成员资料 #Action string 1=DEL, 2=ADD, 3=MOD def user_sync(params) api_path = '/openapi/user/sync' post_api(api_path, params) end #创建部门 #多级部门用/分隔,例如: /IT部/IT产品部 def party_add(party_name) party_sync(:action => 2, :dstpath => party_name) end # 自动创建所有层的部门 # 类似于 mkdir_p # party_add_p('aa/bb/cc/dd')将创建四级部门 def party_add_p(party_name) _party_path = '' party_name.split('/').each do |party| next if party.to_s=='' party_add("#{_party_path}/#{party}") unless party_exists?("#{_party_path}/#{party}") _party_path+=('/'+party) end end # 删除部门 # 多级部门用/分隔,例如: /IT部/IT产品部 def party_delete(party_name) party_sync(:action => 1, :dstpath => party_name) end # 修改部门 # party_mod('/北京','/IT部/IT产品部') 将"/IT部/IT产品部"移动到根目录下,并改名为"北京" def party_mod(party_name, parent_party) party_sync(:action => 3, :dstpath => party_name, :srcpath => parent_party) end # 同步部门信息 def party_sync(params) api_path = '/openapi/party/sync' post_api(api_path, params) end #获取子部门 def party_list(partypath=nil) api_path='/openapi/party/list' post_api(api_path, {:partypath => partypath}) end # 是否存在该部门 def party_exists?(party_path) result = party_list(party_path) result['error']!='party_not_found' end # 获取部门下成员 # 获取不存在的部门的子部门返回 {"error"=>"party_not_found", "errcode"=>"1310"} # 正常结果 {"Count"=>1, "List"=>[{"Value"=>"北京1"}]} def partyuser_list(partypath=nil) api_path = '/openapi/partyuser/list' post_api(api_path, {:partypath => partypath}) end # 添加邮件群组 # group-admin==群组管理者(需要使用一个域中不存在的 邮箱地址) # status--群组状态(分为 4 类 all,inner,group, list) def group_add(group_name, group_admin, status, members) api_path='/openapi/group/add' post_api(api_path, {:group_name => group_name, :group_admin => group_admin, :status => status, :members => members}) end # 删除邮件群组 # group_alias--群组管理员(一个域中不存在的邮箱地址) def group_delete(group_alias) api_path='/openapi/group/delete' post_api(api_path, {:group_alias => group_alias}) end # 添加邮件群组成员 def group_add_member(group_alias, members) api_path = '/openapi/group/addmember' post_api(api_path, {:group_alias => group_alias, :members => members}) end # 删除邮件群组成员 def group_del_member(group_alias, members) api_path = '/openapi/group/deletemember' post_api(api_path, {:group_alias => group_alias, :members => members}) end #返回数据: {access_token":"", "token_type":"Bearer", "expires_in":86400, "refresh_token":""} def get_token url_path = '/cgi-bin/token' url = "https://#{DOMAIN_TOKEN}#{url_path}" json_str = RestClient.post(url, {:grant_type => 'client_credentials', :client_id => @account_name, :client_secret => @key}) json = JSON.load(json_str) @access_token = json['access_token'] json end def post_api(api_path, params) get_token if @access_token.nil? url = "http://#{DOMAIN_API}#{api_path}" JSON.load RestClient.post(url, params, {:Authorization => "Bearer #{@access_token}"}) end end end
true
a9ff21355c83465eec2c2a72622a04020bbb2dcd
Ruby
bukshev/PBXProjMaestro
/Sources/Utilities/FileFinder/physical_files_finder.rb
UTF-8
2,602
2.65625
3
[ "MIT" ]
permissive
# frozen_string_literal: true # MIT License # # Copyright (c) 2019 Ivan Bukshev # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class PhysicalFilesFinder # @!attribute [r] root_directory_path # @return [String] attr_reader :root_directory_path # @!attribute [r] targets_with_pathways # @return [Hash] attr_reader :targets_with_pathways # @param [Hash] targets_with_pathways def initialize(root_directory_path, targets_with_pathways) @root_directory_path = root_directory_path @targets_with_pathways = targets_with_pathways end # @param [String] target_name # @param [Array] file_extensions # @return [Array] def file_names(target_name, file_extensions) path = targets_with_pathways[target_name] files_with_extensions = Dir[path + '/**/*'].filter do |p| !File.directory?(p) && file_extensions.include?(File.extname(p)) end files_with_extensions.map { |f| File.basename f } end # @param [Array] file_extensions # @return [Array] def all_file_names(file_extensions) files_with_extensions = Dir[@root_directory_path + '/**/*'].filter do |p| !File.directory?(p) && file_extensions.include?(File.extname(p)) end files_with_extensions.map { |f| File.basename f } end # @param [Array] file_extensions # @return [Array] def targetless_file_names(file_extensions) all = all_file_names file_extensions targets_file_names = targets_with_pathways.reduce([]) do |memo, (t, _)| file_names = file_names(t, file_extensions) memo << file_names end all - targets_file_names end end
true
4ef25bf0bbab4ea9173e657461a6d0811b5c0439
Ruby
RobertoBarros/isometric_ruby
/face.rb
UTF-8
601
3.53125
4
[]
no_license
class Face FACES = %i[north west south east] def initialize(face: :north) @current_index = FACES.index(face) end def current FACES[@current_index] end def rotate_clockwise @current_index = increment_index end def rotate_anticlockwise @current_index = decrement_index end def next FACES[increment_index] end def previus FACES[decrement_index] end private def increment_index @current_index == FACES.count - 1 ? 0 : @current_index + 1 end def decrement_index @current_index == 0 ? FACES.count - 1 : @current_index - 1 end end
true
257615678ccbd42223122b8757472f76cab9a198
Ruby
vladiim/carprice_crawler
/lib/car_price/crawler.rb
UTF-8
370
2.984375
3
[]
no_license
class Crawler attr_reader :agent def initialize @agent = Mechanize.new end def cars(url) agent.get(url). search('.content').search('a'). map { |car| process_car(car) } end private def get(url) agent.get(url) end def process_car(raw_data) car = CarScrapper.new(raw_data) return if car.not_car car.data end end
true
3e7ebec3a181c56f5802b569bc814490727af1bd
Ruby
ggwc82/rps-challenge
/lib/cpu.rb
UTF-8
294
2.921875
3
[]
no_license
class Cpu def initialize @name = "CPU" end def pick ($rules == 'normal')? (@choice = hands[0..2].sample) : (@choice = hands.sample) end attr_reader :choice, :name private attr_reader :hands def hands ["Rock", "Paper", "Scissors", "Spock", "Lizard"] end end
true
3b142438d62d35602fddf591bc27f1da18602c10
Ruby
kelmerp/tic-tac-toe-ruby
/spec/board_spec.rb
UTF-8
1,332
2.96875
3
[]
no_license
require 'spec_helper' describe Board do before :each do @board = Board.new end describe "#get_lines" do context "with a 3 X 3 board" do it "returns an array containing the 8 lines on the board" do expect(@board.get_lines.size).to eq 8 end end context "with a 4 X 4 board" do it "returns an array containing the 10 lines on the board" do @board = Board.new(:board_size => 4) expect(@board.get_lines.size).to eq 10 end end end describe '#full?' do it "when the board is full should respond true" do @board.content = ["x","o","x","x","o","x","o","x","x"] expect(@board.full?).to be true end it "when the board is not full should respond false" do @board.content = ["x","o","x","x","o","x","o","x",""] expect(@board.full?).to be false end end describe '#mark' do it 'marks the board at the given index' do @board.mark(0, "x") expect(@board.content).to eq ["x","","","","","","","",""] end end describe '#empty?' do it 'with an empty board should be true' do expect(@board.empty?).to be true end it 'with a non-empty board should be false' do @board.content = ["x","","","","","","","",""] expect(@board.empty?).to be false end end end
true
f2b89879aa8f571035ddd2db3efbcc3d7eda4204
Ruby
fvthreee/alexandria
/app/query_builders/sorter.rb
UTF-8
273
2.59375
3
[]
no_license
class Sorter def initialize(scope, params) @scope = scope @column = params[:sort] @direction = params[:dir] end def sort return @scope unless @column && @direction @scope.order("#{@column} #{@direction}") end end
true
df44e76059cf92a7b9bc3c817d2c523c7235ba52
Ruby
InfernoPC/ruby_practice
/AOJ/Q001/Q0019.rb
UTF-8
95
3.25
3
[]
no_license
#Factorial class Integer def fact (1..self).reduce(:*) || 1 end end puts gets.to_i.fact
true
bf5a47f50e103d5d87269ace27672c3686a5a08e
Ruby
shanebarringer/code_session
/loops/each_addition.rb
UTF-8
223
3.875
4
[]
no_license
array = [0, 1, 2, 3, 4, 5] array.each do |x| x = x + 2 #add 2 to each item in the array puts "#{x}." end #puts array.inspect #anything we do inside the block only applies to the ITEM variable inside the block
true
b1c32735e781b309fc8ed77c770d80d0028518a6
Ruby
fabioromeo/code_labs
/Documentos/Notebook/Estudos/Coding/Ruby/maior_ou_menor_v3.rb
UTF-8
1,257
3.875
4
[]
no_license
def da_boas_vindas puts "Bem vindo ao jogo de adivinhar" puts "Qual o seu nome?" nome = gets puts "\n\n" puts "Começaremos o jogo " + nome end def sorteia_numero_secreto puts "escolhendo um número secreto entre 0 e 200..." sorteado = 175 #variável local puts "Escolhido. Que tal adivinhar hoje o nosso numero secreto?" sorteado #devolve o numero secreto digitado como saída da função end def pede_um_numero (tentativa, limite_de_tentativas) puts "\n\n\n\n" puts "Tentativa " + tentativa.to_s + " de " + limite_de_tentativas.to_s puts "Entre com o numero" chute = gets puts "Sera que acertou? Voce chutou " + chute chute.to_i end def verifica_se_acertou (numero_secreto, chute) acertou = numero_secreto == chute.to_i if acertou puts "Acertou!" return true end maior = numero_secreto > chute.to_i if maior puts "o número secreto é maior" else puts "o número secreto é menor" end false end da_boas_vindas numero_secreto = sorteia_numero_secreto #pede o numero secreto da funcao e coloca na variavel global limite_de_tentativas = 5 #variável global for tentativa in 1..limite_de_tentativas chute = pede_um_numero tentativa, limite_de_tentativas if verifica_se_acertou numero_secreto, chute break end end
true
b193982fb9cb620f4fadb8b8547ebd4994390990
Ruby
hyperturing/mastermind
/computer.rb
UTF-8
2,875
3.34375
3
[]
no_license
# frozen_string_literal: true require_relative 'board' require_relative 'utils' require 'set' # Citation: ################ # RubyConf 2018: # Beating Mastermind: Winning with the help of Donald Knuth by Adam Forsyth # http://confreaks.tv/videos/rubyconf2018-beating-mastermind-winning-with-the-help-of-donald-knuth # COMPUTER Player class - Mastermind Guessing AI ################################################################## # Constructor Parameters: # name (string), colors (array), code_size (integer) ########## # Accessible Fields: # score: A integer array of the mastermind score of our previous guess ########## # Methods: ### # enter_code: # Returns a 1122 guess or a guess based on our previous guess: # Our guess is a 3-element array of: # The maximum number of possible scores for this guess # A boolean indicating an impossible guess # Our guess itself ####################################################################### class Computer < Player attr_reader :colors, :code_size attr_accessor :score def initialize(name, colors = '', code_size = 4) super(name) @code_size = code_size @guesses = 0 # Create a hash to hold all possible scores to all possible guesses @all_scores = Hash.new { |h, k| h[k] = {} } @all_answers = colors.repeated_permutation(code_size).to_a @all_answers.product(@all_answers).each do |guess, answer| @all_scores[guess][answer] = Utils.calculate_score(guess, @code_size, answer) end @all_answers = @all_answers.to_set @possible_scores = @all_scores.dup @possible_answers = @all_answers.dup end def enter_code # Minimax algorithm ahead # Keep only possible answers that would match our previous answer's score if @guesses.positive? @possible_answers.keep_if do |answer| @all_scores[@guess][answer] == score end guesses = @possible_scores.map do |guess, scores_by_answer| # Keep only possible scores from guesses that include our answer scores_by_answer = scores_by_answer.select do |answer, _score| @possible_answers.include?(answer) end @possible_scores[guess] = scores_by_answer # Group each possible score for our guess # Keep track of how many times it appears # Our worst case for this guess is the largest group score_groups = scores_by_answer.values.group_by(&:itself) possibility_counts = score_groups.values.map(&:length) worst_case_possibility = possibility_counts.max # Is this guess impossible given our possible answers? impossible_guess = @possible_answers.include?(guess) ? 0 : 1 [worst_case_possibility, impossible_guess, guess] end @guess = guesses.min.last else @guess = %w[blue blue orange orange] end @guesses += 1 @guess end end
true
94eeb46aaa42d5f9fa92a12c1bbd27f3e25b5d76
Ruby
tetuyoko/rumbler
/lib/rumbler.rb
UTF-8
558
3.46875
3
[]
no_license
require 'rumbler/shuffle' # shuffle and progress module Rumbler class << self KEYS = [*1..7] DEFAULT_AMOUNT = 1000 def play(amount = DEFAULT_AMOUNT) shuffle = Shuffle.new(amount, score_board) shuffle.rumble finish end def score_board @score_board ||= create_score_board end def create_score_board values = Array.new(KEYS.size, 0) Hash[KEYS.zip(values)] end def finish winner = score_board.max_by { |_k, v| v }.first puts "#{winner} is got a prize!" end end end
true
ea8cb7495b8fe3feaa3889460b7fc04fffa69bb8
Ruby
rkh/minimal-redjs
/spec/embedded_javascript_spec.rb
UTF-8
2,261
2.71875
3
[]
no_license
require File.expand_path('../spec_helper', __FILE__) shared_examples_for "embedded javascript" do before do begin require library rescue LoadError pending "not installed" end @context = context_class.new end describe :evaluate do statements = %w[true false 42 1.5 1+1] statements << "true ? 10 : 20" << "x = 10; x" statements << '"foo"' << "'bar'" statements.each do |statement| it "should convert #{statement}" do @context.evaluate(statement).should == eval(statement) end end it "returns a javascript function's return value" do @context.evaluate("(function() { return 42; })()").should == 42 end it "wraps and javascript objects" do object = @context.evaluate("({foo: 'bar', baz: 'bang', '5': 5, embedded: {badda: 'bing'}})") object.should_not be_nil object['foo'].should == 'bar' object['baz'].should == 'bang' object['5'].should == 5 object['embedded'].tap do |embedded| embedded.should_not be_nil embedded['badda'].should == 'bing' end end it "converts js Date to ruby Time or Date" do value = @context.evaluate "new Date()" (value.is_a? Time or value.is_a? Date).should be_true end it "wraps functions in proc-like objects" do value = @context.evaluate("(function() { return 42 })") value.should respond_to(:call) # FIXME: therubyracer requires an argument to be passed value.call({}).should == 42 end end describe :[] do it "converts ruby Time to js Date" do @context[:value] = Time.now @context.evaluate("value instanceof Date").should be_true end it "allowes setting javascript vars from ruby" do @context[:foo] = 42 @context.evaluate("foo").should == 42 end it "allowes accessing javascript vars" do @context.evaluate "x = 10" @context[:x].should == 10 end it "maps procs to functions" do @context[:foo] = lambda { 42 } @context.evaluate("foo()").should == 42 end it "wraps any ruby objects" do obj = Object.new @context[:foo] = obj @context.evaluate("foo").should == obj end end describe :load do end end
true
a348ed04cb869cb14402fce514d63a6f622a640b
Ruby
schanur/headless-jukebox
/headless-jukebox/command_param_functions.rb
UTF-8
1,217
2.796875
3
[ "MIT" ]
permissive
require 'pp' def video_feed_url_to_video_url(feed_url) run_cmd('curl -s ' + feed_url + ' | grep ".h264.mp4" | cut -f 2 -d "\"" |head -n 1') .gsub("\n", '') end # Scramble list order and return first item that is a media filename. def random_media_file_from_list(filename_list) filename_list.shuffle.each do |filename| puts "Drop " + + ". No media filename" if !is_media_file(filename) return filename end raise "No media file found in list of files." end # Scramble order and filter out all non media filenames. def random_media_file_list_from_list(filename_list) media_file_list_from_list(filename_list).shuffle end def random_media_file_list_in_path(path) raise "Path does not exist:" + path if !File.directory?(path) pp Dir.entries(path) random_media_file_list_from_list(absolute_file_entries(path)) end # Return single random media filename in path. def random_media_file_in_path(path) raise "Path does not exist:" + path if !File.directory?(path) random_media_file_from_list(absolute_file_entries(path)) end def random_media_file_list_from_random_sub_path(random_walk_start_path) raise "Path does not exist:" + path if !File.directory?(path) raise "Not implemented" end
true
5c7b09a199f4de7085316d737ecaf6ac2d5e9599
Ruby
m1kal/exercism_ruby
/bob/bob.rb
UTF-8
500
3.6875
4
[ "MIT" ]
permissive
class Bob ANSWER_QUESTION = 'Sure.' ANSWER_YELL = 'Whoa, chill out!' ANSWER_BOB = 'Fine. Be that way!' ANSWER = 'Whatever.' def self.hey(remark) return ANSWER_YELL if yell?(remark) return ANSWER_QUESTION if question?(remark) return ANSWER_BOB if empty?(remark) ANSWER end def self.question?(remark) remark[-1] == '?' end def self.yell?(remark) remark == remark.upcase && remark =~ /[A-Z]/ end def self.empty?(remark) !(remark =~ /\S/) end end
true
838c41f4b236246917908a8eb88328bbda838f0d
Ruby
Naomi-Dennis/ruby-music-library-cli-v-000
/lib/music_importer.rb
UTF-8
449
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" class MusicImporter attr_accessor :path, :data, :songs def initialize(path) @path = path end def files filenames = Dir[@path + "/*"]; @data = filenames.collect do |filename| filename = filename.slice(@path.size + 1, filename.size) filename end @data end def import self.files() @songs = @data.collect do |datum| Song.create_from_filename(datum) end @songs end end
true
20423d5eaa48a9b1ea4c94bc96640f17eceec423
Ruby
ThomasD972/Ruby_THP
/Ruby_exo/lib/01_pyramids.rb
UTF-8
391
3.453125
3
[]
no_license
puts "Bonjour combien d'étages veux-tu a ta pyramide ? (nombre impair)" print ">" input = gets.chomp.to_i if (input%2==0) puts "J'tai dis impair jeune délinquant" else 1.upto(input/2+1) do |i| spaces = " " * (input-i) dots = "#" * (i*2-1) puts spaces + dots end end 0.upto(input/2+1) do |i| dots = "#" * (input/2-i)*2 spaces = " " * (i + input/2+1) puts spaces + dots end
true
6874a8dfa9fc9e3f95790135430e49ffe140feb4
Ruby
mutle/fu2
/app/models/channel_tag.rb
UTF-8
631
2.515625
3
[ "MIT" ]
permissive
class ChannelTag < ActiveRecord::Base include SiteScope belongs_to :channel belongs_to :post belongs_to :user class << self def all_tags(site) res = PGDB.query(<<-SQL) SELECT DISTINCT(tag) FROM channel_tags WHERE site_id = #{site.id}; SQL res.map(&:first) end def channel_ids(site, tag) res = PGDB.query(<<-SQL) SELECT DISTINCT(channel_id) FROM channel_tags WHERE site_id = #{site.id} AND tag = \'#{PGDB.quote_string(tag)}\'; SQL res.map(&:first).map(&:to_i) end def posts(site, tag) Post.where(site_id: site.id, channel_id: channel_ids(site,tag)) end end end
true
bf142a84e8f2f27e2789dc0ae4ff065039a49013
Ruby
rossta/exercism-exercises
/ruby/prime-factors/prime_factors.rb
UTF-8
279
3.265625
3
[]
no_license
class PrimeFactors def self.for(n) for_results(n, []) end def self.for_results(n, results) return results if n < 2 return results + [n] if n < 4 2.upto(n).each do |div| return for_results(n / div , results + [div]) if n % div == 0 end end end
true
e5dd1bee0af2dcc22e499eba58b47085000e4450
Ruby
self-unit/week2_homework
/guest.rb
UTF-8
360
3.5
4
[]
no_license
class Guest attr_reader :name, :fav_song attr_accessor :wallet def initialize(name, wallet, fav_song) @name = name @wallet = wallet @fav_song = fav_song end def pay_tab(room_tab) @wallet -= room_tab end def room_has_fav_song(room) if room.songs.any? {|song| song.name == @fav_song} return "Whoo!" end end end
true
37c33faa315b790235bca4ffd45ff1f7f2d24b24
Ruby
morotsman/learning-ruby
/validating_inputs/lib/input_validator.rb
UTF-8
1,425
3.46875
3
[]
no_license
class InputValidator private def filled_in?(input) input != nil && input != "" end def minimum_length?(minimum_length, input) input.size >= minimum_length end def length?(length, input) input.size == length end def only_digits?(input) input !~ /\D/ end def only_letters?(input) input[/[a-zA-Z]+/] == input end def validate_first_name(name) if !filled_in?(name) "The first name must be filled in." elsif !minimum_length?(2, name) name + " is not a valid first name. It is too short." end end def validate_last_name(name) if !filled_in?(name) "The last name must be filled in." elsif !minimum_length?(2, name) name + " is not a valid last name. It is too short." end end def validate_zip_code(code) if !filled_in?(code) || !only_digits?(code) "The ZIP code must be numeric." end end def validate_employee_id(employee_id) if !filled_in?(employee_id) || !length?(7, employee_id) || !only_letters?(employee_id[0,2]) || employee_id[2] != "-" || !only_digits?(employee_id[3,4]) "#{employee_id} is not a valid ID" end end public def validate_input(first_name, last_name, zip_code, employee_id) [validate_first_name(first_name), validate_last_name(last_name), validate_zip_code(zip_code), validate_employee_id(employee_id)].select{|i| i != nil} end end
true
bb78955531235db70d0d993d20fdd60c45c89550
Ruby
rlew421/tech_challenges
/ruby/majority_element.rb
UTF-8
1,641
4.34375
4
[]
no_license
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. # # You may assume that the array is non-empty and the majority element always exist in the array. # # Example 1: # # Input: [3,2,3] # Output: 3 # Example 2: # # Input: [2,2,1,1,1,2,2] # Output: 2 # @param {Integer[]} nums # @return {Integer} # could iterate through each number and add each number to a hash # if the number doesn't exist in the hash yet, add it and set the count to 1 # if the number already exists as a key in the hash, increment its value by 1 # at the end, return the key with the largest value # i would have to create an extra data structure (hash) for this. def majority_element(nums) # if there is only one element, just return the element return nums[0] if nums.length == 1 # create a hash to keep track of the count of each element element_counts = Hash.new # iterate through each element in the array nums.each do |num| # if the element exists as a key in the element_counts hash, increment its value by 1 if element_counts[num] element_counts[num] += 1 else # if the element doesn't exist as a key in the element_count hash, add it and set its value equal to 1 element_counts[num] = 1 end end # at the end, find the key value pair whose value is the highest max_key_value_pair = element_counts.max_by{|k,v| v} # the above max_by returns an array of the key and the value, in this case, [. to get just the key, access the element at the index of 0 max_key_value_pair[0] end
true
56c0f1f13ad03176c44b59dfb2e34db0ec805318
Ruby
DerekMaffett/sea-c21-ruby
/lib/class5/exercise3.rb
UTF-8
1,357
4.0625
4
[ "MIT" ]
permissive
#!/usr/bin/env ruby # # 5 points # # Write a program that copies .jpg files from the source directory to the target # directory, appending the file's size to the end of the file name. # # So, assuming there's a source file that's 12,345 bytes long: # # source/photo.jpg # # the program should copy it to the target file: # # target/photo_12345.jpg # # For example, the program should output to the shell: # # $ ruby 2_rename_your_photos.rb target source # => Copied 10 photos from source to target # # If both source and target directories are not given, the program should output # a helpful usage message and immediately exit. For example: # # $ ruby 2_rename_your_photos.rb # Usage: 3_rename_your_photos.rb SOURCE TARGET # # A few methods you might find useful are: # # File.size(file_path) => integer # # Returns the size of file_path. # # File.basename(file_path, suffix) => base_name # # Returns the last component of the name given in file_path. If suffix is # present at the end of file_path, it is removed. # # File.basename('class5/code.rb', '.rb') #=> 'code' # File.basename('class5/code.rb', '.js') #=> 'code.rb' # # FileUtils.copy_file(source_path, target_path) # # Copies the file contents of source_path to target_path, both of which must # be a file path. require 'fileutils' # replace me
true
d68b3828fbd9ef87b9ae37d4e94ed3d90b2d5da5
Ruby
namthanh174/alpha-blog
/Code/ruby_projects/analyzer.rb
UTF-8
2,236
4.375
4
[]
no_license
# puts "Please enter your first name" # first_name = gets.chomp # puts "Please enter your last name" # last_name = gets.chomp # puts "welcome to the analzer programe #{first_name} #{last_name}" # puts "Your first name has #{first_name.length} characters in it" # puts "Your last name has #{last_name.length} characters in it" # full_name = first_name + " " + last_name # puts "Your name in reverse reads #{full_name.reverse}" # puts "Please enter your first number" # first_number = gets.chomp # puts "Please enter your second number" # second_number = gets.chomp # puts "The first number multiple by second number is : #{first_number.to_i * second_number.to_i}" # puts "The first number divided by the the second number is : #{first_number.to_i / second_number.to_i}" # puts "The first number substracted from the second number is : #{second_number.to_i - first_number.to_i}" # puts "The first number mod the second number is : #{first_number.to_i % second_number.to_i}" def multiply(first_number,second_number) first_number.to_f * second_number.to_f end def divide(first_number,second_number) first_number.to_f / second_number.to_f end def substract(first_number,second_number) first_number.to_f - second_number.to_f end def mod(first_number,second_number) first_number.to_f % second_number.to_f end puts "What do you want to do? 1) multiply 2) divide 3) substract 4) find remainder" prompt = gets.chomp puts "Enter in your first number" first_number = gets.chomp puts "Enter in your second number" second_number = gets.chomp if prompt == '1' puts "You have chosen to multiply #{first_number} with #{second_number}" result = multiply(first_number,second_number) elsif prompt == '2' puts "You have chosen to divide" result = divide(first_number,second_number) elsif prompt == '3' puts "You have chosen to substract" result = substract(first_number,second_number) elsif prompt == '4' puts "You have chosen to find the remainder" result = mod(first_number,second_number) else puts "You have made and invalid choice" end puts "The result is #{result}" # puts "Please enter your first number" # first_number = gets.chomp # puts "Please enter your second number" # second_number = gets.chomp
true
439dfc198a0c87f7470bf6ad4a9f79f2d94a21d2
Ruby
ragueroanna/loops_for_poops
/poo.rb
UTF-8
212
2.984375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby def can_i_poo? puts 'type a "p" for poo' line = $stdin.readline if line.strip == 'p' puts '💩' true else puts "\u{1f639}" false end end loop until can_i_poo?
true
f6398ae1ca0a76169e35cd31400cc2d92aafd88f
Ruby
evanrushton/stickyUnit
/db/migrate/20140709073101_load.rb
UTF-8
13,905
2.6875
3
[]
no_license
class Load < ActiveRecord::Migration def up # Create initial users. down cr = User.new(:login => "Crushton") cr.save(:validate => false) # Create initial units. unit1 = Unit.new(:name => "What is Fair? (Measures of central tendency)
") unit1.user = cr unit1.save(:validate => false) # Create initial goals. goal1 = Goal.new(:level => "4", :goal => "DATA ANALYSIS & PROBABILITY 5. Interpret, organize, and concepts of probability") goal1.unit = unit1 goal1.save(:validate => false) goal2 = Goal.new(:level => "3", :goal => "b. Predict patterns or generalize trends based on given data.") goal2.unit = unit1 goal2.save(:validate => false) goal3 = Goal.new(:level => "3", :goal => "c. Explain the role of fair and bias in sampling and its effect on data.") goal3.unit = unit1 goal3.save(:validate => false) goal4 = Goal.new(:level => "3", :goal => "f. Construct and use a variety of methods (i.e., organized lists, tree-diagrams, Fundamental Counting Principle) to solve real-world problems.") goal4.unit = unit1 goal4.save(:validate => false) goal5 = Goal.new(:level => "3", :goal => "g. Collect data. Select and justify the most appropriate representations to organize, record and communicate data.") goal5.unit = unit1 goal5.save(:validate => false) goal6 = Goal.new(:level => "3", :goal => "h. Use a given mean, mode and/or median of a set of data to construct a data set and determine missing values from a data set.") goal6.unit = unit1 goal6.save(:validate => false) goal7 = Goal.new(:level => "3", :goal => "Mathematics can give us tools that we can apply to complex problems that involve numbers, but it rarely answers all our questions or addresses all the needs in a situation.") goal7.unit = unit1 goal7.save(:validate => false) goal8 = Goal.new(:level => "3", :goal => "Sometimes different mathematical approaches yield different solutions. Different measures of central tendency yield different solutions – the choice depends upon the context.") goal8.unit = unit1 goal8.save(:validate => false) goal9 = Goal.new(:level => "3", :goal => "Not all solutions to real-world uses of mathematics are perfect or beyond criticism. Often, we must defend our solutions using both mathematical and non-mathematical evidence and reasoning. Questions about fairness ultimately involve decisions about values, so math is helpful only up to a point.") goal9.unit = unit1 goal9.save(:validate => false) goal10 = Goal.new(:level => "2", :goal => "What is the best solution to a complex problem? How can I know? How can I best defend and communicate my thinking?") goal10.unit = unit1 goal10.save(:validate => false) goal11 = Goal.new(:level => "2", :goal => "What is fair? How can mathematics help us answer that question? What are the limitations of mathematics in helping us answer that question? What is the fairest grading system?") goal11.unit = unit1 goal11.save(:validate => false) goal12 = Goal.new(:level => "2", :goal => "How can we best use mathematical information to draw non-mathematical conclusions?") goal12.unit = unit1 goal12.save(:validate => false) goal13 = Goal.new(:level => "2", :goal => "How can I best transform this data into useful information? When should mean, median, or mode be used? What are the pros and cons of each measure? In whose interest is it to use which measure?") goal13.unit = unit1 goal13.save(:validate => false) goal14 = Goal.new(:level => "1", :goal => "Definitions of mean, median, and mode; range; variation; bias; trend") goal14.unit = unit1 goal14.save(:validate => false) goal15 = Goal.new(:level => "1", :goal => "Calculate mean, median, and mode") goal15.unit = unit1 goal15.save(:validate => false) goal16 = Goal.new(:level => "1", :goal => "Make and defend decisions on when to use mean, median, and mode") goal16.unit = unit1 goal16.save(:validate => false) # Create initial evidence evidence1 = Evidence.new(:depth => "1", :evidence => "Variety of examples for students to calculate mean, median, and mode") evidence1.unit = unit1 evidence1.save(:validate => false) goal15.evidence = evidence1 goal15.save(:validate => false) evidence2 = Evidence.new(:depth => "1", :evidence => "Multiple scenarios asking for a written defense of, Which is a better measure of center in this case: mean, median or mode?") evidence2.unit = unit1 evidence2.save(:validate => false) goal16.evidence = evidence2 goal16.save(:validate => false) evidence3 = Evidence.new(:depth => "1", :evidence => "Provide definition of mean, median, and mode; range; variation; bias; trend") evidence3.unit = unit1 evidence3.save(:validate => false) goal14.evidence = evidence3 goal14.save(:validate => false) evidence4 = Evidence.new(:depth => "2", :evidence => "Defend a solution to, What is fair? And how might math help?") evidence4.unit = unit1 evidence4.save(:validate => false) goal11.evidence = evidence4 goal11.save(:validate => false) evidence5 = Evidence.new(:depth => "2", :evidence => "Defend a solution to determine which class won a race in which everyone ran, and the data is ambiguous as to meaning.") evidence5.unit = unit1 evidence5.save(:validate => false) goal13.evidence = evidence5 goal10.evidence = evidence5 goal8.evidence = evidence5 goal3.evidence = evidence5 goal13.save(:validate => false) goal10.save(:validate => false) goal8.save(:validate => false) goal3.save(:validate => false) evidence6 = Evidence.new(:depth => "2", :evidence => "Investigate several situations and draw conclusions for, How important is range (variation) and trend when reaching a solution? Should they matter in assigning a final result? Should you be rewarded or penalized for consistency/inconsistency and downward/upward trend?") evidence6.unit = unit1 evidence6.save(:validate => false) goal7.evidence = evidence6 goal2.evidence = evidence6 goal7.save(:validate => false) goal2.save(:validate => false) evidence7 = Evidence.new(:depth => "2", :evidence => "Several example problems providing mean, median, and/or mode with missing values to be discovered.") evidence7.unit = unit1 evidence7.save(:validate => false) goal6.evidence = evidence7 goal6.save(:validate => false) evidence8 = Evidence.new(:depth => "2", :evidence => "Come up with a situation where, depending upon your point of view, one group would want to use one measure while the other would not want that one at all.") evidence8.unit = unit1 evidence8.save(:validate => false) goal9.evidence = evidence8 goal9.save(:validate => false) evidence9 = Evidence.new(:depth => "2", :evidence => "Measure the three types of central tendency for a large set of a data and argue in defense of a best answer for, When should we use mean, median, or mode?") evidence9.unit = unit1 evidence9.save(:validate => false) goal12.evidence = evidence9 goal12.save(:validate => false) evidence10 = Evidence.new(:depth => "2", :evidence => "Based on our study of various measures of central tendency, and the pros and cons of using “averages” in various situations, propose and defend a “fair” system to find the center of a known dataset.") evidence10.unit = unit1 evidence10.save(:validate => false) goal1.evidence = evidence10 goal4.evidence = evidence10 goal5.evidence = evidence10 goal1.save(:validate => false) goal4.save(:validate => false) goal5.save(:validate => false) # Create initial assessments assessment1 = Assessment.new(:rigor => "1", :assessment => "Quiz: calculate mean, median, and mode for 24 different exercises") assessment1.unit = unit1 assessment1.save(:validate => false) evidence1.assessments << assessment1 assessment2 = Assessment.new(:rigor => "3", :assessment => "Expert level task: Who won this year’s 7th grade race around the campus?") assessment2.unit = unit1 assessment2.save(:validate => false) evidence5.assessments << assessment2 assessment3 = Assessment.new(:rigor => "1", :assessment => "Homework and class-work problems (initial answers not graded; used for feedback to student and adjustment of learning plan)") assessment3.unit = unit1 assessment3.save(:validate => false) evidence3.assessments << assessment3 evidence7.assessments << assessment3 assessment4 = Assessment.new(:rigor => "2", :assessment => "Written defense of solution to group activities") assessment4.unit = unit1 assessment4.save(:validate => false) evidence2.assessments << assessment4 evidence4.assessments << assessment4 evidence6.assessments << assessment4 evidence8.assessments << assessment4 evidence9.assessments << assessment4 assessment5 = Assessment.new(:rigor => "3", :assessment => "How should I grade you? Based on our study in this unit of various measures of central tendency, and the pros and cons of using “averages” (calculating the mean and other such measures) in various situations, propose and defend a “fair” grading system for use in this school. How should everyone’s grade in classes be calculated? Why is your system fairer than the current system (or: why is the current system the fairest?) Rubrics: Problem Solving, Presentation Quality") assessment5.unit = unit1 assessment5.save(:validate => false) evidence10.assessments << assessment5 # Create initial activities activity1 = Activity.new(:activity => "Small Groups: Who Won the Race? (Question a.) Guidance from teacher, including:<ul> <li>suggestions for ways to solve the problem prompt to see if other solutions might be possible</li> <li>prompt to graph the data to see if the model it yields is helpful</li></ul>") activity1.assessment = assessment2 activity1.save(:validate => false) activity2 = Activity.new(:activity => "Class, small group: Brief discussion on Question a: What is fair? And how might math help? Ask students to draw some tentative conclusions that will be explored and ‘tested’ later in the unit") activity2.assessment = assessment4 activity2.save(:validate => false) activity3 = Activity.new(:activity => "Class, small group: Introduction of performance task, with reminder on grading policy in this class. Do a KWL – what do we know, what questions do we have: get everyone to share different examples of grading policies they have lived under or heard of from siblings and parents") activity3.assessment = assessment4 activity3.save(:validate => false) activity4 = Activity.new(:activity => "Class: Direct instruction in mean, median, mode, with practice. Textbook and other exercises on mean, median, and mode") activity4.assessment = assessment3 activity4.save(:validate => false) activity5 = Activity.new(:activity => "Class: Discuss further on the question of fairness – “What do we mean when we say that the rules of a game of chance are “not fair”? What role does math play in our judgment?") activity5.assessment = assessment4 activity5.save(:validate => false) activity6 = Activity.new(:activity => "Think, pair, share: Student constructs independent defense to a problem like the hook problem. Pairs discuss, offering feedback to each other on the quality of the other’s solution and defense. Whole class discusses examples, and tries to answer the Unit Questions i. and ii.") activity6.assessment = assessment4 activity6.save(:validate => false) activity7 = Activity.new(:activity => "Small group task: come up with a situation where, depending upon your point of view, one group would want to use one measure while the other would not want that one at all. (e.g. employee wants a raise to the median salary, while employer wants to offer the mean salary). Each group will have to explain their sample argument (and a solution to the argument, if there is one) to the whole class.") activity7.assessment = assessment4 activity7.save(:validate => false) activity8 = Activity.new(:activity => "Class/small group. Scenario: Because of your expertise in math, you have been hired as a consultant by [choose one: NFL, Southern Conference, Rock Hall of Fame, Olympic Skating Committee] to recommend a more fair way of assigning scores. Propose and defend your idea to the Executive Committee... How important is range (variation) and trend when reaching a solution?") activity8.assessment = assessment4 activity8.save(:validate => false) activity9 = Activity.new(:activity => "Class: Return to the original problem of the unit: Now who do you think won the race? Using what has been learned, students re-evaluate the problem and their solutions to it.") activity9.assessment = assessment1 activity9.save(:validate => false) activity10 = Activity.new(:activity => "Individual: Final Task/Question Q. iv: So, given all we have learned, what is the fairest grading system?") activity10.assessment = assessment5 activity10.save(:validate => false) activity11 = Activity.new(:activity => "Think, pair share: Question Q. a. Students first write an answer in their journal, discuss their answers in pairs, and share answers in class. Any remaining questions are filed away for another unit on the same issues.") activity11.assessment = assessment4 activity11.save(:validate => false) end def down Goal.delete_all Unit.delete_all User.delete_all end end
true
a1437940c0d80b9730ea3cebb09b167fb1e20925
Ruby
jasonlhoward/ls-basics
/user_input/e5.rb
UTF-8
214
3.21875
3
[]
no_license
loop do print 'How many lines do you want? Enter an integer >= 3: ' answer = gets.chomp.to_i next puts 'That\'s not enough lines.' if answer < 3 break answer.times { puts 'Launch School is the best!' } end
true
7ef2a98822e0fdbce76116aa1cb132b0d446a5b1
Ruby
pwojcikpl/ArtGallery
/app/models/image.rb
UTF-8
3,078
2.625
3
[]
no_license
class Image < ActiveRecord::Base def file= (f) @file = f end def validate # Empty 'name' field is not allowed errors.add_on_empty 'name' # @file should contain file uploaded by HTTP # it is either StringIO object (if file was smaller than 10Kb) # or Tempfile (otherwise) if not (@file.kind_of? StringIO or @file.kind_of? Tempfile) errors.add_to_base("No file file selected") return end # We can't use StringIO data to call external programs # So, if object is StringIO -- we have to create Tempfile # Unfortunatly, in Rails it is impossible to force all uploads to be Tempfiles if @file.kind_of? StringIO # Yes, if @file is StringIO, create new Tempfile and copy everything to it @real_file = Tempfile.new("AEGALLERY") while not @file.eof? @real_file.write @file.read end else # Most uploads will be Tempfiles @real_file = @file end # Here is a call to ImageMagick tool identity # it prints to standard output # type, width and height of images # (this is specified by -format %m,%w,%h) identify = `#{IMAGE_MAGICK_PATH}/identify -format %m,%w,%h #{@real_file.path} 2>&1` # Now identity is a string like "JPEG,640,480" # We split this string to array @jpeg_info = identify.split(',', 3) # convert width and height to integer and assign it to object fields self.width = @jpeg_info[1].to_i self.height = @jpeg_info[2].to_i # Finally, cheking if everything was fine with this image # if file was not valid JPEG -- something will fail here if @jpeg_info == nil or @jpeg_info[0] != 'JPEG' or self.width <= 0 or self.height <= 0 errors.add_to_base("Wrong image format (use only JPEG) or broken data") return end end def after_save dest_photo = "#{RAILS_ROOT}/public/photo/f/#{self.id}.jpeg" dest_photo_t = "#{RAILS_ROOT}/public/photo/t/#{self.id}.jpeg" # Copying Tempfile to our storage, # which is a subdirectory 'photo/f' in 'public' # directory of Rails project FileUtils.cp(@real_file.path, dest_photo); # Setting right permissions FileUtils.chmod 0644, dest_photo # call image magick 'convert' utility to # generate 200x200 thumbnail `#{IMAGE_MAGICK_PATH}/convert -size 200x200 #{dest_photo} \ -resize 200x200 -quality 90 +profile \"*\" #{dest_photo_t} 2>&1` end def after_destroy # Deleting image files FileUtils.safe_unlink("#{RAILS_ROOT}/public/photo/f/#{self.id}.jpeg") FileUtils.safe_unlink("#{RAILS_ROOT}/public/photo/t/#{self.id}.jpeg") end def img_tag "<img src='/photo/f/#{self.id}.jpeg' width='#{self.width}' height='#{self.height}' alt='#{self.name}'>" end def img_tag_thumbnail kf = 200.0 / ( width > height ? width : height ) tw = (width.to_f * kf).to_i th = (height.to_f * kf).to_i "<img src='/photo/t/#{self.id}.jpeg' width='#{tw}' height='#{th}' alt='#{self.name}'>" end end
true
8552839d857272ab3621ff6fc4e137c979579bdd
Ruby
docljn/i_need_a_budget_in_ruby_sinatra
/models/vendor.rb
UTF-8
1,555
2.984375
3
[]
no_license
# vendor.rb require_relative('../db/sql_runner.rb') class Vendor attr_reader :id attr_accessor :name def initialize(options) @id = options['id'].to_i if options['id'] @name = options['name'] end # delete def self.delete_all() sql = "DELETE FROM vendors;" sql_result = SqlRunner.run(sql) end # delete def self.delete_one(id) sql = "DELETE FROM vendors WHERE id = $1;" values = [id] sql_result = SqlRunner.run(sql, values) end # read def self.select_all() sql = "SELECT * FROM vendors;" sql_result = SqlRunner.run(sql) transactions_array = sql_result.map {|hash| Vendor.new(hash)} end # read def self.select_one(id) sql = "SELECT * FROM vendors where id = $1;" values = [id] sql_result = SqlRunner.run(sql, values) vendor = Vendor.new(sql_result[0]) end # create & update def save() if @id update() else insert() end end def transactions() sql = "SELECT * FROM transactions WHERE vendor_id = $1;" values = [@id] sql_result = SqlRunner.run(sql, values) transactions = sql_result.map {|hash| Transaction.new(hash)} end private def insert() # create sql = "INSERT INTO vendors (name) VALUES ($1) RETURNING id;" values = [@name] sql_result = SqlRunner.run(sql, values) @id = sql_result[0]['id'] end def update() # update sql = "UPDATE vendors SET (name) = ($1) WHERE id = $2;" values = [@name, @id] sql_result = SqlRunner.run(sql, values) end end # vendor.rb
true
55761dcce493f65b3f474be0bd214cb76427786e
Ruby
nirmalsi/trainings
/Tranings/ruby_program/module_staff.rb
UTF-8
188
3.21875
3
[]
no_license
module Staff def swim "i am swimming!" end end class Animal end class Dog < Animal include Staff end class Cat < Dog end dog = Dog.new cat = Cat.new puts dog.swim puts cat.swim
true
81dca2419a876d169d287f7e94377395468ea535
Ruby
amandeep1420/ruby-basics-exercises
/9_conditionals/9_cool_numbers.rb
UTF-8
142
3.875
4
[]
no_license
# my answer: number = rand(10) if number == 5 puts '5 is a cool number!' else puts 'Other numbers are cool too!' end # 100% correct.
true
7d98b78f3f440a4c02000c45542b0e1565cfb6af
Ruby
kashfiarahman89688/midterm_ror
/0b.rb
UTF-8
506
4.625
5
[]
no_license
#0b #b) The second method you have to fill in is sort_array_plus_one. This method takes in an array of integers, sorts it, #then increments every element by 1, and returns it. It does not matter if this method is destructive or not. def sort_array_plus_one(array) array.sort! {|x, y| x <=> y} puts "Input array :" print array print "\n" puts "Result :" for i in array do print i.to_i+1 print ", " end end data = [3, 5, 4, 7, 8, 6, 2, 9, 2] sort_array_plus_one(data)
true
44746b98058128db4f2150921e66bde6ae20223a
Ruby
juliemiller/poker
/spec/card_spec.rb
UTF-8
377
2.734375
3
[]
no_license
require 'rspec' require 'card.rb' describe Card do let(:card) { Card.new( :king, :spades ) } it "knows its suit" do expect( card.suit ).to eq( :spades ) end it "has a type" do expect( card.type ).to eq( :king ) end it "has a color" do expect( card.color ).to eq( :black ) end it "has a value" do expect( card.value ).to eq( 13 ) end end
true
6b9806f1d2c9482836a94688450934c385a77944
Ruby
tfpractice/tfp_metaprogramming
/lib/tfp_metaprogramming/callable/procs/arity.rb
UTF-8
405
2.640625
3
[ "MIT" ]
permissive
module TfpMetaprogramming module Callable module Procs module Arity def arity_proc proc {|x,y| [x, y] } end def arity_lambda ->(x,y) { [x, y] } end def call_for_arity(&callable) # begin callable.call(1) # rescue ArgumentError => e # e # end end end end end end
true
5d5eb0cd8382bf5396858e16f41f1d9dbcb0fcbe
Ruby
blabash/aA_homework
/simon/lib/simon.rb
UTF-8
1,132
3.5625
4
[]
no_license
class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @sequence_length = 1 @game_over = false @seq = [] self.play end def play self.take_turn until @game_over == true self.take_turn end self.game_over_message self.reset_game end def take_turn p self.show_sequence self.require_sequence if @game_over == false self.round_success_message @sequence_length += 1 end end def show_sequence self.add_random_color end def require_sequence puts "Repeat back sequence, one color at a time" @seq.each do |color| input = gets.chomp @game_over = true if input.downcase != color end end def add_random_color @seq << COLORS[0] @seq << COLORS[rand(0...COLORS.length)] end def round_success_message "good job!" end def game_over_message "game over, too bad." end def reset_game @sequence_length = 1 @game_over = false @seq = [] end end simon = Simon.new
true
edf399479d075f682456003d0496d9148f7638fb
Ruby
chrnobyl/guessing-cli-prework
/guessing_cli.rb
UTF-8
349
3.84375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def run_guessing_game puts "Guess a number between 1 and 6." num = rand(1..6).to_s command = "" until command == "exit" command = gets.chomp if command == num puts "You guessed the correct number!" elsif command != num puts "The computer guessed #{num}." else break end puts "Goodbye!" end end
true
1fb6ab5bbb71940303be00639d0e84a9990a9cf8
Ruby
kellyredding/xmlss
/test/unit/style/interior_tests.rb
UTF-8
1,707
2.515625
3
[ "MIT" ]
permissive
require "assert" require 'xmlss/style/interior' require 'enumeration/assert_macros' class Xmlss::Style::Interior class UnitTests < Assert::Context include Enumeration::AssertMacros desc "Xmlss::Style::Interior" before { @i = Xmlss::Style::Interior.new } subject { @i } should have_enum :pattern, { :none => "None", :solid => "Solid", :gray75 => "Gray75", :gray50 => "Gray50", :gray25 => "Gray25", :gray125 => "Gray125", :gray0625 => "Gray0625", :horz_stripe => "HorzStripe", :vert_stripe => "VertStripe", :reverse_diag_stripe => "ReverseDiagStripe", :diag_stripe => "DiagStripe", :diag_cross => "DiagCross", :thick_diag_cross => "ThickDiagCross", :thin_horz_stripe => "ThinHorzStripe", :thin_vert_stripe => "ThinVertStripe", :thin_reverse_diag_stripe => "ThinReverseDiagStripe", :thin_diag_stripe => "ThineDiagStripe", :thin_horz_cross => "ThinHorzCross", :thin_diag_cross => "ThinDiagCross" } should have_class_method :writer should have_accessor :color, :pattern_color should "know its writer" do assert_equal :interior, subject.class.writer end should "set it's defaults" do assert_equal nil, subject.color assert_equal nil, subject.pattern assert_equal nil, subject.pattern_color end should "set attributes at init" do i = Xmlss::Style::Interior.new({ :color => "#000000", :pattern => :solid, :pattern_color => "#FF0000" }) assert_equal "#000000", i.color assert_equal "Solid", i.pattern assert_equal "#FF0000", i.pattern_color end end end
true
6459397f07e02a3ffb76f5bccc8ece35088b8139
Ruby
uk-gov-mirror/guidance-guarantee-programme.output-uat
/lib/sample_output_document.rb
UTF-8
2,122
2.5625
3
[ "MIT" ]
permissive
require_relative './output_document' require 'faker' Faker::Config.locale = 'en-GB' class SampleOutputDocument < OutputDocument def initialize(id: nil, format: 'standard', variant: nil, attendee_name: nil, attendee_address_line_1: nil, attendee_address_line_2: nil, attendee_address_line_3: nil, attendee_town: nil, attendee_county: nil, attendee_postcode: nil, attendee_country: nil, lead: nil, guider_first_name: nil, guider_organisation: nil, appointment_date: nil, supplementary_benefits: nil, supplementary_debt: nil, supplementary_ill_health: nil, supplementary_defined_benefit_pensions: nil) id ||= rand(123456) attendee_name ||= [Faker::Name.prefix.gsub(/\./, ''), Faker::Name.first_name, Faker::Name.last_name].join(' ') attendee_address_line_1 ||= Faker::Address.street_address attendee_address_line_2 ||= [Faker::Address.secondary_address, nil].sample attendee_address_line_3 ||= attendee_address_line_2 && [Faker::Address.street_name, nil].sample attendee_town ||= Faker::Address.city attendee_county ||= [Faker::Address.county, nil].sample attendee_postcode ||= Faker::Address.postcode guider_first_name ||= Faker::Name.first_name guider_organisation ||= ['The Pensions Advisory Service', 'Pension Wise'].sample appointment_date ||= Faker::Date.forward(1_825).strftime('%-e %B %Y') supplementary_benefits = [true, false].sample supplementary_debt = [true, false].sample supplementary_ill_health = [true, false].sample supplementary_defined_benefit_pensions = [true, false].sample lead ||= 'You recently had a Pension Wise guidance appointment with ' + "#{guider_first_name} from #{guider_organisation} on #{appointment_date}." variant ||= 'standard' super end end
true
3ef977f1e57d26f773975a9f80a500fbd6e459aa
Ruby
potapovDim/full
/ruby/po/editor/share/color-picke-unusedr.rb
UTF-8
874
2.890625
3
[]
no_license
#color picker class ColorPicker #css selectors def initialize(browser) @browser = browser @color_picker_pointer = '.pointer_35h' @alpha_input = '[data-test="input-number-input"]' @saturation = '[data-test="color-picker-saturation"]>div' @hue_vertical = '.hue-vertical' end def change_color_saturation(x, y, place) #change color case place when "hue" @browser.element(css: @hue_vertical).drag_and_drop_by x, y when "saturation" @browser.element(css: @saturation).drag_and_drop_by x, y end return self end def change_alpha_slider_saturation(x) @browser.element(css: @color_picker_pointer).fire_event "mouseover" @browser.element(css: @color_picker_pointer).drag_and_drop_by x, 0 end def input_alpha_palette(percent) @browser.element(css: @alpha_input).send_keys percent end end
true
8e4652b43d1bcb55036e923ec19672ec6db046c5
Ruby
tjwudi/learn-ruby
/meta-prog/include.rb
UTF-8
131
3.140625
3
[]
no_license
module M def foo puts 'foo' end private def bar puts 'bar' end end class C include M end c = C.new c.foo c.bar
true
2962dd353a3fe70ad450899387bb40323359fae4
Ruby
relteq/simx
/bin/export-aurora-xml
UTF-8
1,246
2.5625
3
[]
no_license
#!/usr/bin/env ruby topdir = File.expand_path("..", File.dirname(__FILE__)) libdir = File.join(topdir, "lib") $LOAD_PATH.unshift libdir require 'simx/argos' optdef = { "h" => true, "help" => true, "log" => true } opts = Argos.parse_options(ARGV, optdef) if ARGV.size != 2 or not ARGV.grep(/^-./).empty? or opts["h"] or opts["help"] puts <<-END Usage: #{$0} [opts] db scenario_id Export specified scenario from database and print xml to stdout. The db argument may be any valid database connection string: sqlite://foo.db postgres://user:password@host:port/database_name The scenario_id is the integer id of a row in the scenarios table. Options: --log Print full SQL log to stderr. END exit end db_url = ARGV[0] scenario_id = Integer(ARGV[1]) require 'sequel' require 'nokogiri' DB = Sequel.connect db_url if opts["log"] require 'logger' DB.loggers << Logger.new($stderr) end require 'db/schema' Aurora.create_tables? require 'db/model/aurora' require 'db/export/scenario' module Aurora def self.export_scenario id scenario = Scenario[id] scenario.to_xml end end puts Aurora.export_scenario(scenario_id)
true
44e98f7864b7d45c00308dcf15e95b0c8944a8e9
Ruby
th7/programming-challenges
/non-adjacent-robbery/benchmark.rb
UTF-8
408
2.84375
3
[]
no_license
require 'benchmark' require './non_adjacent_robbery_v1' v1 = NonAdjacentRobbery Object.send(:remove_const, :NonAdjacentRobbery) require './non_adjacent_robbery_v2' v2 = NonAdjacentRobbery Object.send(:remove_const, :NonAdjacentRobbery) n = 1_000_00 Benchmark.bm(10) do |x| x.report('v' + v1.v) {n.times{v1.rob([1,2,3,4,5,6,7,8,9,0])}} x.report('v' + v2.v) {n.times{v2.rob([1,2,3,4,5,6,7,8,9,0])}} end
true
2b45afbea00cac592372b39c7ac5d757f67a9797
Ruby
AllanaOliveira/UFFMAIL
/app/helpers/students_helper.rb
UTF-8
455
2.640625
3
[]
no_license
module StudentsHelper def translate_attribute(object = nil,method = nil) if object && method object.model.human_attribute_name(method) else "Informe os parâmetros corretamente" end end def choose_email(student) byebug emails = [] nome = student.name 5.times do |i| email = Faker::Internet.free_email(nome) email.split("@")[0] +"@uff.br" emails << email end return emails end end
true
dfc0421d35a802526426b046c323bf7bcc6486ee
Ruby
pablotarga/project-euler
/00004_largest_palindrome.rb
UTF-8
991
3.984375
4
[]
no_license
module Math def self.largest_palindrome(pow:2) min, max, found = 10**(pow-1), (10**pow)-1, 0 a = b = max begin product = a * b found = product if product > found && product.palindrome? if b > min && product > found b -= 1 else a, b = a-1, max break if a * b <= found end end while a > min found end end class Integer def palindrome? (str = self.to_s) == str.reverse end end puts Math.largest_palindrome pow: 2 puts Math.largest_palindrome pow: 3 puts Math.largest_palindrome pow: 4 puts Math.largest_palindrome pow: 5 puts Math.largest_palindrome pow: 6 # require 'benchmark' # Benchmark.bm do |x| # x.report('2 digits'){ Math.largest_palindrome pow: 2 } # x.report('3 digits'){ Math.largest_palindrome pow: 3 } # x.report('4 digits'){ Math.largest_palindrome pow: 4 } # x.report('5 digits'){ Math.largest_palindrome pow: 5 } # x.report('6 digits'){ Math.largest_palindrome pow: 6 } # end
true
58dea5e0eb97e7271063871497a376a4b4e91b86
Ruby
Gyenh/learn_ruby_rspec
/04_simon_says/simon_says.rb
UTF-8
407
3.890625
4
[]
no_license
def echo(name) name end def shout(a) a.upcase end def repeat(a, b) a = a + " " a = a * b a = a[0...-1] a end def start_of_word(word, b) word.slice(0...b) end def first_word(a) a.split[0] end def titleize(a) lowercase_words = %w{a an the and but or for nor of} a.split.each_with_index.map{|x, index| lowercase_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ") end
true
d35de2fff8d2246fb1a8d670759cbe81f8f6974c
Ruby
aequihua/vcap-addsvc
/test.rb
UTF-8
627
3.09375
3
[]
no_license
def create_instance_cmdline(path) puts "estoy entrando a crear el comando pinky" cmdline = "#{path}" comando = "memcached " cmdline.each_line do |s| paso = s.split if paso.length>1 if paso[0].downcase=="port" comando = comando + " -p"+paso[1] else if paso[0].downcase=="daemonize" comando = comando + " -D" end end end end puts "voy a ejecutar:" puts comando cmdline end def process_file(filename) puts "estoy entrando a procesar " + filename text = File.read(filename) create_instance_cmdline(text) end process_file("./pelos4.txt")
true
f756b499e5e158b809b3a9db05b7d271eb344362
Ruby
mikereinhart/labs
/week1/524_tdd_bank/bank_spec2.rb
UTF-8
1,002
3.171875
3
[]
no_license
require_relative "bank" describe Bank do describe '#new' do it 'builds a new bank with a name' do bank = Bank.new('MyCiti') bank.should be_instance_of Bank bank.name.should == 'MyCiti' end end end describe '#open_account' do it 'opens a new account' do bank = Bank.new('MyCiti') account = bank.open_account('zlu', 500) account[:name].should == 'zlu' end it 'has an initial balance' do bank = Bank.new('MyCiti') account = bank.open_account('zlu', 500) account.balance.should == 500 end it 'opens two accounts' do bank = Bank.new('MyCiti') account1 = bank.open_account('zlu', 500) account2 = bank.open_account('omar', 5000) account1[:balance].should == 500 account2[:balance].should == 5000 end end describe '#deposit' do it 'adds money to account' do bank = Bank.new('MyCiti') zlu_account = bank.open_account('zlu', 500) bank.deposit('zlu', 250) zlu_account[:balance].should == 750 end it 'adds money to correct account' it 'blah blah' end
true
21b1deba21915603e9f993a403d78e722c865914
Ruby
laurenrosie/student-directory
/directory.rb
UTF-8
4,312
4.0625
4
[]
no_license
@center_by = 60 @students = [] require 'csv' # method printing just the header def print_header puts "The students of Villians Academy".center(@center_by) puts "-------------".center(@center_by) end # method printing the student name and cohort using .each_with_index def print_students_list @students.each_with_index do |student, index| puts "#{index+1}. #{student[:name]} (#{student[:cohort]} cohort)".center(@center_by) end end # method to print the footer def print_footer @students.count==1 ? final_word = "student" : final_word = "students" puts "Overall, we have #{@students.count} great #{final_word}".center(@center_by) end # method to check if string input is one of the entries of the array values def check_input(input, values) input_ok = false values.each do |value| input_ok = true if input.include?(value) end return input_ok end # method to get cohort or put to default def get_cohort cohort = STDIN.gets.chomp cohort = "November" if cohort.empty? return cohort end # method to get the cohort value from the user and check it, if not okay loop def get_and_check_cohort cohorts = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] puts "And the cohort?" cohort = get_cohort input_ok = check_input(cohort, cohorts) while !input_ok puts "That isn't a month....the cohort?" cohort = get_cohort input_ok = check_input(cohort, cohorts) end return cohort end # method adding hash with name and cohort to the students array def assign_students(name, cohort) @students << {name: name, cohort: cohort.to_sym, country_of_birth: :unknown, height: :unknown, hobbies: :unknown} end # method to get input from user to define the students hash def input_students puts "Please enter the names of the students" puts "To finish, just hit return twice for name input" name = STDIN.gets.chomp while !name.empty? do cohort = get_and_check_cohort assign_students(name, cohort) puts "Now we have #{@students.count} students" puts "Another name?" name = STDIN.gets.chomp end puts "Input successful" end # method to print the interactive menu def print_menu puts "1. Input the students" puts "2. Show the students" puts "3. Save the list to a file" puts "4. Load the list to a file" puts "9. Exit" end # method to show the list of students def show_students print_header print_students_list print_footer end # either gets filename or if file doesn't exist asks user again def get_filename puts "Enter a file you wish to use:" filename = STDIN.gets.chomp while !(File.exists?(filename)) puts "Sorry filename not recognised, try again:" filename = STDIN.gets.chomp end return filename end # method to process the selection made by the user in interactive menu def process(selection) case selection when "1" input_students when "2" show_students puts "Show successful" when "3" save_students when "4" filename = get_filename load_students(filename) when "9" exit else puts "I don't know what you mean, try again" end end # method to run the interactive menu def interactive_menu loop do print_menu process(STDIN.gets.chomp) end end # method to save the students array into a file students.csv def save_students #open the file for writing filename = get_filename #save each entry of the array @students into the file CSV.open(filename, "wb") do |csv| @students.each do |student| student_data = [student[:name], student[:cohort]] csv << student_data end end end # method to load the students from the students.csv file def load_students(filename = 'students.csv') CSV.foreach(filename) do |line| name = line[0] cohort = line[1] assign_students(name, cohort) end end # method to try load students from the file provided on the command line or the default def try_load_students ARGV.first.nil? ? filename = "students.csv" : filename = ARGV.first if File.exists?(filename) load_students(filename) puts "Loaded #{@students.count} from #{filename}" else puts "Sorry, #{filename} doesn't exist." exit end end try_load_students interactive_menu
true
9f792da30001626ab089377a1b4110d7a28b5c47
Ruby
cellog/testable
/lib/testable/element.rb
UTF-8
6,903
3.171875
3
[ "MIT" ]
permissive
require "watir" module Testable module_function NATIVE_QUALIFIERS = %i[visible].freeze def elements? @elements end def recognizes?(method) @elements.include? method.to_sym end def elements @elements ||= Watir::Container.instance_methods unless @elements end module Pages module Element # This iterator goes through the Watir container methods and # provides a method for each so that Watir-based element names # cane be defined on an interface definition, as part of an # element definition. Testable.elements.each do |element| define_method(element) do |*signature, &block| identifier, signature = parse_signature(signature) context = context_from_signature(signature, &block) define_element_accessor(identifier, signature, element, &context) end end private # A "signature" consists of a full element definition. For example: # # text_field :username, id: 'username' # # The signature of this element definition is: # # [:username, {:id=>"username"}] # # This is the identifier of the element (`username`) and the locator # provided for it. This method separates out the identifier and the # locator. def parse_signature(signature) [signature.shift, signature.shift] end # Returns the block or proc that serves as a context for an element # definition. Consider the following element definitions: # # ul :facts, id: 'fact-list' # span :fact, -> { facts.span(class: 'site-item')} # # Here the second element definition provides a proc that contains a # context for another element definition. That leads to the following # construction being sent to the browser: # # @browser.ul(id: 'fact-list').span(class: 'site-item') def context_from_signature(*signature, &block) if block_given? block else context = signature.shift context.is_a?(Proc) && signature.empty? ? context : nil end end # This method provides the means to get the aspects of an accessor # signature. The "aspects" refer to the locator information and any # qualifier information that was provided along with the locator. # This is important because the qualifier is not used to locate an # element but rather to put conditions on how the state of the # element is checked as it is being looked for. # # Note that "qualifiers" here refers to Watir boolean methods. def accessor_aspects(element, *signature) identifier = signature.shift locator_args = {} qualifier_args = {} gather_aspects(identifier, element, locator_args, qualifier_args) [locator_args, qualifier_args] end # This method is used to separate the two aspects of an accessor -- # the locators and the qualifiers. Part of this process involves # querying the Watir driver library to determine what qualifiers # it handles natively. Consider the following: # # select_list :accounts, id: 'accounts', selected: 'Select Option' # # Given that, this method will return with the following: # # locator_args: {:id=>"accounts"} # qualifier_args: {:selected=>"Select Option"} # # Consider this: # # p :login_form, id: 'open', index: 0, visible: true # # Given that, this method will return with the following: # # locator_args: {:id=>"open", :index=>0, :visible=>true} # qualifier_args: {} # # Notice that the `visible` qualifier is part of the locator arguments # as opposed to being a qualifier argument, like `selected` was in the # previous example. This is because Watir 6.x handles the `visible` # qualifier natively. "Handling natively" means that when a qualifier # is part of the locator, Watir knows how to intrpret the qualifier # as a condition on the element, not as a way to locate the element. def gather_aspects(identifier, element, locator_args, qualifier_args) identifier.each_with_index do |hashes, index| next if hashes.nil? || hashes.is_a?(Proc) hashes.each do |k, v| methods = Watir.element_class_for(element).instance_methods if methods.include?(:"#{k}?") && !NATIVE_QUALIFIERS.include?(k) qualifier_args[k] = identifier[index][k] else locator_args[k] = v end end end [locator_args, qualifier_args] end # Defines an accessor method for an element that allows the "friendly # name" (identifier) of the element to be proxied to a Watir element # object that corresponds to the element type. When this identifier # is referenced, it generates an accessor method for that element # in the browser. Consider this element definition defined on a class # with an instance of `page`: # # text_field :username, id: 'username' # # This allows: # # page.username.set 'tester' # # So any element identifier can be called as if it were a method on # the interface (class) on which it is defined. Because the method # is proxied to Watir, you can use the full Watir API by calling # methods (like `set`, `click`, etc) on the element identifier. # # It is also possible to have an element definition like this: # # text_field :password # # This would allow access like this: # # page.username(id: 'username').set 'tester' # # This approach would lead to the *values variable having an array # like this: [{:id => 'username'}]. # # A third approach would be to utilize one element definition within # the context of another. Consider the following element definitions: # # article :practice, id: 'practice' # # a :page_link do |text| # practice.a(text: text) # end # # This would allow access like this: # # page.page_link('Drag and Drop').click # # This approach would lead to the *values variable having an array # like this: ["Drag and Drop"]. def define_element_accessor(identifier, *signature, element, &block) locators, qualifiers = accessor_aspects(element, signature) define_method(identifier.to_s) do |*values| if block_given? instance_exec(*values, &block) else locators = values[0] if locators.empty? access_element(element, locators, qualifiers) end end end end end end
true
02cf0df483ed85921bf30506aee1081c8c86492d
Ruby
nrhyan/launch_school
/contact_data.rb
UTF-8
1,385
3.0625
3
[]
no_license
contact_data = [["[email protected]", "123 Main st.", "555-123-4567"], ["[email protected]", "404 Not Found Dr.", "123-234-3454"]] contacts = {"Joe Smith" => {}, "Sally Johnson" => {}} contact_data = ["[email protected]", "123 Main st.", "555-123-4567"] contacts = {"Joe Smith" => {}} fields = [:email, :address, :phone] contacts.each {|name, hash| fields.each { |fields| hash[fields] = contact_data.shift }} sam_data = ['Tuck', 'Castro', 'Google'] sam = ['Sam'] sam_fields = [:pet, :city, :job] sam.each_with_index {|(name, hash), idx| sam_fields.each { |field| hash[field] = contact_data[idx].shift } } #sam.each {|name, hash| #sam_fields.shift {|fields| #hash[fields] = sam_data.shift #}} =begin sarah_data = ['chickens', 'Bellingham', 'Hospital'] sarah = ['Sarah'] sarah_fields = [:pet, :city, :job] sarah.each {|name, hash| sarah_fields.each {|fields| hash[fields] = sarah_data.shift }} =begin contacts["Joe Smith"] = {email: contact_data[0][0]} contacts["Joe Smith"] = {address: contact_data[0][1]} contacts["Joe Smith"] = {phone: contact_data[0][2]} contacts["Sally Johnson"] = {email: contact_data[1][0]} contacts["Sally Johnson"] = {address: contact_data[1][1]} contacts["Sally Johnson"] = {phone: contact_data[1][2]} puts contacts contacts["Joe Smith"][:email] contacts["Sally Johnson"][:email] puts "Joe's phone number is #{contacts["Joe Smith"][:phone]}" puts "Sally's address is #{contacts["Sally Johnson"][:address]}" =end
true
830ccbff360c8d7b087dc949e93c8dc52c11ad32
Ruby
JumpStartGeorgia/Work-Gender-Inequality
/app/models/faq_translation.rb
UTF-8
468
2.53125
3
[ "MIT" ]
permissive
class FaqTranslation < ActiveRecord::Base belongs_to :faq attr_accessible :faq_id, :question, :answer, :locale validates :question, :answer, :presence => true def required_data_provided? provided = false provided = self.question.present? && self.answer.present? return provided end def add_required_data(obj) self.question = obj.question if self.question.blank? self.answer = obj.answer if self.answer.blank? end end
true
63e35d67906ad253176b0cb5b4624cb305c04ee0
Ruby
plammiez/moss.rb
/test/testnoisefilterwithc.rb
UTF-8
534
2.609375
3
[]
no_license
#!/usr/bin/env ruby #Testing the Noise Filter #Unit Tests FTW! require 'test/unit' require '../lib/myth/filter.rb' class TestNoiseFilter < Test::Unit::TestCase def test_remove_comments() fp=File.open('../conf/c.conf') confinstance=Myth::Filter::FilterConfset.new(fp) text_contents=File.read('./cfile.c') instance=Myth::Filter::NoiseFilter.new(text_contents,confinstance) ans=instance.get_filtered_text #Write the text after filtering File.open('Cdump.txt','w') { |fp| fp.puts(ans) } end end
true
5c230cf0f9f8e0d7db016feaecb774999604d905
Ruby
iharmonyharper/movies
/lib/movie/modern_movie.rb
UTF-8
152
2.578125
3
[]
no_license
module Movies class ModernMovie < Movie def to_s "#{@title} — современное кино: играют #{@actors}" end end end
true
823b460a87b1b6f3ddd810becbbc1f02dd04c76b
Ruby
inglesp/ruby-crash-course
/examples/nine_times_table_3.rb
UTF-8
113
3.171875
3
[]
no_license
# nine_times_table_3.rb i = 1 while true puts "#{i} * 9 = #{i * 9}" i += 1 if i > 10 break end end
true
dcdefc43ea6679b8bc6385219778d20d3670d5e1
Ruby
mkroman/meta-rpc_client
/lib/meta/rpc/client.rb
UTF-8
2,249
3.03125
3
[]
no_license
# frozen_string_literal: true module Meta module RPC # {Client} is the main interface you'll be working with to connect to Meta's # RPC server. It opens a single TCP connection to the given +url+ and takes # care of encrypting and decrypting the messages using a shared key. # # @example # client = Meta::RPC::Client.new 'tcp://localhost:31337', 'shared_secret' # params = { # 'network' => '*', # 'channel' => '#test', # 'message' => 'hello, world!' # } # # client.call 'message', params class Client # Constructs a new {Client} that connects to a given +url+ and uses the # given +shared_secret+ for message encryption. # # @param url [String] the URL of the RPC server. # @param shared_secret [String] the shared shared_secret used for # encryption. # # @raise [SharedSecretError] if the provided +shared_secret+ is invalid. def initialize url, shared_secret @url = URI url @shared_secret = shared_secret @connection = Connection.new @url.host, @url.port @box = RbNaCl::SimpleBox.from_secret_key shared_secret.to_s.b rescue RbNaCl::LengthError => e raise SharedSecretError, e.message end # (see Connection#connect) def connect @connection.connect end # (see Connection#connected?) def connected? @connected end # Sends a remote procedure call +method+ and +params+. # # @param method [#to_s] the method we want to invoke. # @param params [Hash] the parameters we want to invoke the call with. # # @example # # Send a message in `#test` on all networks where the client is idling # client.call 'message', 'network' => '*', 'channel' => '#test', # 'message' => 'hello, world!' def call method, params json = { 'method' => method.to_s, 'params' => params } @connection.send @box.encrypt MultiJson.dump json read_response end def read_response return unless (nonce_and_data = @connection.read_packet) @box.decrypt nonce_and_data end end end end
true
c2661fe5bf5d598cd24db7ea66b436b2597f0e53
Ruby
ivanternovyi/repo
/zavd.rb
UTF-8
144
2.8125
3
[]
no_license
require 'singleton' class Student attr_accessor :age include Singleton end K = Student.instance B = Student.instance K.age = 17 B.age p B
true
2d643f6c534d852631fb9f265028db007fecc715
Ruby
chiibis/rasn1
/spec/types/octet_string_spec.rb
UTF-8
1,871
2.671875
3
[ "MIT" ]
permissive
require_relative '../spec_helper' module RASN1::Types describe OctetString do describe '.type' do it 'gets ASN.1 type' do expect(OctetString.type).to eq('OCTET STRING') end end describe '#initialize' do it 'creates a OctetString with default values' do os = OctetString.new expect(os).to be_primitive expect(os).to_not be_optional expect(os.asn1_class).to eq(:universal) expect(os.default).to eq(nil) end end describe '#to_der' do it 'generates a DER string' do os = OctetString.new os.value = 'NOP' expect(os.to_der).to eq(binary("\x04\x03NOP")) end it 'generates a DER string according to ASN.1 class' do os = OctetString.new(class: :context) os.value = 'a' expect(os.to_der).to eq(binary("\x84\x01a")) end it 'generates a DER string according to default' do os = OctetString.new(default: 'NOP') os.value = 'NOP' expect(os.to_der).to eq('') os.value = 'N' expect(os.to_der).to eq(binary("\x04\x01N")) end it 'generates a DER string according to optional' do os = OctetString.new(optional: true) os.value = nil expect(os.to_der).to eq('') os.value = 'abc' expect(os.to_der).to eq(binary("\x04\x03abc")) end it 'serializes a Types::Base object when set as value' do os = OctetString.new int = Integer.new(:int) int.value = 12 os.value = int expect(os.to_der).to eq(binary("\x04\x03\x02\x01\x0c")) end end describe '#parse!' do let(:os) { OctetString.new } it 'parses a DER OCTET STRING' do os.parse!(binary("\x04\x02\x01\x02")) expect(os.value).to eq(binary("\x01\x02")) end end end end
true
5ad2f871e9387f52e7ab2e3b7e040d54eb0fa3d7
Ruby
razorpay/ifsc
/scraper/scripts/utils.rb
UTF-8
1,401
2.734375
3
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
require '../../src/ruby/ifsc' def sanitize(str) return nil if str.nil? or str.length==0 ["┬ô", "┬û",'┬ö','┬Æ','┬á','┬æ','┬ù','ý','ý','┬á','Â'].each do |pattern| str.gsub!(pattern,' ') end str.gsub!('├ë','e') str.gsub!('├å','a') str.gsub!('├ë','e') str.gsub!('`',"'") str.gsub!('ý'," ") # replace newlines str.gsub!("\n", " ") # Remove all spaces (including nbsp) at the start and end of the string str.gsub(/\A[[:space:]]+|[[:space:]]+\z/, '') end # Some rows have last 2 columns shifted by 2 # Check for numeric values of STATE in RTGEB0815.xlsx for examples # This checks and fixes those def fix_row_alignment!(row) log "#{row['IFSC']}: Using State = '#{row['CITY2']}' STD_CODE=#{row['STATE']}, PHONE=#{row['STD CODE']} and discarding PHONE=#{row['PHONE']}", :info row['STATE'],row['STD CODE'], row['PHONE'] = row['CITY2'], row['STATE'], row['STD CODE'] end def fix_pipe_delimited_address!(row) log "Splitting address= #{row['ADDRESS']}. New values=", :info d = row['ADDRESS'].split '|' row['PHONE'] = d[-1] row['STD CODE'] = d[-2] row['STATE'] = d[-3] row['CITY2'] = d[-4] row['CITY1'] = d[-5] row['ADDRESS'] = d[-6] log row.select{|k,v| ['ADDRESS','PHONE', 'STD CODE', 'STATE', 'CITY1', 'CITY2'].include? k}, :info end def bank_name_from_code(code) Razorpay::IFSC::IFSC.bank_name_for(code) end
true
777e346408aa0a1093711729b0cc522dbb348677
Ruby
achambel/conference-track-manager
/lib/conference-track-manager/talk.rb
UTF-8
881
2.90625
3
[]
no_license
require 'securerandom' module ConferenceTrackManager module Model class Talk attr_reader :title, :duration attr_accessor :schedule def initialize(line) line_splited = line.split duration = line_splited.last == "lightning" ? 5 : line.split.last.to_i line_splited.pop title = line_splited.join(" ") title = SecureRandom.uuid.gsub("-", "").hex if title.length == 0 @title = title @duration = duration end def hash @title.hash ^ @duration.hash end def eql?(other) @title == other.title && @duration == other.duration end def ==(other) @title == other.title && @duration == other.duration end def to_s "<Talk @schedule=#{@schedule}, @title=#{@title}, @duration=#{@duration}>" end end end end
true
8f48b7e57567fd0639900d23cf43d974c6300345
Ruby
armandylon/todo-ruby-basics-001-prework-web
/lib/ruby_basics.rb
UTF-8
391
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def division(num1 = 42, num2 = 7) num1/num2 end def assign_variable(value = "Bob") value end def argue(phrase = "I'm right and you are wrong!") phrase end def greeting(greeting = "Hi there, ", name = "Bobby!") greeting end def return_a_value(phrase = "Nice") phrase end def last_evaluated_value(phrase = "expert") phrase end def pizza_party(food = "cheese") food end
true
1108a3e6ddbb90747d9fb7ba00d048b71bd07de4
Ruby
sifterapp/sifter-ruby
/lib/sifter/project.rb
UTF-8
1,085
2.515625
3
[ "MIT" ]
permissive
# Wrapper for a Sifter project. Fetch projects using Sifter::Account. class Sifter::Project < Hashie::Dash property :name property :archived property :primary_company_name property :url property :api_url property :issues_url property :milestones_url property :people_url property :api_milestones_url property :api_people_url property :api_issues_url property :api_categories_url # Fetch all the issues on this project. Returns an array of Sifter::Issue # objects. def issues Sifter. get(api_issues_url). fetch("issues", []). map { |i| Sifter::Issue.new(i) } end # Fetch all the milestones for this project. Returns an array of # Sifter::Milestone objects. def milestones Sifter. get(api_milestones_url). fetch("milestones", []). map { |m| Sifter::Milestone.new(m) } end # Fetch all the people linked to this project. Returns an array of # Sifter::Person objects. def people Sifter. get(api_people_url). fetch("people", []). map { |p| Sifter::Person.new(p) } end end
true
2ad4268fc5aa4b24d7e7580587336f1fad7effb9
Ruby
takehome1/takehome
/lib/rover.rb
UTF-8
242
2.828125
3
[]
no_license
class Rover attr_reader :position, :direction, :instructions def initialize(position:, direction:, instructions:) @position = position @direction = direction @instructions = instructions end end
true
b6b31b654251aee055b7eed22866e7e1754b765f
Ruby
Forison/Testing-custom_enum
/spec/custom_enum_spec.rb
UTF-8
6,857
3.546875
4
[ "MIT" ]
permissive
require './enum_methods/custom_enum.rb' RSpec.describe Enumerable do let(:test_array_one) { [1, 2, 3, 4, 5] } let(:test_array_two) { ['a','a','a','b'] } let(:test_array_three) { ['kofi','ama', 99] } let(:test_array_four) { ['kofi','ama', 'adwoa'] } let(:test_array_five) { ['kofi','akosua', 'adwoa'] } let(:test_array_six) { %w[ant bear cat] } let(:empty_array_test) { [ ] } let(:test_array_bool_1) { [false, false, true] } let(:test_array_bool_2) { [false, false, false] } let(:hash_test){ { 1 => 'hi', 2 => 'hello', 3 => 'how'} } describe "#my_each" do it " It returns each element in array when given a block " do expect( test_array_one.my_each { |a| a } ).to eql(test_array_one) end it " It returns each key or value in hash when given a block with two parameter " do expect( hash_test.my_each { |a,b| b } ).to eql( hash_test ) end end describe "#my_each_with_index" do it "The first parameter returns each element in an array whilst the second parameter returns the current index of the element in the Array" do expect( test_array_one.my_each_with_index { |value, index| value} ).to eql(test_array_one) end end describe " #my_count(para = nil) " do it "It returns the number of elements in array when no parameter is given and no block is passed " do expect( test_array_one.my_count ).to eql( 5 ) end it "It returns the number of the argument that exist in the array it operates upon,when no block is given " do expect( test_array_two.my_count('a') ).to eql( 3 ) end it "It returns the number of that exist in the array based on the condition specified in the block " do expect( test_array_two.my_count { |a| a =='b' } ).to eql( 1 ) end end describe "#my_all?(arg = nil)" do it "It return true if array is empty and neither a block or agument is passed" do expect( empty_array_test.my_all? ).to eql(true) end it "It return false if all element in the array are not of the same boolean value and neither a block or argument is given" do expect( test_array_bool_1.my_all? ).to eql(false) end it "It return true if all element in the array are of the same boolean value and neither a block or argument is given" do expect( test_array_bool_1.my_all? ).to eql(false) end it "It return true if all element in the array is of the same type as the argument passed " do expect( test_array_one.my_all?( Integer ) ).to eql(true) end it "It return true based on the codition specified in the block when give a block" do expect( test_array_six.all? { |word| word.length >= 4 } ).to eql(false) end it "It return false if none of the above condition is not true" do expect( test_array_five.my_all? { |word| word.length == 3 } ).to eql(false) end end describe "#my_none?(arg = nil)" do it "It return true if array is empty and neither a block or agument is passed" do expect( empty_array_test.my_none? ).to eql(true) end it "It return false if all element in the array are not true and neither a block or argument is given" do expect( test_array_bool_1.my_none? ).to eql(false) end it "It return true if all element in the array is of the same type as the argument passed " do expect( test_array_bool_2.my_none?).to eql(true) end it "It return true based on the codition specified in the block when give a block" do expect( test_array_six.my_none? { |word| word.length >= 4 } ).to eql(true) end it "It return false if none of the above condition is not true" do expect( test_array_five.my_none? { |word| word.length == 3 } ).to eql(true) end end describe "#my_any?(arg = nil)" do it "It return false if array is empty and neither a block or agument is passed" do expect( empty_array_test.my_any? ).to eql(false) end it "It return true if any element in the array is true and neither a block or argument is given" do expect( test_array_bool_1.my_any? ).to eql(true) end it "It return true if any element in the array is of the same type as the argument passed " do expect( test_array_three.my_any?( Integer ) ).to eql(true) end it "It return true based on the codition specified in the block when give a block" do expect( test_array_four.my_any? { |word| word.length >= 3 } ).to eql(true) end it "It return false if none of the above condition is not true" do expect( test_array_five.my_any? { |word| word.length == 3 } ).to eql(false) end end describe "#my_select" do it "It returns a new array based on the value specified in the in the block" do expect( test_array_one.my_select{ | a | a > 3} ).to eql( [ 4,5 ] ) end end describe "#my_map" do it " It returns each elements in an Array when one parameter is passed in the block" do expect( test_array_one.my_map { |e| e} ).to eql([1,2,3,4,5]) end it " It returns a modified array based on the condition specified in the block " do expect( test_array_one.my_map { |e| e * 2 } ).to eql([2,4,6,8,10]) end it " It returns an array of true or false based on the condition specified in the block " do expect( test_array_one.my_map { |e| e < 3 } ).to eql( [true,true,false,false,false] ) end it " It returns the key and the value of each element in an array by passing two arguments to the block " do expect( hash_test.my_map { |e ,f| f } ).to eql( hash_test ) end end describe "#my_inject(param = nil)" do it "It returns a value based on the operation specified in the block whilst no argument is given" do expect( test_array_one.my_inject { |acc,value| acc + value} ).to eql(15) end it "It returns a value based on the operation specified in the block whilst and the argument is given" do expect( test_array_one.my_inject(1) { |acc,value| acc + value} ).to eql(16) end end end
true
8c2c80db5bb37420f6bb5a0512737d3c8208831a
Ruby
app2641/translaunder
/lib/translaunder/response_parser.rb
UTF-8
595
2.84375
3
[ "MIT" ]
permissive
#encoding: utf-8 require 'json' module TransLaunder class ResponseParser def initialize text @text = text end def parse @text = decode @text extract_text end private def decode text encoding = 'UTF-8' text.gsub!(/(\\x26#39;)/, "'") text.force_encoding(encoding).encode(encoding) end def extract_text texts = @text.split("[[[")[1].sub!(/\]\].*/, ']').gsub!(/"/, '').split("],[") texts.map! do |t| t = t.split(",") t.first unless t.first.empty? end texts.join("") end end end
true
c3e3ef5f52f7f5f8d8cb8bb4d363ef732855a375
Ruby
cmkoller/choose-your-own-adventure
/server.rb
UTF-8
3,530
2.515625
3
[]
no_license
require 'dotenv' require 'csv' require 'pg' require 'sinatra' require 'sinatra/activerecord' require 'sinatra/flash' require 'omniauth-github' require_relative 'config/application' Dotenv.load Dir['app/**/*.rb'].each { |file| require_relative file } helpers do def current_user user_id = session[:user_id] @current_user ||= User.find(user_id) if user_id.present? end def signed_in? current_user.present? end end def set_current_user(user) session[:user_id] = user.id end def authenticate! unless signed_in? flash[:notice] = 'You need to sign in if you want to do that!' redirect '/' end end get '/' do redirect '/stories' end get '/auth/github/callback' do auth = env['omniauth.auth'] user = User.find_or_create_from_omniauth(auth) set_current_user(user) flash[:notice] = "You're now signed in as #{user.username}!" redirect '/' end get '/sign_out' do session[:user_id] = nil flash[:notice] = "You have been signed out." redirect '/' end get '/stories' do @stories = Story.all erb :'/stories/index' end post '/stories' do if params[:delete] # FIGURE OUT HOW TO SANATIZE THIS Story.delete([params[:delete]]) redirect '/stories' elsif params[:edit] redirect "/create/#{params[:edit]}" end end get '/story/:index' do redirect "/story/#{params[:index]}/1" end get '/story/:index/:page' do story_id = params[:index] page_id = params[:page] # SANATIZE THIS @story = Story.find(story_id) @page = Page.where("story_id = ?", story_id).find_by page_num: page_id @actions = {@page.action1 => @page.dest1, @page.action2 => @page.dest2, @page.action3 => @page.dest3, @page.action4 => @page.dest4} @actions.delete_if { |k, v| k.nil? || v.nil? } if @actions.empty? @end_point = true else @end_point = false end erb :'/stories/show' end get '/create' do erb :'/create/new_story' end post '/create' do title = params[:title] user_id = session[:user_id] story = Story.create(title: title, user_id: user_id) id = story.id redirect "/create/#{id}" end get '/create/:story_id' do @id = params[:story_id] @story = Story.find(@id) @pages = Page.where(story_id: @id) erb :'/create/new_page' end post '/create/:story_id' do @id = params[:story_id] if params[:delete] # SANATIZE THIS Page.delete(params[:delete]) else # Write the new page to the PAGES database page_num = params[:page_id] page_header = params[:page_header] page_body = params[:page_text] story_id = params[:story_id] # Option 1 if params[:opt_1] != "" action1 = params[:opt_1] dest1 = params[:id_1] else action1 = NIL dest1 = NIL end # Option 2 if params[:opt_2] != "" action2 = params[:opt_2] dest2 = params[:id_2] else action2 = NIL dest2 = NIL end # Option 3 if params[:opt_3] != "" action3 = params[:opt_3] dest3 = params[:id_3] else action3 = NIL dest3 = NIL end # Option 4 if params[:opt_4] != "" action4 = params[:opt_4] dest4 = params[:id_4] else action4 = NIL dest4 = NIL end Page.create({page_header: page_header, page_body: page_body, action1: action1, dest1: dest1, action2: action2, dest2: dest2, action3: action3, dest3: dest3, action4: action4, dest4: dest4, story_id: story_id, page_num: page_num}) end # Redirect to display the page redirect "/create/#{params[:story_id]}" end
true
789e185f0ddf94c825a0f12b7422a3b49458ec64
Ruby
syfo/the_force
/lib/the_force/slugs.rb
UTF-8
967
3.0625
3
[ "MIT" ]
permissive
# CRZ - given a name to slug-ize, and either a list or a table and column, make a unique slug # - There's are inherent race conditions here, naturally. # - Should go like "b" -> "b_1" # e.g. TheForce.unique_slug("My Gallery", Gallery, :permalink) # e.g. TheForce.unique_slug("My Gallery", ["My_Gallery", "MY GALLERY"]) # e.g. before_validate 'self.permaslug = TheForce.unique_slug self.title, Article, :permaslug' # e.g. before_validate 'self.permaslug = TheForce.unique_slug self.heading, Section.find_all_by_article_id(self.article.id).map {|s| s.heading}' module TheForce def self.unique_slug(title, *others) arr = others[0].find(:all).map { |e| e.send(others[1]) } if others.length == 2 arr = others.first if others.length == 1 base = title.strip.downcase.gsub(/\s+/, '_').gsub(/[^a-zA-Z0-9_]+/, '') slug, suffix = base, "1" while arr.include?(slug) do suffix.succ! slug = "#{base}_#{suffix}" end slug end end
true
50037405fc951f705abd389398c71664e54bb5f9
Ruby
Shadae/VariousThings
/second_week/Baker_class.rb
UTF-8
311
2.96875
3
[]
no_license
class Baker attr_accessor :eggs, :butter, :rolling_pin def initialize @flour = 2 @butter = 5 @sugar = 3 @eggs =23 end def self.find_all_the_bakers def make_cookies heat_oven(350) end def heat_oven(temperature) puts "The oven is heating up to #{temp}" end end
true
814a36194abc4b7d92b00c5746cfea3db8375158
Ruby
jichen3000/colin-ruby
/test/require_test/relative_test/a.rb
UTF-8
130
2.515625
3
[]
no_license
class A p "a" end class B p "b" end module AM class A p "a" end class B p "b" end end def mm puts "mm" end
true
b7a58f6b7f673e0d36904ffd3d1cc8afaa85cb12
Ruby
verdi327/weatherbase
/lib/weatherbase/client.rb
UTF-8
1,558
3.0625
3
[ "MIT" ]
permissive
module WeatherbaseApi class Client attr_reader :agent def initialize @agent = Mechanize.new end def weather_for(location) #fetch page with correct url with location for all possible matches #click one of the matches #returns an object representing the data agent.get locations_for(location) agent.page.link_with(:text => location.capitalize).click DataSet.new(agent.page) end def locations_for(location) "http://www.weatherbase.com/search/search.php3?query=#{location}" end end class DataSet attr_reader :page def initialize(page_data) @page = page_data end def location_name page.search("#left-content h1").first.text end def average_annual_temperature page.search("table:nth-child(3) .data").first.text end def average_number_of_days_above_90 page.search("table:nth-child(17) .data").first.text end def average_number_of_days_below_32 page.search("table:nth-child(19) .data").first.text end def average_morning_relative_humidity page.search("table:nth-child(27) .data").first.text end def collect_data name = location_name avg_temp = average_annual_temperature days_above_90 = average_number_of_days_above_90 days_below_32 = average_number_of_days_below_32 avg_humidity = average_morning_relative_humidity WeatherbaseApi::HistoricWeather.new(name, avg_temp, days_above_90, days_below_32, avg_humidity) end end end
true
50ccb296dfbfa6b3b0ad277b1056abebc7613b08
Ruby
knightstick/aoc2020
/lib/aoc2020/day_eleven.rb
UTF-8
4,237
3.453125
3
[]
no_license
require 'pry' module Aoc2020 module DayEleven class << self def part_one(input) end_up_occupied(grid(input)) end def part_two(input) end_up_occupied(grid(input), :new_state_visible) end def grid(input) input.chomp.split("\n").each.with_index.reduce({}) do |grid_acc, (line, i)| line.chars.each.with_index.reduce(grid_acc) do |inner_acc, (char, j)| inner_acc.merge([i, j] => seat_from_char(char)) end end end def seat_from_char(char) case char when 'L' :empty when '.' :floor when '#' :occupied else raise "Unknown char: #{char}" end end def end_up_occupied(grid, state_method = :new_state) new_grid, changed = step(grid, state_method) return end_up_occupied(new_grid, state_method) if changed new_grid.count do |_point, value| value == :occupied end end def step(grid, new_state_method = :new_state) grid.reduce([{}, false]) do |(grid_acc, changed), ((x, y), value)| new_value = send(new_state_method, [x, y], grid) new_changed = changed || (value != new_value) [grid_acc.merge([x, y] => new_value), new_changed] end end def neighbour_points(point) x, y = point [ [x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1], [x - 1, y - 1], [x - 1, y + 1], [x + 1, y - 1], [x + 1, y + 1] ] end def new_state(point, grid) value = grid[point] return value if value == :floor return :occupied if value == :empty && no_occupied_neighbours?(point, grid) return :empty if value == :occupied && too_many_occupied_neighbours?(point, grid) value end def new_state_visible(point, grid) value = grid[point] return value if value == :floor return :occupied if value == :empty && no_visible_occupied_neighbours?(point, grid) return :empty if value == :occupied && too_many_visible_occupied_neighbours?(point, grid) value end def no_occupied_neighbours?(point, grid) neighbour_points(point).none? { |pt| grid[pt] == :occupied } end def all_direction_vectors [ [-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1] ] end def no_visible_occupied_neighbours?(point, grid) all_direction_vectors.each do |vector| neighbour = visible_in_direction(point, grid, vector) return false if neighbour == :occupied end true end def too_many_occupied_neighbours?(point, grid) occupied = 0 neighbour_points(point).each do |pt| neighbour = grid[pt] occupied += 1 if neighbour == :occupied return true if occupied >= 4 end false end def too_many_visible_occupied_neighbours?(point, grid) occupied = 0 all_direction_vectors.each do |vector| neighbour = visible_in_direction(point, grid, vector) occupied += 1 if neighbour == :occupied return true if occupied >= 5 end false end def print_grid(grid) max_x = grid.keys.max { |(x, _y), _value| x }[0] max_y = grid.keys.max { |(_x, y), _value| y }[1] print "\n" (0..max_x).each do |x| puts (0..max_y).map { |y| square_char(grid[[x, y]]) }.join('') end end def square_char(square) case square when :empty 'L' when :occupied '#' when :floor '.' else raise "Unknown square #{square}" end end def visible_in_direction(point, grid, vector) x, y = point diff_x, diff_y = vector next_point = [x + diff_x, y + diff_y] next_value = grid[next_point] return visible_in_direction(next_point, grid, vector) if next_value == :floor next_value end end end end
true
013750a2d39549ff52c9af1d6b8d70cc57ab9a16
Ruby
sahana-vajrakumar/Project-3
/app/models/movie_poster.rb
UTF-8
778
2.625
3
[]
no_license
class MoviePoster < ApplicationRecord def self.get_poster_path_cached( id ) m = MoviePoster.find_by tmdb_id: id if m puts "=" * 80 puts "FOUND IN DB: #{ id }" p m return [m.poster_path, m.overview] end # fallback to API request, but save results in our DB movie = HTTParty.get("https://api.themoviedb.org/3/movie/#{ id }?api_key=fa4617d76537ac386ebb1909138783d4") puts "API FALLBACK FOR #{ id }:" if movie && movie['poster_path'] puts movie['poster_path'] puts movie['overview'] # binding.pry MoviePoster.create tmdb_id: id, poster_path: movie['poster_path'], overview: movie['overview'] return movie['poster_path'] end puts "******** MOVIE NOT FOUND IN TMDB (#{ id })" end end
true
c63ac940d19a55fcc429e64b4770e9da688ca584
Ruby
smileart/invisible_logger
/lib/invisible_logger.rb
UTF-8
8,575
2.890625
3
[ "MIT" ]
permissive
# frozen_string_literal: true # encoding: UTF-8 # A tool to output complex logs with minimal intrusion and smallest possible # footprint in the "host" code + additional ability to aggregate separate logs class InvisibleLogger # Lib Semantic Version Constant VERSION = '0.1.1' # Read-only content of the buffered logs # @see #buffer attr_reader :aggregator # Read-only "level" the aggregated log is going to be flushed with # @see Logger # @see #level attr_reader :log_level # Create new invisible logger instance # # @note Use `INV_LOGGER_DEBUG` env var to enable global debug mode # @note Use `INV_LOGGER_DEBUG_MARKER` env var to change default debug marker # # @example # LOG_STENCIL = { # sum: { # vars: [:a, :b, :@sum], # level: :debug, # template: <<~LOG # %<a>s +| # %<b>s → | # %<@sum>s # Splendid! Magnificent! # LOG # }, # warning: { # vars: [:text], # level: :warn, # template: '>>>>>>> %<text>s' # }, # additional_info: { # template: "Additional INFO and nothing more... 👐" # }, # eval_example: { # vars: { const: 'self.class.const_get(:LOG_STENCIL)' }, # template: 'We can log constants and method calls:: %<const>s' # } # } # # ENV['INV_LOGGER_DEBUG'] = '1' # ENV['INV_LOGGER_DEBUG_MARKER'] = '🚀 ' # # class Test # include TestLogStencil # # def initialize # @logger = Logger.new(STDOUT) # @il = InvisibleLogger.new(logger: @logger, log_stencil: LOG_STENCIL) # # @sum = '42 (Wonderful! Glorious!)' # end # # def sum(a, b) # a + b # @il.l(binding, :sum, aggregate: true) # end # # def one(text) # @il.l(binding, :warning, aggregate: false, debug: true) # @il.l(binding, :eval_example) # end # # def test # @il.l(binding, :additional_info, aggregate: true) # @il.f! # end # end # # t = Test.new # t.sum(2, 3) # t.one('Beware of beavers!') # t.test # # @param [Object] logger any object with standard Logger compartable interface # @param [Hash] log_stencil a Hash with the names, levels, templates and var lists (see example!) def initialize(logger:, log_stencil:) @logger = logger @log_stencil = log_stencil @aggregator = '' @log_level = :info @debug_marker = ENV['INV_LOGGER_DEBUG_MARKER'] || '▶️ ' end # Log something # # @param [Binding] context pass the current context (aka binding) # @param [Symbol] name the name of the log stencil to use # @param [Boolean] aggregate should the logger aggregate this message or log (default: false) # @param [Boolean] debug the debug mode flag. Outputs the marker # and the name along with tht message (default: false) # # @note ⚠️ WARNING!!! Keep in mind that `debug` parameter could be overwritten with INV_LOGGER_DEBUG # environment variable # # @raise [KeyError] if we work in debug mode # @return [Boolean] true if the message was logged successfully, false if the message wasn't logged # due to anny reason (including aggregation) def log(context, name, aggregate: false, debug: false) return unless context.respond_to?(:eval) && @log_stencil&.fetch(name, nil) @log_level, log_template, log_values = init_stencil_for(context, name, debug) log_text = render_log(log_template, log_values) aggregate ? accumulate(log_text) : flush(@log_level, log_text) rescue KeyError => e handle_template_error(e, debug) end # Flush the aggregated message and clean the accumulator var on success # # @note ⚠️ WARNING!!! This method empties the message accumulator on successfull log flushing # @note ⚠️ WARNING!!! Aggregated message will be logged with the level of the last stencil # # @return [String, Nil] empty String (latest aggregator state) of nil def flush!(dev_null = false) @aggregator = '' if dev_null || flush(@log_level, @aggregator) end # A short alias for the flush! method (to make the logging footprint even smaller) alias f! flush! # A short alias for the log method (to make the logging footprint even smaller) # @note Beware of potential letters gem incompartability http://lettersrb.com alias l log # An alias to get the content of the buffered logs alias buffer aggregator # An alias to get a level the aggregated log is going to be flushed with alias level log_level private # Flush the aggregated message if the level is supported by the Logger provided # # @return [Boolean] true if the level method is supported and called, false otherwise def flush(level, log) return if !log || log.empty? @logger.respond_to?(level) ? [email protected](level, log).nil? : false end # Stencil handling method — extracts level, template and vars, converts vars to String, # encodes them to UTF-8, links var names to the values from context # @see Ruby `format` method for template string / template values Hash reference # # @param [Binding] context context to evaluate vars/expression in # @param [Symbol] name the name of the log stencil # @param [Boolean] debug render template in debug mode # # @return [Array(Symbol, String, Hash)] returns and array of log_method (Symbol), log_template (template String), # log_values (Hash for the template String) def init_stencil_for(context, name, debug = false) stencil = @log_stencil&.fetch(name) log_method = stencil.fetch(:level, nil) || :info log_template = init_log_template(stencil, name, debug) log_values = init_log_values(stencil, context) [log_method, log_template, log_values] end # Accumulate aggreagated log message and return false # # @param [String] message the message to put to the "aggregator" buffer # # @return [Boolean] false to return from log method (meaning nothing was logged to the output) def accumulate(message) @aggregator += " #{message}" if message false end # Fetch the template for the given name from the stencil + take the debug mode into account # # @param [Hash] stencil a Hash with the names, levels, templates and var lists (see example!) # @param [Symbol] name the name of the log stencil # @param [Boolean] debug render template in debug mode # # @return [String, Nil] fully prepared template string or nil def init_log_template(stencil, name, debug = false) log_template = stencil.fetch(:template, nil) log_template = debug || ENV['INV_LOGGER_DEBUG'] ? "#{@debug_marker}#{name} :: #{log_template}" : log_template log_template&.split("|\n")&.join(' ')&.strip end # Form log values to put into the template using given context # # @param [Hash] stencil a Hash with the names, levels, templates and var lists (see example!) # @param [Binding] context context to take vars/expression values from # # @return [Hash, Nil] Hash with all the values ready for `format` method or nil in case of no vars def init_log_values(stencil, context) log_values = {} log_vars = stencil.fetch(:vars, []) log_vars.each do |v| if v.respond_to?(:each_pair) log_values[v.keys.first] = context.eval(v.values.first.to_s) else log_values[v] = context.eval(v.to_s) end end log_values = log_values.each_with_object({}) { |(k, v), h| h[k.to_sym] = v.to_s.dup.force_encoding('UTF-8') } log_values.empty? ? nil : log_values end # Render log message (fill template placeholders with the respective values) or receive a static String # # @param [String] template standard ruby tempalte string with named placeholders # @param [Hash] values standard ruby Hash with respective key names to fill placeholders # # @return [String] Rendered template string with filled placeholders filled with the respective values def render_log(template, values) template && values ? format(template, values) : template end # Handle log method exceptions (takes into account the debug mode) # # @param [Exception] exception the exception to handle # # @raise [KeyError] if we work in debug mode # @return [String] Rendered template string with filled placeholders filled with the respective values def handle_template_error(exception, debug = false) raise exception if debug || ENV['INV_LOGGER_DEBUG'] end end
true
621d58835939974da27893c799440d2018445468
Ruby
mwagner19446/wdi_work
/w01/d03/Isaac/tip.rb
UTF-8
279
3.71875
4
[]
no_license
puts "Enter the price of your meal" price = gets.chomp.to_f puts "Enter the tax percentage" tax_rate = gets.chomp.to_f puts "What percentage would you like to tip" tip_rate = gets.chomp.to_f total = price + (price * (tax_rate/100)) + (price * (tip_rate/100)) print total.round(2)
true
e6ce6c582e051e0436f400609c1ac027bec479c0
Ruby
khaning96/Calc
/Calculator.rb
UTF-8
1,275
3.421875
3
[]
no_license
class Calculator def Evaluate (math) #Parentheses if math =~ /\((\d+[+\-\*\/\^]\d+)\)/ #Recursion time math.gsub!(/\(\d+[+\-\*\/\^]\d+\)/, Evaluate($1)) end #Exponents if math =~ /(([0-9]*\.?[0-9]*)\^([0-9]*\.?[0-9]*))/ math.gsub!(/(([0-9]*\.?[0-9]*)\^([0-9]*\.?[0-9]*))/, ($2.to_f**$3.to_f).to_s) end #Multiplication if math =~ /([0-9]*\.?[0-9]*)\*([0-9]*\.?[0-9]*)/ math.gsub!(/([0-9]*\.?[0-9]*)\*([0-9]*\.?[0-9]*)/, ($1.to_f*$2.to_f).to_s) puts $1 puts $2 end #Division if math =~ /((\d+)\/(\d+))/ math.gsub!(/((\d+)\/(\d+))/, ($2.to_f/$3.to_f).to_s) end #Addition if math =~ /((\d+)\+(\d+))/ math.gsub!(/((\d+)\+(\d+))/, ($2.to_f+$3.to_f).to_s) end #Subtraction if math =~ /((\d+)\-(\d+))/ math.gsub!(/((\d+)\-(\d+))/, ($2.to_f-$3.to_f).to_s) end #Stop the recursion if math !~ /[+\-\*\/\^]/ return math end #Final Step Evaluate(math) end end puts "Enter your equation below:" equation = gets Mathematica = Calculator.new puts Mathematica.Evaluate(equation) while equation.upcase != "STOP" puts "Enter your equation or type STOP to exit:" equation = gets.chomp puts Mathematica.Evaluate(equation) end
true
0a6947391134b89ac10da97c50128d3a4110ce5b
Ruby
tell-k/code-snippets
/ruby/map_between.rb
UTF-8
104
3.15625
3
[]
no_license
test = [1, 2, 3, 4, 5] def f(x) x.each_cons(2).map{|y,z| yield(y,z)} end p f(test){|x, y| x + y}
true
99144a6fe780791f8fa4048bd15033c60b5336ec
Ruby
tamietta/phase-0-tracks
/ruby/word-game/word-game.rb
UTF-8
2,472
4.34375
4
[]
no_license
class WordGame attr_reader :secret, :guess_count, :word_state, :guesses # METHOD: initialise word game # INPUT: secret word as string # OUTPUT: WordGame instance def initialize(secret) @secret = secret @guess_count = secret.length @word_state = ["_"] * secret.length @guesses = [] end # METHOD: check if guess correct # INPUT: guessed letter as string # OUTPUT: true or false def guess_correct?(guess) @secret.include? guess end # METHOD: check if guess duplicated # INPUT: guessed letter as string # OUTPUT: true or false def duplicate?(guess) @guesses.include? guess end # METHOD: add guess to tracked guesses if not duplicated # INPUT: guessed letter as string # OUTPUT: array of tracked guesses def add_guess(guess) duplicate?(guess) ? @guesses : @guesses << guess end # METHOD: update remaining guess count # INPUT: N/A # OUTPUT: integer of remaining guesses def update_guess_count @guess_count > 0 ? @guess_count -= 1 : @guess_count end # METHOD: display word state # INPUT: N/A # OUTPUT: word state as string def display_word_state @word_state.join(" ") end # METHOD: update word state with most recently added guess # INPUT: N/A # OUTPUT: updated word state def update_word_state @secret.chars.each_with_index do |letter, idx| @word_state[idx] = letter if @guesses[-1] == letter end @word_state end def game_win? @secret == @word_state.join end end # USER INTERFACE puts "Welcome to the word game!" print "Player #1, please enter a secret word: " secret = gets.chomp.downcase wordgame = WordGame.new(secret) puts "Player #2, the secret word has #{wordgame.secret.length} letters." while wordgame.guess_count > 0 && !wordgame.game_win? do puts "\nSecret Word: " + wordgame.display_word_state puts "You have #{wordgame.guess_count} guesses left." puts "Please enter a guess: " guess = gets.chomp.downcase if wordgame.duplicate?(guess) puts "You have already guessed that letter." # redo elsif wordgame.guess_correct?(guess) puts "Correct guess!" else puts "Sorry, #{guess.inspect} is not in the secret word." wordgame.update_guess_count end wordgame.add_guess(guess) wordgame.update_word_state end if wordgame.game_win? puts "Congratulations! You guessed the secret word!" else puts "You have run out of guesses." puts "Game over." end
true
2283fcb7137e2b28350904b3d78ff2f980326fd2
Ruby
potatoHVAC/hackerrank
/ruby/tut_hello_hackerrank.rb
UTF-8
183
2.578125
3
[]
no_license
#https://www.hackerrank.com/challenges/ruby-hello-world/problem #completed Oct 2017 # Enter your code here. Read input from STDIN. Print output to STDOUT print "Hello HackerRank!!"
true
ef37075cedb8d0a44b110f8238932ec5128fcf5d
Ruby
jcompagni10/rand_gen
/lib/rand_gen.rb
UTF-8
4,132
3.59375
4
[]
no_license
require_relative "binary_min_heap" class RandomGenerator attr_reader :output_queue def initialize(gen_amt) @output_queue = [] @thread_output = gen_amt / 5 @running = false @thread_queues = Array.new(5) { [] } end #start random generator threads and writer thread def start @running = true gen_threads = start_generators writer = start_writer gen_threads.each(&:join) kill_proccess writer.join end #returns frequency for last hundred outputs def get_freq #instantiate with values to ensure consistent ordering freq = { 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0 } #sum up freqencies of each number last_100 = get_last_100 last_100.each do |item| freq[item.to_i] += 1 end # convert to percentage freq.each do |key, val| #divide by real length to handle case of less than 100 outputs freq[key] = val / last_100.length.to_f end freq end private def kill_proccess @running = false end #helper method to return last 100 outputs def get_last_100 last_100 = [] lines = File.readlines('./output.txt').reverse[0...100] lines.each do |line| last_100 << line.chomp.split(", ")[0] end last_100 end ################# # Writer Methods # ################# def start_writer fill_queues setup_heap Thread.new do while @running || [email protected]? ensure_order_and_write end end end #creates a Binary Min Heap to ensure ordered output def setup_heap @heap = BinaryMinHeap.new @thread_queues.each do |queue| @heap.push(queue.shift) end end # ensure all queues remain filled until the generators are done generating # and and the output queue has been emmptied def fill_queues while @thread_queues.any?(&:empty?) && (@running || !@output_queue.empty?) el = @output_queue.shift @thread_queues[el[:thread]] << el if el end end #uses a minheap to ensure ordered data output before writing to disc def ensure_order_and_write fill_queues unless @heap.empty? #extract the minimum element from the heap extracted_el = @heap.extract write_to_disk(extracted_el) #add the next element from the same thread to the heap from_queue = extracted_el[:thread] fill_queues next_el = @thread_queues[from_queue].shift if next_el @heap.push(next_el) end end end #write rand val and timestamp to disc def write_to_disk(output) path = "./output.txt" time = output[:time].strftime("%H:%M:%S:%N") output_string = output[:value].to_s + ", " + time + "\n" File.open(path, 'a') { |file| file.write(output_string) } end ################### # Generator Methods # #################### # Creats 5 seperate writer generator threads def start_generators threads = [] 5.times do |idx| thread = Thread.new { contious_generation } thread[:id] = idx threads << thread end threads end #continious generation for each thread until @thread_ouput is reached def contious_generation @thread_output.times do rand_gen end end #genertes numbers in the specifiied proportions def rand_gen rand100 = rand(1..100) if (0..50).cover?(rand100) output_val = 1 elsif (51..75).cover?(rand100) output_val = 2 elsif (76..90).cover?(rand100) output_val = 3 elsif (91..95).cover?(rand100) output_val = 4 elsif (96..100).cover?(rand100) output_val = 5 end handle_output(output_val) end #handles output random number -- adds to last 100 and output queue def handle_output(val) thread_id = nil while thread_id.nil? thread_id = Thread.current[:id] end p val output = { value: val, thread: thread_id, time: Time.now } @output_queue << output end end # convenience method to run and test code if $0 === __FILE__ File.open('./output.txt', 'w') { |file| file.write("") } random_gen = RandomGenerator.new(5000) random_gen.start p random_gen.get_freq end
true
e6935538efd28ffd2af371fbdb8dc019f248656c
Ruby
Valeri01/PPS-ELSYS-2017-softwares
/domashno_pps.rb
UTF-8
626
2.921875
3
[]
no_license
require 'csv' require 'matrix' mat1 = "./matrix1.csv" mat2 = "./matrix2.csv" csv1 = Array.new csv2 = Array.new csv1_red = 0 csv1_kolona = 0 csv2_red = 0 csv2_kolona = 0 CSV.foreach(mat1) do |rows| csv1 << rows.map(&:to_i) csv1_red =+ 1 csv1_kolona = rows.size end CSV.foreach(mat2) do |rows| csv2 << rows.map(&:to_i) csv2_red =+ 1 csv2_kolona = rows.size end begin if csv1_kolona != csv2_kolona || csv1_red != csv2_red puts "undefined" else (Matrix.rows(csv1) + Matrix.rows(csv2)).symmetric? puts "true" end rescue ExceptionForMatrix::ErrDimensionMismatch puts "false" end
true
892a4ee26628227b4cec703c10fd232d5f85250b
Ruby
BrodyRichardson/WIP
/WIP.rb
UTF-8
1,665
3.84375
4
[]
no_license
def Start item = ["Fountain Drink", "Frozen Drink", "Candy Bars", "Chips", "Hamburger", "Cheeseburger", "Hot Dog", "Chili Dog", "Pop Corn",] itemprice = ["1.00","1.50","1.00","0.50","2.00","2.50","1.50","2.00","0.50"] MenuDisplay(item, itemprice) UserSelection(item,itemprice) Totals() end def MenuDisplay(item, itemprice) $choices = [1,2,3,4,5,6,7,8,9,10] x=1 items = item.zip(itemprice) items.each do |item, itemprice| print x print ".) " print item print ": " print itemprice puts x += 1 end end def UserSelection(item,price1) userchoice = 0 until $choices.include?(userchoice) print "Make a selection" userchoice = gets.to_i end receipt=[] $cost = [] if userchoice == 1 receipt.push(1.00) elsif userchoice == 2 receipt.push(1.50) elsif userchoice == 3 receipt.push(1.00) elsif userchoice == 4 receipt.push(0.50) elsif userchoice == 5 receipt.push(2.00) elsif userchoice == 6 receipt.push(2.50) elsif userchoice == 7 receipt.push(1.50) elsif userchoice == 8 receipt.push(2.00) elsif userchoice == 9 receipt.push(0.50) end x=0 item.each do |i| if userchoice - 1 == x $cost.push(price1(x)) else next end end Totals() end def Totals x = 0 for i in $cost x += i end tax = x * 0.06 total = x + tax print "Subtotal \n", x print "Tax Total \n", tax print "Total Due", total end Start()
true
bea166057a48924a66b8f43609f383dc293e1417
Ruby
G9A2HvK9/tictactoe_techtest
/spec/game_spec.rb
UTF-8
1,038
2.84375
3
[]
no_license
describe Game do subject { Game.new } let (:game0) { Game.new(0) } let (:game1) { Game.new(1)} let (:grid) { subject.grid } it { is_expected.to be_an_instance_of(Game) } it { is_expected.to have_attributes(turn: nil) } it { is_expected.to respond_to(:play_move).with(2).arguments } it "should initialize with a grid, which is an instance of the grid class" do expect(grid).to be_an_instance_of(Grid) end describe "Functionality" do it "allows player to play an X move" do expect {game0.play_move(0,0)}.to change{game0.grid.field[0][0]}.by(1) end it "allows player to play an O move" do expect {game1.play_move(0,0)}.to change{game1.grid.field[0][0]}.by(-1) end it "resets the turn from 0 to 1 after a player has played their move" do expect {game0.play_move(0,0)}.to change{game0.turn}.by(1) end it "resets the turn from 1 to 0 after a player has played their move" do expect {game1.play_move(0,0)}.to change{game1.turn}.by(-1) end end end
true
31ab813903a3fcdd7693af709470e11000d56b64
Ruby
yenisbel/ruby_exercises
/practice-code.rb
UTF-8
10,519
4.15625
4
[]
no_license
require 'rspec/autorun' #By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. #What is the nth prime number? def nth_prime(n) arry_prime = [] value = 2 while arry_prime.size < n if is_prime?(value) arry_prime << value end value += 1 end arry_prime[-1] end def is_prime?(num) if num <= 1 return false end value = 2 while value < num return false if (num % value == 0) value += 1 end true end #Largest Prime Factor #The prime factors of 13195 are 5, 7, 13 and 29. Thus, the largest prime factor of 13195 is 29. #What is the largest prime factor of the number 600851475143 ? def largest_factor(number) result = prime_factors(number).sort result[-1] end def prime_factors(num) value = 1 arry = [] while value < num if is_prime?(value) && (num % value == 0) arry << value end value += 1 end arry end # A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits. # must return true or false depending upon whether the given number is a Narcissistic number. # For example, take 153 (3 digits): 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 def dig_number(number) arr_dig = number.to_s.chars count = arr_dig.size arr_dig.map {|dig| dig.to_i ** count} end def narci_number(num) sum = dig_number(num) return true if num == sum.reduce(:+) end #Let sum_of_proper_divisors(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). #If we run a number, num1, through the function, we will get num2. What if we run num2 through the function? #If sum_of_proper_divisors(num1) == num2 AND sum_of_proper_divisors(num2) == num1, where num1 != num2, #then num1 and num2 are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; #therefore sum_of_proper_divisors(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so sum_of_properdivisors(284) = 220. #Evaluate the sum of all the amicable numbers under 10000. def sum_of_proper_divisors(n) sum_factor1 = factors_numbers(n).reduce(:+) number2 = sum_factor1 sum_factor2 = factors_numbers(number2).reduce(:+) if (n == sum_factor2) && (number2 == sum_factor1) && (n != number2) return "Yes, amicable with #{number2}" else "No" end end def factors_numbers(number) arry_factor = [] (1...number).each do |num| if (number % num == 0) arry_factor << num end end arry_factor end #Count the palindromes. Determine how many palindromes are in a string. #Order of the string must be preserved. A palindrome is a string that is the same #characters reading it forwards as reading it backwards. Anagram must be of length 3 or more and preserve the given order. # EX: is_palindrome?("banana") == 2 # there are 2 "ana" anagrams in this example def is_palindrome?(string) counter = 0 if string.length == 0 || string.length == 1 return counter elsif string[0]==string[-1] is_palindrome?(string[1..-2]) counter += 1 elsif string[0]!=string[-1] is_palindrome?(string[1..-1]) else false end end #You have a hash of keys that are users and values that are hashes of their movie ratings (also in the form of a hash). #The user’s movie ratings are also in a hash of key value pairs of movie names and ratings #from 1 to 10. Create a hash containing the average ratings for each movies generated from the ratings made by all the users in the input. #avg_movie_ratings(user_ratings) == {"Avengers"=>6.8, "Little Mermaid"=>6.0, "Inception"=>8.4, "Independence Day"=>6.5} def avg_movie_ratings(user_ratings) sum_rating = Hash.new(0) counter_hash = Hash.new(0) ave_rating = Hash.new(0) user_ratings.each_value do |hash_value| hash_value.each do |film_name, raiting| sum_rating[film_name] += raiting counter_hash[film_name] += 1 end end sum_rating.each do |movie, sum| ave_rating[movie] = sum.to_f / counter_hash[movie] end ave_rating end def avg_movie_ratings(user_ratings) result_hash = {} user_ratings.each_value do |hash_value| hash_value.each do |film_name, raiting| result_hash[film_name] ||= [0,0] result_hash[film_name][0] += raiting result_hash[film_name][1] += 1 end end result_hash.each do |movie, values| result_hash[movie] = values[0].to_f/values[1] end result_hash end # Define a method that accepts two arguments, a string and an integer. The method should return #a copy of the string with the nth letter removed. def remove_nth_letter(string, n) string[0..n-1] + string[n+1..-1] end # Define a method that chunks an array into a nested array of sub-arrays of length n. The last array may be of #length less than n if the original array's size does not divide evenly by n. # chunk([1,2,3,4,5], 2) => [[1,2], [3,4], [5]] def chunk(array, n) arr_result = [] sub_arr = [] i = 0 while i < array.length num = array[i] if sub_arr.length == n arr_result << sub_arr sub_arr = [] end sub_arr << num i += 1 end arr_result << sub_arr arr_result end # Define a method that multiplies the frequencies of the periods, commas, hyphens, semicolons, question marks, #and exclamation points in a given string and returns the product. If any punctuation does not occur, don't include it #in the product, i.e., don't multiply by zero! def product_punctuation(str) sign_str = "!.,-;?" result = 1 if str == sign_str return result end numbers_sign = str.each_char.count {|elem| sign_str.include?(elem)} result *= numbers_sign end # Translate a sentence into pig-latin! The first consonants go to the end of the word, then add "ay". def pig_latin(sentence) words = sentence.split result = words.map do |word| latinize(word) end result.join(" ") end def latinize(word) vowels = ["a","e","i","o","u"] alpha =('a'..'z').to_a consonants = (alpha - vowels).join if vowels.include?(word[0]) word += "ay" elsif consonants.include?(word[0]) && consonants.include?(word[1]) && consonants.include?(word[2]) word[3..-1]+ word[0..2]+ "ay" elsif consonants.include?(word[0]) && consonants.include?(word[1]) word[2..-1] + word[0..1] + "ay" else word[1..-1] + word[0] + "ay" end end $success_count = 0 $failure_count = 0 def deep_dup(arr) arr.inject([]) { |acc, el| el.is_a?(Array) ? acc << deep_dup(el) : acc << el } end def note_success(returned, invocation, expectation) puts "success: #{invocation} => #{expectation}" $success_count += 1 end def note_failure(returned, invocation, expectation) puts "failure: #{invocation}: expected #{expectation}, returned #{returned}" $failure_count += 1 end def format_args(args) o_args = deep_dup(args) o_args.map! do |arg| arg = prettify(arg) arg.class == Array ? arg.to_s : arg end o_args.join(', ') end def prettify(statement) case statement when Float statement.round(5) when String "\"#{statement}\"" when NilClass "nil" else statement end end def equality_test(returned, invocation, expectation) if returned == expectation && returned.class == expectation.class note_success(returned, invocation, expectation) else note_failure(returned, invocation, expectation) end end def identity_test(returned, invocation, expectation, args) if returned.__id__ == args[0].__id__ equality_test(returned, invocation, expectation) else puts "failure: #{invocation}: You did not mutate the original array!" $failure_count += 1 end end def method_missing(method_name, *args) method_name = method_name.to_s expectation = args[-1] args = args[0...-1] if method_name.start_with?("test_") tested_method = method_name[5..-1] print_test(tested_method, args, expectation) else method_name = method_name.to_sym super end end def print_test(method_name, args, expectation) returned = self.send(method_name, *args) returned = prettify(returned) expectation = prettify(expectation) args_statement = format_args(args) invocation = "#{method_name}(#{args_statement})" method_name.include?("!") ? identity_test(returned, invocation, expectation, args) : equality_test(returned, invocation, expectation) rescue Exception => e puts "failure: #{invocation} threw #{e}" puts e.backtrace.select {|t| !t.include?("method_missing") && !t.include?("print_test")} $failure_count += 1 end puts "\wnth_prime:\n" + "*" * 15 + "\n" test_nth_prime(6, 13) test_nth_prime(10, 29) puts "\wlargest_factor:\n" + "*" * 15 + "\n" test_largest_factor(13195, 29) test_largest_factor(3195, 71) puts "\wnarci_numbe:\n" + "*" * 15 + "\n" test_narci_number(153, true) test_narci_number(1634, true) puts "\wsum_of_proper_divisors:\n" + "*" * 15 + "\n" test_sum_of_proper_divisors(220, "Yes, amicable with 284") test_sum_of_proper_divisors(1184, "Yes, amicable with 1210") puts "\wavg_movie_ratings:\n" + "*" * 15 + "\n" test_avg_movie_ratings({ "Ryan" => {"Avengers" => 8, "Little Mermaid" => 8, "Inception" => 9}, "Clay" => {"Avengers" => 9, "Inception" => 10, "Independence Day" => 7}, "Christine" => {"Avengers" => 9, "Little Mermaid" => 8, "Inception" => 7}, "Jon" => {"Avengers" => 5, "Little Mermaid" => 2, "Inception" => 8}, "David" => {"Avengers" => 3, "Inception" => 8, "Independence Day" => 6} }, {"Avengers"=>6.8, "Little Mermaid"=>6.0, "Inception"=>8.4, "Independence Day"=>6.5}) puts "\wremove_nth_letter:\n" + "*" * 15 + "\n" test_remove_nth_letter("helloworld", 5, "helloorld") test_remove_nth_letter("helloworld", -3, "hellowold") puts "\wchunk:\n" + "*" * 15 + "\n" test_chunk([1,2,3,4,5], 2, [[1,2], [3,4], [5]]) test_chunk([1, 8, 9, 4, "hey", "there"], 2, [[1, 8], [9, 4], ["hey", "there"]]) puts "\wproduct_punctuation:\n" + "*" * 15 + "\n" test_product_punctuation("!.,-;?", 1) test_product_punctuation("There's a certain Slant of light, Winter Afternoons - That oppresses, like the Heft Of Cathedral Tunes - ", 4) puts "\wpig_latin:\n" + "*" * 15 + "\n" test_pig_latin("i speak pig latin", "iay eakspay igpay atinlay") test_pig_latin("throw me an aardvark", "owthray emay anay aardvarkay") puts puts "TOTAL CORRECT: #{$success_count} / #{$success_count + $failure_count}" puts "TOTAL FAILURES: #{$failure_count}" $success_count = 0 $failure_count = 0
true
c818124037afaf29c82737f6e0d4519bb2fcf3c8
Ruby
hackarts/wesabot
/lib/campfire/polling_bot/plugins/airbrake/airbrake/error.rb
UTF-8
1,201
2.625
3
[ "MIT" ]
permissive
module Airbrake class Error include DataMapper::Resource property :id, Serial property :error_id, Integer, :required => true attr_accessor :field # Given a block of XML returned from the Airbrake API, return an # Airbrake::Error object def self.from_xml(xml) field = {} xml.xpath('./*').each do |node| content = node.content # convert to proper ruby types type = node.attributes['type'] && node.attributes['type'].value case type when "boolean" content = content == "true" when "datetime" content = Time.parse(content) when "integer" content = content.to_i end key = node.name.tr('-','_') field[key.to_sym] = content end error = new() error.field = field error.error_id = field[:id] return error end def summary "#{@field[:error_message]} at #{@field[:file]}:#{@field[:line_number]}" end def [](key) key = key.to_s.tr('-','_').to_sym @field[key] end def eql?(other) self.error_id.eql?(other.error_id) end def hash self.error_id.hash end end end
true
80c7c9b3cfe8e5297aec123c25542b90914dba28
Ruby
theachyutkadam/ruby_learning_basic
/school_operation/school.rb
UTF-8
3,738
3.765625
4
[]
no_license
class Classroom @@classroom = [] def process_classroom_creation print "How many class are you like to Add : " number_of_class = gets.chomp.to_i $school_count = @@classroom i = 0 while i < number_of_class print "Enter your #{i+1} class name : " c_name = gets.to_s.capitalize @@classroom << c_name i +=1 end choice_messages_of_classroom end def choice_messages_of_classroom puts "You Add Classroom successfully" puts " 1 Display ClassRoom : " puts " 2 See Menu list : " puts " 3 Exit : " print "Enter Your Choice : " choice_value = gets.chomp.to_i operation_on_variable(choice_value) end def operation_on_variable(choice_value) n= choice_value case n when 1 display_class when 2 obj_school=School.new obj_school.select_value_for_next_operation when 3 puts "Thanks You" else if n >=4 || n <=0 puts "Wrong Choice! Plz Enter the 1 to 4 " end end end def display_class if @@classroom.nil? puts "Your Class Details : " @@classroom.each {|cls| puts "#{cls}"} else puts "Enter first classroom details: " process_classroom_creation end end end class Student @@student_info = [] def create_student puts "Add Student Details : " print "Select Student ClassRoom using 1 To #{$school_count.count} : " classroom_count = gets.to_i classroom_count = classroom_count-1 classroom = $school_count[classroom_count] print "Enter Student Name : " stud_name = gets print "Enter Student Age : " stud_age = gets.to_i print "Enter Student Mark(%) : " stud_mark = gets.chomp.to_f stud_info_hash = {stud_name: stud_name, stud_age: stud_age, stud_mark: stud_mark, classroom: classroom} @@student_info.push(stud_info_hash) @@student_info.each {|attri, val| puts " #{attri} = #{val}"} School.new.select_value_for_next_operation end def show_student_info if @@student_info.nil? puts "Enter firsts Student Information : " obj_student.create_student else puts " 1 Display All Student : " puts " 1 Display classroom student : " puts " 2 See Menu List : " puts " 3 Exit : " print "Enter Your Choice : " stud_info = gets.chomp.to_i operation_on_student_list(stud_info) end end def operation_on_student_list(stud_info) n = stud_info case n when 1 @@student_info.each {|attri, val| puts " #{attri} = #{val}"} when 2 select_value_for_next_operation when 3 puts "Thanks You" else if n >=4 || n <=0 puts "Wrong Choice! Plz Enter the 1 to 3 " end end end end class School def school_info print "Enter your school name : " $school_name = gets puts "The School Name is : #{$school_name.capitalize}" select_value_for_next_operation end def select_value_for_next_operation puts " 1 Add New ClassRoom : " puts " 2 Add New Student : " puts " 3 List of ClassRoom : " puts " 4 List of Student : " puts print "Enter Your Choice : " selected_choice = gets.chomp.to_i operation_on_selected_number(selected_choice) end def operation_on_selected_number(selected_choice) n = selected_choice obj_class = Classroom.new obj_student = Student.new case n when 1 obj_class.process_classroom_creation when 2 obj_student.create_student when 3 obj_class.display_class when 4 obj_student.show_student_info else if n >=4 || n <=0 puts "Wrong Choice! Plz Enter the 1 to 4 " end end end end obj_school = School.new obj_school.school_info
true
d7eafa27bd393473fdd1cca1553ceee9970338cc
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/robot-name/697b3defa5cd44f487ca5df155aafcdc.rb
UTF-8
392
3.265625
3
[]
no_license
class Robot ALPHABET = ('A'..'Z').to_a NUMERIC = (1..9).to_a def reset @last_name = @name @name = nil end def name @name ||= generate_name end private def generate_name alph = ALPHABET.dup.shuffle[0,2].join num = NUMERIC.dup.shuffle[0,3].join result = "#{alph}#{num}" result = generate_name if result == @last_name result end end
true