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
5f4aab5464314b08bb8226ea3d81dfa49bcf0b43
Ruby
baxtjm/my-first-repo
/Day 3/tip_calculator_hackathon.rb
UTF-8
363
3.546875
4
[]
no_license
puts "What's your subtotal" subtotal = gets.to_f puts "What would you like to tip" gratuity_percentage = gets.to_f puts "How many people did you eat with?" num_people = gets.to_f gratuity = subtotal * gratuity_percentage total_bill = subtotal + gratuity my_share = total_bill / num_people puts "The total bill is #{total_bill}" puts "I need to pay #{my_share}"
true
b74cda036bcdc2439b26a330cd61f17c9a9a5804
Ruby
pfranciskoe/pk_aa_cw
/w4d1/tic_tac_toe_supercomp/lib/tic_tac_toe_node.rb
UTF-8
1,897
3.578125
4
[]
no_license
require_relative 'tic_tac_toe' class TicTacToeNode attr_reader :board, :next_mover_mark, :prev_move_pos def initialize(board, next_mover_mark, prev_move_pos = nil) @board = board # instance of Board, has 2D array as board inside @next_mover_mark = next_mover_mark @prev_move_pos = prev_move_pos end def losing_node?(evaluator) #self is a node return false if self.board.tied? return true if self.board.over? && self.board.winner != evaluator return false if self.board.over? && (self.board.winner == evaluator || self.board.winner == nil) if self.next_mover_mark == evaluator self.children.all? do |child| child.losing_node?(evaluator) end else self.children.any? do |child| child.losing_node?(evaluator) end end end def winning_node?(evaluator) return true if self.board.over? && self.board.winner == evaluator return false if self.board.over? && (self.board.winner != evaluator || self.board.winner == nil) if self.next_mover_mark == evaluator self.children.all? do |child| child.winning_node?(evaluator) end else self.children.any? do |child| child.winning_node?(evaluator) end end end # This method generates an array of all moves that can be made after # the current move. def children new_children = [] @board.rows.each.with_index do |row, i| row.each.with_index do |ele, j| if @board.empty?([i, j]) new_board = @board.dup new_board[[i,j]] = @next_mover_mark if @next_mover_mark == :x mark = :o else mark = :x end new_child = TicTacToeNode.new(new_board, mark, [i,j]) new_children << new_child end end end new_children end end
true
ad95c3b37a0333ccb82a5f9de6c14e9c5cbd6626
Ruby
mijkami/ruby_newb
/exo_13.rb
UTF-8
132
3.171875
3
[]
no_license
puts "Bonjour, quelle est ton année de naissance ?" i= gets.chomp.to_i loop do i += 1 puts i if i == 2018 break end end
true
2c201b4308903d0711b44cf68610aba2d6b619da
Ruby
jebitok-dev/dsa
/find-the-duplicates-jebitok-dev/challenge.rb
UTF-8
384
3.34375
3
[]
no_license
def duplicates(arr1, arr2) new_arr1 = *arr1 new_arr2 = *arr2 new_arr1.each do |i| if new_arr2.include?(i) new_arr2.delete_at(new_arr2.find_index(i)) end end new_arr2.sort! end p duplicates([203, 204, 205, 206, 207, 208, 203, 204, 205, 206], [203, 204, 204, 205, 206, 207, 205, 208, 203, 206, 204, 205, 206]) # => [204, 205, 206]
true
7115bd9fb6c3e877b13bc1c81170829ce0c3b281
Ruby
dbilek/gig
/lib/gig/greper.rb
UTF-8
3,335
3.03125
3
[]
no_license
require "net/http" require "open-uri" require 'json' ITEMS_PER_PAGE = 50 API_URL = "https://api.github.com" module Gig class Greper attr_reader :options attr_accessor :uri def initialize(options = []) @options = options url = API_URL + "/search/repositories" @uri = generate_uri(url, options) end def grep begin response = get_http_response(uri) response_parsed = JSON.parse(response.body) response_message = response_parsed["message"] raise StandardError.new(response_message) unless response.code == "200" items = response_parsed["items"] directory_name = options.join("-") images_before = count_files(directory_name) make_storage_directory(directory_name) items.each do |item| avatar_url = item["owner"]["avatar_url"] download_image(avatar_url, directory_name) print "." end show_download_info(images_before, directory_name) handle_pagination(response["link"]) rescue StandardError => error puts "An error occurred, please check parameters you typed or contact technical support." puts "Error message: " + error.inspect end end private def generate_uri(api_url, options) query_option = options.any? ? options.join("+") : "" search_url = api_url + "?q=#{query_option}&per_page=#{ITEMS_PER_PAGE}" URI.parse(search_url) end def get_http_response(uri) Net::HTTP.get_response(uri) end def make_storage_directory(directory_name) Dir.mkdir directory_name unless Dir.exist?(directory_name) end def download_image(avatar_url, directory_name) raise StandardError.new("Missing storage directory") unless Dir.exist?(directory_name) avatar_name = "avatar_" + avatar_url.split("/").last.split("?").first + ".jpg" return if File.exist?("#{directory_name}/#{avatar_name}") open(avatar_url) do |image| File.open("#{directory_name}/#{avatar_name}", "wb") do |file| file.write(image.read) end end end def show_download_info(images_before, directory_name) all_images = count_files(directory_name) downloaded_images = (images_before - all_images).abs puts puts "Total: #{all_images} images" if downloaded_images > 0 puts "Downloaded #{downloaded_images} images." else puts "There's no new downloaded images." end puts "----------------------------------------------------------" end def count_files(directory_name) Dir["#{directory_name}/*"].length end def handle_pagination(response_link) puts "Do want to continue with next page? Type 'yes' or 'no'" user_answer = STDIN.gets.strip if user_answer == "yes" pagination_links = pagination_links(response_link) next_page_url = pagination_links["next"] @uri = URI.parse(next_page_url) self.grep end end def pagination_links(response_link) links = {} response_link.split(',').each do |link| link.strip! parts = link.match(/<(.+)>; *rel="(.+)"/) links[parts[2]] = parts[1] end links end end end
true
74e90bb722c317e5b67adcedf1d3428fc1b244dc
Ruby
ju-to-sh/rsv_app
/reservation.rb
UTF-8
2,099
3.296875
3
[]
no_license
class Reservation attr_accessor :id, :user_name, :datetime, :contents, :created_at def initialize(id, user_name, datetime, contents, created_at) @id = id @user_name = user_name @datetime = datetime @contents = contents @created_at = created_at end def self.valid_name name = gets.chomp.strip while name == "" puts "無効な名前です。もう一度入力してください" printf "予約者名:" name = gets.chomp.strip end name end def self.valid_year year = gets.chomp.to_i while year < Date.today.year puts "予約年が過ぎています。もう一度入力してください" printf "予約年(YYYY):" year = gets.chomp.to_i end year end def self.valid_month month = gets.chomp.to_i until 0 < month && month <= 12 puts "1~12を入力してください" printf "予約月(MM):" month = gets.chomp.to_i end month end def self.valid_day(year, month) initial_day = gets.chomp.to_i days_of_month = Date.new(year, month, -1).mday day = reenter_of_day(initial_day, days_of_month) end def self.valid_hour hour = gets.chomp.to_i until 0 <= hour && hour <= 23 puts "0~23を入力してください" printf "予約時間(時 HH):" hour = gets.chomp.to_i end hour end def self.valid_minutes minutes = gets.chomp.to_i until minutes == 0 || minutes == 30 puts "0もしくは30を入力してください" printf "予約時間(分 MM):" minutes = gets.chomp.to_i end minutes end def self.valid_contents contents = gets.chomp.strip while contents == "" puts "無効な予約内容です。もう一度入力してください" printf "予約内容:" contents = gets.chomp.strip end contents end def self.reenter_of_day(day, days_of_month) until 0 < day && day <= days_of_month puts "1~#{days_of_month}を入力してください" printf "予約日(DD):" day = gets.chomp.to_i end day end end
true
b2b68b70dc3f43a26a4c226c9c3f5201a04908f9
Ruby
amiel/quantum-delta
/lib/quantum-delta/invalid_delta_combinations.rb
UTF-8
521
2.953125
3
[ "MIT" ]
permissive
module QuantumDelta class InvalidDeltaCombinations attr_reader :period def initialize(period) @period = period end def invalid_combinations (0..(period - 1)).map { |n| combinations_for(n) }.flatten end private def combinations_for(n) incrementer = BaseIncrementer.new(period, n) incrementer.all.select { |string| sum_string(string) == period - n } end def sum_string(string) string.split(//).map(&:to_i).inject(0) { |a, e| a + e } end end end
true
c9b5961ed34dcc8085213317113e9c5a01de8e1e
Ruby
tarujkhan/tic-tac-toe-rb-online-web-sp-000
/lib/tic_tac_toe.rb
UTF-8
4,245
3.71875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def display_board(board) divider = "|" lines = "-----------" puts " #{board[0]} #{divider} #{board[1]} #{divider} #{board[2]} " puts "#{lines}" puts " #{board[3]} #{divider} #{board[4]} #{divider} #{board[5]} " puts "#{lines}" puts " #{board[6]} #{divider} #{board[7]} #{divider} #{board[8]} " end def position_taken?(board, index) # puts display_board(board) # if board[index] == " " # false # elsif board[index] == "" # false # elsif board[index] == nil # false # elsif board[index] == "X" || board[index] == "O" # true end def valid_move?(board, index) #binding.pry if !position_taken?(board, index) && index.between?(0, 8) true else false end end def move(board, index, token) board[index] = token end def input_to_index(user_input) changed_input = user_input.to_i changed_input -= 1 return changed_input end def turn(board) puts "Please enter 1-9:" user_input = gets.strip index = input_to_index(user_input) if valid_move?(board, index) move(board, index, current_player(board)) display_board(board) else turn(board) #user_input = gets.strip end end def turn(board) puts "Please enter 1-9:" user_input = gets.strip index = input_to_index(user_input) while !valid_move?(board, index) puts "Please enter 1-9:" user_input = gets.strip index = input_to_index(user_input) end move(board, index, current_player(board)) #move is valid display_board(board) # else # turn(board) #user_input = gets.strip end # def turn(board) # puts "Please enter 1-9:" # user_input = gets.strip # index = input_to_index(user_input) # if !valid_move?(board, index) # # user_input = gets.strip # turn(board) # else # move(board, index, token = "X") # display_board(board) # end # end # def play(board) # player_turn = 0 # while player_turn < 9 # turn(board) # player_turn += 1 # end # end require 'pry' # Helper Method def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [0,4,8], [1,4,7], [2,4,6,], [2,5,8]] def won?(board) #binding.pry WIN_COMBINATIONS.each do |wc| #binding.pry win_index_1 = wc[0] win_index_2 = wc[1] win_index_3 = wc[2] position_1 = board[win_index_1] position_2 = board[win_index_2] position_3 = board[win_index_3] if position_1 == "X" && position_2 == "X" && position_3 == "X" return wc end end false end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [0,4,8], [1,4,7], [2,4,6,], [2,5,8]] def won?(board) #binding.pry WIN_COMBINATIONS.each do |wc| #binding.pry win_index_1 = wc[0] win_index_2 = wc[1] win_index_3 = wc[2] position_1 = board[win_index_1] position_2 = board[win_index_2] position_3 = board[win_index_3] if position_1 == "X" && position_2 == "X" && position_3 == "X" || position_1 == "O" && position_2 == "O" && position_3 == "O" return wc end end false end def full?(board) board.all? do |brd| brd == "X" || brd == "O" end end def draw?(board) if !won?(board) && full?(board) return true # elsif !won?(board) && !full?(board) # return false else won?(board) return false #else end end def over?(board) if won?(board) || draw?(board) || full?(board) return true else return false end end def winner(board) if won?(board) board[won?(board)[0]] else nil end end def current_player(board) if turn_count(board) % 2 == 0 #if board % 2 == 0 "X" else "O" end end def turn_count(board) counter = 0 board.each do |brd| if brd == "X" || brd == "O" counter += 1 brd end end counter end def play(board) input = gets.chomp turn(board) until over?(board) #turn #end if won?(board) puts "Congratulations #{winner(board)}!" elsif draw?(board) puts "Cat\'s Game!" end end
true
96b3ca7656965ef0ff004f56a9971fb6d5ebad83
Ruby
Itsindigo/boris
/spec/bike_spec.rb
UTF-8
520
2.5625
3
[]
no_license
require 'bike' RSpec.describe Bike do bike = described_class.new it {is_expected.to respond_to(:working?)} it "should report the bike's working status" do expect(bike.working?).to eq("Working") end it "should change the working status of a bike to false" do expect{bike.report_broken}.to change{bike.bike_status}.from("Working").to("Broken") end it "should change the working status of bike to in transit" do expect{bike.in_transit}.to change{bike.bike_status}.to("In Transit") end end
true
0c20aa735314ff661f00ed37fb9957bde0b1b87f
Ruby
citelao/3am-Jazz-Band
/scratch/PlayerTest.rb
UTF-8
1,888
3.21875
3
[]
no_license
require 'unimidi' require_relative '../Factories/ChordFactory' require_relative '../Cues/Rest' require_relative '../Player' require_relative '../Instrument' require_relative '../Cue' tempo = 120 #bpm $quarter = 60.0 / tempo $eighth = $quarter / 2 $triplet = $quarter / 3 puts $quarter, $eighth, $triplet # Prompt the user to select an output output = UniMIDI::Output.gets piano = Instrument.new() bass = Instrument.new() player = Player.new(output, [piano, bass]) d = "f#3 a3 c#4 e4" # missing d3 g = "b3 d4 f#4 a4" # missing g3 a = "c#4 e4 g4 b4" # missing a3 def jazz(chord) [ first(chord), second(chord) ].flatten end def first(chord) [ ChordFactory.chordFromNoteNames(chord, 75, $quarter).cues, Rest.new(2 * $triplet).cues, ChordFactory.chordFromNoteNames(chord, 50, 1 * $triplet).cues, Rest.new(2 * $quarter).cues ].flatten end def second(chord) [ Rest.new(2 * $triplet).cues, ChordFactory.chordFromNoteNames(chord, 70, $quarter).cues, Rest.new(1 * $triplet).cues, ChordFactory.chordFromNoteNames(chord, 50, 1 * $triplet).cues, Rest.new($quarter + 2 * $triplet).cues ].flatten end piano.add([Cue.new([[0xFF, 0, 0]], 0)]) # reset 40.times do |i| piano.add(jazz(d)) piano.add(jazz(g)) piano.add(jazz(d)) piano.add(first(a)) piano.add(second(g)) piano.add(jazz(d)) 8.times do bass.add(ChordFactory.chordFromNoteNames("d3", 70, $quarter, 2).cues) end 8.times do bass.add(ChordFactory.chordFromNoteNames("g2", 70, $quarter, 2).cues) end 8.times do bass.add(ChordFactory.chordFromNoteNames("d3", 70, $quarter, 2).cues) end 4.times do bass.add(ChordFactory.chordFromNoteNames("a2", 70, $quarter, 2).cues) end 4.times do bass.add(ChordFactory.chordFromNoteNames("g2", 70, $quarter, 2).cues) end 8.times do bass.add(ChordFactory.chordFromNoteNames("d3", 70, $quarter, 2).cues) end end # puts player.cues player.run
true
8ab21e44b3376f88149906a3d625999729274ce1
Ruby
andistuder/ruby-hack
/task.rb
UTF-8
218
2.859375
3
[]
no_license
# a simple ruby task, run like this: # API_KEY=<MYKEY> bundle exec ruby task.rb Hello World require_relative 'lib/translator' input = ARGV.join(" ") translator = Translator.new puts translator.translate(input)
true
977c6b677871192f122b8d53716fe06ea18a99e1
Ruby
mrnugget/ttf2eot
/lib/ttf2eot.rb
UTF-8
1,403
3.140625
3
[]
no_license
module TTF2EOT # Public: Converts a TTF font file to an EOT font. # # input - the input TTF font as a String (representing a path) or IO object # (responding to #read). # output - the output destination as a String (representing a path) or IO # object where the EOT font will be written. # # Examples: # # TTF2EOT.convert("input.ttf", "output.eot") # # => #<File:output.eot> # # input = StringIO.new(File.read("input.ttf")) # output = StringIO.new # TTF2EOT.convert(input, output) # # => #<StringIO:0x007f815a83a210> # # Returns the output IO object. # Raises TTF2EOT::ConversionError if the input data is invalid. def convert(input, output) input = File.open(input, "rb") unless input.respond_to?(:read) output = File.open(output, "wb") unless output.respond_to?(:write) source = input.read header = eot_header(source) output.write header output.write source output.flush output end module_function :convert # Internal: Get an EOT header for a TTF font. # # font_data - a String containing valid TTF font data. # # Returns a String with the EOT header for the input data. # Raises TTF2EOT::ConversionError if the input data is invalid. def eot_header(font_data) raise NotImlementedError, "this method is defined by the ttf2eot c extension" end end require "ttf2eot_ext"
true
623d2230c5e0ce13dcf1d17fc0a6d8214a1af939
Ruby
blambeau/yargi
/examples/random.rb
UTF-8
594
2.71875
3
[ "MIT" ]
permissive
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'yargi' COLORS = ["blue", "red", "yellow", "green"] # We build a random graph with approximately 20 vertices # and 60 edges (will be stripped by default). Each vertex # will have a color picked at random. graph = Yargi::Digraph.random(20,60) do |r| r.vertex_builder = lambda{|v,i| v[:color] = COLORS[Kernel.rand(COLORS.size)] } end # The label of each vertex will be its depth Yargi::Decorate::DEPTH.execute(graph) graph.vertices.add_marks{|v| {:label => v[:depth]}} # Print as a dot graph puts graph.to_dot
true
43d605335382f454af2f977715df56af8ccfe542
Ruby
jordanmaguire/frontier_generators
/lib/frontier/attribute/validation/uniqueness.rb
UTF-8
1,475
2.703125
3
[]
no_license
class Frontier::Attribute::Validation::Uniqueness < Frontier::Attribute::Validation # attribute: name # key: "uniqueness" # args: true OR {scope: :user_id} def initialize(attribute, key, args) super # For a scope: argument, ensure the value is :value if args.is_a?(Hash) && args["scope"] && args["scope"].is_a?(String) args["scope"] = args["scope"].include?(":") ? args["scope"] : ":" + args["scope"] end end def as_spec if args.present? raw = <<-STRING describe "validating uniqueness" do subject { FactoryGirl.create(#{attribute.model.name.as_symbol}) } it { should #{full_assertion} } end STRING raw.rstrip else raise(ArgumentError, "uniqueness validation must have at least one argument or be 'true'") end end private def basic_assertion "validate_uniqueness_of(#{attribute.as_symbol})" end def additional_spec_options if args.present? && args.is_a?(Hash) additional_spec_options_collection end end # It is possible to have multiple. EG: # minimum: 0 # maximum: 100 # We should build: ["is_at_least(0)", "is_at_most(100)"] def additional_spec_options_collection args.collect do |key, value| case key.to_s when "scope" "scoped_to(#{value})" else raise(ArgumentError, "Unknown property: #{key}") end end end def full_assertion [basic_assertion, additional_spec_options].compact.join(".") end end
true
fe44cb1c34ff51f259699455192a8375f744bc1b
Ruby
cigraphics/ArchiveBot
/cogs/log_db.rb
UTF-8
1,249
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'analysand' class LogDb def initialize(uri, credentials) @db = Analysand::Database.new(uri) @credentials = credentials end ## # Given an array of the form # # [JSON string, numeric, ..., JSON string, numeric] # # and an amplified job, this method JSON-parses all strings, generates # CouchDB documents of the form # # { "_id": (string), # "score": (score), # "log_data": (JSON object) # } # # and then adds those documents to the database identified by the given URI. # # Raises an Analysand::BulkOperationFailed if the database write fails. # Raises a JSON::ParserError if any of the log strings cannot be interpreted # as JSON. def add_entries(entries, job) return if entries.empty? docs = entries.map do |entry, score| make_doc(entry, score, job) end @db.bulk_docs!(docs, @credentials) end private def make_doc(entry, score, job) uuid = "#{job.ident}:#{job.started_at}:#{score}" { '_id' => uuid, 'ident' => job.ident, 'log_entry' => JSON.parse(entry), 'score' => score, 'started_at' => job.started_at, 'started_by' => job.started_by, 'url' => job.url, 'version' => 1 } end end
true
6c5831105c4211f35a93f1f58a15b628bfced392
Ruby
kjferris/intro_to_programming
/exercises/chap4_ex3.rb
UTF-8
259
3.921875
4
[]
no_license
puts "please enter a number between 0 and 100" num = gets.chomp.to_i if num > 100 || num < 0 puts "Your number is not between 0 and 100" elsif num >= 51 puts "Your number is between 50 and 100" else num <= 0 puts "Your number is between 0 and 50" end
true
449603e8ef628d97be036eb7f6e1108071f8fbab
Ruby
bikeonastick/snapdragon
/spec/lib/snapdragon/path_spec.rb
UTF-8
2,918
2.6875
3
[ "MIT" ]
permissive
require_relative '../../../lib/snapdragon/path' describe Snapdragon::Path do describe "#initialize" do it "stores the raw path in an instance variable" do path = Snapdragon::Path.new('some/path:423') path.instance_variable_get(:@raw_path).should eq('some/path:423') end context "when given a path and line number" do it "stores the path in an instance variable" do path = Snapdragon::Path.new('some/path:423') path.instance_variable_get(:@path).should eq('some/path') end it "stores the line number in an instance variable" do path = Snapdragon::Path.new('some/path:423') path.instance_variable_get(:@line_number).should eq(423) end end context "when given a path" do it "stores teh path in an instance variable" do path = Snapdragon::Path.new('some/path') path.instance_variable_get(:@path).should eq('some/path') end end end describe "#spec_files" do let(:path) { Snapdragon::Path.new('some/path') } context "when does NOT exist" do before do path.stub(:exists?).and_return(false) end it "returns an empty array" do path.spec_files.should eq([]) end end context "when does exist" do before do path.stub(:exists?).and_return(true) end context "when is a directory" do before do path.stub(:is_a_directory?).and_return(true) end it "constructs a spec directory" do Snapdragon::SpecDirectory.should_receive(:new).and_return(stub.as_null_object) path.spec_files end it "returns the spec files recursively found in the spec directory" do spec_files = stub spec_dir = stub(spec_files: spec_files) Snapdragon::SpecDirectory.should_receive(:new).and_return(spec_dir) path.spec_files.should eq(spec_files) end end context "when is NOT a directory" do before do path.stub(:is_a_directory?).and_return(false) end it "constructs a spec file" do Snapdragon::SpecFile.should_receive(:new) path.spec_files end it "returns an array containing a newly constructed spec file" do spec_file = stub Snapdragon::SpecFile.stub(:new).and_return(spec_file) path.spec_files.should eq([spec_file]) end end end end describe "#has_line_number?" do context "when the given raw path has a line number" do it "returns true" do path = Snapdragon::Path.new('some/path:234') path.has_line_number?.should be_true end end context "when the given raw path does NOT have a line number" do it "returns false" do path = Snapdragon::Path.new('some/path') path.has_line_number?.should be_false end end end end
true
debb7c608957429d26ff9eec33e023aa7a861bc1
Ruby
CinnaBomb/knight-traversal
/knight.rb
UTF-8
2,059
3.78125
4
[]
no_license
class Knight attr_accessor :position, :parent, :children def initialize(position=[0,0], parent = nil) @position = position @parent = parent @children = possible_moves_for(position) end #returns array of possible moves for position #only used to create children of nodes def possible_moves_for(position) possible_moves = [] x = position[0] y = position[1] possible_moves.push( [x+1, y+2], [x-2, y-1], [x+2, y-1], [x+2, y+1], [x-2, y+1], [x-1, y-2], [x-1, y+2], [x+1, y-2]) possible_moves end #returns array of valid nodes from children(possible_moves) at position def valid_moves_for(position, possible_moves) valid = [] parent_node = self possible_moves.each do |new_position| valid << Knight.new(new_position, parent_node) if valid_move?(new_position) == true end valid end #check whether move is on board def valid_move?(new_position) if (new_position[0] >=0 && new_position[0] <=7) && (new_position[1] >=0 && new_position[1] <=7) return true end false end #returns array of the node path def path(node) arr = [node.position] while node.parent != nil node = node.parent arr.unshift(node.position) end arr end #returns path of node def knight_moves(start_pos, end_pos) self.position = start_pos node = self if node.position == end_pos return path(node) end parent_node = self nodes = valid_moves_for(start_pos, self.children) until nodes.empty? node = nodes.shift if node.position == end_pos return path(node) else parent_node = node valid_moves_for(node.position, node.children).each do |n| n.parent = parent_node nodes << n end end end end end # k = Knight.new # puts k.knight_moves([3,3],[3,3]).inspect # puts k.knight_moves([0,0],[1,2]).inspect # puts k.knight_moves([0,0],[3,3]).inspect # puts k.knight_moves([3,3],[0,0]).inspect # puts k.knight_moves([0,0],[7,7]).inspect # puts k.knight_moves([3,3],[4,3]).inspect #k.knight_moves([3,3],[4,3]) #=>[3,3], [4,5], [2,4], [4,3]
true
7625d5a8eabfc6b5baeec20c6426312a14c9054c
Ruby
chrisortman/configurious
/lib/configurious/transformer.rb
UTF-8
1,112
2.703125
3
[ "MIT" ]
permissive
require 'configurious/operations' module Configurious class Transformer def initialize @steps = [] end def add(path, value) op = Configurious::Operations::Add.new op.path = path op.content = value @steps << op end def replace(path, with:, part: nil) r = Configurious::Operations::Replace.new r.path = path r.part = part r.content = with @steps << r end def change(path, to:) r = Configurious::Operations::Replace.new r.path = path r.content = to @steps << r end def update(path, &block) r = Configurious::Operations::Update.new r.path = path r.applies(&block) @steps << r end def remove(path) r = Configurious::Operations::Remove.new r.path = path @steps << r end def change_key(path, to:) r = Configurious::Operations::ChangeKey.new r.path = path r.content = to @steps << r end def apply(content) @steps.each do |t| t.apply(content) end content end end end
true
f557652094cbd6b4855e06bbcd6b3355ccb1a811
Ruby
hiltonatgithub/looping-while-until-001-prework-web
/lib/until.rb
UTF-8
219
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def using_until levitation_force = 6 # Continued own until zero reached. until levitation_force == 10 print "Wingardium Leviosa\n" levitation_force += 1 end end
true
bc32b98026cd206fa78fad13ce6af857b62acaf1
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/strain/616befc0e49441158f3ff829a86f0f95.rb
UTF-8
321
3.265625
3
[]
no_license
class Array def method_missing(method_name, &block) result = [] i = 0 while i < self.length case method_name when :keep result << self[i] if block.call(self[i]) when :discard result << self[i] if not(block.call(self[i])) end i += 1 end result end end
true
1ce926b9d3eca2b73fd28df6eedd91d17c6196f9
Ruby
overtakermtg/Experiencia14
/Ejercicio2.rb
UTF-8
792
4.09375
4
[]
no_license
# Dado el arreglo nombres = ["Violeta", "Andino", "Clemente", "Javiera", "Paula", "Pia", "Ray"] # Se pide: # 1. Extraer todos los elementos que excedan mas de 5 caracteres utilizando el método # .select. # 2. Utilizando .map crear una arreglo con los nombres en minúscula. # 3. Utilizando .select para crear un arreglo con todos los nombres que empiecen con P. # 4. Utilizando .map crear un arreglo único con la cantidad de letras que tiene cada # nombre. # 5. Utilizando .map y .gsub eliminar las vocales de todos los nombres. print nombres.select{|i| i.size() > 5} print "\n" print nombres.map{|i| i.downcase()} print "\n" print nombres.select{|i| i[0] == "P"} print "\n" print nombres.map{|i| [i.size()] } print "\n" print nombres.map{|i| i.gsub(/[aeiou]/, '*') } print "\n"
true
14d656cb77a76ac7953b583904986e49b7dbbde2
Ruby
reproio/remote_syslog_sender
/lib/remote_syslog_sender/sender.rb
UTF-8
2,125
2.5625
3
[ "MIT" ]
permissive
require 'socket' require 'syslog_protocol' module RemoteSyslogSender class Sender # To suppress initialize warning class Packet < SyslogProtocol::Packet def initialize(*) super @time = nil end end attr_reader :socket attr_accessor :packet def initialize(remote_hostname, remote_port, options = {}) @remote_hostname = remote_hostname @remote_port = remote_port @whinyerrors = options[:whinyerrors] @packet_size = options[:packet_size] || 1024 @packet = Packet.new local_hostname = options[:hostname] || options[:local_hostname] || (Socket.gethostname rescue `hostname`.chomp) local_hostname = 'localhost' if local_hostname.nil? || local_hostname.empty? @packet.hostname = local_hostname @packet.facility = options[:facility] || 'user' @packet.severity = options[:severity] || 'notice' @packet.tag = options[:tag] || options[:program] || "#{File.basename($0)}[#{$$}]" @socket = nil end def transmit(message, packet_options = nil) message.split(/\r?\n/).each do |line| begin next if line =~ /^\s*$/ packet = @packet.dup if packet_options packet.tag = packet_options[:program] if packet_options[:program] packet.hostname = packet_options[:local_hostname] if packet_options[:local_hostname] %i(hostname facility severity tag).each do |key| packet.send("#{key}=", packet_options[key]) if packet_options[key] end end packet.content = line send_msg(packet.assemble(@packet_size)) rescue if @whinyerrors raise else $stderr.puts "#{self.class} error: #{$!.class}: #{$!}\nOriginal message: #{line}" end end end end # Make this act a little bit like an `IO` object alias_method :write, :transmit def close @socket.close end private def send_msg(payload) raise NotImplementedError, "please override" end end end
true
24a263d9662a1c9bce6c8bbb1d562a51a53bbc0f
Ruby
learn-co-students/nyc-chi-042621
/0629-1-crud/db/seeds.rb
UTF-8
955
3.15625
3
[]
no_license
# #CREATE# # # Model.create(hash_of_attributes) # inst = Model.new(hash_of_attributes) # inst.save unf = Book.create( name: "Series of Unfortunate Events", author: "Lemony Snicket", page_count: rand(100)) fortunate = Book.create( name: "Series of Fortunate Events", author: "Lime Snicket", page_count: rand(100)) evt = Book.new( name: "Series of Events", author: "Orangey Snicket", page_count: rand(100)) evt.save # #READ# # # Model.find(id) -> Instance OR Error Out # Model.find_by(hash_of_attributes) -> Instance OR nil # Model.where(hash_of_attributes) -> Array of instances OR an empty array # #UPDATE# # # inst = Model.find(id) # inst.update(hash_of_attributes) fort = Book.find_by(name: "Series of Fortunate Events") fort.update(page_count: 1000, author: "Lime Snickers") # #DELETE/DESTROY# # # inst = Model.find(id) # inst.destroy twilight = Book.create(name: "Twilight", author: "Stephanie Meyers", page_count: 100) twilight.destroy
true
486e0620add5e32a4c0ace08295c6e7149d69568
Ruby
dotnotation/hairless_furever
/lib/hairless_furever/cli.rb
UTF-8
2,535
3.5625
4
[ "MIT" ]
permissive
class HairlessFurever::CLI def call #start scraping method HairlessFurever::DogCatcher.catch_dog_breeds #welcome user and set flow of program puts "\nWelcome to Hairless Furever!\n" puts "\nHere you can learn all about hairless dog breeds.\n" puts "U・ᴥ・U" puts " u u" @input = "" until @input == "exit" fetched_dogs fetch_user_dog end farewell end def fetched_dogs #getting all the dog breeds @dogs = HairlessFurever::Dog.all puts "\nPlease enter the number of the dog you would like more information on.\n" @dogs.each.with_index(1) {|dog, index| puts "#{index}. #{dog.name}"} end def fetch_user_dog chosen_dog = gets.strip.to_i #getting and checking user input to make sure it is valid show_dog(chosen_dog) if valid_input(chosen_dog, @dogs) end def valid_input(user_input, data) #input needs to be less than the amount of data(dog breeds) but more than 0 and can't be a negative number user_input.to_i.between?(1, data.length) #user_input.to_i <= data.length && user_input.to_i > 0 also works end def show_dog(chosen_dog) #show dog name and description dog = @dogs[chosen_dog -1] puts "#{dog.name}: #{dog.description}" puts "\nWould you like to get more information on this dog? (y/n)\n" @input = gets.strip if @input == "y" details(dog) else continue end end def details(dog) #show more details about the selected dog breed #dog = @dogs[chosen_dog -1] puts "#{dog.height}" puts "#{dog.weight}" puts "#{dog.physical_characteristics}" continue end def continue #see if user wants to continue or exit puts "\nPress any key to see the list of dogs again. Type 'exit' to leave.\n" @input = gets.strip end def farewell puts "" puts " /)-_-(\\" puts " (o o)" puts " .-----__/\\o/" puts " / __ / " puts " \\__/\\ / \\_\\ |/ " puts " \\\\ || " puts " // || " puts " |\\ |\\ " puts "\nThanks for stopping by.\n" puts "" end end
true
80bb32c8eb3184ddfbf7a0317964fda5f931a836
Ruby
MislavGunawardena/Back-End-Lesson01
/excercises/small_problems_repeat/set1.7/7.rb
UTF-8
299
3.53125
4
[]
no_license
def show_multiplicative_average(numbers) multiplicative_average = numbers.inject(&:*) / numbers.size.to_f puts format("The result is %.3f", multiplicative_average) end show_multiplicative_average([1, 10, 1]) show_multiplicative_average([3, 5]) show_multiplicative_average([2, 5, 7, 11, 13, 17])
true
61be6c15948083148e77b259200d784ac0de5135
Ruby
markkauffman22/ttt-8-turn-bootcamp-prep-000
/lib/turn.rb
UTF-8
1,463
4.25
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end def valid_move?(board, i) # check if position is taken or if it is 'out-of-bounds' ... if (position_taken?(board, i) == true) || (i > 8) || (i < 0) return false else return true end end def input_to_index(input) input = input.to_i index = input - 1 print "Returning: " puts index return index end def update_array_at_with(board, index, value) index = index.to_i board[index] = value puts " " print "Index: " puts index print "BOARD Value: " puts board[index] return board end def move(board, index, value = "X") index = index.to_i new_board = update_array_at_with(board, index, value) display_board(new_board) end def position_taken?(board, i) if board.length != 0 puts board[i] end if board.length == 0 puts "ZERO LENGTH" return false elsif (board[i] == "X") || (board[i] == "O") puts "true" return true else puts false return false end end def turn(board) puts "Please enter 1-9:" input = gets.strip index = input_to_index(input) if valid_move?(board, index) move(board, index, value = "X") else turn(board) end end
true
b0ae7c8204ea5be31bb8bddb6c033f1586e5df89
Ruby
gammons/todolist-ruby
/lib/todo-cli/filter.rb
UTF-8
2,901
3.015625
3
[ "MIT" ]
permissive
module Todo class Filter def initialize(todos = [], input = nil) @todos = todos.clone @input = input end def filter return todos if @input.nil? filter_archived filter_projects filter_contexts filter_date group end def group g = nil @input.scan(/by \w+/) {|m| g = m.gsub(/by /,'') } case g when "p","project" then group_by_project when "c","context" then group_by_context else @todos end end def grouped? @input.scan(/by \w+/).size > 0 end def filter_projects projects = Parser.new.projects(@input) return @todos if projects.empty? @todos = @todos.select {|t| t.projects.any? {|proj| projects.include?(proj) } } end def filter_contexts contexts = Parser.new.contexts(@input) return @todos if contexts.empty? @todos = @todos.select {|t| t.contexts.any? {|proj| contexts.include?(proj) } } end def filter_date from, to = parse_date_range return @todos if from == nil && to == nil @todos = @todos.select {|t| t.due && (Date.parse(t.due) >= from) && (Date.parse(t.due) <= to) } end def parse_date_range date_str = @input.split("due ").last case date_str when "this week" now = Date.today sunday = now - now.wday saturday = now + (6 - now.wday) [sunday, saturday] when "next week" now = Date.today sunday = now - now.wday saturday = now + (6 - now.wday) [sunday + 7, saturday + 7] when "tom","tomorrow" [Date.today + 1, Date.today + 1] when "tod","today" [Date.today, Date.today] else d = Chronic.parse(date_str) return if d.nil? [d.to_date,d.to_date] end end private def group_by_project all_projects = @todos.map {|t| t.projects }.flatten.uniq grouped = all_projects.map do |proj| {proj => @todos.select {|t| t.projects.include?(proj) } } end if @todos.any? {|t| t.projects.size == 0 } grouped << {"No Project" => @todos.select {|t| t.projects.size == 0 } } end grouped end def group_by_context all_contexts = @todos.map {|t| t.contexts }.flatten.uniq grouped = all_contexts.map do |cont| {cont => @todos.select {|t| t.contexts.include?(cont) } } end if @todos.any? {|t| t.contexts.size == 0 } grouped << {"No Context" => @todos.select {|t| t.contexts.size == 0 } } end grouped end def filter_archived archived = @input.split(' ').last == 'archived' archived ? archived_todos : unarchived_todos end def archived_todos @todos = @todos.select {|t| t.archived? } end def unarchived_todos @todos = @todos.select {|t| !t.archived? } end end end
true
e4e3cb8c311dad4bef8f42f161558307ab7e96ec
Ruby
FlisAnn/ruby_excercises
/number3.rb
UTF-8
756
4.8125
5
[]
no_license
# '4' == 4 ? puts("TRUE") : puts("FALSE") # if the statement is true show TRUE, otherwise FALSE # It's false since we are comparing a String to Int =begin rescue => exception end x = 2 if ((x * 3) / 2) == (4 +4 -x -3) puts "Did you get it right?" else puts "Did you?" end =end # 2 * 3 / 2 = 3 and 4 + 4 - 2 - 3 = 6 # Terminal will print Did you get it right since that is true =begin y = 9 x = 10 if (x + 1) <= (y) puts "alright" elsif (x + 1) >= (y) puts "Alright now" elsif (y + 1) == x puts "ALRIGHT NOW!" else puts "Alrighty!" end =end # Alright now def equal_to_four(x) if x == 4 puts "yup" else puts "nope" end equal_to_four(5) end # the end for def was missing
true
33ae1e1a56e6296da3ef012362af10a8cc18aa98
Ruby
01022012/medical-appointments
/vendor/rails/activesupport/test/core_ext/module_test.rb
UTF-8
4,371
3.015625
3
[ "MIT", "Apache-2.0" ]
permissive
require File.dirname(__FILE__) + '/../abstract_unit' module One end class Ab include One end module Xy class Bc include One end end module Yz module Zy class Cd include One end end end class De end Somewhere = Struct.new(:street, :city) Someone = Struct.new(:name, :place) do delegate :street, :city, :to => :place delegate :state, :to => :@place delegate :upcase, :to => "place.city" end class Name delegate :upcase, :to => :@full_name def initialize(first, last) @full_name = "#{first} #{last}" end end $nowhere = <<-EOF class Name delegate :nowhere end EOF $noplace = <<-EOF class Name delegate :noplace, :tos => :hollywood end EOF class ModuleTest < Test::Unit::TestCase def test_included_in_classes assert One.included_in_classes.include?(Ab) assert One.included_in_classes.include?(Xy::Bc) assert One.included_in_classes.include?(Yz::Zy::Cd) assert !One.included_in_classes.include?(De) end def test_delegation_to_methods david = Someone.new("David", Somewhere.new("Paulina", "Chicago")) assert_equal "Paulina", david.street assert_equal "Chicago", david.city end def test_delegation_down_hierarchy david = Someone.new("David", Somewhere.new("Paulina", "Chicago")) assert_equal "CHICAGO", david.upcase end def test_delegation_to_instance_variable david = Name.new("David", "Hansson") assert_equal "DAVID HANSSON", david.upcase end def test_missing_delegation_target assert_raises(ArgumentError) { eval($nowhere) } assert_raises(ArgumentError) { eval($noplace) } end def test_parent assert_equal Yz::Zy, Yz::Zy::Cd.parent assert_equal Yz, Yz::Zy.parent assert_equal Object, Yz.parent end def test_parents assert_equal [Yz::Zy, Yz, Object], Yz::Zy::Cd.parents assert_equal [Yz, Object], Yz::Zy.parents end def test_as_load_path assert_equal 'yz/zy', Yz::Zy.as_load_path assert_equal 'yz', Yz.as_load_path end end module BarMethodAliaser def self.included(foo_class) foo_class.alias_method_chain :bar, :baz end def bar_with_baz bar_without_baz << '_with_baz' end def quux_with_baz! quux_without_baz! << '_with_baz!' end def quux_with_baz? false end end class MethodAliasingTest < Test::Unit::TestCase def setup Object.const_set(:FooClassWithBarMethod, Class.new) FooClassWithBarMethod.send(:define_method, 'bar', Proc.new { 'bar' }) @instance = FooClassWithBarMethod.new end def teardown Object.send(:remove_const, :FooClassWithBarMethod) end def test_alias_method_chain assert @instance.respond_to?(:bar) feature_aliases = [:bar_with_baz, :bar_without_baz] feature_aliases.each do |method| assert [email protected]_to?(method) end assert_equal 'bar', @instance.bar FooClassWithBarMethod.send(:include, BarMethodAliaser) feature_aliases.each do |method| assert @instance.respond_to?(method) end assert_equal 'bar_with_baz', @instance.bar assert_equal 'bar', @instance.bar_without_baz end def test_alias_method_chain_with_punctuation_method FooClassWithBarMethod.send(:define_method, 'quux!', Proc.new { 'quux' }) assert [email protected]_to?(:quux_with_baz!) FooClassWithBarMethod.send(:include, BarMethodAliaser) FooClassWithBarMethod.alias_method_chain :quux!, :baz assert @instance.respond_to?(:quux_with_baz!) assert_equal 'quux_with_baz!', @instance.quux! assert_equal 'quux', @instance.quux_without_baz! end def test_alias_method_chain_with_same_names_between_predicates_and_bang_methods FooClassWithBarMethod.send(:define_method, 'quux!', Proc.new { 'quux' }) FooClassWithBarMethod.send(:define_method, 'quux?', Proc.new { true }) assert [email protected]_to?(:quux_with_baz!) assert [email protected]_to?(:quux_with_baz?) FooClassWithBarMethod.send(:include, BarMethodAliaser) FooClassWithBarMethod.alias_method_chain :quux!, :baz FooClassWithBarMethod.alias_method_chain :quux?, :baz assert @instance.respond_to?(:quux_with_baz!) assert @instance.respond_to?(:quux_with_baz?) assert_equal 'quux_with_baz!', @instance.quux! assert_equal 'quux', @instance.quux_without_baz! assert_equal false, @instance.quux? assert_equal true, @instance.quux_without_baz? end end
true
abd88e2ccb677154e109e0e6b97f5847365c55ab
Ruby
flaviuvr/wolfpack-ror-internship
/Assignment2/carCleaningService.rb
UTF-8
3,209
3.34375
3
[]
no_license
require 'time' # Describes the schedule by which the service operates module Schedule START_TIME_HOUR = 8 END_TIME_HOUR = 17 def self.open?(time) open_time?(time) && open_day?(time) end def self.open_time?(current_time) current_time.hour > START_TIME_HOUR && current_time.hour < END_TIME_HOUR end def self.open_day?(current_day_of_week) !(current_day_of_week.saturday? || current_day_of_week.sunday?) end end # Clients of the car wash service. Will be updated once their car is ready for pick up and then pick a time to come for it class User attr_reader :name, :car, :time_of_arrival attr_accessor :time_of_pickup def initialize(name, car, time_of_arrival) @name = name @car = car @time_of_arrival = time_of_arrival end def notify puts "#{name} was notified" set_pick_up_time puts "#{name} will be there to pick car up #{time_of_pickup}" end def set_pick_up_time # Sets a random time after the current one (in HOURS) @time_of_pickup = Time.new + rand(1..100) * 10 * 60 * 60 Schedule.open?(time_of_pickup) ? time_of_pickup : set_pick_up_time end end # Describes the identifier of each car, their license plate number class Car attr_reader :license_plate_number def initialize(license_plate_number) @license_plate_number = license_plate_number end end # Handles the actual cleaning of the cars class Station attr_reader :name def initialize(name) @name = name end def clean_car(car) puts "Now cleaning car #{car.license_plate_number} on #{name}" puts "Done cleaning car #{car.license_plate_number} on #{name}" end end # The working service that handles the added cars and notifies the users class Service attr_accessor :clients, :station1, :station2 def initialize @clients = {} @station1 = Station.new('Station 1') @station2 = Station.new('Station 2') end def add_new_client(client) clients[client] = client.car puts "#{client.name} came in at #{client.time_of_arrival} with car #{client.car.license_plate_number}" end def notify_client(client) client&.notify end def move_to_station(client1, client2) clean_car_in_station(station1, client1) clean_car_in_station(station2, client2) unless client2.nil? end def clean_car_in_station(station, client) car = clients[client] station.clean_car(car) notify_client(client) clients.delete(client) end def work return unless Schedule.open?(Time.now) move_to_station(clients.keys[0], clients.keys[1]) until clients == {} end end bmw = Car.new('CJ 93 RIF') vw = Car.new('CJ 72 RIF') ford = Car.new('B 113 PBD') toy = Car.new('B 12 AAA') audi = Car.new('CJ 11 AUD') alfa = Car.new('CJ 11 ALF') user1 = User.new('Flaviu', bmw, Time.new) user2 = User.new('Ionut', vw, Time.new) user3 = User.new('Vlad', ford, Time.new) user4 = User.new('Dan', toy, Time.new) user5 = User.new('Alex', audi, Time.new) user6 = User.new('Adi', alfa, Time.new) service = Service.new service.add_new_client(user1) service.add_new_client(user2) service.add_new_client(user3) service.add_new_client(user4) service.add_new_client(user5) service.add_new_client(user6) service.work
true
5d73c5bc2f5f16fb9f983894719c41f867b6d993
Ruby
wley3337/Flatiron-Students-Connect-Backend
/app/models/user.rb
UTF-8
712
2.546875
3
[]
no_license
class User < ApplicationRecord has_many :notes accepts_nested_attributes_for :notes has_many :user_references has_many :references, through: :user_references validates :username, uniqueness: true, presence: true validates :first_name, presence: true validates :last_name, presence: true has_secure_password # creates a serialized version of user for json token response def serialize_user return {id: self.id, username: self.username, firstName: self.first_name, lastName: self.last_name, roll: self.roll, startDate: self.start_date, notes: self.notes.map{|note| note.serialize_note}, references: self.references.map{|ref| ref.serialize_reference}} end end
true
91e534b1ab17bb972caaa77162a4b46d35fc16d3
Ruby
miguelvieira123/BetESSEntrega
/MVC/Gambler.rb
UTF-8
290
2.921875
3
[]
no_license
class Gambler < Object attr_reader :username , :password, :coins def initialize @username = "John Doe" @password @coins = 0.0 end def setUsername(usr) @username = usr end def setPassword(passwd) @password = passwd end def setCoins(coins) @coins = coins end end
true
7b51bb6528713072ea8aa136122b3b47ff9a3d26
Ruby
inhortte/rt_rails3.2
/app/models/user.rb
UTF-8
1,040
2.6875
3
[]
no_license
require 'digest' class User < ActiveRecord::Base attr_accessor :password attr_accessible :username, :password, :password_confirmation # validates :password, :presence => true, # :confirmation => true, # :length => { :within => 6..40 } before_save :encrypt_password def has_password?(submitted_password) encrypted_password == encrypt(submitted_password) end def self.authenticate(un, pw) user = User.find_by_username(un) return nil if user.nil? return user if user.has_password?(pw) end def remember_me! self.remember_token = encrypt("#{salt}--#{id}--#{Time.now.utc}") self.save end private def encrypt_password unless password.nil? self.salt = make_salt unless has_password?(password) self.encrypted_password = encrypt(password) end end def encrypt(string) secure_hash("#{salt}--#{string}") end def make_salt secure_hash("#{Time.now.utc}--#{password}") end def secure_hash(string) Digest::SHA2.hexdigest(string) end end
true
47ec5bceda2dfac6885b094c4b453bd0734a10fe
Ruby
nerdyamigo/learnruby
/exercs/mystuff.rb
UTF-8
185
3.4375
3
[]
no_license
# this goes in mystuff.rb class MyStuff def initialize() @tangerine = "And now a thousand years between" end attr_reader :tangerine def apple() puts "I AM APPLES!" end end
true
983a56014f7ae57d94c14ea1ec070eacf31fc2e0
Ruby
loyaldev03/cultivation-app
/app/commands/cultivation/append_material_use.rb
UTF-8
1,074
2.59375
3
[]
no_license
# Call this method instead of SaveMaterialUse if want to: # 1. append new product to use module Cultivation class AppendMaterialUse prepend SimpleCommand attr_reader :current_user, :id, :items def initialize(current_user, id, items) @current_user = current_user @id = id.to_bson_id @items = items end def call save_record end private def save_record record = Cultivation::Task.find(id) if !items.nil? items.each do |item| p_id = item[:product_id] uom = resolve_uom(item[:uom], item[:product_id]) m = record.material_use.build( product_id: p_id, quantity: item[:quantity] || 0, uom: uom, ) # Rails.logger.debug "\t\t\t>>>> m: #{m.inspect}" end end record.save! record end def resolve_uom(uom, product_id) if uom.blank? product = Inventory::Product.find(product_id) product.catalogue.common_uom else uom end end end end
true
437244853491f96823866b83dbd9f28773eebde0
Ruby
cato-hga/TimeTracker
/db/seeds.rb
UTF-8
1,646
2.65625
3
[]
no_license
@employee = Employee.create(email: "[email protected]", password: "asdfasdf", password_confirmation: "asdfasdf", first_name: "John", last_name: "Snow", phone: "8138422213") puts "1 employee createed" AdminUser.create(email: "[email protected]", password: "asdfasdf", password_confirmation: "asdfasdf", first_name: "Admin", last_name: "Name", phone: "8138422213") puts "1 Admin user created" AuditLog.create!(user_id: @employee.id, status: 0, start_date: Date.today - 6.days) AuditLog.create!(user_id: @employee.id, status: 0, start_date: Date.today - 13.days) AuditLog.create!(user_id: @employee.id, status: 0, start_date: Date.today - 20.days) puts "3 audit logs have been created" 100.times do |post| Post.create(date: Date.today, rationale: "#{post} There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc. ", user_id: @employee.id, overtime_request: 2.5) end puts "100 posts have been created"
true
48936c2ac3cf9f8c78be6f010fe62719cc04136e
Ruby
ayumin/apex
/lib/apex/converter.rb
UTF-8
5,106
2.921875
3
[ "MIT" ]
permissive
#!/usr/bin/ruby # -*- coding: utf-8 -*- module Apex module Converter # # ApexコードをJavaDocが解釈できるJavaコードに変換します。 # # ApexとJavaのコード仕様の違いをなるべく吸収し、JavaDocで解釈可能なスケルトン # コードとして出力します。主な相違点は下記のとおりです。 # # - 文字列リテラル # Javaではシングルクオーテーションで囲まれた文字列は1つの文字のみをあらわし # ますがApexではシングルクオートで文字列を表現します。そのためApexコード中 # のすべての文字列リテラルはJavaの規則に沿うようにダブルクオーテーションに # 置換されます。 # # - virtual with/without sharing 修飾 # - override 修飾 # def to_java result = "" in_comment = false @code.each_line do |line| #----------------------------------------------------------------------- # Javaで解釈できないコードを削除する #----------------------------------------------------------------------- line.chomp! line.gsub!(/\"/,"\\\"") line.gsub!(/\'/,"\"") line.sub!(/global /,'public ') line.sub!(/virtual /,'') line.sub!(/with /,'') line.sub!(/without /,'') line.sub!(/sharing /,'') line.sub!(/override /,'') line.gsub!(/ string /, ' String ') line.gsub!(/ integer /, ' Integer ') line.gsub!(/Class/, 'class') line.gsub!(/MAP/, 'Map') if line =~ /\/\// line.sub!(/\/\//,'/*') line += "*/" end #----------------------------------------------------------------------- # コメントモードの場合、改行を付加して出力行内にコメント終了トークンが # ある場合はコメントモードを終了する #----------------------------------------------------------------------- if in_comment in_comment = false if line =~ R_COMMENT_END result += line + "\n" else #----------------------------------------------------------------------- # コメントモードでないときに、行内にコメント開始がある場合コメントモー # ドを開始し改行を付加して出力 #----------------------------------------------------------------------- if line =~ R_COMMENT_START in_comment = true unless line =~ R_COMMENT_END result += line + "\n" else #----------------------------------------------------------------------- # コメントモードでなく行内にコメント開始がない場合、クラス、メソッド、 # フィールドのいずれかであるか判定する #----------------------------------------------------------------------- ## クラス定義の場合、改行を付加して出力 #----------------------------------------------------------------------- if line =~ R_DEF_CLASS if line =~ /\{/ line = line + "\n" else line = line + "{\n" end result += line #----------------------------------------------------------------------- ## コンストラクタ定義の場合、中括弧を閉じて出力 #----------------------------------------------------------------------- elsif line =~ R_DEF_CONSTRACTOR if line =~ /\}/ line = line + "\n" else line = line + "}\n" end result += line #----------------------------------------------------------------------- ## メソッド定義の場合、抽象メソッドは改行を付加して出力する ## メソッドの型がvoidの場合は中括弧を閉じそれ以外の場合はnullを返すコー ## ドを付加して出力 #----------------------------------------------------------------------- elsif line =~ R_DEF_METHOD unless $2 =~ /abstract/ if $3 == "void" if line =~ /\}/ line = line + "\n" else line = line + "}\n" end else if line =~ /\}/ line = line + "\n" else line = line + "return null;}\n" end end end result += line #----------------------------------------------------------------------- ## フィールド定義の場合、改行を付加して出力 #----------------------------------------------------------------------- elsif line =~ R_DEF_FIELD result += line + "\n" end end end end result + "\n}\n" end end end
true
571eab8475a3d72b6f750df6196993c1b40e484f
Ruby
matheusjohannaraujo/exemplos_ruby
/estrutura_de_repeticao/teste_2.rb
UTF-8
313
3.796875
4
[ "MIT" ]
permissive
def separador puts "-" * 30 end separador vet = [7, 895, 9, 6, 36, 81, 55454, 3563] for i in 0...vet.size puts "Pelo for: #{vet[i]}" end separador vet.each do |i| puts "Pelo each: #{i}" end separador obj_hash = { a: 1, b: 2, c: 3 } obj_hash.each do |k, v| puts "Chave: #{k} | Valor: #{v}" end
true
de720232e2977acd7f5a7f159cbe37dd0f3811f3
Ruby
maetl/mementus
/spec/structure/indexed_graph_example.rb
UTF-8
2,657
2.546875
3
[ "MIT" ]
permissive
require 'spec_helper' shared_examples_for "an indexed graph data structure" do |supports_edge_ids: false| describe '#new' do it 'starts with empty node list' do expect(structure.nodes_count).to eq(0) end it 'starts with empty edge list' do expect(structure.edges_count).to eq(0) end end describe '#set_node' do it 'assigns a node object to the graph' do structure.set_node(Mementus::Node.new(id: 1)) expect(structure.nodes_count).to eq(1) expect(structure.edges_count).to eq(0) end end describe '#set_edge' do it 'adds an edge object to the graph' do structure.set_edge(Mementus::Edge.new(from: Mementus::Node.new(id: 1), to: Mementus::Node.new(id: 2))) expect(structure.nodes_count).to eq(2) expect(structure.edges_count).to eq(1) end end describe '#has_node?' do it 'tests for the presence of a given node by value' do node = Mementus::Node.new(id: 1) structure.set_node(node) expect(structure.has_node?(node)).to be true end it 'tests for the presence of a given node by id' do node = Mementus::Node.new(id: 1) structure.set_node(node) expect(structure.has_node?(1)).to be true end end describe '#has_edge?' do it 'tests for the presence of a given edge by value' do edge = Mementus::Edge.new(from: Mementus::Node.new(id: 1), to: Mementus::Node.new(id: 2)) structure.set_edge(edge) expect(structure.has_edge?(edge)).to be true end it 'tests for the presence of a given edge by id' do edge = Mementus::Edge.new(id: 123, from: Mementus::Node.new(id: 1), to: Mementus::Node.new(id: 2)) structure.set_edge(edge) expect(structure.has_edge?(123)).to be true end if supports_edge_ids it 'tests for the presence of a given edge between nodes' do edge = Mementus::Edge.new(from: Mementus::Node.new(id: 1), to: Mementus::Node.new(id: 2)) structure.set_edge(edge) expect(structure.has_edge?(1, 2)).to be true end if supports_edge_ids end describe '#node(id)' do it 'finds a node by id' do edge = Mementus::Edge.new(from: Mementus::Node.new(id: 1), to: Mementus::Node.new(id: 2)) structure.set_edge(edge) expect(structure.node(1).id).to eq(edge.from.id) end end describe '#nodes' do it 'lists all nodes in the graph' do edge = Mementus::Edge.new(from: Mementus::Node.new(id: 1), to: Mementus::Node.new(id: 2)) structure.set_edge(edge) expect(structure.nodes.first.id).to eq(edge.from.id) expect(structure.nodes.last.id).to eq(edge.to.id) end end end
true
4a93af09a6e3333dab0b1871fbb86ff8a14d2e5f
Ruby
sebas095/Ruby
/class/proc.rb
UTF-8
147
3.125
3
[]
no_license
def hi proc1, proc2 proc1.call proc2.call end proc1 = Proc.new { puts "Hola proc1" } proc2 = Proc.new { puts "Hola proc2" } hi(proc1, proc2)
true
dd092676e1de8253c1151b297c5ee7ed11aca20c
Ruby
ginter/hackerrank
/sherlock_and_squares.rb
UTF-8
120
2.828125
3
[]
no_license
t = gets.to_i t.times.map do a, b = gets.split(' ').map(&:to_i) p (Math.sqrt(a).ceil..Math.sqrt(b).floor).count end
true
0410df4c830c8c39a35c4bbb10f05d519599f68b
Ruby
moinvirani/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
543
4
4
[]
no_license
def echo(word) return word end def shout(word) return word.upcase end def repeat(word, num=2) return ("#{word} " * num).strip #strip removes all the whitespace in a string end def start_of_word(word, num=0) return ("#{word.slice(0,num)}") end def first_word(word) return ("#{word.split[0]}") end def titleize(word) ignore_words = ["and", "over", "the"] split = word.split(" ").each { |x| ignore_words.include?(x)? x : x.capitalize! } # one line if statement (ternary operator) split[0].capitalize! split.join(" ") end
true
5f8c121a5ab0594d81cbf0758dd26684c85f975f
Ruby
dunkkle/whois-bot
/bot.rb
UTF-8
4,293
3.234375
3
[]
no_license
# DNS Bot # This script is the skeleton for a bot that will automatically check DNS and Whois records for a given domain. # # Uses net/dns gem: https://github.com/bluemonk/net-dns # Uses whois gem: https://whoisrb.org/ # # require 'sinatra' require 'slack-ruby-client' require 'net/dns' require 'whois' require 'net/http' require 'json' require 'uri' # Just returns a nice message if someone visits the URL directly. get '/' do "hello world!" end # Construct the message that gets sent back to Slack after the Whois query finishes # http://mikeebert.tumblr.com/post/56891815151/posting-json-with-nethttp # https://coderwall.com/p/c-mu-a/http-posts-in-ruby def json_response_test(response_url, whois_response) data_output = {text: whois_response, response_type: "ephemeral"} json_headers = {"Content-type" => "application/json"} uri = URI.parse(response_url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true res = http.post(uri.path, data_output.to_json, json_headers) return nil end def json_prelim_response(response_url, user_name) data_output = {text: "Hi " + user_name + ", let me check on that for you! Please hold...", response_type: "ephemeral"} json_headers = {"Content-type" => "application/json"} uri = URI.parse(response_url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true res = http.post(uri.path, data_output.to_json, json_headers) return nil end # Define methods - Whois and DNS/Host.. def whois_query(domain) #whois = Whois::Client.new # run a Whois query on the domain we're passing in. Returns an object, but can be called as a string # if necessary (i.e. puts result) # result = whois.lookup(domain) # puts result # Return the whole record? # puts result # Return only some specific info... # domain_that_was_queried = result.domain # domain_created_on_date = result.created_on #Time/Nil # domain_updated_date = result.updated_on #Time/Nil # domain_expiration_date = result.expires_on # domain_registrar = result.registrar.name # domain_nameservers = result.nameservers # domain_registrant_contacts = result.registrant_contacts # # Let's output some of this stuff, to see if it's working. # # need to put all this in a JSON POST message... #puts "You asked about" + domain_that_was_queried.to_s + "...here's what I know: " # puts "Registered at:" + domain_registrar.to_s # puts "Expires on:" + domain_expiration_date.to_s # puts "Contact info:" + domain_registrant_contacts.to_s # puts domain_nameservers record = Whois.whois(domain).parser domain_name = record.domain created_date = record.created_on last_updated = record.updated_on.to_s expiration_date = record.expires_on.to_s registrar = record.registrar.name #registrant_contacts = record.registrant_contacts.to_s #nameservers = record.nameservers.name puts "__Domain Name:__ " + domain_name.to_s + "\n Created Date: " + created_date.to_s @whois_response = "*Domain Name:* " + domain_name.to_s + "\n First Registered On: " + created_date.to_s + "\n Last Updated On: " + last_updated.to_s + "\n Expires On: " + expiration_date.to_s + "\n *Registrar:* " + registrar.to_s end def dns_query(domain) result = Resolver(domain) # a_records = Net::DNS::Resolver.start(domain, Net::DNS::A) # mx_records = Net::DNS::Resolver.start(domain, Net::DNS::MX) # header = a_records.header # answer = a_records.answer # mx_answer = mx_records.answer # #puts "The packet is #{packet.data.size} bytes" # #puts "It contains #{header.anCount} answer entries" # answer.any? {|ans| p ans} # #@dns_response = answer.to_s # @dns_response = answer.to_s "\n" + mx_answer.to_s @dns_response = result.to_s end def whois domain = params.fetch('text').strip user_name = params.fetch('user_name') response_url = params.fetch('response_url') json_prelim_response(response_url, user_name) if domain =~ /^(.*?\..*?$)/ whois_query(domain) #dns_query(domain) json_response_test(response_url, @whois_response) else "put a real domain name in, fool" end end # Now the fun starts. Once someone POSTs to this app, it will return information. post '/' do whois end post '/host/?' do dns end post '/test' do 'Hello can you hear me' end
true
302e1b8bb4f9dde5c54deb7f1c5bc871d93b80d7
Ruby
anchietajunior/improving-jaya-test
/app/services/events/event_creator_service.rb
UTF-8
714
2.578125
3
[]
no_license
module Events class EventCreatorService < ApplicationService def initialize(request) @request = JSON.parse(request) end def call Result.new(true, nil, create_event!) rescue StandardError => e Result.new(false, e.message, nil) end private attr_accessor :request def create_event! Event.create! event_params end def action request.first.last end def event_type request.keys[1] end def number request["#{event_type}"]["number"] end def event_params {}.tap do |hash| hash[:event_type] = event_type hash[:number] = number hash[:action] = action end end end end
true
7df547ab5f621ca62cd814a898efb3b737311db8
Ruby
casualjim/ironrubyinaction
/Chapter 2/Listing2.10.rb
UTF-8
1,488
3.84375
4
[]
no_license
class MusicLibrary < Array def add_album(artist, title) # The << operator pushes an item onto the end of the array. self << [artist, title] self end def search_by_artist(key) reject { |b| !match_item(b, 0, key) } end def search_by_artist_or_title(key) # reject returns a new array containing elements that return false # to the provided expression. reject { |b| !match_item(b, 0, key) && !match_item(b, 1, key) } end private def match_item(b, index, key) b[index].index(key) != nil end def method_missing(method, *args) method_match = /find_(.+)/.match(method.to_s) return search_by_artist_or_title(method_match.captures[0]) if method_match super end end l = MusicLibrary.new l.add_album("Lenny Kravitz", "Mama said").add_album("Kruder & Dorfmeister", "Sofa surfers") l.add_album("Massive Attack", "Safe from harm").add_album("Paul Oakenfold", "Bunkha") p "Find Kravitz:" l.find_Kravitz.each do |item|; p item; end p "Find Ma:" l.find_Ma.each do |item|; p item; end p "Find Bu:" l.find_Bu.each do |item|; p item; end begin l.nonexisting_Kravitz rescue # p dumps a variable to the screen, hence the quotes in the output. p "The method nonexisting_Kravitz doesn't exist" end # Outputs the following: # # "Find Kravitz:" # ["Lenny Kravitz", "Mama said"] # "Find Ma:" # ["Lenny Kravitz", "Mama said"] # ["Massive Attack", "Safe from harm"] # "Find Bu:" # ["Paul Oakenfold", "Bunkha"] # "The method nonexisting_Kravitz doesn't exist"
true
3f26f5e06d647fa716e0b2cec620dd05938ccd8b
Ruby
ekrako/CtCI-6th-Edition-Ruby
/Chap_1_Arrays_and_Strings/Q1_08_Zero_Matrix.rb
UTF-8
399
2.625
3
[ "MIT" ]
permissive
require 'pp' def zero_column(matrix, col_index) matrix.each_with_index do |item, row_index| item[col_index] = 0 end end def zero_matrix(matrix) zMatrix = Marshal.load(Marshal.dump(matrix)) matrix.each_with_index{|row,i| row.each_with_index{|value,j| if value==0 zMatrix[i].map!{|output| output=0} zero_column(zMatrix,j) end } } return zMatrix end
true
b864c2b994fae43a3262f89535f32685201b22f8
Ruby
obliviusm/my_enumerable
/my_enumerable.rb
UTF-8
160
3.1875
3
[]
no_license
module MyEnumerable def map new_list = self.class.new self.each { |x| new_list << (yield x) } if block_given? new_list end end
true
af28862f8e289de706d22c90e77e565dcb55ea8c
Ruby
tagirahmad/Ruby
/lesson9/accessors.rb
UTF-8
1,106
2.8125
3
[]
no_license
module Accessors def self.included(base) base.extend ClassMethods end # rubocop: disable Metrics/MethodLength module ClassMethods def attr_accessor_with_history(*names) history_arr = [] names.each do |name| var_name = "@#{name}".to_sym history_var_name = "@#{name}_history".to_sym define_method(name) { instance_variable_get(var_name) } define_method("#{name}_history".to_sym) { instance_variable_get(history_var_name) } define_method("#{name}=".to_sym) do |value| instance_variable_set(history_var_name, history_arr << instance_variable_get(var_name)) "#{name} = #{instance_variable_set(var_name, value)}" end end end # rubocop: enable Metrics/MethodLength def strong_attr_accessor(var, var_class) var_name = "@#{var}".to_sym define_method(var) { instance_variable_get(var_name) } define_method("#{var}=".to_sym) do |value| raise TypeError if var_class != value.class.to_s "#{var} = #{instance_variable_set(var_name, value)}" end end end end
true
f70e590f78ccf3274692ddc18b4907e8932a685b
Ruby
cielavenir/procon
/hackerrank/bon-appetit.rb
UTF-8
106
2.5625
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby n,k,*c=`dd`.split.map(&:to_i) r=c.pop-(c.reduce(:+)-c[k])/2 puts r==0 ? 'Bon Appetit' : r
true
f6040b856b1045d5a23f81461c41e2af1a00f0bb
Ruby
sugaryourcoffee/syc-svpro
/lib/sycsvpro/transposer.rb
UTF-8
2,246
3.25
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Operating csv files module Sycsvpro # Tranposes rows to columns and vice versa # # Example # # infile.csv # | Year | SP | RP | Total | SP-O | RP-O | O | # | ---- | -- | -- | ----- | ---- | ---- | --- | # | | 10 | 20 | 30 | 100 | 40 | 140 | # | 2008 | 5 | 10 | 15 | 10 | 20 | 10 | # | 2009 | 2 | 5 | 5 | 20 | 10 | 30 | # | 2010 | 3 | 5 | 10 | 70 | 10 | 100 | # # outfile.csv # | Year | | 2008 | 2009 | 2010 | # | ----- | --- | ---- | ---- | ---- | # | SP | 10 | 5 | 5 | 3 | # | RP | 20 | 10 | 10 | 5 | # | Total | 30 | 15 | 15 | 10 | # | SP-O | 100 | 10 | 10 | 70 | # | RP-O | 40 | 20 | 20 | 10 | # | O | 140 | 10 | 30 | 100 | # class Transposer include Dsl # infile contains the data that is operated on attr_reader :infile # outfile is the file where the result is written to attr_reader :outfile # filter that is used for rows attr_reader :row_filter # filter that is used for columns attr_reader :col_filter # Create a new Transpose # Sycsvpro::Transpose(infile: "infile.csv", # outfile: "outfile.csv", # rows: "0,3-5", # cols: "1,3").execute def initialize(options = {}) @infile = options[:infile] @outfile = options[:outfile] @row_filter = RowFilter.new(options[:rows]) @col_filter = ColumnFilter.new(options[:cols]) end # Executes the transpose by reading the infile and writing the result to # the outfile def execute transpose = {} File.open(@infile).each_with_index do |line, index| line = unstring(line) next if line.empty? result = @col_filter.process(@row_filter.process(line, row: index)) next if result.nil? result.split(';').each_with_index do |col, index| transpose[index] ||= [] transpose[index] << col end end File.open(@outfile, 'w') do |out| transpose.values.each { |value| out.puts value.join(';') } end end end end
true
493399e4e66e7815067ba444043ada0b6debe03c
Ruby
bkerley/rong
/rong-server/spec/rong/server/game_spec.rb
UTF-8
2,801
2.828125
3
[]
no_license
require 'spec_helper' describe Rong::Server::Game do let(:game) { Rong::Server::Game.new(800, 600) } context "initialization" do it "expects an x and y dimension" do expect { Rong::Server::Game.new }.to raise_error(ArgumentError) expect { Rong::Server::Game.new(50) }.to raise_error(ArgumentError) expect { Rong::Server::Game.new(50, 50) }.to_not raise_error end it "accepts a GameState to set the ball and paddles" do game_state = Rong::Elements::Entities::GameState.new([123, 456], [789, 101]) game = Rong::Server::Game.new(0, 0, game_state) game.paddles.first.y.should == 123 game.paddles.last.y.should == 456 game.ball.x.should == 789 game.ball.y.should == 101 end end context "the game state" do it "has 2 scores" do game.scores.should have(2).scores end it "has a ball" do game.ball.should be_a_kind_of(Rong::Elements::Entities::Ball) end context "the paddles" do it "exist as a pair" do game.paddles.should have(2).paddles game.paddles.first.should be_a_kind_of(Rong::Elements::Entities::Paddle) game.paddles.last.should be_a_kind_of(Rong::Elements::Entities::Paddle) end end context "board dimensions" do it "has length" do game.board_length.should == 800 end it "has height" do game.board_height.should == 600 end end end context "game state updates" do describe "#add_listener" do it "accepts listeners for updates" do game.add_listener("listener_one") game.add_listener("listener_two") game.listeners.should include("listener_one") game.listeners.should include("listener_two") end end describe "#update_listeners" do it "sends a state update to all listeners" do listeners = [stub, stub].map do |s| s.should_receive(:update_game_state) game.add_listener s s end game.update_listeners end it "sends current_game_state in the update" do game.stub(:current_game_state => 'the game state') listener = stub listener.should_receive(:update_game_state).with('the game state') game.add_listener(listener) game.update_listeners end end describe "#current_game_state" do it "returns a GameState with the current state" do expected = Rong::Elements::Entities::GameState.new([20, 40], [42, 1337]) current = Rong::Server::Game.new(0, 0, expected).current_game_state current.first_paddle_position.should == 20 current.second_paddle_position.should == 40 current.ball_position.should == [42, 1337] end end end end
true
814e6e9b3ac80b8da225d79c337195c058a4754f
Ruby
livash/AppAcademy_work
/w1d7/exam_1/lib/03_fibonacci.rb
UTF-8
315
3.265625
3
[]
no_license
def fibs(fibs_to_ret) return [0] if fibs_to_ret == 1 return [0,1] if fibs_to_ret == 2 return [] if fibs_to_ret == 0 #else build fibs sequence last_number = fibs(fibs_to_ret - 1)[-1] second_to_last_number = fibs(fibs_to_ret - 1)[-2] fibs(fibs_to_ret - 1) + [last_number + second_to_last_number] end
true
a2a397ec4f357cf2785f7599b577e93e393307d5
Ruby
yauhenininjia/computational_methods
/lib/custom_matrix.rb
UTF-8
2,184
3.015625
3
[]
no_license
module CustomMatrix def custom_pretty_print string = '' maxes = array_maxes row_vectors.each do |row| row.each_with_index do |value, index| string.concat " #{value.to_s.rjust(maxes[index])}" end string.concat("\n") end string end def custom_inverse begin determinant = custom_determinant raise ExceptionForMatrix::ErrNotRegular, 'Determinant is equal to 0' if determinant == 0 (1.0 / determinant) * custom_adjoint.transpose rescue ExceptionForMatrix::ErrNotRegular => e puts e.message end end def custom_adjoint Matrix.build(row_vectors.count, column_vectors.count) do |row, column| cofactor = custom_determinant(custom_additional_minor(row, column)) ((-1) ** (row + column)) * cofactor end end def custom_transpose Matrix.build(column_vectors.count, row_vectors.count) { |row, column| row_vectors[column][row] } end def custom_determinant(matrix = self) return matrix.first if matrix.count == 1 && matrix.first.is_a?(Numeric) result = 0 matrix.row_vectors.first.each_with_index do |value, index| cofactor = custom_determinant(matrix.custom_additional_minor(0, index)) result += ((-1) ** index) * value * cofactor end result end def custom_additional_minor(row_to_remove, column_to_remove) with_removed_row = row_vectors.map do |row| row_vectors.to_a.index(row) == row_to_remove ? nil : row end.compact with_removed_column = with_removed_row.map do |row| row.map.with_index do |value, column_index| column_index == column_to_remove ? nil : value end.to_a.compact end minor = with_removed_column Matrix.build(row_vectors.count - 1, column_vectors.count - 1) do |row, column| minor[row][column] end end def swap_rows(first_row, second_row) @rows[first_row], @rows[second_row] = @rows[second_row], @rows[first_row] end private def array_maxes row_vectors.reduce([]) do |maxes, row| row.each_with_index do |value, index| maxes[index] = [(maxes[index] || 0), value.to_s.length].max end maxes end end end
true
6e3e8eacf2cab97ab84d6ee73920d74177a2b8f1
Ruby
flyingbird1221/diffj
/src/main/ruby/diffj/ast/imports.rb
UTF-8
2,472
3
3
[]
no_license
#!/usr/bin/jruby -w # -*- ruby -*- require 'diffj/ast/element' module DiffJ class ImportsComparator < ElementComparator IMPORT_REMOVED = "import removed: {0}" IMPORT_ADDED = "import added: {0}" IMPORT_SECTION_REMOVED = "import section removed" IMPORT_SECTION_ADDED = "import section added" def import_to_string imp # skip the first token (which is "import") str = "" tk = imp.token(0).next while tk if tk == imp.token(-1) break else str << tk.image tk = tk.next end end str end def first_type_token cu # this too is a C-style array types = cu.type_declarations t = types.length > 0 ? types[0].token(0) : nil # if there are no types (ie. the file has only a package and/or import # statements), then just point to the first token in the compilation unit. t || cu.token(0) end def mark_import_section_added from, toimports fromtk = first_type_token from added fromtk, fromtk, toimports[0].token(0), toimports[-1].token(-1), IMPORT_SECTION_ADDED end def mark_import_section_removed fromimports, to totk = first_type_token to deleted fromimports[0].token(0), fromimports[-1].token(-1), totk, totk, IMPORT_SECTION_REMOVED end def make_import_map imports name_to_imp = Hash.new imports.each do |imp| str = import_to_string imp name_to_imp[str] = imp end name_to_imp end def compare_import_blocks fromimports, toimports from_names_to_imps = make_import_map fromimports to_names_to_imps = make_import_map toimports names = from_names_to_imps.keys + to_names_to_imps.keys names.each do |name| fromimp = from_names_to_imps[name] toimp = to_names_to_imps[name] if fromimp.nil? added fromimports[0], toimp, IMPORT_ADDED, name elsif toimp.nil? deleted fromimp, toimports[0], IMPORT_REMOVED, name end end end def compare from, to fromimports = from.imports toimports = to.imports if fromimports.empty? if !toimports.empty? mark_import_section_added from, toimports end elsif toimports.empty? mark_import_section_removed fromimports, to else compare_import_blocks fromimports, toimports end end end end
true
c7aca53da14fe6641bb76801572207af09a35cb4
Ruby
pupca/lovecode_shop
/vendor/core_extensions/time.rb
UTF-8
3,874
3.265625
3
[]
no_license
class Time # Create Time object from given object # # Time.from(Time.now) # => 2014-07-03 11:52:29 +0200 # Time.from(Date.today) # => 2014-07-03 00:00:00 +0200 # Time.from(DateTime.now) # => 2014-07-03 11:53:50 +0200 # Time.from('1404381277') # => 2014-07-03 11:54:37 +0200 # Time.from('5.days.from_now') # => 2014-07-08 12:04:14 +0200 # Time.from('2.minutes.ago') # => 2014-07-03 12:02:50 +0200 # Time.from('2014-07-08 12:04:14 +0200') # => 2014-07-08 12:04:14 +0200 # Time.from(1404381277) # => 2014-07-03 11:54:37 +0200 # # @param [Time|Date|DateTime|String|Fixnum] obj # # @return [Time] def self.from(obj) case obj when Time obj when Date, DateTime obj.to_time when String from_string(obj) when Fixnum, Float at(obj) else raise ArgumentError, "Object of type #{obj.class} can't be parsed as valid Time" end end # Create Time object from given string # # Time.from('1404381277') # => 2014-07-03 11:54:37 +0200 # Time.from('5.days.from_now') # => 2014-07-08 12:04:14 +0200 # Time.from('2.minutes.ago') # => 2014-07-03 12:02:50 +0200 # Time.from('2014-07-08 12:04:14 +0200') # => 2014-07-08 12:04:14 +0200 # # @param [String] str # # @return [Time] def self.from_string(str) if str =~ /^[-+]?[0-9]*\.?[0-9]+$/ at($LAST_MATCH_INFO[0].to_f) elsif str =~ /^(\d+)\.(second|seconds|minute|minutes|day|days)\.(from_now|ago)$/ $LAST_MATCH_INFO[1].to_i.send($LAST_MATCH_INFO[2].to_sym).send($LAST_MATCH_INFO[3].to_sym) else parse(str) end end # Convert current time to stamp # # Time.now.to_stamp # => "1405376196.805000" # # @return [String] def to_stamp "#{tv_sec}.#{tv_usec}" end # Create time object from its stamp representation # # Time.from_stamp('1405376196.805000') # => 2014-07-15 00:16:36 +0200 # # @param [String] stamp # # @return [Time] def self.from_stamp(stamp) sec, usec = stamp.to_s.split('.') at(sec.to_i, usec.to_i) end def distance_in_words(to_time) from_time = self from_time, to_time = to_time, from_time if from_time > to_time distance_in_minutes = ((to_time - from_time) / 60.0).round distance_in_seconds = (to_time - from_time).round case distance_in_minutes when 0..1 case distance_in_seconds when 0..4 then 'less than 5 seconds' when 5..9 then 'less than 10 seconds' when 10..19 then 'less than 20 seconds' when 20..39 then 'half a minute' when 40..59 then 'less than a minute' else '1 minute' end when 2...45 amount = distance_in_minutes "#{amount} minutes" when 45...90 'about 1 hour' when 90...1_440 amount = (distance_in_minutes / 60.0).round "about #{amount} hours" when 1_440...2_520 '1 day' when 2_520...43_200 amount = (distance_in_minutes / 1_440.0).round "#{amount} days" when 43_200...86_400 amount = (distance_in_minutes / 43_200.0).round "about #{amount} month#{'s' if amount > 1}" when 86_400...525_600 amount = (distance_in_minutes / 43_200.0).round "#{amount} months" else remainder = distance_in_minutes % 525_600 distance_in_years = distance_in_minutes.div(525_600) if remainder < 131_400 amount = distance_in_years "about #{amount} year#{'s' if amount > 1}" elsif remainder < 394_200 amount = distance_in_years "over #{amount} year#{'s' if amount > 1}" else amount = distance_in_years + 1 "almost #{amount} year#{'s' if amount > 1}" end end end end
true
9ea27c9d08835e8d3827f9aa609fbef990997c5e
Ruby
Codaisseur/day4-oop-exercises
/4-1/main.rb
UTF-8
154
2.578125
3
[]
no_license
# ./main.rb require_relative 'space_ship' ship = SpaceShip.new('Millenium Falcon', 'gray') ship.print_details ship.paint('rainbow') ship.print_details
true
db3ece50bad822dd7a75334154f86e068b8b5a8b
Ruby
ellesuzuki/Episode9
/pandas.rb
UTF-8
335
2.984375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'rubygems' require 'bundler/setup' #Bundler.require require 'about-suzuki' puts 'Hello! Thanks for using this gem.' puts suzuki = Suzuki.new puts "The author's name is #{suzuki.name}." puts puts "Her favorite color is #{suzuki.fave_color}, while her favorite food is #{suzuki.fave_food}." puts puts "That's all for now!"
true
494657ecb909b834825bc06f5fe1dd5d83463942
Ruby
adriandelarco/week2_ironhack
/Day4/age.rb
UTF-8
106
2.75
3
[]
no_license
class Age def self.calculate(year) year == "" ? 0 : (Time.now.strftime "%Y").to_i - year.to_i; end end
true
e9d424c8d9e56767b337cd47195250c92df64aaa
Ruby
joelbyler/rspec-junklet
/spec/spec_helper.rb
UTF-8
2,240
2.671875
3
[ "MIT" ]
permissive
# spec_helper.rb PROJECT_ROOT=Pathname.new(File.expand_path(File.join(File.dirname(__FILE__), '..'))) require_relative PROJECT_ROOT + "lib" + "rspec" + "junklet" require "pry" require "byebug" # Since we've kept rigidly to 80-columns, we can easily # Do a pretty side-by-side diff here. This won't handle # Line deletions/insertions but for same/same diffs it'll # work fine. ESC = 27.chr GREEN = "%c[%sm" % [ESC, 32] RED = "%c[%sm" % [ESC, 31] RESET = "%c[0m" % ESC def dump_hline puts(("-" * 80) + "-+-" + ("-" * 80)) end def dump_captions puts "%-80s | %s" % ["EXPECTED", "GOT"] end def dump_header dump_hline dump_captions end def dump_footer dump_hline end def line_pairs(expected_lines, got_lines) expected_lines.zip(got_lines).map { |words| words.map {|w| w ? w.rstrip : "" } } end def dump_diff(expected_lines, got_lines) dump_header line_pairs(expected_lines, got_lines).each do |a,b| color_code = a == b ? GREEN : RED puts "#{color_code}%-80s | %s#{RESET}" % [a,b] end dump_footer end # be_in - working inverse of #cover and #include, e.g. # # let(:range) { (1..5) } # let(:list) { [1,2,3,4,5] } # let(:val) { 3 } # # specify { expect(range).to cover val } # specify { expect(val).to be_in range } # specify { expect(list).to include val } # specify { expect(val).to be_in list } # # Why? Because sometimes I think reading order is important. For example, if the # options for a command can vary and we want to assert that they contain a known # correct value, I prefer # # specify { expect(options).to include value } # # As it is the options that are in question here. But if the list of known # options is fixed, and the code under test returns a value that we want to # prove is inside the list of known options, I prefer # # specify { expect(value).to be_in options } # # ...and yes, I frequently put an #in? method on Object that takes a collection, # and simply calls collection.include?(self) internally. Again just because # reading order. RSpec::Matchers.define :be_in do |list| match do |element| list.include? element end end gem_root = File.expand_path(File.join(File.dirname(__FILE__), "..")) Dir[File.join(gem_root, 'spec/support/**/*.rb')].each { |f| require f }
true
bd775fa15d48082fdb2b2a944b8e41deb2c03d9b
Ruby
puneet18190/desy
/spec/lib/autoload/thread_proc_spec.rb
UTF-8
2,204
2.8125
3
[]
no_license
require 'spec_helper' describe ThreadProc do describe '.new' do context 'when initialized with a block' do subject { described_class.new {} } let(:raw_sources) do { close_connection_before_execution_true: "proc do\n CLOSE_CONNECTION_PROC.call\n block.call\n end", close_connection_before_execution_false: "proc do\n begin\n block.call\n ensure\n CLOSE_CONNECTION_PROC.call\n end\n end" } end it "returns a #{described_class} instance" do expect(subject.class).to eq described_class end context 'when "close_connection_before_execution" option is true' do subject { described_class.new(close_connection_before_execution: true) {} } it 'calls CLOSE_CONNECTION_PROC before executing the passed block' do expect(subject.to_raw_source).to eq raw_sources[:close_connection_before_execution_true] end end context 'when "close_connection_before_execution" option is false' do subject { described_class.new(close_connection_before_execution: false) {} } it 'calls CLOSE_CONNECTION_PROC after executing the passed block' do expect(subject.to_raw_source).to eq raw_sources[:close_connection_before_execution_false] end end context 'when "close_connection_before_execution" is not passed' do subject { described_class.new {} } it 'behaves like if "close_connection_before_execution" was false' do expect(subject.to_raw_source).to eq raw_sources[:close_connection_before_execution_false] end end context 'when the initializing block is a ThreadProc' do let(:initializing_block) { ThreadProc.new {} } subject { described_class.new &initializing_block } it 'returns it' do expect(subject).to be initializing_block end end end context 'when initialized without block' do subject { described_class.new } it { expect { subject }.to raise_error ArgumentError, 'tried to create Proc object without a block' } end end end
true
fb0c6bd7ba24d2f8b171c02da15f2e4361669d17
Ruby
Jackmt9/programming-univbasics-nds-nds-to-insight-raw-brackets-lab-nyc-web-012720
/lib/nds_extract.rb
UTF-8
1,070
3.234375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'directors_database' require "pry" def directors_totals(nds) # Remember, it's always OK to pretty print what you get *in* to make sure # that you know what you're starting with! # # # The Hash result be full of things like "Jean-Pierre Jeunet" => "222312123123" result = { } # # Use loops, variables and the accessing method, [], to loop through the NDS # and total up all the # ... # ... # ... # # # Be sure to return the result at the end! result = {} names = [] count1 = 0 total_array = [] while nds.length > count1 count2 = 0 # names << nds[count1][:name] result[ nds[count1][:name] ] = 0 total = 0 while nds[count1][:movies].length > count2 # total += nds[count1][:movies][count2][:worldwide_gross] result[nds[count1][:name]] += nds[count1][:movies][count2][:worldwide_gross] count2 += 1 end count1 += 1 total_array << total # binding.pry # result[names[count1]] = total end # binding.pry return result nil end
true
e6649e29e04ae7c9f7b6928ea21a982b24c1b829
Ruby
i2w/token_generator
/lib/token_generator.rb
UTF-8
714
3.171875
3
[ "MIT" ]
permissive
require "securerandom" require "token_generator/version" module TokenGenerator extend self def token(length = self.length, group_size = self.group_size) token = (1..length).map{ random_char }.join hyphenize(token, group_size) end def hyphenize(input, group_size = self.group_size) return input if group_size < 1 input.split('').each_slice(group_size).map(&:join).join('-') end def random_char charset[SecureRandom.random_number(charset.size)] end attr_writer :charset, :group_size, :length def charset @charset ||= %w{2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z} end def group_size @group_size ||= 5 end def length @length ||= 20 end end
true
125515f580733f63b69cba52d899839343b964ee
Ruby
jmanero/net-block
/lib/net/block/address.rb
UTF-8
3,785
2.859375
3
[]
no_license
# frozen_string_literal: true require_relative 'bitset' module Net module Block # An IPv4 network address # class Address ZERO = 0 THIRTY_ONE = 31 THIRTY_TWO = 32 attr_reader :address attr_reader :mask attr_reader :metadata # Construct an Address from a CIDR string # def self.from(string, **metadata) dotted, mask_length = string.split('/') octets = dotted.split('.').map(&:to_i) mask_length ||= THIRTY_TWO # If argument didn't have a /MASK, default to /32 mask_length = mask_length.to_i ## IPv4 Validation unless mask_length.between?(ZERO, THIRTY_TWO) raise ArgumentError, "Mask length `#{mask}` is not valid for an IPv4 address" end unless octets.length == 4 && octets.all? { |o| o.between?(ZERO, 255) } raise ArgumentError, "Address `#{dotted}` is not a valid IPv4 address in dotted-decimal form" end ## Generate BitSet from address octets. BitSets are little-endian! address = octets.map { |octet| BitSet.from(octet, 8) }.reverse.reduce(:+) new(address, BitSet.mask(mask_length, THIRTY_TWO), **metadata) end def initialize(address, mask, **metadata) @address = address @mask = mask @metadata = metadata end def network Address.new(mask & address, mask.clone) end def broadcast Address.new(address | !mask, mask.clone) end # If this is a network address, ANDing w/ mask should be a NOOP # def network? (address & mask) == address end # Test if a given address is a sub-network of this address # def subnet?(other) return false if other.length <= length (mask & other.address) == address end # Calculate the super-block of this address. For a host-address, this is # the network address. For a network-address, this is the next-shortest mask # def parent return network unless network? return @parent unless @parent.nil? ## Calculate the next shortest prefix supermask = mask.clone supermask.flip!(THIRTY_TWO - length) @parent = Address.new(supermask & address, supermask) end # Calculate the bottom subnet of the next most specific prefix # def left_child raise RangeError, 'Cannot allocate an address with mask longer than 32' if length == THIRTY_TWO return @left_child unless @left_child.nil? ## Calculate the next longest prefix submask = mask.clone submask.flip!(THIRTY_ONE - length) @left_child = Address.new(network.address.clone, submask) end # Calculate the top subnet of the next most specific prefix # def right_child raise RangeError, 'Cannot allocate an address with mask longer than 32' if length == THIRTY_TWO return @right_child unless @right_child.nil? ## Calculate the next longest prefix submask = mask.clone submask.flip!(THIRTY_ONE - length) ## Increment next-most-significant bit in network address. Should always be Zero ## for the `network` Address instance. subnet = network.address.clone subnet.flip!(THIRTY_ONE - length) @right_child = Address.new(subnet, submask) end def length mask.ones end def ==(other) length == other.length && address == other.address end def <=>(other) address <=> other.address end def to_s annotations = metadata.map { |k, v| "#{k}: #{v}" }.join(', ') "#{address.v4}/#{mask.ones} #{annotations}" end end end end
true
b6350e748d92caea845715d838bc4d6729abe08b
Ruby
rsupak/appacademy2020
/SoftwareEngineeringFundamentals/rspec_exercise_4/lib/part_2.rb
UTF-8
327
3.625
4
[]
no_license
def proper_factors(num) (1...num).select { |n| (num % n).zero? } end def aliquot_sum(num) proper_factors(num).sum end def perfect_number?(num) num == aliquot_sum(num) end def ideal_numbers(n) arr = [] current = 1 while arr.size < n arr << current if perfect_number?(current) current += 1 end arr end
true
20a5c7e8fcee1e815fae831bab60768bc587998c
Ruby
katemorris/backend_mod_1_prework
/day_1/exercises/ex3.rb
UTF-8
809
4.4375
4
[]
no_license
puts "I will now count my chickens:" # outputs a line of text puts "Hens #{25.0 + 30.0 / 6.0}" # does some simple math to count hens puts "Roosters #{100.0 - 25.0 * 3.0 % 4.0}" # same for roosters puts "Now I will count the eggs:" # text output puts 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # maths! puts "Is it true that 3.0 + 2.0 < 5.0 - 7.0?" # text output puts 3.0 + 2.0 < 5.0 - 7.0 # maths! puts "What is 3.0 + 2.0? #{3.0 + 2.0}" # This is a text output along with some math. puts "What is 5.0 - 7.0? #{5.0 - 7.0}" puts "Oh, that's why it's false." # text output puts "How about some more." # text output puts "Is it greater? #{5.0 > -2.0}" # This is a text output along with a true/false test. puts "Is it greater or equal? #{5.0 >= -2.0}" puts "Is it less or equal? #{5.0 <= -2.0}"
true
185681bf1176d242023d17e4d706f1dc482c9b26
Ruby
alfonsojimenez/amazon-instance
/lib/amazon-instance/amazon-ec2.rb
UTF-8
2,282
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
require 'AWS' require 'socket' require 'timeout' class AmazonEC2 def initialize(access_key, secret_key, ec2_server, elb_server) @ec2 = AWS::EC2::Base.new(:access_key_id => access_key, :secret_access_key => secret_key, :server => ec2_server) @elb = AWS::ELB::Base.new(:access_key_id => access_key, :secret_access_key => secret_key, :server => elb_server) end def launch_instance(environment, config, config_dir) config[:base64_encoded] = true if !config[:on_boot].nil? File.open(config_dir+'on-boot/'+config[:on_boot]) do |content| config[:user_data] = content.read.gsub!('{environment}', environment) end end instance = @ec2.run_instances(config.to_hash) instance_id = instance['instancesSet']['item'].first['instanceId'] if config[:load_balancer] attach_instance_to_load_balancer(instance_id, config[:load_balancer]) end host_by_instance(instance_id) end def valid_group?(group_name) valid_group = false @ec2.describe_security_groups['securityGroupInfo']['item'].each do |group| valid_group = true if group['groupName'] == group_name end valid_group end def host_by_instance(instance_id) host = nil while host == nil do instances = @ec2.describe_instances({:instance_id => instance_id}) host = instances['reservationSet']['item'].first['instancesSet']['item'].first['dnsName'] sleep 2 end host end def attach_instance_to_load_balancer(instance_id, load_balancer_name) @elb.register_instances_with_load_balancer(:load_balancer_name => load_balancer_name, :instances => [instance_id]) end def sleep_till_ssh_is_open(host) while ssh_open?(host) do sleep(3) end end def ssh_open?(host) begin Timeout::timeout(1) do begin s = TCPSocket.new(host, 22) s.close return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH return false end end rescue Timeout::Error end return false end end
true
f932614e518fe82512d7be7218ed5157a3b276e0
Ruby
thanq/Thanq-s-Note
/ruby/ruby.rb
GB18030
1,663
3.625
4
[]
no_license
class MegaGreeter attr_accessor :names def initialize(names = "world") @names = names end def say_hi if @names.nil? puts "..." elsif @names.respond_to?("each") @names.each do |name| puts "HEllo #{name}" end else puts "Hello #{@names} !" end end def say_bye if @names.nil? puts "..." elsif @names.respond_to?("join") puts "goodbye #{@names.join(",")} . come back " else puts "goodbye #{@names} . come back soon " end end end if __FILE__ == $0 mg = MegaGreeter.new mg.say_hi mg.say_bye mg.names=["Albert" , "brenda" , "Dave" ] mg.say_hi mg.say_bye mg.names = nil mg.say_hi mg.say_bye end ʹ end ؼclassȵĶ } require ؼ import ؼ еijԱ˽е, ⲿͨ ʱ () ȻԲҪ һжǶ , 1, 2.1 ûо̬ У ֻDZǩ ûоͺǰ ľ ֻñ , liek : a = [1,2] : int[] a = {1,2} ûз foo = Foo.new("hi") , Foo foo = new Foo("hi"); 췽 initialize , ͬ mixin interfaces YAML nil null == Ƿrubyеֵ , javaе equals equal?() жDzͬһ , java е == __FILE__ == $0 ǰĽűʼű class Greeter def initialize (name = "define" ) @name = name #ʵ # ез ʹ @name õ end end 
true
066741feed08f9a68e60b9cce68add8f42ed2c47
Ruby
mikel-codes/rubymine
/sortHash.rb
UTF-8
2,979
3.640625
4
[]
no_license
require_relative 'word_char.rb' #require_relative 'sortHash.rb' require 'test/unit' raw_text = %{The problem breaks down into two parts. First, given some text as a string, return a list of words. That sounds like an array. Then, build a count for each distinct word. That sounds like a use for a hash---we can index it with the word and use the corresponding entry to keep a count.} wordlist = conciseFormula(raw_text) counter = letsHashitUp(wordlist) # sort_by returns a subset list of key,value pair in superset list # [[],[],[]] format return n_count = counter.sort_by { | word, count | count } # looking at key,value pair frm th code block sort using value ie count top_five = n_count.last(5); # returns the last five for i in 0...5 word = top_five[i][0] count = top_five[i][1] puts "#{word} .... #{count}" end # Test/unit module || Framewwork allows this kind of testing using the assert_equal mtd class Testing < Test::Unit::TestCase def test_empty_str() assert_equal([],conciseFormula("")) assert_equal([],conciseFormula(" ")) end def test_single_str() assert_equal(["cats"],conciseFormula("cats")) assert_equal(["cats"],conciseFormula(" cats ")) end def test_much_words() assert_equal(["the","quick", "brown", "fox" , "jumps" ,"over","a","lazy","dog"], conciseFormula("The quick brown fox jumps over a lazy dog")) end def test_punc_marks() assert_equal(["the", "cat's", "mat"], conciseFormula("<The!> cat's, -mat.")) end end # Fibonnaci series def fib_num2max(max) i1, o1 = 1,1 while (i1 <= max) yield i1 i1, o1 = o1, i1 + o1 end end puts "Printing the Fibonacci series" fib_num2max(100) {|f| print f, " "} class ErraticArray def find each do |value| return value if yield(value) end end end puts p [2,4,6,2,43,56] p [2,4,6,2,43,56].find {|v| v * v > 30} ['Q','l','K'].collect{ |x| print x.succ, " " } f = File.open("line.rb") f.each.with_index do |line,index| puts "line at #{index}: #{line}" end f.close() triangular_nums = Enumerator.new do |yielder| number = 0 count = 1 loop do number += count count += 1 yielder.yield number end end 5.times { puts triangular_nums.next, " " } def infinite_select(enum,&block) Enumerator.new do |yielder| enum.each do |value| yielder.yield(value) if block.call(value) end end end p infinite_select(triangular_nums) {|val| val % 10 == 0 }.first(4) puts p infinite_select(triangular_nums) {|val| val % 10 == 0 && val.to_s =~ /3/ }.first(5) # Enumerator lazy Methods def Integer.all Enumerator.new do |yielder, n: 0| loop do yielder.yield(n += 1) end end.lazy end p Integer.all.first(20)
true
7ead5fb9eba6040d6b44f0226b0a473d91058aa9
Ruby
jcovell/my-first-repository
/workit2/fe10.rb
UTF-8
340
4.125
4
[]
no_license
# 10.C an hash values be arrays? Can you have an array of hashes? (give examples) # Ans1: Yes, hash values can be arrays. # Example: hash = { county1: [Berwick, Eliot, Portsmouth], county2: [York, Wells, others] } # Ans2: Yes, you can have an array of hashes. # Example: array = [ {town: Berwick}, {town: Bridgton}, {:town => Windham} ]
true
0650dca6277f0d4ac67b32218f5eee513ac77b3a
Ruby
Hermanverschooten/duration
/lib/duration/time/holidays.rb
UTF-8
345
3.03125
3
[ "MIT" ]
permissive
# -*- encoding : utf-8 -*- class Time module Holidays # Time object for this Christmas. def christmas local(Time.now.year, 12, 25) end # Time object to new years day. def new_years local(Time.now.year + 1, 1) end alias_method :xmas, :christmas alias_method :newyears, :new_years end end
true
503862dd7856896c0d831e5330dc8ef09a2a3d00
Ruby
yggie/minesweeper-ruby
/app/risk_manifold.rb
UTF-8
586
2.9375
3
[ "MIT" ]
permissive
class RiskManifold def initialize end def take_turn(state) cells = state.unexplored_cells.map do |cell| risk_factor = state.cells_around(cell.x, cell.y).inject(1) do |total, neighbouring_cell| if inner_cell.explored? n = state.cells_around(neighbouring_cell.x, neighbouring_cell.y) .select(&:unexplored?).size total * neighbouring_cell.state * n else total end end { cell: cell, risk: risk_factor } end.sort_by{ |rcell| rcell.fetch(:risk) } end def rebuild_risk_manifold end end
true
35a75ae67882b999328bc3c433b650d91428050e
Ruby
onigra/gotenyama_trust_bus_api
/app/models/busall.rb
UTF-8
475
2.71875
3
[]
no_license
class Busall include ActiveModel::Model include DateType PLACE_LIST = ["shinagawa", "gotenyama"] validates :from_place, inclusion: { in: PLACE_LIST, message: "Invalid place. Valid place is gorenyama or shinagawa." } attr_accessor :from_place def initialize(from_place) @current_datetime = DateTime.now @from_place = from_place end def timetable @timetable ||= "Timetables::From#{@from_place.capitalize}".constantize.send(date_type) end end
true
53c2669985a6e6a9b4e8e8c4b6e7891c724976d0
Ruby
widygui93/ruby-tutorial
/p062instVarInherit.rb
UTF-8
216
3.59375
4
[]
no_license
class C def initialize @n = 100 end def increase_n @n *= 20 end end class D < C def show_n puts "n is #{@n}" end end d = D.new d.show_n d.increase_n d.show_n d2 = D.new d2.show_n
true
da80a7e2b647f8f5a9c129e605f245f4e7b39a78
Ruby
arekf/repofeed
/app/services/github_api/repo.rb
UTF-8
560
2.671875
3
[]
no_license
# frozen_string_literal: true module GithubAPI class Repo < Base API_URL = 'https://api.github.com' attr_reader :owner, :name def initialize(owner, name) @owner = owner @name = name end def info api_response(api_endpoint) end def commits api_response(api_endpoint(:commits)) end private def api_endpoint(endpoint_name = '') endpoint_name = "/#{endpoint_name}" unless endpoint_name.blank? "#{GithubAPI::Base::API_URL}/repos/#{owner}/#{name}#{endpoint_name}" end end end
true
db1b40ec5be0d072de7a26d884798a7493eb15d3
Ruby
hvgaming/collections_practice-v-000
/collections_practice.rb
UTF-8
272
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(num) num.sort do|a,b| a <=> b end end def sort_array_desc(num) num.sort {|a,b| -(a <=> b)} end def sort_array_char_count(string) string.sort do |a,b| a.length <=> b.length end end def swap_elements(array) end end
true
a534ed1a8596dd5c25f3017fdb44979c7aeadb8b
Ruby
sorah/emony
/lib/emony/output_router.rb
UTF-8
1,113
2.765625
3
[ "MIT" ]
permissive
require 'thread' require 'emony/utils/operation_threadable' require 'emony/outputs' require 'emony/tag_matching/matcher' module Emony class OutputRouter include Emony::Utils::OperationThreadable def initialize(outputs) @outputs = initialize_outputs(outputs) @matcher = TagMatching::Matcher.new(outputs.keys) @lock = Mutex.new init_operation_threading end def put(window) @queue << window end def perform(op) perform_put op end def perform_put(window) output = output_for_label(window.label) if output output.put(window) else # TODO: warn end end private def setup @outputs.each_value(&:setup) end def teardown @outputs.each_value(&:teardown) end def output_for_label(label) @outputs[@matcher.find(label)] end def initialize_outputs(outputs) outputs.map do |k,v| if v.kind_of?(Hash) [k.to_s, Emony::Outputs.find(v[:type]).new(v)] else [k.to_s, v] end end.to_h end end end
true
16965bd3204c92706cb4544072dbfd86e0f6cd5c
Ruby
karino-minako/paiza-d-quick-solution-set
/shoe-size.rb
UTF-8
526
3.71875
4
[]
no_license
# 靴のサイズ表記には、一般的な cm(センチメートル)の表記以外に、USサイズとUKサイズがあります。 # メンズの靴の場合、 # ・USサイズは、cmの表記から18を引いたもの # ・UKサイズは、cmの表記から18.5を引いたもの # として求めることができます。 # cmで表されたメンズ靴のサイズを、USサイズとUKサイズに変換して出力してください。 line = gets.to_f us = line - 18 uk = line - 18.5 puts "#{us} " + "#{uk}"
true
05bdd34ca954a098cf85eb891ace6d3947fb0420
Ruby
smeds1/Ruby_Practice
/Unit5/stat.rb
UTF-8
732
3.890625
4
[]
no_license
#Sam Smedinghoff #3/13/18 #stat.rb #find mode of a list of numbers def mode(nums) most = 0 mostN = 0 last = 0 count = 0 nums.each do |n| if n == last count += 1 else if most < count most = count mostN = last end count = 1 last = n end end return mostN end #get numbers one by one puts "Enter a list of numbers one at a time" puts "Enter q when done" numbers = [] loop do num = gets.strip if num == 'q' break else numbers << num.to_f end end numbers = numbers.sort #print stats puts "Min: #{numbers.min}" puts "Mean: #{numbers.sum/numbers.length}" puts "Median: #{numbers[numbers.length/2]}" puts "Max: #{numbers.max}" puts "Mode: #{mode(numbers)} "
true
bb79a62e12491b2161c2b7fb75ac1f3ee0089d46
Ruby
si405/BART_upstream
/bart_upstream/app/controllers/bartjourneys_controller.rb
UTF-8
5,233
2.671875
3
[]
no_license
class BartjourneysController < ApplicationController include BartjourneysHelper def new @bartstations = get_station_names_DB @bartjourney = Bartjourney.new end # Create a new journey using the params provided from # the view and redirect back to the main index page def create @bartjourney = Bartjourney.new(bartjourney_params) # if user_signed_in? # @bartjourney.user_id = current_user.user_id # end # Save the journeys for analytics if @bartjourney.save flash[:success] = "Journey created" redirect_to bartjourney_path(@bartjourney) else flash[:error] = "Unable to save journey. Please try again" render :create end end def show @bartjourney = Bartjourney.find(params[:id]) @bartjourney_direction = @bartjourney.direction @bartjourney_options = calculate_bart_times(@bartjourney) return @bartjourney_options, @bartjourney_direction end def sms # Get your Account Sid and Auth Token from twilio.com/user/account account_sid = 'PN0cb7e951004cf11c976200617361437f' auth_token = '' @client = Twilio::REST::Client.new account_sid, auth_token message_body = params["Body"] from_number = params["From"] # Parse the message body to get the origin and destination stations. Origin is considered # to be the first station code, destination the second. # The 3rd field represents the direction n = normal, r = reverse, nothing defaults to reverse sms_message_array = [] # For testing, assume certain stations if not invoked via Twilio if message_body != nil sms_message_array = message_body.split sms_message_array[0] = sms_message_array[0].upcase sms_message_array[1] = sms_message_array[1].upcase else sms_message_array[0] = "EMBR" sms_message_array[1] = "CONC" sms_message_array[2] = "Reverse" end # Get the short codes from the database to verify the stations station_codes = get_station_codes_DB start_station = nil start_station_id = nil end_station = nil end_station_id = nil direction = nil i = 0 if sms_message_array != nil sms_message_array.each do |sms_entry| if station_codes.include?(sms_entry) if i == 0 start_station = sms_entry i = i + 1 elsif i == 1 end_station = sms_entry i = i + 1 elsif i > 1 if sms_entry == ('n' or 'N') direction = 'Normal' else direction = 'Reverse' end end end end # Get the station IDs for the selected stations # Searching the hash using "hash.key" didn't work. Revisit later station_codes.each do |station_code,station_id| if station_code == start_station start_station_id = station_id end if station_code == end_station end_station_id = station_id end end # Create the Bartjourney entry @bartjourney = Bartjourney.new @bartjourney.start_station_id = start_station_id @bartjourney.end_station_id = end_station_id @bartjourney.direction = direction # if user_signed_in? # @bartjourney.user_id = current_user.user_id # end # Save the journeys for analytics if @bartjourney.save # Get the route information @bartjourney_direction = @bartjourney.direction @bartjourney_options = calculate_bart_times(@bartjourney) # Find the furthest you can travel for each train # Destination[1] is the station code, 2 is the time and 3 is the # final destination of the train @train_response = {} latest_time = 100 furthest_station = "" furthest_destination = "" # Find the furthest stations for each train by comparing the departure # times. Once the departure time at a station is greater than the prior # station this indicates that the furthest station is the prior one as # departure times are in descending order @bartjourney_options.each do |train_destination,train_details| latest_time = 100 train_details.each do |station,destination| if station[3].to_i > latest_time.to_i break else latest_time = station[3] furthest_station = station[2] furthest_destination = destination end end if latest_time != 100 @train_response[train_destination] = [furthest_station,latest_time,furthest_destination] end end # Format the results to send back via SMS # {["SFIA", 2]=>["MONT", 3, "PITT"], ["DALY", 4]=>["16TH", 11, "PITT"]} sms_message = "" @train_response.each do |departing_train, furthest_station| sms_message = sms_message + "#{departing_train[0]} train in #{departing_train[1]} min to #{furthest_station[0]} meets #{furthest_station[2]} transfer in #{furthest_station[1]} mins " end # Send the information back via SMS twiml = Twilio::TwiML::Response.new do |r| r.Message "#{sms_message}" end render :text => twiml.text end end end def testme @bartjourney = test_program end private def bartjourney_params params.require(:bartjourney).permit(:start_station_id, :end_station_id, :user_id, :direction) end end
true
63ce7f75f3a00acefd42fe6bd28001e1cbf483b6
Ruby
aturkewi/object-relations-assessment-assessment-test
/app/models/customer.rb
UTF-8
663
3.203125
3
[]
no_license
class Customer attr_accessor :first_name, :last_name @@all = [] def initialize(name) @first_name = name.split(" ")[0] @last_name = name.split(" ")[1] @@all << self end def self.all @@all end def self.find_by_name(full_name) all.find{|customer| customer.full_name == full_name} end def self.find_all_by_first_name(first_name) all.select{|customer| customer.first_name == first_name} end def self.all_names all.map{|customer| customer.full_name} end def full_name "#{first_name} #{last_name}" end def add_review(content, restaurant) Review.new(content, self, restaurant) end end
true
eeacc356a2b8c8b3278431c0518cc288148e90af
Ruby
brettapeters/exercism-ruby
/rna-transcription/rna_transcription.rb
UTF-8
446
3.546875
4
[]
no_license
# RNA Transcription. A program that takes a DNA nucleotide sequence and # returns its RNA complement. class Complement VERSION = 2 def self.of_dna(dna) fail ArgumentError unless dna.match('^[GCTA]+$') dna.gsub(/[GCTA]/, 'G' => 'C', 'C' => 'G', 'T' => 'A', 'A' => 'U') end def self.of_rna(rna) fail ArgumentError unless rna.match('^[GCUA]+$') rna.gsub(/[GCUA]/, 'G' => 'C', 'C' => 'G', 'U' => 'A', 'A' => 'T') end end
true
19ff3fcf1a1296cb6ec7f036a968f026da5d0995
Ruby
mark-bah/sailfishScripts
/Romo/Scraper.rb
UTF-8
803
2.953125
3
[]
no_license
require 'ckan' #Dir["/Users/markpileggi/Documents/workspace/ckan/lib/ckan/*.rb"].each {|file| require file } class Scraper attr_accessor :line attr_accessor :hash attr_accessor :hashList def initialize @hash = Hash.new @hashList = [] puts "initializing app: #{@line}" end def createDictionary(line) keyArray = [] valueArray = [] @hash = Hash.new keyArray = line.scan(/@(.*?)=/) puts "keyArray #{keyArray}" valueArray = line.scan(/"([^"]*)"/) puts "commaArray #{valueArray}" index = 0; for element in valueArray do puts "key #{keyArray[index]}" puts "value #{element}" @hash[keyArray[index]] = element index = index + 1 end puts "FINAL HASH: #{@hash}" hashList.push(@hash) end end
true
deda381b71a40f80e6e43b5972ea76fd4caecff7
Ruby
colinxfleming/github_clawgrabber_ruby
/lib/github_clawgrabber/fetcher.rb
UTF-8
1,402
2.71875
3
[ "MIT" ]
permissive
require 'httparty' module GithubClawgrabber # Handle Github GraphQL interactions class Fetcher GITHUB_GRAPHQL_ENDPOINT = 'https://api.github.com/graphql'.freeze class << self def fetch(auth_token, repo, filepath, branch) response = make_api_call auth_token, repo, filepath, branch content = JSON.parse(response.body)['data']['repository']['object']['text'] shape_response filepath, content end private def make_api_call(auth_token, repo, filepath, branch) headers = define_headers auth_token post_json = define_post_json repo, filepath, branch HTTParty.post GITHUB_GRAPHQL_ENDPOINT, body: post_json, headers: headers end def define_headers(auth_token) { 'Authorization' => "bearer #{auth_token}", 'User-Agent' => 'github_clawgrabber_ruby' } end def define_post_json(repo, filepath, branch) repository = "repository(owner: \"#{repo.split('/')[0]}\", name: \"#{repo.split('/')[1]}\")" object = "object(expression: \"#{branch}:#{filepath}\")" json = "query { #{repository} { #{object} { ... on Blob { text } } } }" { query: json }.to_json end def shape_response(filepath, content) [ { file: filepath, content: content } ] end end end end
true
ee721b6bd6bff5b864f23446abd75119a9e01fc9
Ruby
mrjabba/gitlish
/delish_reformat.rb
UTF-8
428
2.78125
3
[]
no_license
require 'nokogiri' class Delishreformat def initialize(*args) puts "start" @file_path = "delicious-20101217.htm" f = File.open(@file_path) doc = Nokogiri::XML(f) nodes = doc.xpath("//DT/A") nodes.each { |element| puts "<bookmark><title>#{element.text}</title><url>#{element['HREF']}</url><tags>#{element['TAGS']}</tags></bookmark>" } f.close puts "end" end end Delishreformat.new
true
23f01f673899456e946f7c6c94ae32fca9262bb2
Ruby
ahmadr9279/05-jukebox-cli-lab
/lib/jukebox.rb
UTF-8
911
3.390625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
songs = [ "Phoenix - 1901", "Tokyo Police Club - Wait Up", "Sufjan Stevens - Too Much", "The Naked and the Famous - Young Blood", "(Far From) Home - Tiga", "The Cults - Abducted", "Phoenix - Consolation Prizes", "Harry Chapin - Cats in the Cradle", "Amos Lee - Keep It Loose, Keep It Tight" ] def list(songs) arr = {} songs.each_with_index do |song, i| # arr << {i+1: song} puts "#{i+1}. #{song}" end end def help puts "I accept the following commands: - help : displays this help message - list : displays a list of songs you can play - play : lets you choose a song to play - exit : exits this program" end def exit_jukebox puts "Goodbye" end def play puts "What's your song's number or name" num = gets.chomp arr.each do |number, song| if number == num puts song elsif num == song puts song else puts "Invalid input, please try again" end end end
true
7b00709465cfa85a80f7d1eceeedaa891301ec67
Ruby
JE27/contacts-client
/contacts_controller/contacts_controller.rb
UTF-8
2,645
2.59375
3
[]
no_license
module ContactsController def contacts_index_action response = Unirest.get("http://localhost:3000/contacts") contacts = response.body puts JSON.pretty_generate(contacts) end def contacts_create_action print "Enter contact ID" input_id = gets.chomp response = Unirest.get("http://localhost:3000/contacts/#{input_id}") contacts = response.body puts JSON.pretty_generate(contacts) end def contacts_show_action client_params = {} print "First Name: " client_params[:first_name] = gets.chomp print "Middle Name: " client_params[:middle_name] = gets.chomp print "Last Name: " client_params[:last_name] = gets.chomp print "Email: " client_params[:email] = gets.chomp print "Phone number: " client_params[:phone_number] = gets.chomp print "Bio: " client_params[:bio] = gets.chomp response = Unirest.post( "http://localhost:3000/contacts", parameters: client_params ) if response.body == 200 conacts = response.body puts JSON.pretty_generate(contacts) else errors = response.body["errors"] errors.each do |error| puts error end end end def contacts_update_action print "Enter Contact id: " input_id = gets.chomp response = Unirest.get("http://localhost:3000/contacts/#{input_id}") conacts = response.body client_params = {} print "First Name(#contacts[first_name]}): " client_params[:first_name] = gets.chomp print "Middle Name(#contacts[middle_name]}): " client_params[:middle_name] = gets.chomp print "Last Name(#contacts[last_name]}): " client_params[:last_name] = gets.chomp print "Email(#contacts[email]}): " client_params[:email] = gets.chomp print "Phone number(#contacts[phone_number]}): " client_params[:phone_number] = gets.chomp print "Bio(#contacts[bio]}): " client_params[:bio] = gets.chomp response = Unirest.patch( "http://localhost:3000/contacts", parameters: client_params ) if response.body == 200 conacts = response.body puts JSON.pretty_generate(contacts) else errors = response.body["errors"] errors.each do |error| puts error end end end def contacts_destroy_action print "Enter Contact id:" input_id = gets.chomp response = Unirest.delete("http://localhost:3000/contacts/#{input_id}") contacts = response.body puts contacts["message"] end end end
true
a705f1c5f921b30b0155be8ca6df55b43b3b4026
Ruby
justinlecc/playogo-ice-booking
/lib/date_time_formatter.rb
UTF-8
1,426
3.625
4
[]
no_license
class DateTimeFormatter def initialize() @short_months = ['Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'] end def shortToMidDateStr(date) date_a = date.split('-') if date_a.length != 3 raise "ERROR: date string did not contain 3 components in DateTimeFormatter::shortToMidDateString" end month_index = date_a[1].to_i - 1 day_s = date_a[2].to_i.to_s #pick up here... attribute not working return @short_months[month_index] + ' ' + day_s + ' ' + date_a[0] end def secondsToTimeStr(seconds) hours = (seconds / 3600) % 24; minutes = (seconds % 3600) / 60; if (seconds % 60) != 0 raise "ERROR: seconds that weren't a multiple of 60 were passed into TimeFormatting::secondsToTimeString" elsif minutes > 59 raise "ERROR: minutes > 59 in TimeFormatting::secondsToTimeString" end hours_s = '' minutes_s = '' postfix = '' # Get hours string if hours == 0 hours_s = '12' postfix = 'am' elsif hours < 12 hours_s = hours.to_s postfix = 'am' elsif hours == 12 hours_s = '12' postfix = 'pm' else hours_s = (hours % 12).to_s postfix = 'pm' end # Get minutes string if minutes < 10 minutes_s = '0' + minutes.to_s else minutes_s = minutes.to_s end return hours_s + ':' + minutes_s + postfix end end
true
b61b055d77955410d3c36b600cae64c65f273a0f
Ruby
macsrok/CloudApp---Code-sample
/app/services/asset_scrape_service.rb
UTF-8
2,205
2.96875
3
[]
no_license
## This Service is takes a url an array of media types on initialization # It then parses the html page at the provided URL and scrapes out the URLS for each of the assets. class AssetScrapeService require 'open-uri' require 'uri' require 'mimemagic' ASSET_TAGS = %w( img video svg script link ).join(', ') def initialize params @url = params[:url] #page to be scraped end def call! return nil unless self.valid? parse_page end def valid? return false if validate_url(@url).nil? true end private def parse_page begin page = Nokogiri::HTML(open(@url)) #open page with Nokogiri rescue return nil end process_tags(page.search(ASSET_TAGS)) end def process_tags tags results = [] tags.each do |tag| url = process_tag_url tag unless url.blank? || validate_url(url).nil? name = extract_name url mime_type = extract_mime_type name unless name.nil? || mime_type.nil? results << {name: name, url: url, mime_type: mime_type} end end end results end def process_tag_url tag case tag.name.downcase when 'video' #video url = extract_url_from_source tag else url = extract_url tag end url end def extract_url tag url = tag['src'] || tag['href'] prepend_url url end def extract_url_from_source tag url = tag['src'] || tag.search('source[type="video/mp4"]').first.try(:[], 'src') #for the purposes of the sample I only care about mp4s for video prepend_url url end def prepend_url url return nil if url.nil? url = url.prepend('https:') if url.start_with? '//' #if protocol not specified use https url = url.prepend(@url) if url.start_with? '/' #if relative url prepend url url end def extract_name url uri = URI.parse(url) File.basename(uri.path) end def validate_url url url = URI.parse(url) rescue false unless url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS) return nil end true end def extract_mime_type name mime_type = MimeMagic.by_path(name) return nil if mime_type.nil? mime_type.type end end
true
d2129db622ca4716507bb29490fbf6a0b9bdff1d
Ruby
00mjk/interview-cake
/CompressURLList/compress_url_list.rb
UTF-8
182
2.71875
3
[ "MIT" ]
permissive
class CompressURLList def initialize @visited = {} end def visit_url(url) host = URI::parse(url).host return if @visited[host] @visited[host] = true end end
true
020b3e6b608a5afbbfd9c4b6b003914f322df86f
Ruby
extremeboredom/pubtrip
/test/unit/member_test.rb
UTF-8
1,881
2.84375
3
[]
no_license
require 'test_helper' class MemberTest < ActiveSupport::TestCase test "group is required" do member = Member.new assert member.invalid? assert_equal ["can't be blank"], member.errors[:group] end test "user is required" do member = Member.new assert member.invalid? assert_equal ["can't be blank"], member.errors[:user] end test "with group and user is valid" do member = Member.new member.group = groups(:wft_special) member.user = users(:bob) assert member.valid? end test "duplicate group and user combination is invalid" do member = Member.new member.group = groups(:wft) member.user = users(:bob) assert member.invalid? assert_equal ["has already been taken"], member.errors[:user_id] end test "owner of a group cannot also be a member" do member = Member.new group = groups(:wft) member.group = group; member.user = group.owner assert member.invalid?, "The owner of a group cannot also be a member of it" assert_equal ["is also the owner"], member.errors[:user] end test "user_email will set the user field" do member = Member.new member.user_email = users(:bob).email assert_equal users(:bob), member.user end test "user_email will return the email of the user" do member = Member.new member.user = users(:bob) assert_equal users(:bob).email, member.user_email end test "user_email will set user to nil if the email is incorrect" do member = Member.new user = users(:bob) member.user = user assert_equal user, member.user member.user_email = '[email protected]' assert_nil member.user end test "user_email will return the last entered email even if the user is nil" do member = Member.new member.user_email = '[email protected]' assert_nil member.user assert_equal '[email protected]', member.user_email end end
true
7f400d13dd4cd0004bc844bc0e5f531c1909769c
Ruby
krsnachandra/learning-light
/server/app/models/course.rb
UTF-8
945
2.546875
3
[]
no_license
class Course < ApplicationRecord belongs_to :instructor has_many :chapters has_many :sections, through: :chapters has_many :all_reviews, class_name: 'Review' def reviews all_reviews.where({show_flag: true}) end def for_user(user_id) sections = sections_for_user(user_id) section_count = sections.count completion = ((sections.count { |s| s[:completed] == true }).to_f / section_count) { completion: completion, name: name, id: id, description: description, instructor: instructor, reviews: reviews.to_a.map { |r| r.with_user(user_id) }, chapters: chapters_for_user(user_id), coursename: coursename, blurb: blurb, sections: sections, } end def sections_for_user(user_id) sections.order(:section_number).to_a.map { |s| s.for_user(user_id) } end def chapters_for_user(user_id) chapters.order(:chapter_number).to_a.map { |c| c.for_user(user_id) } end end
true
27c7315ee2a016587ff9df052cdf12726df1ed70
Ruby
sleepingkingstudios-archive/examples-records
/lib/person.rb
UTF-8
537
3.171875
3
[]
no_license
# lib/person.rb require 'record' # Data class for storing information about a person. class Person < Record attributes *%w(last_name first_name middle_initial gender date_of_birth favorite_color).map(&:intern) # @return [String] The person's gender in full string format. Can return # "Female", "Male", or "Other". def gender case when @attributes[:gender] =~ /f/i "Female" when @attributes[:gender] =~ /m/i "Male" else "Other" end # case end # method gender end # class Person
true
851c601e55de775261a2cf6a7a68aaa401731e58
Ruby
GyozaGuy/GyozaGuyAPI
/spec/models/post_spec.rb
UTF-8
4,448
2.609375
3
[]
no_license
require 'spec_helper' describe Post do let(:post) { FactoryGirl.build :post } subject { post } it { should respond_to(:title) } it { should respond_to(:time) } it { should respond_to(:content) } it { should respond_to(:published) } it { should respond_to(:user_id) } # it { should not_be_published } # Fails because of a missing variable it { should validate_presence_of :title } it { should validate_presence_of :time } # it { should validate_timeliness_of :time } # TODO: maybe use https://github.com/adzap/validates_timeliness it { should validate_presence_of :content } it { should validate_presence_of :user_id } it { should belong_to :user } describe '.filter_by_title' do before(:each) do @post1 = FactoryGirl.create :post, title: 'Test post 1 of doom' @post2 = FactoryGirl.create :post, title: 'Test post 2' @post3 = FactoryGirl.create :post, title: 'Test post of doom 3' @post4 = FactoryGirl.create :post, title: 'Test post 4' end context "when a 'doom' title pattern is sent" do it 'returns the 2 posts matching' do expect(Post.filter_by_title('doom')).to have(2).items end it 'returns the posts matching' do expect(Post.filter_by_title('doom').sort).to match_array([@post1, @post3]) end end end describe '.before_or_equal_to_time' do before(:each) do @post1 = FactoryGirl.create :post, time: Time.now @post2 = FactoryGirl.create :post, time: Time.at(628232400) @post3 = FactoryGirl.create :post, time: Time.now + 1.day @post4 = FactoryGirl.create :post, time: 1.day.ago end it 'returns the posts which are before or equal to the time' do expect(Post.before_or_equal_to_time(Time.now).sort).to match_array([@post1, @post2, @post4]) end end describe '.after_or_equal_to_time' do before(:each) do @post1 = FactoryGirl.create :post, time: Time.now @post2 = FactoryGirl.create :post, time: Time.at(628232400) @post3 = FactoryGirl.create :post, time: Time.now + 1.day @post4 = FactoryGirl.create :post, time: 1.day.ago end it 'returns the posts which are after or equal to the time' do expect(Post.after_or_equal_to_time(Time.now).sort).to match_array([@post3]) # The original Time.now used on post1 is no longer current so should not match end end describe '.recent' do before(:each) do @post1 = FactoryGirl.create :post, time: Time.now @post2 = FactoryGirl.create :post, time: Time.at(628232400) @post3 = FactoryGirl.create :post, time: Time.now + 1.day @post4 = FactoryGirl.create :post, time: 1.day.ago @post2.touch @post3.touch end it 'returns the most updated records' do expect(Post.recent).to match_array([@post3, @post2, @post4, @post1]) end end describe '.search' do before(:each) do @post1 = FactoryGirl.create :post, title: 'Test post 1 of doom', content: 'This is sample content' @post2 = FactoryGirl.create :post, title: 'Test post 2', content: 'Hola there' @post3 = FactoryGirl.create :post, title: 'Test post of doom 3', content: 'Eat mor chikin' @post4 = FactoryGirl.create :post, title: 'Test post 4', content: 'Well howdy of doom' end context "when title 'doom' and content 'howdy' are set" do it 'returns an empty array' do search_hash = { title_keyword: 'doom', content_keyword: 'howdy' } expect(Post.search(search_hash)).to be_empty end end context "when title 'doom' and content 'chikin' are set" do it 'returns post3' do search_hash = { title_keyword: 'doom', content_keyword: 'chikin' } expect(Post.search(search_hash)).to match_array([@post3]) end end context "when keyword 'doom' is set" do it 'returns post1, post3, and post4' do search_hash = { keyword: 'doom' } expect(Post.search(search_hash).sort).to match_array([@post1, @post3, @post4]) end end context 'when an empty hash is sent' do it 'returns all of the posts' do expect(Post.search({})).to match_array([@post1, @post2, @post3, @post4]) end end context 'when post_ids is present' do it 'returns the post from the ids' do search_hash = { post_ids: [@post1.id, @post2.id] } expect(Post.search(search_hash)).to match_array([@post1, @post2]) end end end end
true
c30ea2ca2e7bd8b2d6001e3671260525e0401bc4
Ruby
sharanchavadi/Ruby-Exersises
/api_requests.rb
UTF-8
1,971
2.96875
3
[]
no_license
require 'httparty' require 'JSON' require 'pry' url = "http://localhost:3000/api/v1/states" response = HTTParty.get("#{url}") states = JSON.parse(response.body) puts "The states and codes are :" states.each do |state| puts "#{state["code"]} - #{state["name"]}" end puts "Enter the code to find the state" state_code = gets.chomp states.each do |state| if state_code == state["code"] puts "#{state["code"]} state found" end end url = "http://localhost:3000/api/v1/states/" puts "Enter the state code" s_code = gets.chomp response = HTTParty.get("#{url}#{s_code}") state = JSON.parse(response.body) puts "#{state["code"]} - #{state["name"]}" url = "http://localhost:3000/api/v1/states" puts "Enter the state code:" code = gets.chomp puts "Enter the state name:" name = gets.chomp HTTParty.post("#{url}", body: {"state" => {"code" => "#{code}", "name" => "#{name}"}, :headers => {'Content-Type' => 'application/json' }}) url = "http://localhost:3000/api/v1/states" response = HTTParty.get("#{url}") states = JSON.parse(response.body) puts "Enter the code to find the state and delete:" state_code = gets.chomp url = "http://localhost:3000/api/v1/states/" states.each do |state| if state_code == state["code"] #puts "#{state["code"]} state found" HTTParty.delete("#{url}#{state["code"]}") puts "Record deleted" end end url = "http://localhost:3000/api/v1/states" response = HTTParty.get("#{url}") states = JSON.parse(response.body) puts "Enter the record to be updated:" state_code = gets.chomp url = "http://localhost:3000/api/v1/states/" states.each do |state| if state_code == state["code"] #puts "#{state["code"]} state found" puts "Enter the new value for code" code = gets.chomp puts "Enter the new value for state name" name = gets.chomp HTTParty.put("#{url}#{state_code}", body: {"state" => {"code" => "#{code}", "name" => "#{name}"}, :headers => {'Content-Type' => 'application/json' }}) end end
true
ce5ed6f1231e3e475ffb555df4522bb54d395b3a
Ruby
kariya/TVS2-hikaritv
/TVS/Plug-In/hikaritv/record.rb
UTF-8
191
2.703125
3
[]
no_license
f = open(ARGV[0], "r") while (line = f.gets) if (line =~ /.*\[.*\]$/) crid = line.sub(/^.*\[/, "").sub(/\]$/, "") print "SET CRID=" + crid break end end
true
dfdce1c6fb6a8577c0e2598496c9ebb919a4bfbc
Ruby
rvt-tex/programming-univbasics-4-array-simple-array-manipulations-online-web-prework
/lib/intro_to_simple_array_manipulations.rb
UTF-8
814
3.28125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def artist = [" nickleback", "ariana", "usher", "dmx"] next_artist = "jay-z" artist.push(next_artist) end def artist = [" nickleback", "ariana", "usher", "dmx"] next_artist = "max" artist.unshift end def artist = [" nickleback", "ariana", "usher", "dmx"] usher_artist = artist.pop end #pop_with_arg def artist = [" nickleback", "ariana", "usher", "dmx"] ariana = artist.shift end #shift_with_args #using_concat def numbers = [5, 7, 8, 9] numbers.concar([1, 2, 3]) end #using_insert def artist = [" nickleback", "ariana", "usher", "dmx"] artist.insert(2, 'black rob') end #using_uniq def artist = [1, 2, 4, 4, 4, 20, 5, 6, 20, 23] artist.uniq end #using_flatten #using_delete #using_delete_at def artist = [" nickleback", "ariana", "usher", "dmx"] artist.delete_at(2) end
true
75e8005bbb83ea0030d2af1a3a9adfd37c4aa9d8
Ruby
dzackgarza/coursera_saas
/hw_one/hw_one_part_2.rb
UTF-8
1,362
4.0625
4
[]
no_license
# Part 2 class WrongNumberOfPlayersError < StandardError ; end # Raised when strategy is not 'R', 'P', or 'S' class NoSuchStrategyError < StandardError ; end # Given a two element list, return the name and strategy of the winning player. def rps_game_winner(game) raise WrongNumberOfPlayersError unless game.length == 2 p1strat = game[0][1].downcase p2strat = game[1][1].downcase raise NoSuchStrategyError unless ["r", "p", "s"].include?(p1strat) or ["r", "p", "s"].include?(p2strat) # So many comparisons! #TODO There must be a better way. if p1strat == "r" && p2strat == "p" or p1strat == "p" && p2strat == "s" or p1strat == "s" && p2strat == "r" puts "#{game[1][0]} wins against #{game[0][0]}." return game[1] else puts "#{game[0][0]} wins against #{game[1][0]}." return game[0] end end def rps_tournament_winner(tournament) if tournament[0][0].length == 2 return rps_game_winner([rps_tournament_winner(tournament[0]), rps_tournament_winner(tournament[1])]) else return rps_game_winner([tournament[0], tournament[1]]) end end tournament = [ [ [ ["Armando", "P"], ["Dave", "S"] ], [ ["Richard", "R"], ["Michael", "S"] ], ], [ [ ["Allen", "S"], ["Omer", "P"] ], [ ["David E.", "R"], ["Richard X.", "P"] ] ] ] #winner = rps_tournament_winner(tournament) #puts "#{winner[0]} wins the tournament with #{winner[1]}"
true
f7dd8588526d5b5dde9dad3c970fd2b160671a85
Ruby
transitland/transitland-datastore
/app/controllers/concerns/jwt_auth_token.rb
UTF-8
805
2.515625
3
[ "MIT" ]
permissive
# https://github.com/jimjeffers/rails-devise-cors-jwt-example/blob/master/lib/auth_token.rb module JwtAuthToken extend ActiveSupport::Concern SIGNING_ALGORITHM = 'HS256' def self.issue_token(payload) payload['exp'] = 24.hours.from_now.to_i # Set expiration to 24 hours. JWT.encode(payload, Rails.application.secrets.secret_key_base, SIGNING_ALGORITHM) end def self.valid?(token) begin JWT.decode(token, Rails.application.secrets.secret_key_base, true, { algorithm: SIGNING_ALGORITHM }) rescue false end end def verify_jwt_token if request.headers['Authorization'].present? token = request.headers['Authorization'].split(' ').last if JwtAuthToken.valid?(token) return true end end return head :unauthorized end end
true
6912d6ce7589d860eabb89cb6f62b2466eb0a566
Ruby
byverdu/boris_bikes
/lib/bike.rb
UTF-8
866
3.265625
3
[]
no_license
class Bike attr_reader :serial_number attr_accessor :rent_time, :return_time $bikes = [] def serial_number_generator sn = ("A".."Z").to_a.sample(3).join indicative1 =(0..9).to_a.sample(3).join indicative2 =(0..9).to_a.sample(2).join indicative3 =(0..9).to_a.sample(5).join "#{sn} #{indicative1}-#{indicative2}-#{indicative3}" end def initialize(serial_number: serial_number_generator) @broken = false @serial_number = serial_number end def rent! @rent_time = Time.now.round(0) end def return! @return_time = Time.now.round(0) raise "You have to pay!" if seconds_rented > 1800 end def seconds_rented @return_time - @rent_time end def broken? @broken end def break! @broken = true end def fix! @broken = false end def store_serial_number $bikes << {:serial_number => @serial_number} end end
true