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
cf00c18c781ff929723cc84caa235c990e8b5e90
Ruby
mmabraham/Games
/guessing-game/guessing_game.rb
UTF-8
612
3.78125
4
[]
no_license
def guessing_game target = rand(1..100) count = 1 puts "guess a number" loop do guess = gets.chomp.to_i guess == target ? break : puts(guess) guess > target ? puts(" too high") : puts(" too low") count += 1 end puts "You got it in #{count} guesses" puts target end def shuffle_file(input_path) input_arr = File.readlines(input_path) output_path = input_path.sub(".", "-shuffled.") File.open(output_path, "w") do |f| input_arr.shuffle.each { |line| f.puts(line) } end end if $PROGRAM_NAME == __FILE__ ARGV.empty? ? guessing_game : shuffle_file(ARGV[0].chomp) end
true
66df2d95c4b05df4e9e4083c0a844b8dc2974913
Ruby
guilffer/kanbangit
/lib/kanbangit/item.rb
UTF-8
881
2.859375
3
[]
no_license
require 'yaml' module Kanbangit class Item attr_reader :name def initialize(name, env) @name = name @env = env create_itemfile_if_necessary load_itemfile end def create_itemfile_if_necessary unless File.exists?(itemfile_path) @data = {'column' => 'todo'} update_file end end def load_itemfile @data = YAML.load_file itemfile_path() end def itemfile_path File.join(@env.items_path, name+'.yml') end def update (key, value) @data[key.to_s] = value update_file end def method_missing(method_name) @data[method_name.to_s] if @data.has_key? method_name.to_s end private def update_file File.open itemfile_path, 'w' do |file| file.write(@data.to_yaml) end end end end
true
74f52c21bcd4daa886212d2e74813832b1dcb3b0
Ruby
jayantsharma/rubyScripts
/problem1.rb
UTF-8
448
3.390625
3
[]
no_license
def solution(word) possibleAnagrams = word.chars.to_a.permutation.map(&:join) answer = Array.new file = File.new("wl.txt", "r") lines = file.readlines lines.each do |line| word = line.chomp possibleAnagrams.include?(word) answer.push(word) if possibleAnagrams.include?(word) end return answer end puts "----", solution("beat") #a = Array.new #lines = readlines #lines.each { |line| a.push(line.chomp.to_i) } #puts solution(a)
true
34696cc759fd8fb4f117211922eb8388fb25a3a5
Ruby
MelissaKroese/ruby-quizzes
/quiz3.rb
UTF-8
147
4
4
[]
no_license
puts "What is your name?" name=gets.chomp if name == "Alice" puts "Hi #{name}" elsif name == "Bob" puts "Hi #{name}" else puts "Hi there" end
true
c8a917974f7b9b231bf6213632537fa6ac2082c6
Ruby
psyomn/wlog
/lib/wlog/commands/fetch_git_commits_standard.rb
UTF-8
731
2.5625
3
[]
no_license
require 'wlog/commands/commandable' require 'wlog/commands/fetch_git_commits' require 'wlog/tech/git_commit_parser' module Wlog # We don't set the repo and author - get it directly from keyvalue # Use the other git fetcher if you want something more configurable # @author Simon Symeonidis class FetchGitCommitsStandard < Commandable # @param from date start # @param to date end # authors def initialize(from, to) @from, @to = from, to @author = KeyValue.get('author') @repo = KeyValue.get('git') end # Run the parser on the repo; yield commits def execute cmd = FetchGitCommits.new(@from, @to, @repo, @author) cmd.execute @commits = cmd.commits nil end attr_accessor :commits end end
true
1b7af91e81a287634728b6338e22d64ae6e991b3
Ruby
bbensky/pine_ruby_book_exercises
/ch11_reading_writing_plus/try_more_yaml.rb
UTF-8
446
2.921875
3
[]
no_license
require 'yaml' test_array = [['Age In Years', 37], ['Age In Years (text)', '37'], ['Fav Color', 'Green'], ['Likes Nachos', true], ['Likes Whiskey', 'true']] test_string = test_array.to_yaml filename = 'description.text' File.open filename, 'w' do |f| f.write test_string end read_string = File.read filename read_array = YAML::load read_string puts read_string puts puts read_array
true
4e7cb40b554e7d39526e3d39fa643f67fc8adad2
Ruby
aydarsh/projecteuler
/problem91.rb
UTF-8
347
3.125
3
[]
no_license
require "matrix" def num_right_triangles n (0..n).to_a. repeated_permutation(2).to_a.drop(1). combination(2). map{|el| [Vector.elements(el[0]), Vector.elements(el[1])]}. select do |el| el[0].inner_product(el[1])==0 or el[0].inner_product(el[1]-el[0])==0 or el[1].inner_product(el[1]-el[0])==0 end.size end p num_right_triangles 50
true
3925c755768c2c239f49a20c788bc2c36c5d900c
Ruby
jagaapple/string_foundation.rb
/lib/string_foundation/like.rb
UTF-8
664
3.34375
3
[ "MIT" ]
permissive
# ============================================================================== # LIB - STRING FOUNDATION - LIKE # frozen_string_literal: true # ============================================================================== require_relative "convertible" class String # Check whether a string is an integral number. def like_i? return false unless self.to_i? num = self.without_leading_zeros (num.to_i == num.to_i) && !num.include?(".") end # Check whether a string is a floating point number. def like_f? return false unless self.to_f? num = self.without_leading_zeros (num.to_i != num.to_f) || num.include?(".") end end
true
c77813161bb9431dac4103e7a5e815df820ceb2e
Ruby
PianoFF/anagram-detector-london-web-102819
/lib/anagram.rb
UTF-8
488
3.671875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Your code goes here! require "pry" class Anagram attr_accessor :word def initialize (word) @word = word end def match(array) word_letters = word.chars array.select do |word| word.chars.sort == word_letters.sort end end end # def select(array) # a = [] # array.each do |item| # return_value = yield item # if return_value == true # a << item # end # end # a # end
true
ac1db6abd15bcb0365b529ce141ee12eccb33d23
Ruby
Royathe/Viope-Ruby-Workspace
/Viope/Luku3.rb
UTF-8
2,798
3.296875
3
[]
no_license
#TEHTÄVÄ 5 pelaaja = 0 tieto = 0 valinta = 0 while valinta < 4 puts "1: Torakka 2: Jalka 3: Ydinpommi 4: lopeta" puts "Valitse (1-4):" valinta = gets.to_i tval = rand(3) + 1 unless valinta == 4 if valinta == tval puts "Valitsitte saman, tasapeli." elsif valinta == 1 print "Valitsit torakan, tietokone valitsi " if tval == 2 puts "jalan." puts "Tietokone voitti." tieto = tieto + 1 elsif tval == 3 puts "ydinpommin." puts "Voitit!" pelaaja = pelaaja + 1 end elsif valinta == 2 print "Valitsit jalan, tietokone valitsi " if tval == 3 puts "ydinpommin." puts "Tietokone voitti." tieto = tieto + 1 elsif tval == 1 puts "torakan." puts "Voitit!" pelaaja = pelaaja + 1 end elsif valinta == 3 print "Valitsit ydinpommin, tietokone valitsi " if tval == 1 puts "torakan." puts "Tietokone voitti." tieto = tieto + 1 elsif tval == 2 puts "jalan." puts "Voitit!" pelaaja = pelaaja + 1 end end puts "Peli on pelaaja #{pelaaja} : tietokone #{tieto}" end end #TEHTÄVÄ 4 =begin puts "Oraakkeli vastaa kyllä/ei-muodossa" puts "Kirjoita kysymyksesi Oraakkelille:" teksti = gets puts "Kysymyksesi oli: #{teksti}" print "Tähän Oraakkeli vastasi: " sat = rand(100) case sat when 0..19 then print "Ei missään nimessä!" when 20..44 then print "Ei varmaankaan" when 45..54 then print "En osaa sanoa." when 55..79 then print "Luultavasti kyllä." when 80..90 then print "Ehdottomasti kyllä." end #TEHTÄVÄ 3 =begin user = "Erkki" pass = "haukionkala" puts "Anna nimi: " nameinp = gets.chomp if nameinp == user puts "Anna salasana: " passinp = gets.chomp if passinp == pass puts "Hei Erkki!" else puts "Et ole Erkki." end else puts "En tunne sinua." end #TEHTÄVÄ 2 =begin print "Valitse x-akselin arvo väliltä 0-9: "; x = gets.to_i print "Valitse y-akselin arvo väliltä 0-9: "; y = gets.to_i if x < 0 or y < 0 puts "Annoit negatiivisen arvon." elsif x < 5 and y < 5 puts "Olet vasemmassa alakulmassa." elsif x < 5 and y > 4 puts "Olet vasemmassa yläkulmassa." elsif x > 4 and y > 4 puts "Olet oikeassa yläkulmassa." elsif x > 4 and y < 5 puts "Olet oikeassa alakulmassa." end #TEHTÄVÄ 1 =begin puts "Anna 1. luku:" arvo1 = gets arvo1 = arvo1.to_f puts "Anna 2. luku:" arvo2 = gets arvo2 = arvo2.to_f puts "(Y)hteen-, (V)ähennys- vai (K)ertolasku?" valinta = gets.chomp tulos = 0 if valinta == "Y" tulos = arvo1 + arvo2 elsif valinta == "V" tulos = arvo1 - arvo2 elsif valinta == "K" tulos = arvo1 * arvo2 end puts "Tulos on #{tulos}" =end
true
7ecdc7ca47e839d6b64ef4b3954767779a70a40c
Ruby
INTJBrandon/oo-tic-tac-toe-bootcamp-prep-000
/lib/tic_tac_toe.rb
UTF-8
2,738
4.09375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class TicTacToe def initialize(board = nil) @board = board || Array.new(9, " ") end WIN_COMBINATIONS = [ [0,1,2], # Top Row Win [3,4,5], # Middle Row Win [6,7,8], # Bottom Row Win [0,3,6], # First Column Win [1,4,7], # Second Column Win [2,5,8], # Third Column Win [0,4,8], # Diagonal Win from Left [6,4,2] # Diagonal Win from Right ] def display_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 input_to_index(user_input) user_input.to_i - 1 end def move(index, current_player) @board[index] = current_player end def position_taken?(position) if @board[position] == " " || @board[position] == "" || @board[position] == nil return false else return true end end def valid_move?(position) if position_taken?(position) == true || position.between?(0,8) == false return false else return true end end def turn_count counter = 0 @board.each do |player| if player == "X" || player == "O" counter += 1 end end counter end def current_player turn = turn_count if turn.even? return "X" else return "O" end end def turn puts "Please enter 1-9:" user_input = gets.strip position = input_to_index(user_input) if valid_move?(position) move(position, current_player) display_board else turn end end def won? wins_combo = false if @board == [" ", " ", " ", " ", " ", " ", " ", " ", " "] return false else WIN_COMBINATIONS.each do |wins| char1 = "X" char2 = "O" if @board[wins[0]] == char1 && @board[wins[1]] == char1 && @board[wins[2]] == char1 || @board[wins[0]] == char2 && @board[wins[1]] == char2 && @board[wins[2]] == char2 wins_combo = wins end end wins_combo end end def full? @board.none?{|spaces| spaces == " "} end def draw? if full? == true && won? == false return true end end def over? if draw? return true elsif full? return true elsif won? return true else return false end end def winner win_combo = won? if win_combo index = win_combo[0] return @board[index] else return nil end end def play until over? turn end if won? puts "Congratulations #{winner}!" else draw? puts "Cat's Game!" end end end
true
9639f5398efae771f8587c77537401ecdaea1db6
Ruby
kelvin8773/data-algorithm
/6-sorting-challenges/ex8.8-find-the-duplicates.rb
UTF-8
1,583
3.625
4
[ "MIT" ]
permissive
require 'benchmark/ips' def duplicates(arr1, arr2) res = arr2.clone arr1.each do |x| res.delete_at(res.index(x)) end res.sort! end def duplicates_e(arr1, arr2) map1 = arr1.each_with_object(Hash.new(0)) { |num, map| map[num] += 1 } map2 = arr2.each_with_object(Hash.new(0)) { |num, map| map[num] += 1 } map2.select { |key, value| value > map1[key] }.keys.sort end def duplicates_y(arr1, arr2) source = arr1.each_with_object(Hash.new(0)){|num, hash| hash[num]+=1} compare= arr2.each_with_object(Hash.new(0)){|num, hash| hash[num]+=1} res = [] compare.each {|key, value| res << key if value > source[key]} res.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] # p duplicates([10, 3, 17, 11, 5, 10, 3, 9, 11, 33, 41, 22, 8, 17, 3, 11, 35, 52, 73, 88], [22, 3, 10, 11, 33, 41, 11, 5, 3, 17, 10, 3, 9, 11, 52, 73, 88, 35, 10, 11, 3, 8, 17, 8]) # =>[3, 8, 10, 11] list1 = [203, 204, 205, 206, 207, 208, 203, 204, 205, 206] list2 = [203, 204, 204, 205, 206, 207, 205, 208, 203, 206, 204, 205, 206] # list1 = [10, 3, 17, 11, 5, 10, 3, 9, 11, 33, 41, 22, 8, 17, 3, 11, 35, 52, 73, 88] # list2 = [22, 3, 10, 11, 33, 41, 11, 5, 3, 17, 10, 3, 9, 11, 52, 73, 88, 35, 10, 11, 3, 8, 17, 8] Benchmark.ips do |x| x.config(:time => 3, :warmup => 2) x.report("Kelvin's Method") {duplicates(list1, list2)} x.report("Yunus's Method") {duplicates_y(list1, list2)} x.report("Ebuka's Method") {duplicates_e(list1, list2)} x.compare! end
true
540ab2344effdce6660eac85eb1b735b4f3d3a1b
Ruby
maxdunn210/MaxWiki
/vendor/plugins/drag_and_drop_media/app/models/drag_and_drop_media_model.rb
UTF-8
2,487
2.671875
3
[ "MIT", "BSD-2-Clause" ]
permissive
require 'xmlrpc/client' require 'rexml/document' require 'open-uri' class DragAndDropMediaModel attr_reader :display_name, :tags, :user, :page, :per_page, :on # initialize client instance, and set parameters to nil # note that success does not indicate that api_key is ok def initialize( name, per_page = 8, default_tag = 'okapi' ) @display_name = name @api_key = @api_path = @api_index = nil @on = false @dirty = true @tags = default_tag @user = @items = nil @page = 1 @per_page = per_page end def visible! @on = true end def toggle @on = !@on end def forward @page += 1 @dirty = true end def backward if @page > 1 @page -= 1 @dirty = true end end def update (tags, user) @page = 1 @tags = tags @user = user @dirty = true end def search(tags=@tags,user=@user,page=@page) if @tags == tags && @page == page && @user == user && !@dirty return @items end @dirty = false @tags = tags @user = user @page = page @items = search_implementation( @tags, @user, @page, @per_page ) if @items && @items.size > @per_page @items = @items[((@page-1)*@per_page)..(@page*@per_page-1)] end return @items end def xmlrpc_client(host,path,port) XMLRPC::Client.new(host,path,port) end def xmlrpc_get_xml(method,args,item_string) str = @api_path.call(method,args) res = REXML::Document.new(str) items = res.root.elements.to_a(item_string) end def uri_get_xml(args,item_str) req = @api_path.dup args.each do |x| req << x[0] + '=' + x[1] + '&' end req.gsub!(/&\Z/,'') lines = nil open( req ) { |file| lines = file.read } res = REXML::Document.new( lines ) return res.root.get_elements(item_str) end def uri_get_response(args) req = @api_path.dup args.each do |x| req << x[0] + '=' + x[1] + '&' end req.gsub!(/&\Z/,'') lines = nil open( req ) { |file| lines = file.read } return lines end # this is for testing and needs to be overridden def search_implementation( tags, user, page, per_page ) if tags == 'testtag' items = [] 1.upto(20) {|i| items<< ('tag_'+i.to_s)} return items elsif user == 'testuser' items = [] 1.upto(20) {|i| items<< ('user_'+i.to_s)} return items elsif !user && !tags return nil else return [] end end end
true
702600015d6c4546ea5282398815f65c4fcf0136
Ruby
miraissan/dxruby_blocks
/block_collision/coll_circle/atari_en6.rb
UTF-8
1,528
3.15625
3
[ "Unlicense" ]
permissive
# 衝突判定の自作(円);atari_array(jibun, array) (判定相手が配列) # 衝突の有/無で ぶつかった最初のオブジェクト/nil require 'dxruby' def atari?(jibun, aite) x0 = jibun.x rad_x0 = jibun.image.width / 2 cen_x0 = x0 + rad_x0 y0 = jibun.y rad_y0 = jibun.image.height / 2 cen_y0 = y0 + rad_y0 x1 = aite.x rad_x1 = aite.image.width / 2 cen_x1 = x1 + rad_x1 y1 = aite.y rad_y1 = aite.image.height / 2 cen_y1 = y1 + rad_y1 # 半径は長径と短径の1/2に設定 # 半径同士の和 cir_dis = (rad_x0 + rad_y0) / 2 + (rad_x1 + rad_y1) / 2 # 2乗で比較する cir_dis_2 = cir_dis **2 dist_2 = (cen_x0 - cen_x1) ** 2 + (cen_y0 - cen_y1) ** 2 cir_dis_2 >= dist_2 end def atari_array(jibun, array) array.each do |a| if atari?(jibun, a) return a end end nil end image0 = Image.new(100, 100).circle_fill( 50, 50, 50, C_WHITE) image1 = Image.new(200, 200).circle_fill(100, 100, 100, C_WHITE) image2 = Image.new(200, 200).circle_fill(100, 100, 100, C_RED) ball = Sprite.new(300, 400, image0) block1 = Sprite.new(110, 130, image1) block2 = Sprite.new(390, 130, image1) blocks = [block1, block2] font = Font.new(32) Window.loop do ball.x = Input.mouse_pos_x ball.y = Input.mouse_pos_y ball.draw col = atari_array(ball, blocks) p col if col Window.draw_font(0, 0, "hit!", font) col.image = image2 Sprite.draw(blocks) col.image = image1 else Sprite.draw(blocks) end end
true
e07a2aff55101ff6f3fe6efe030268390f44c4cd
Ruby
ngoctoandhv/Ruby_Basic
/03. Ruby - Methods/01.Method-arguments.rb
UTF-8
388
3.515625
4
[]
no_license
def calculate_value(x,y) x + y end def calculate_value(value='default', arr=[]) puts value puts arr.sum end def calculate_value(x,y,*otherValues) puts otherValues end def accepts_hash(arguments) # print out what it received print "got: ", arguments.inspect end # Ruby 2.0 def calculate_value(a, b, c: true, d: false) puts a, b, c, d end
true
b30808804e85d5e535aa2236f3fdd68ebf2a5284
Ruby
compwron/knowgame
/lib/round.rb
UTF-8
825
3.796875
4
[]
no_license
class Round NEXT = 'next' DONE = 'done' attr_reader :filename, :remaining_tries def initialize(filename, remaining_tries) @filename = filename @remaining_tries = remaining_tries @next_round = @game_over = @correct = false @wrong_guesses = 0 end def guess(guessed_filename) correct = @filename == guessed_filename correct ? @correct = @next_round = true : @wrong_guesses += 1 @next_round = true if guessed_filename == NEXT || @wrong_guesses == @remaining_tries if guessed_filename == DONE @game_over = true @next_round = false end end def next_round? _mercy filename @next_round end def game_over? _mercy filename @game_over end def correct? @correct end def _mercy(filename) puts "File was: #{filename}" end end
true
c4f2318b5b9594fc58b7c4a8e90dd9294de89487
Ruby
Dmitry-White/Ruby-Task
/script.rb
UTF-8
3,683
3.125
3
[ "MIT" ]
permissive
require 'nokogiri' require 'curb' require 'csv' #------------------ Reading Input ------------------------------- ARGC = ARGV.length if ARGC < 2 or ARGC > 2 puts "Usage: ruby <input_file> <output_file> <URL>" abort end output = ARGV[0] address = ARGV[1] puts 'Input received. Getting source html file.' #---------------------------------------------------------------- #---------------- Nokogiri Parse Function ------------------------- def get_html(link) url = Curl.get(link) do |curl| #curl.verbose = true curl.follow_location = true curl.ssl_verify_peer = false end html = Nokogiri::HTML(url.body_str) html end # --------------------------------------------------------------- html = get_html(address) url = html.xpath('//link[@rel="canonical"]/@href').to_s puts 'Source html file received.' another_page = true page_num = 1 urls_num = 0 puts 'Initiating page URL listing sequence.' #------------------- Scrap with Xpath ------------------------- url_list = Array.new while another_page == true numb = 0 urls = Array.new html.xpath('//div/h5/a/@href').each do |url| urls << url numb += 1 end urls_num += numb url_list << urls #-------------------- Check for the next page -------------------------- disabled_right_button = html.xpath('boolean(//li[@id="pagination_next_bottom" and not(@class="disabled pagination_next")])') if disabled_right_button html = get_html(url + "?p=#{page_num+1}") else another_page = false end #-------------------------------------------------------------------------- puts " Added product links from page " + page_num.to_s page_num += 1 end #----------------------------------------------------------------- len = url_list.length puts 'Pages are listed. Total number of links: ' + urls_num.to_s #------------------- Write file with list of page links ---------- link_num=0 File.open("url_output.txt", "wb") do |file| (0..len-1).each do |index| file.puts(url_list[index]) link_num += 1 end end #----------------------------------------------------------------- puts 'Initiating scrapping sequence.' #-------------------- Search for products details ------------------ url_list = File.readlines('url_output.txt') product_num = 1 url_list.each do |link| link = link.strip product_html = get_html(link) product_name = product_html.xpath('//div[@class="product-name"]/h1/text()') product_weights = product_html.xpath('//li/span[@class="attribute_name"]/text()') product_prices = product_html.xpath('//li/span[@class="attribute_price"]/text()') product_images = product_html.xpath('//a[@data-fancybox-group="other-views"]/@href') #--------------------------- Write CSV file --------------------------------------- CSV.open(output, 'a') do |row| (0..product_weights.length-1).each do |index| row << ['Name: ', product_name.to_s.strip + ' - ' + product_weights[index].to_s] row << ['Price: ', product_prices[index].to_str] row << ['Image: ', product_images[index]] row << ['-----------------------------------------------------------------------------'] end end #---------------------------------------------------------------------------------- puts " Description of product " + product_num.to_s + " added to .csv file." product_num += 1 #-------------------- Limit number of links scrapped-------------------- if product_num == 50 break end #----------------------------------------------------------------------- end puts 'Scraping complete. Refer to ' + ARGV[0] + ' file for script output.' #-------------------------------------------------------------------------
true
58283284a273d5393fd46c3177740bde4e41ccc0
Ruby
XanderStrike/artist-fanart-finder
/lib/google.rb
UTF-8
446
2.703125
3
[]
no_license
class GoogleFetcher < Base def initialize(fetcher) @fetcher = fetcher end def fetch(artist) get_art_from_google(artist) end private def get_art_from_google(artist) Google::Search::Image.new(query: "#{artist} music", image_size: Configuration.preferred_sizes, image_type: :photo).each do |image| next unless (image.width * 1.0 / image.height) > 1.25 download(artist, image.uri) break end end end
true
c6a47a0876de3aed4ff726635c1d33254a3d4fb9
Ruby
chrislabarge/event-manager
/event_manager.rb
UTF-8
424
2.984375
3
[]
no_license
require "csv" puts "EventManager Initialized" contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol contents.each do |row| name = row[:first_name] zipcode = row[:zipcode] if zipcode.nil? zipcode = "00000" elsif zipcode.length < 5 zipcode = zipcode.rjust 5, "0" elsif zipcode.length > 5 zipcode = zipcode[0..4] end puts "#{name} #{zipcode}" end 3.times { puts "----------"}
true
a92f0229bd034c7fbee8618772c6a57d558cb247
Ruby
Stella-Nthenya/Ruby-Object-Oriented-Programming-Exercises
/120_oop_exercises/basics_accessor_methods/guarenteed_formatting.rb
UTF-8
365
4.53125
5
[]
no_license
# Using the following code, add the appropriate accessor methods so that @name is capitalized upon assignment. class Person attr_reader :name def name=(name) # manually write the setter method @name = name.capitalize # format upon assignment end end person1 = Person.new person1.name = 'eLiZaBeTh' puts person1.name # Expected output: # Elizabeth
true
937cddc8a961ee1124bfefd41ef8648d39c4ead2
Ruby
jcoyne/rdf
/lib/rdf/model/term.rb
UTF-8
2,248
3.203125
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
module RDF ## # An RDF term. # # Terms can be used as subjects, predicates, objects, and contexts of # statements. # # @since 0.3.0 module Term include RDF::Value include Comparable ## # Compares `self` to `other` for sorting purposes. # # Subclasses should override this to provide a more meaningful # implementation than the default which simply performs a string # comparison based on `#to_s`. # # @abstract # @param [Object] other # @return [Integer] `-1`, `0`, or `1` def <=>(other) self.to_s <=> other.to_s end ## # Compares `self` to `other` to implement RDFterm-equal. # # Subclasses should override this to provide a more meaningful # implementation than the default which simply performs a string # comparison based on `#to_s`. # # @abstract # @param [Object] other # @return [Integer] `-1`, `0`, or `1` # # @see http://www.w3.org/TR/rdf-sparql-query/#func-RDFterm-equal def ==(other) super end ## # Determins if `self` is the same term as `other`. # # Subclasses should override this to provide a more meaningful # implementation than the default which simply performs a string # comparison based on `#to_s`. # # @abstract # @param [Object] other # @return [Integer] `-1`, `0`, or `1` # # @see http://www.w3.org/TR/rdf-sparql-query/#func-sameTerm def eql?(other) super end ## # Returns a base representation of `self`. # # @return [RDF::Value] def to_base self end ## # Returns `true` if `self` is a {RDF::Term}. # # @return [Boolean] def term? true end ## # Returns itself. # # @return [RDF::Value] def to_term self end protected ## # Escape a term using standard character escapes # # @param [String] string # @return [String] def escape(string) string.gsub('\\', '\\\\'). gsub("\b", '\\b'). gsub("\f", '\\f'). gsub("\t", '\\t'). gsub("\n", '\\n'). gsub("\r", '\\r'). gsub('"', '\\"') end end # Term end # RDF
true
99dca9f65cc02b7983180d81f64d959748394267
Ruby
rsmease/ruby-misc
/greet.rb
UTF-8
111
3.421875
3
[]
no_license
def greet(name) if name.nil? or name === "" return nil else return "hello " + name + "!" end end
true
b146231f20ddda1647046841e6e6a5dc12795171
Ruby
vikkanaev/mkdev.me
/lib/movie_industry/by_country.rb
UTF-8
676
2.859375
3
[]
no_license
module MovieIndustry class ByCountry def initialize(movie_collection) @movie_collection = movie_collection end def method_missing(method, *args, &block) return super if prohibited_country_name?(method) raise(ArgumentError, "Country filter can't be called with args or block") if block || args.any? @movie_collection.filter(country: sym_to_filter(method)) end def respond_to_missing?(method, *) !prohibited_country_name?(method) || super end private def prohibited_country_name?(method) method.to_s =~ /\?|\!|=/ end def sym_to_filter(sym) /#{sym.to_s.gsub('_', ' ')}/i end end end
true
0459dd3e3c60d3abc3755bacf83f297602476500
Ruby
ajdil91/rails-mister-cocktail
/db/seeds.rb
UTF-8
2,449
2.609375
3
[]
no_license
require 'json' require 'rest-client' # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # url = "https://www.thecocktaildb.com/api/json/v1/1/list.php?i=list" # json = open(url).read # ingredients = JSON.parse(json) # ingredients.each do |ingredient| # Ingredient.create(name: ingredient["strIngredient1"]) # end # Destroying old database puts "=========Destroying Old Cocktails and Ingredients===========" Cocktail.destroy_all Ingredient.destroy_all # Seeding users puts "=========Creating Users========" User.create( username: "FedM", description: "Loves cocktails", photo: "akjhhd", email: "[email protected]", encrypted_password: '123456' ) # Seeding cocktails puts "=========Saving Cocktails==========" response = RestClient.get('https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Ordinary_Drink') drinks = JSON.parse(response.body)['drinks'] drinks.first(10).each do |drink| id = drink['idDrink'] response = RestClient.get("https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=#{id}") drinks = JSON.parse(response.body)['drinks'][0] Cocktail.create!(name: drinks['strDrink'], description: drinks['strCategory'], remote_photo_url: drinks['strDrinkThumb'], user: User.first) end # Seeding Ingredients puts "========Saving Ingredients============" # API Ingredients response = RestClient.get('https://www.thecocktaildb.com/api/json/v1/1/list.php?i=list') ingredients = JSON.parse(response.body)['drinks'] ingredients.each do |ingredient| Ingredient.create(name: ingredient['strIngredient1']) end # Custom Ingredients Ingredient.create(name: "lemon") Ingredient.create(name: "lime") Ingredient.create(name: "ice") Ingredient.create(name: "tonic") Ingredient.create(name: "pineapple juice") Ingredient.create(name: "orange juice") Ingredient.create(name: "fruit punch") Ingredient.create(name: "mint leaves") Ingredient.create(name: "rum") Ingredient.create(name: "gin") Ingredient.create(name: "tequila") Ingredient.create(name: "vodka") Ingredient.create(name: "whiskey") Ingredient.create(name: "champange") puts "===========New Database Seeded Successfully==============="
true
500c552e682e9974c7930ae6344067f6ac949065
Ruby
yashp82099/ruby-oo-object-relationships-kickstarter-lab-atlanta-web-111819
/lib/project.rb
UTF-8
423
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Project attr_reader :title def initialize(title) @title = title end def add_backer(backer) ProjectBacker.new(self, backer) end def backers # a = ProjectBacker.all.map do |pb| # pb.project == self # end # a.map{|a|a.backer} ProjectBacker.all.select{|pb| pb.project == self}.map{|i| i.backer} end end
true
ca53b8eb2328fe5f12e4581d555b194ca02c1a51
Ruby
JvPelai/stock_picker
/stock_picker.rb
UTF-8
1,096
3.96875
4
[]
no_license
def stock_picker (stocks) buying_day = stocks[0] selling_day = stocks[1] possible_profits = [] operations = [] #calculates the profits of each possible operation stocks.each_with_index do |stock,index| buying_day = index + 1 while index < stocks.length - 1 do i = stocks[index + 1].to_i selling_day = stocks.find_index(i)+1 profit = i - stock possible_profits.push(profit) operations.push([buying_day,selling_day, profit]) index += 1 end end buy_low = 0 sell_high = 0 highest = possible_profits.sort[-1] #loops through each operation to find the buying and selling days with the highest profit operations.each do |days| p days if days[2] == highest buy_low = days[0].to_i sell_high = days[1].to_i end end puts "Your best option would be to buy the stocks on day #{buy_low}, and sell it on day #{sell_high}, for a profit of $#{highest} dollars" end stock_picker([17,3,6,9,15,8,6,1,10])
true
587869ad455a46ea7f088bce9ec4091bf55f909d
Ruby
hunter3142/Pillar-Vending-Machine
/models/coins.rb
UTF-8
415
3.140625
3
[]
no_license
require_relative 'inventory' class Coins attr_accessor :inserted_coin_total, :total_change def initialize @inserted_coin_total = 0 @total_change = 0 end def insert_coin (inserted_coin) @inserted_coin_total += inserted_coin end def reset_totals @inserted_coin_total = 0 @total_change = 0 end def change_due(item) @total_change = inserted_coin_total - item.price end end
true
c2e5f671885404f26993b50b021a0f840da9a1a3
Ruby
clementlo/tealeaf1_prework
/chomp.rb
UTF-8
646
3.578125
4
[]
no_license
puts 'Hello there, what\'s your first name?' first_name = gets.chomp puts 'Hello there, what\'s your middle name name?' middle_name = gets.chomp puts 'Hello there, what\'s your last name?' last_name = gets.chomp puts 'Pleased to meet you, ' + first_name + ' ' + middle_name + ' ' + last_name + '!' full_name_length = first_name.length + middle_name.length + last_name.length puts 'Your full name contains ' + full_name_length.to_s + ' letters!' puts 'Hey there, what\'s your favourite number?' favourite_number = gets.chomp new_favourite_number = favourite_number.to_i + 1 puts 'Hey, how about ' + new_favourite_number.to_s + '? It\'s bigger!'
true
415a889c9becaf46c7643badf1c6f21a2d156495
Ruby
mzakzook/sql-crowdfunding-lab-sf-web-091619
/lib/sql_queries.rb
UTF-8
1,804
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your sql queries in this file in the appropriate method like the example below: # # def select_category_from_projects # "SELECT category FROM projects;" # end # Make sure each ruby method returns a string containing a valid SQL statement. def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title "SELECT title, SUM(amount) FROM projects JOIN pledges ON pledges.project_id == projects.id GROUP BY title ORDER BY title ASC;" end def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name "SELECT name, age, SUM(amount) FROM users JOIN pledges ON pledges.user_id == users.id GROUP BY users.id ORDER BY name ASC;" end def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal "SELECT title, SUM(pledges.amount) - funding_goal FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY title, funding_goal HAVING SUM(pledges.amount) >= funding_goal;" # WHERE SUM(pledges.amount) >= funding_goal # GROUP BY pledges.project_id; end def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_summed_amount "SELECT name, SUM(pledges.amount) FROM users JOIN pledges ON users.id = pledges.user_id GROUP BY name ORDER BY SUM(pledges.amount) ASC;" end def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category "SELECT category, amount FROM projects JOIN pledges ON projects.id = pledges.project_id WHERE category = 'music';" end def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category "SELECT category, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id WHERE category = 'books' GROUP BY category;" end
true
8b538a36efcddd30e8ee3dc823309fb81236bade
Ruby
Rizzooo/ruby-objects-has-many-lab-onl01-seng-pt-052620
/lib/author.rb
UTF-8
446
3.203125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Author attr_accessor :name @@post_count = 1 def initialize(name) @name = name @posts = [] end def add_post(posting) @posts << posting posting.author = self @@post_count += 1 end def add_post_by_title(posting) posting = Post.new(posting) add_post(posting) end def posts Post.all.select {|posts| posts.author == self} end def self.post_count @@post_count end end
true
1a079c490441998355a4f81f5a963e72ef777133
Ruby
weaponisedbutterfly/warehouse_picker
/warehouse_picker_functions.rb
UTF-8
1,223
2.546875
3
[]
no_license
WAREHOUSE = [ {bay: "a10", item: "rubber band"}, {bay: "a9", item: "glow stick"}, {bay: "a8", item: "model car"}, {bay: "a7", item: "bookmark"}, {bay: "a6", item: "shovel"}, {bay: "a5", item: "rubber duck"}, {bay: "a4", item: "hanger"}, {bay: "a3", item: "blouse"}, {bay: "a2", item: "stop sign"}, {bay: "a1", item: "needle"}, {bay: "c1", item: "rusty nail"}, {bay: "c2", item: "drill press"}, {bay: "c3", item: "chalk"}, {bay: "c4", item: "word search"}, {bay: "c5", item: "thermometer"}, {bay: "c6", item: "face wash"}, {bay: "c7", item: "paint brush"}, {bay: "c8", item: "candy wrapper"}, {bay: "c9", item: "shoe lace"}, {bay: "c1", item: "leg warmers"}, {bay: "b1", item: "tyre swing"}, {bay: "b2", item: "sharpie"}, {bay: "b3", item: "picture frame"}, {bay: "b4", item: "photo album"}, {bay: "b5", item: "nail filer"}, {bay: "b6", item: "tooth paste"}, {bay: "b7", item: "bath_fizzers"}, {bay: "b8", item: "tissue box"}, {bay: "b9", item: "deodorant"}, {bay: "b10", item:"cookie jar"}, ] def number_of_rows() WAREHOUSE.length end def item_at_bay(bay) i = 0 when bay == WAREHOUSE[:bay] return WAREHOUSE[:item] end # def found_item() # WAREHOUSE[6]
true
d72a6bfee3b3894c627d9d7993f345ae3779a2fd
Ruby
uncoder/invoicer
/lib/invoicer/calculator.rb
UTF-8
3,151
3.0625
3
[]
no_license
module Invoicer class Calculator def initialize @amount_fields = [:amount, :vat_amount, :total_amount] @items = [] reset_totals end def add_items(items, fields = {}) # append and map items items_list = items.map do |item| formatted_item = {} [:unit_amount, :qty, :vat].each { |key| formatted_item[key] = item[fields[key]] } formatted_item end @items = @items.concat items_list end def calculate reset_totals # group items and iterate grouped_items.each do |vat, items| # round down amounts amount = RoundedFloat.new(items.map { |i| i[:unit_amount] * i[:qty] }.inject(:+), 2) vat_amount = RoundedFloat.new(amount.float / 100 * vat, 2) total_amount = RoundedFloat.new(amount.float + vat_amount.float, 2) # store round values to group totals for mapping @group_totals[vat] = { amount: amount.round_values, vat_amount: vat_amount.round_values, total_amount: total_amount.round_values, } # store accurate values for total amounts @invoice_totals[:amount] += amount.float @invoice_totals[:vat_amount] += vat_amount.float @invoice_totals[:total_amount] += total_amount.float end round_totals check_and_correct_amounts end def invoice_totals Hash[ *@amount_fields.collect { |k| [ k, sprintf('%.2f', @invoice_totals["rounded_#{k}"]) ] }.flatten ] end def group_totals readable_group_totals = {} @group_totals.keys.each do |vat| readable_group_totals[vat] = Hash[ *@amount_fields.collect { |k| [ k, sprintf('%.2f', @group_totals[vat][k][:rounded]) ] }.flatten ] end readable_group_totals end private def check_and_correct_amounts # correct all amounts @amount_fields.each do |key| # check if need correction (total - aggregated) aggregated_amount = @group_totals.map { |g| g[1][key][:rounded] }.inject(:+) total_amount = @invoice_totals["rounded_#{key}"] diff = ((total_amount - aggregated_amount) * 100).to_i # correct amount if diff > 0 # make list of remains list = @group_totals.map { |g| { vat: g[0], remain: g[1][key][:remain] } } # sort list by remains DESC list = list.sort_by {|g| g[:remain] }.reverse # add by 1 cent from diff to elements with bigest remain list.take(diff).each do |list_item| @group_totals[list_item[:vat]][key][:rounded] += 0.01 end end end end def grouped_items @items.group_by { |item| item[:vat] } end def reset_totals @invoice_totals = Hash.new(BigDecimal.new(0, BIG_DECIMAL_PRECISION)) @group_totals = {} end def round_totals # use normal rounding for invoice totals @invoice_totals.keys.each do |key| @invoice_totals["rounded_#{key}"] = BigDecimal.new( @invoice_totals[key].round(2), BIG_DECIMAL_PRECISION ) end end end end
true
de33e89d6a6a5d9a22d10cd7e78a136ea1787ac8
Ruby
NREL/OpenStudio-resources
/model/simulationtests/plenums.rb
UTF-8
6,670
2.53125
3
[ "BSD-2-Clause" ]
permissive
# frozen_string_literal: true require 'openstudio' require_relative 'lib/baseline_model' model = BaselineModel.new always_on_schedule = model.alwaysOnDiscreteSchedule # make a 2 story, 100m X 50m, 10 zone core/perimeter building model.add_geometry({ 'length' => 100, 'width' => 50, 'num_floors' => 3, 'floor_to_floor_height' => 4, 'plenum_height' => 1, 'perimeter_zone_depth' => 3 }) # add windows at a 40% window-to-wall ratio model.add_windows({ 'wwr' => 0.4, 'offset' => 1, 'application_type' => 'Above Floor' }) # add thermostats model.add_thermostats({ 'heating_setpoint' => 24, 'cooling_setpoint' => 28 }) # add ASHRAE System type 07, VAV w/ Reheat model.add_hvac({ 'ashrae_sys_num' => '07' }) # create plenum # There is onyl one airLoopHVAC so this is reliable air_handler = model.getAirLoopHVACs.first hot_water_plant = model.getBoilerHotWaters.first.plantLoop.get story_1_core_thermal_zone = model.getThermalZoneByName('Story 1 Core Thermal Zone').get story_1_north_thermal_zone = model.getThermalZoneByName('Story 1 North Perimeter Thermal Zone').get story_1_south_thermal_zone = model.getThermalZoneByName('Story 1 South Perimeter Thermal Zone').get story_1_east_thermal_zone = model.getThermalZoneByName('Story 1 East Perimeter Thermal Zone').get story_1_west_thermal_zone = model.getThermalZoneByName('Story 1 West Perimeter Thermal Zone').get story_2_core_thermal_zone = model.getThermalZoneByName('Story 2 Core Thermal Zone').get story_2_north_thermal_zone = model.getThermalZoneByName('Story 2 North Perimeter Thermal Zone').get story_2_south_thermal_zone = model.getThermalZoneByName('Story 2 South Perimeter Thermal Zone').get story_2_east_thermal_zone = model.getThermalZoneByName('Story 2 East Perimeter Thermal Zone').get story_2_west_thermal_zone = model.getThermalZoneByName('Story 2 West Perimeter Thermal Zone').get story_3_core_thermal_zone = model.getThermalZoneByName('Story 3 Core Thermal Zone').get story_3_north_thermal_zone = model.getThermalZoneByName('Story 3 North Perimeter Thermal Zone').get story_3_south_thermal_zone = model.getThermalZoneByName('Story 3 South Perimeter Thermal Zone').get story_3_east_thermal_zone = model.getThermalZoneByName('Story 3 East Perimeter Thermal Zone').get story_3_west_thermal_zone = model.getThermalZoneByName('Story 3 West Perimeter Thermal Zone').get conditioned_zones = air_handler.thermalZones conditioned_zones.each do |zone| air_handler.removeBranchForZone(zone) end supply_plenum1 = story_1_core_thermal_zone return_plenum1 = story_3_core_thermal_zone supply_plenum2 = story_1_north_thermal_zone return_plenum2 = story_3_north_thermal_zone reheat_coil = OpenStudio::Model::CoilHeatingWater.new(model, always_on_schedule) terminal = OpenStudio::Model::AirTerminalSingleDuctVAVReheat.new(model, always_on_schedule, reheat_coil) hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) # Add zone between two plenums air_handler.addBranchForZone(story_2_core_thermal_zone, terminal) story_2_core_thermal_zone.setSupplyPlenum(supply_plenum1) story_2_core_thermal_zone.setReturnPlenum(return_plenum1) # Add zone between zone splitter/mixer (no plenum) terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_2_north_thermal_zone, terminal) zone_splitter = air_handler.zoneSplitter zone_mixer = air_handler.zoneMixer # Add zones between zone splitter and return plenum 2 terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_2_south_thermal_zone, terminal) story_2_south_thermal_zone.setReturnPlenum(return_plenum2) terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_2_east_thermal_zone, terminal) story_2_east_thermal_zone.setReturnPlenum(return_plenum2) terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_2_west_thermal_zone, terminal) story_2_west_thermal_zone.setReturnPlenum(return_plenum2) # Add zones between supply plenum 2 and zone mixer terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_3_south_thermal_zone, terminal) story_3_south_thermal_zone.setSupplyPlenum(supply_plenum2) terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_3_east_thermal_zone, terminal) story_3_east_thermal_zone.setSupplyPlenum(supply_plenum2) terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_3_west_thermal_zone, terminal) story_3_west_thermal_zone.setSupplyPlenum(supply_plenum2) # Add zone between supply and return plenum 2 terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_1_south_thermal_zone, terminal) story_1_south_thermal_zone.setSupplyPlenum(supply_plenum2) story_1_south_thermal_zone.setReturnPlenum(return_plenum2) # Add zone between supply 1 and return plenum 2 terminal = terminal.clone(model).to_AirTerminalSingleDuctVAVReheat.get hot_water_plant.addDemandBranchForComponent(terminal.reheatCoil) air_handler.addBranchForZone(story_1_west_thermal_zone, terminal) story_1_west_thermal_zone.setSupplyPlenum(supply_plenum1) story_1_west_thermal_zone.setReturnPlenum(return_plenum2) # assign constructions from a local library to the walls/windows/etc. in the model model.set_constructions # set whole building space type; simplified 90.1-2004 Large Office Whole Building model.set_space_type # add design days to the model (Chicago) model.add_design_days # save the OpenStudio model (.osm) model.save_openstudio_osm({ 'osm_save_directory' => Dir.pwd, 'osm_name' => 'in.osm' })
true
03a8c1fc41dbb444b5268cfc3e389a1ff67e4eb6
Ruby
rr326/Speedtest
/test/test_utils.rb
UTF-8
1,735
2.6875
3
[ "MIT" ]
permissive
require 'minitest/autorun' require_relative '../lib/speedtest/utils' require_relative '../lib/speedtest/measure' class TestUtils < MiniTest::Test include Speedtest def test_nbyte_string string = Utils.nbyte_string(100) assert_equal string.length, 100 string = Utils.nbyte_string(1, units=:KB) assert_equal string.length, 1024 string = Utils.nbyte_string(1, units=:MB) assert_equal string.length, 1024*1024 assert_raises(RuntimeError) { Utils.nbyte_string(100, units=:FOO) } assert_raises(RuntimeError) { Utils.nbyte_string(100, units='MB') } end end class TestUtils < MiniTest::Test include Speedtest def test_timer time, retval = Utils.timer do sleep 0.06 'success!' end assert_equal retval, 'success!' assert_equal time.round(1), 0.1 end end class TestUtils < MiniTest::Test def test_measure # Test expected return Speedtest::Utils.stub :get_file, '0' do st=Speedtest::Measure.new res = st.latency assert !res.error? assert_in_delta 0.1, 0.1, res.duration end def raise_IO_Error(*args) raise IOError.new('Force expected error') end # Test handled failure Speedtest::Utils.stub :get_file, self.method(:raise_IO_Error) do st=Speedtest::Measure.new res = st.latency assert res.error? assert_equal -1, res.error[:errno] end def raise_other_Error(*args) raise RuntimeError.new('Force unexpected error') end # Test unexpected failure Speedtest::Utils.stub :get_file, self.method(:raise_other_Error) do st=Speedtest::Measure.new res = st.latency assert res.error? assert_equal -2, res.error[:errno] end end end
true
1c05a0425c23298d4bcdfcc4850367d7f9ded4ef
Ruby
xing/israkel
/lib/israkel/simctl.rb
UTF-8
431
2.640625
3
[]
no_license
class SIMCTL def self.list `xcrun simctl list` end def self.booted_devices_uuids devices = self.list.split("\n") devices.keep_if { |entry| entry =~ /(\(Booted\))/ } devices.map { |device| device.match(/\(([^\)]+)\)/)[1] } end def self.shutdown(device_uuid) system "xcrun simctl shutdown #{device_uuid}" end def self.erase(device_uuid) system "xcrun simctl erase #{device_uuid}" end end
true
c2ebda8fbb8c0f42c43d35bda6ce320b77f7fdbf
Ruby
yojindo/key-for-min-value-nyc01-seng-ft-060120
/key_for_min.rb
UTF-8
247
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def key_for_min_value(name_hash) min_value = 1000 item = '' if name_hash == {} return nil end name_hash.each do |key,value| if value < min_value min_value = value item = key end end item end
true
d24eafbdc155213c9dddb29c7e1e3dfcf2bf56f0
Ruby
KristenWilde/Launch-School-Ruby
/blocks_procs_lambdas/easy1/encrypted.rb
UTF-8
877
2.65625
3
[]
no_license
def decipher(string) string.chars.map {|chr| rotate13(chr) }.join end def rotate13(char) return char unless char.match(/[a-z, A-Z]/) key = if char.downcase == char then ("a".."z").to_a else ("A".."Z").to_a end key.rotate(key.index(char))[13] end names = %w( Nqn Ybirynpr Tenpr Ubccre Nqryr Tbyqfgvar Nyna Ghevat Puneyrf Onoontr Noqhyynu Zhunzznq ova Zhfn ny-Xujnevmzv Wbua Ngnanfbss Ybvf Unyog Pynhqr Funaaba Fgrir Wbof Ovyy Tngrf Gvz Orearef-Yrr Fgrir Jbmavnx Xbaenq Mhfr Wbua Ngnanfbss Fve Nagbal Ubner Zneiva Zvafxl Lhxvuveb Zngfhzbgb Unllvz Fybavzfxv Tregehqr Oynapu ) names.each {|name| puts decipher name }
true
ca27580bb5f6243a7eb6c81bb7eb39abb790834e
Ruby
debugger1809/Classes_Objects_Variables
/Factorial_exception.rb
UTF-8
348
3.703125
4
[]
no_license
# Negative Factorial Exception class Numbers def factorial(n) raise NegativeFactorial, "The number provided is negative." if n < 0 (1..n).inject(1, :*) end def test_negative assert_raises NegativeFactorial do factorial(-1) end end a = Numbers.new n = ARGV[0].to_i if n a.factorial(n) else puts "Please provide input" end end
true
ff1e20f56d9bcf0c857c156784cf3a5bdbee6e79
Ruby
samueldana/indentation
/lib/indentation/array_mod.rb
UTF-8
3,478
3.71875
4
[ "MIT" ]
permissive
# Monkey patch Array with indentation methods class Array # Appends a given separator(s) to all but the last element in an array of Strings # or if performed on an array of arrays, appends the separator element to the end of each array except the last def append_separator(*separators) len = length ret_array = [] each_with_index do |element, i| new_element = element.dup unless i == len - 1 separators.each do |separator| new_element << separator end end ret_array << new_element end ret_array end # Append the given separator(s) to the current array def append_separator!(*separators) len = length each_with_index do |element, i| next if i == len - 1 separators.each do |separator| element << separator end end end # Return an indented array of strings (or an array of other arrays containing strings) # Arguments: # * num - How many of the specified indentation to use. # Default for spaces is 2. Default for other is 1. # If set to a negative value, removes that many of the specified indentation character, # tabs, or spaces from the beginning of the string # * i_char - Character (or string) to use for indentation def indent(num = nil, i_char = ' ') collect do |array_element| array_element.indent(num, i_char) end end # Apply indentation to this array # Arguments: # * num - How many of the specified indentation to use. # Default for spaces is 2. Default for other is 1. # If set to a negative value, removes that many of the specified indentation character, # tabs, or spaces from the beginning of the string # * i_char - Character (or string) to use for indentation def indent!(num = nil, i_char = ' ') collect! do |array_element| array_element.indent!(num, i_char) end end # Get the least indentation of all elements def find_least_indentation(*args) collect{|array_element| array_element.find_least_indentation(*args) }.min end # Find the least indentation of all elements and remove that amount (if any) # Can pass an optional modifier that changes the indentation amount removed def reset_indentation(modifier = 0) indent(-find_least_indentation + modifier) end # Replaces the current array with one that has its indentation reset # Can pass an optional modifier that changes the indentation amount removed def reset_indentation!(modifier = 0) indent!(-find_least_indentation + modifier) end # Join an array of strings using English list punctuation. def english_join(conjunction = 'and', separator = ', ', oxford_comma = true) len = length # Return empty string for empty array return '' if len == 0 # Return only element as string if length is 1 return self[0].to_s if len == 1 # Return comma-less conjunction of elements if length is 2 return "#{self[0]} #{conjunction} #{self[1]}" if len == 2 # Return comma joined conjunction of elemements join_str = '' each_with_index{|ele, i| str = if !oxford_comma && i == len - 2 "#{ele} #{conjunction} " # rubocop:disable Layout/IndentationWidth elsif i == len - 2 "#{ele}#{separator}#{conjunction} " elsif i == len - 1 ele.to_s else "#{ele}#{separator}" end join_str << str } join_str end end
true
4edc225468342fce7a50f92aa1f1524bd4dbbd9c
Ruby
tsuyopon/ruby
/basic_rescue/sample1.rb
UTF-8
71
2.515625
3
[]
no_license
begin 1 / 0 rescue puts "何か問題が発生しました。" end
true
de0633c916a71664499ebe34e9bd0554e8a878e7
Ruby
Solnse/mismo_enum
/app/models/mismo_enum/loan_state_type.rb
UTF-8
2,234
2.578125
3
[ "MIT" ]
permissive
# app/models/mismo_enum/loan_state_type.rb # enum class MismoEnum::LoanStateType < MismoEnum::Base validates_presence_of :name validates_uniqueness_of :name def self.description 'Identifies the state in time for the information associated with this '+ 'occurrance of LOAN' end def self.seed [[1, 'AtBankruptcyFiling', 'A snapshot of the loan data at the time a '+ 'borrower files for bankruptcy.'], [2, 'AtClosing', 'A snapshot of the loan data at the completion of the '+ 'closing process. This is sometimes referred to as "original".'], [3, 'AtConversion', 'For loans with a conversion option, a snapshot of '+ 'the loan data at the time the conversion features become effective '+ '(e.g., biweekly to monthly payments; adjustable to fixed rate '+ 'amortization).'], [4, 'AtEstimate', 'A snapshot of the loan data at the point in time when '+ 'a loan estimate is disclosed.'], [5, 'AtModification', 'For loans which undergo term modifications not '+ 'originally specified in the note, a snapshot of the loan data at '+ 'the time the new note terms become effective.'], [6, 'AtRelief', 'For loans subject to payment relief, a snapshot of the '+ 'loan data at the time the relief is initiated.'], [7, 'AtReset', 'For balloon mortgages with a reset feature, a snapshot '+ 'of the loan data on the balloon maturity date at the time the '+ 'borrower exercises the reset option to modify and extend the '+ 'balloon note.'], [8, 'AtTransfer', 'A snapshot of the loan data as of the effective date '+ 'of the servicing transfer.'], [9, 'AtTrial', 'A snapshot of the loan data at the initiation of a trial '+ 'period for a workout modification.'], [10, 'AtUnderwriting', 'A snapshot of the loan data at the point at which '+ 'the underwriting recommendation is made.'], [11, 'Current', 'A snapshot of the loan data as of the "Loan State Date".'] ].each { |id, entry, desc| create(id: id, name: entry, description: desc) } end end
true
525a02072068e90226e92007dd73b7113bd6de71
Ruby
Harmonickey/EnHabit
/Core/Applicants/convert_to_renter.rb
UTF-8
3,041
2.703125
3
[]
no_license
#!/usr/local/bin/ruby absPath = Dir.pwd base = absPath.split("/").index("public_html") deploymentBase = absPath.split("/")[0..(base + 1)].join("/") #this will reference whatever deployment we're in $: << "#{deploymentBase}/Libraries" require 'json' require 'moped' require 'bson' Moped::BSON = BSON def InsertRenterFromApplicant(userId, landlordId, address, unit, rent, listingId) mongoSession = Moped::Session.new(['127.0.0.1:27017']) # our mongo database is local mongoSession.use("enhabit") # this is our current database renterObj = Hash.new renterObj["UserId"] = userId renterObj["LandlordId"] = landlordId renterObj["Address"] = address renterObj["Unit"] = unit renterObj["Rent"] = rent renterObj["HasPaidRent"] = false document = Hash.new #Username has a unique constraint attached, so we want to catch the raised error just in case begin mongoSession.with(safe: true) do |session| session[:renters].insert(renterObj) end # set IsRented for the listing that was associated with this applicant queryObj = Hash.new queryObj["_id"] = Moped::BSON::ObjectId.from_string(listingId.to_s) session[:listings].find(queryObj).update('$set' => {:IsRented => true}) rescue Moped::Errors::OperationFailure => e document["Error"] = e end mongoSession.disconnect return document.to_json end def GetListingData(listingId) mongoSession = Moped::Session.new(['127.0.0.1:27017']) # our mongo database is local mongoSession.use("enhabit") # this is our current database begin queryObj = Hash.new queryObj["_id"] = Moped::BSON::ObjectId.from_string(listingId.to_s) listing = Array.new mongoSession.with(safe: true) do |session| listing = session[:listings].find(queryObj).to_a end if listing.count == 0 return nil else return { :Address => listing[0]["Address"], :Unit => listing[0]["Unit"], :Rent => listing[0]["Rent"]} end rescue Moped::Errors::OperationFailure => e return nil end end # renter needs userId, landlordId, address, and rent # this requires ApplicantId (oid) begin data = JSON.parse(ARGV[0].delete('\\')) if not ARGV[0].nil? and not ARGV[0].empty? userId = ARGV[1].split(",")[0] if not ARGV[0].nil? key = ARGV[2] if not ARGV[2].nil? isAdmin = ARGV[3].to_b applicantId = data["ApplicantId"] # oid for applicant entry applicantData = GetApplicantData(data["ApplicantId"]) listingData = GetListingData(applicantData[:ListingId]) puts InsertRenterFromApplicant(applicantData[:UserId], applicantData[:LandlordId], listingData[:Address], listingData[:Unit], listingData[:Rent], applicantData[:ListingId]) rescue Exception => e puts e.inspect end
true
991cf075ba971c60d7950aecfc5d0e6bc5c339c3
Ruby
vishnurv2/CI_RB
/features/step_definitions/vehicle_grid_steps.rb
UTF-8
2,613
2.53125
3
[]
no_license
# frozen_string_literal: true And(/^I delete the vehicles in the grid$/) do on(AutoPolicySummaryPage) do |page| page.vehicle_info_panel.scroll.to #make sure to keep one vehicle at least. loop do @found_vehicle = page.vehicle_info_panel.vehicles.last break if page.vehicle_info_panel.vehicles.count == 1 @found_vehicle.delete end end end And(/^I add (\d+) random vehicles from the auto summary page$/) do |number_of_vehicles_to_add| on(AutoPolicySummaryPage) do |page| @added_vehicles = [] number_of_vehicles_to_add.times do |i| page.vehicle_info_panel.add_button_element.scroll.to :bottom page.vehicle_info_panel.add_button page.wait_for_processing_overlay_to_close #rand(20) + 2000 i2 = i+7 random_vehicle = { vehicle_year: 2000 + (i2 % 13), vehicle_make: i2 % 31, vehicle_model: i2 % 11, vehicle_style: 0, vehicle_use: 0, address: { address_line_1: "3715 KIRKLYNN DR", city: "NEW HAVEN", state: 'Indiana', zip: "46774" } } page.auto_vehicle_modal.populate_with random_vehicle page.auto_vehicle_modal.save_and_close @added_vehicles << random_vehicle end end end # ------ Everything below this line is unverified ------------------------------------- # # When(/^I try to delete the last (vehicle|other vehicle)$/) do |vehicle_or_other| on(AutoPolicySummaryPage) do |page| @found_vehicle = page.vehicle_info_panel.send("#{vehicle_or_other.snakecase}s").last @found_vehicle.delete_button end end Then(/^I should see a prompt asking me if I'm sure I want to remove the (vehicle|other vehicle)$/) do |_vehicle_or_other| expect(@found_vehicle.remove_confirm_message?).to be_truthy end When(/^I answer (.*) to the remove (vehicles|other vehicles) prompt$/) do |which, vehicle_or_other| on(AutoPolicySummaryPage) do |page| @orig_vehicle_count = page.vehicle_info_panel.send("#{vehicle_or_other.snakecase}").count @found_vehicle.delete_button if @found_vehicle.delete_button? @found_vehicle.send("delete_#{which}") end end Then(/^the (vehicles|other vehicles) should (remain in the list|be removed)$/) do |vehicle_or_other, which| on(AutoPolicySummaryPage) do |page| expected = which == 'be removed' ? @orig_vehicle_count - 1 : @orig_vehicle_count expect(page.vehicle_info_panel.send("#{vehicle_or_other.snakecase}").count).to eq(expected) if page.vehicle_info_panel.send("#{vehicle_or_other.snakecase}?") end end And(/^I delete all vehicles but one$/) do on(AutoPolicySummaryPage).vehicle_info_panel.remove_all_vehicles_but_one end
true
ec55c9729292d511d34081b5c90f4276b7851e84
Ruby
uchoaaa/brazilian-rails
/template/brazilian-rails.rb
UTF-8
5,723
2.6875
3
[]
no_license
# # Brazilian Rails Template # Author: Rafael Uchôa # http://putshelloworld.wordpress.com/ # # # Feel free to fork it! # # Rewrite environment.rb to config the timezone and i18n # THIS BLOCK SHOULD BE FIRST OF ALL file "config/environment.rb", <<-ENV RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| config.time_zone = 'Brasilia' config.i18n.default_locale = 'pt-BR' end ENV # Brazilian-Rails # sudo gem install brazilian-rails # (for more details, see http://github.com/tapajos/brazilian-rails/tree/master ) gem "brdinheiro", :version => ">= 2.1.6" gem "brazilian-rails", :version => ">= 2.1.6" gem "brcep", :version => ">= 2.1.6" gem "brcpfcnpj", :version => ">= 2.1.6" gem "brdata", :version => ">= 2.1.6" gem "brdinheiro", :version => ">= 2.1.6" gem "brhelper", :version => ">= 2.1.6" gem "brnumeros", :version => ">= 2.1.6" gem "brstring", :version => ">= 2.1.6" # Initialize git git :init # Uchoaaa's activerecord_i18n_defaults # (for more details, see http://github.com/uchoaaa/activerecord_i18n_defaults/tree/master ) plugin "activerecord_i18n_defaults", :git => "git://github.com/uchoaaa/activerecord_i18n_defaults.git", :submodule => true # i18n pt-BR.yml # (for more details, see http://github.com/svenfuchs/rails-i18n/tree/master ) file "config/locales/pt-BR.yml", <<-CODE pt-BR: # formatos de data e hora date: formats: default: "%d/%m/%Y" short: "%d de %B" long: "%d de %B de %Y" only_day: "%d" day_names: [Domingo, Segunda, Terça, Quarta, Quinta, Sexta, Sábado] abbr_day_names: [Dom, Seg, Ter, Qua, Qui, Sex, Sáb] month_names: [~, Janeiro, Fevereiro, Março, Abril, Maio, Junho, Julho, Agosto, Setembro, Outubro, Novembro, Dezembro] abbr_month_names: [~, Jan, Fev, Mar, Abr, Mai, Jun, Jul, Ago, Set, Out, Nov, Dez] order: [:day,:month,:year] time: formats: default: "%A, %d de %B de %Y, %H:%M hs" time: "%H:%M hs" short: "%d/%m, %H:%M hs" long: "%A, %d de %B de %Y, %H:%M hs" only_second: "%S" datetime: formats: default: "%Y-%m-%dT%H:%M:%S%Z" am: '' pm: '' # date helper distancia em palavras datetime: distance_in_words: half_a_minute: 'meio minuto' less_than_x_seconds: one: 'menos de 1 segundo' other: 'menos de {{count}} segundos' x_seconds: one: '1 segundo' other: '{{count}} segundos' less_than_x_minutes: one: 'menos de um minuto' other: 'menos de {{count}} minutos' x_minutes: one: '1 minuto' other: '{{count}} minutos' about_x_hours: one: 'aproximadamente 1 hora' other: 'aproximadamente {{count}} horas' x_days: one: '1 dia' other: '{{count}} dias' about_x_months: one: 'aproximadamente 1 mês' other: 'aproximadamente {{count}} meses' x_months: one: '1 mês' other: '{{count}} meses' about_x_years: one: 'aproximadamente 1 ano' other: 'aproximadamente {{count}} anos' over_x_years: one: 'mais de 1 ano' other: 'mais de {{count}} anos' # numeros number: format: precision: 3 separator: ',' delimiter: '.' currency: format: unit: 'R$' precision: 2 format: '%u %n' separator: ',' delimiter: '.' percentage: format: delimiter: '.' precision: format: delimiter: '.' human: format: precision: 1 delimiter: '.' support: array: sentence_connector: "e" skip_last_comma: true # Active Record activerecord: attributes: _all: created_at: "Data de Criação" updated_at: "Data de Atualização" # your_model: # model_attr: "Nice Name" errors: template: header: one: "{{model}} não pôde ser salvo: 1 erro" other: "{{model}} não pôde ser salvo: {{count}} erros." body: "Por favor, cheque os seguintes campos:" messages: inclusion: "não está incluso na lista" exclusion: "não está disponível" invalid: "não é válido" confirmation: "não bate com a confirmação" accepted: "precisa ser aceito" empty: "não pode ser vazio" blank: "não pode ser vazio" too_long: "é muito longo (não mais do que {{count}} caracteres)" too_short: "é muito curto (não menos do que {{count}} caracteres)" wrong_length: "não é do tamanho correto (precisa ter {{count}} caracteres)" taken: "não está disponível" not_a_number: "não é um número" greater_than: "precisa ser maior do que {{count}}" greater_than_or_equal_to: "precisa ser maior ou igual a {{count}}" equal_to: "precisa ser igual a {{count}}" less_than: "precisa ser menor do que {{count}}" less_than_or_equal_to: "precisa ser menor ou igual a {{count}}" odd: "precisa ser ímpar" even: "precisa ser par" CODE # Config GIT # (for more details, see http://gist.github.com/88502 ) file '.gitignore', <<-CODE log/*.log log/*.pid db/*.db db/*.sqlite3 db/schema.rb tmp .DS_Store doc/api doc/app config/database.yml CODE # TIP: Never commit your database.yml! run "cp config/database.yml config/database.yml.sample" # Initialize submodules git :submodule => "init" git :add => "." git :commit => "-a -m 'Initial commit. (Copy config/database.yml.sample to config/database.yml and customize.)'"
true
aa3bb83f32d0163047d340cf1792fc1f6af7d73f
Ruby
codeclanstudentls/Week2_Homework_Day1
/cars_spec.rb
UTF-8
1,632
3.59375
4
[]
no_license
require('minitest/autorun') require('minitest/rg') require_relative('cars') class TestCars < MiniTest::Test def setup end def test_colour_of_car car_colour = Cars.new('yellow', 'Beetle', 100, 0) assert_equal( 'yellow', car_colour.colour()) end def test_model_of_car car_model = Cars.new('yellow', 'Beetle', 100, 0) assert_equal('Beetle', car_model.model()) end def test_level_of_fuel fuel = Cars.new('yellow', 'Beetle', 100, 0) accelerate = Cars.new('yellow', 'Beetle', 100, 0) assert_equal(95, fuel.fuel_level()) assert_equal(10, accelerate.speed()) end # def test_speed_of_car # accelerate = Cars.new('yellow', 'Beetle', 100, 0) # assert_equal(10, accelerate.speed()) # end # end end # EXTENSIONS =begin - Add a driver property to the car, which should be assigned a person object. This is going to be like the river/fish/bear link where you have require_relative('person') and also the Person.class data? - Add a 'pick_up_passengers' method to the car, which takes in a person as an argument and stores them inside the car object. This is going to be similar to how the Bear got the fish from the river. Is it worth making a set-sized array of say a maximum of 5 passangers? and then we add people to the array using unshift or the .push methods - Add a method to count how many passengers are currently in the car. This probably involves making an empty array? and then using .size or .length to count the no. of items in that array? or can we just have a .count in our assert_equals part? (5, passangers_in_car.count()) __Make sure to write tests for your classes!!__ =end
true
3f848bb3f0ba5c10da996d7a8f94287b9e1f5f97
Ruby
guerragiancarlo8/Tanks
/hello.rb
UTF-8
4,249
3.265625
3
[]
no_license
require 'gosu' def media_path(file) File.join(File.dirname(File.dirname(__FILE__)), 'media',file) end class Explosion #mientras mas algo este valor, más lento el proceso de la animación. Es decir, que mientras más #alto esté este número, más tiempo tardará el array con la animación en recorrer. FRAME_DELAY = 10 #esta es el spritesheet. tiene 64 "frames" y se leen de izquierda a derecha SPRITE = media_path('explosion.png') def self.load_animation() #cada frame mide 128 x 128. saca las imagenes del spritesheet, guardado en la variable SPRITE Gosu::Image.load_tiles(SPRITE,128,128,{:tileable => false}) end def self.load_sound(window) Gosu::Sample.new(window, media_path('explosion.mp3')) end def initialize(animation, sound, x, y) #le pasas una animación, junto con unas coordenadas. inicializa en @animation[0] @animation = animation sound.play @x, @y = x, y @current_frame = 0 end def update #incrementas el frame(de los 64) si el frame acaba de expirarse @current_frame += 1 if frame_expired? end def draw return if done? #mage contiene el frame con el cual vamos a empezar. ver abajo. #dividimos el width y el height de la imagen para que quede centrado el fueguito en el #lugar donde demos click. en este caso sería @x - 128/2 = 64. x - 64, y - 64 image = current_frame image.draw(@x - image.width / 2.0, @y - image.height / 2.0, 0) end def done? #cuando haya terminado de recorrer el array de @animation, es que #la animación ha terminado. @current_frame == @animation.size end def sound #podríamos haber simplemente invocado la variable @sound arriba #pero parece que el autor quiso hacer un método específico para ello. @sound.play end private def current_frame #del array de los 64 fueguitos, te saca la imagen que corresponda al current fraome #un ejemplo @animation[1 % 64] == @animation[1], @animation[2%64] == @animation[2] @animation[@current_frame % @animation.size] end def frame_expired? #si ve que el último frame se renderizó después que el frame_delay, renderiza la nueva imagen. #por eso es que si incrementamos el frame delay, el fueguito se verá más lento al renderizar. now = Gosu.milliseconds @last_frame ||= now if (now-@last_frame) > FRAME_DELAY @last_frame = now end end end class GameWindow < Gosu::Window BACKGROUND = media_path('country_field.png') def initialize(width=800, height=600, fullscreen=false) super self.caption = "Hola Animación" @background = Gosu::Image.new(self, BACKGROUND, {:tileable => false}) #@animation va a ser el spritesheet. @animation = Explosion.load_animation() #la musiquita que tocará en el transcurso de todo el juego @music = Gosu::Song.new(self, media_path('menu_music.mp3')) @music.volume = 0.5 @music.play(true) #ahora sí vamos a bajar el sonido de una explosión @sound = Explosion.load_sound(self) @explosions = [] end def update #traversar el array de @explosions. Si ve que hay una para la cual #su método 'done?' sea true, la saca del array. @explosions.reject!(&:done?) #para todas las explosiones que queden en @explosions, llama #el método de clase Explosion::update a cada una y recalcula #su variable de Explosion::@current_frame. @explosions.map(&:update) end def button_down(id) #si apretamos escape. salir del juego close if id == Gosu::KbEscape #si apretamos el ratón, creamos una nueva instancia de Exposion, supliéndole #el array de imágenes de fueguito, junto con la x,y de donde se dio click en pantalla if id == Gosu::MsLeft @explosions.push(Explosion.new(@animation, @sound, mouse_x, mouse_y)) end end def needs_cursor? true end def needs_redraw? #esto evita tener que renderizar cada una de las imágenes cada vez #que invocamos la función "Draw". Es un método específico de Gosu #que se puede re-escribir. Así conservamos memoria. !@scene_ready || @explosions.any? end def draw #pinta la imagen de trasfondo (la del campito) #llama al método de Explosion::draw a todas #las explosiones que hayan en el array. @scene_ready ||= true @background.draw(0,0,0) @explosions.map(&:draw) end end GameWindow.new.show
true
d35d710f76f34b32424540ba04fd0e603b149279
Ruby
jv1056/Knight_Path-W1D5-
/00_tree_node.rb
UTF-8
421
3.078125
3
[]
no_license
require 'byebug' class PolyTreeNode attr_reader :parent, :children, :value def initialize(value) @parent = nil @children = [] @value = value end def parent @parent end def children @children end def value @value end def parent=(dad) debugger if dad.nil? unless dad.children.include?(self) @parent = dad dad.children << self end end end
true
f854605b09237bead62dc8511fbe914f351c43e2
Ruby
meghanstovall/backend_module_0_capstone
/day_1/ex6.rb
UTF-8
652
4.625
5
[]
no_license
# creating 5 variables types_of_people = 10 x = "There are #{types_of_people} types of people." binary = "binary" do_not = "don't" y = "Those who know #{binary} and those who #{do_not}." # using variables x and y puts x puts y # using variables x and y again just differently puts "I said: #{x}." puts "I also said: '#{y}'." # creating two more variables hilarious = false joke_evaluation = "Isn't that joke so funny?! #{hilarious}" # using the variable joke_evaluation puts joke_evaluation # creating two more variables for strings w = "This is the left side of..." e = "a string with a right side." # using the two string variables puts w + e
true
f8c207fe04cb8380cc42cf4dcee423959d8b3229
Ruby
martinos/functional_ruby_presentation
/github_lambda.rb
UTF-8
1,394
2.53125
3
[]
no_license
require 'open-uri' require 'json' require 'pry-nav' require 'pp' require './utils' include Utils cache = Utils.cache.(expired.(60)) logger = Logger.new($stdout).method(:info) slack_printer = -> a { system(%{curl -s -X POST --data-urlencode 'payload={"text": "#{a}", "channel": "#autonotifications", "username": "martinosis", "icon_emoji": ":monkey_face:"}' https://hooks.slack.com/services/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}); a } print = -> a { logger.(a) } time = Utils.time.(print) debug = Utils.debug.(print) # String -> String fetch_repo = -> user_name { open("https://api.github.com/users/#{user_name}/repos?per_page=100").read } # String -> String safe_fetch_repo = fetch_repo >>+ retry_fn >>+ cache.("coucou.json") >>+ time.("fetching repo") hash_of = -> fields , hash { Hash[fields.map { |(key, fn)| [key, fn.(hash[key])] }] }.curry array_of = -> fn, value { value.kind_of?(Array) ? value.map(&fn) : [] }.curry id = -> a { a } # String -> Hash String Int language_count = safe_fetch_repo >>~ parse_json >>~ array_of.(hash_of.({"name" => id, "language" => id})) >>~ count_by.(at.("language") >>~ default.("N/A") >>~ apply.(:upcase)) language_count.("Martinos") # => {"VIML"=>3, "COFFEESCRIPT"=>1, "ELIXIR"=>13, "RUBY"=>42, "SHELL"=>4, "JAVASCRIPT"=>3, "ELM"=>8, "HTML"=>6, "VIM SCRIPT"=>1, "N/A"=>5, "GO"=>2, "C"=>1, "CSS"=>2}
true
f8f4ba8ceb54601b20b3dab94522bf9c67ce63df
Ruby
Zajn/gameboy-disassembler
/disassembler.rb
UTF-8
1,305
3.015625
3
[]
no_license
# frozen_string_literal: true class Disassembler attr_reader :rom attr_accessor :address OPCODE_MAP = { '31' => { instruction: "LD SP", size: 2 }, 'af' => { instruction: "XOR A", size: 0 }, '21' => { instruction: "LD HL", size: 2 }, '32' => { instruction: "LDD HL, A", size: 0 }, 'cb7c' => { instruction: "BIT 7, H", size: 0 }, '20' => { instruction: "JR NZ", size: 1 }, '0e' => { instruction: "LD C", size: 1 } } def initialize(path_to_rom) @rom = File.open(path_to_rom) end def disassemble until rom.eof? address = rom.pos buffer = rom.readbyte.to_s(16) # Check for extended instructions buffer << rom.readbyte.to_s(16) if buffer == 'cb' if OPCODE_MAP[buffer] instruction = OPCODE_MAP[buffer][:instruction] size = OPCODE_MAP[buffer][:size] arguments = [] size.times do arguments.push(rom.readbyte.to_s(16)) end separator = arguments.any? ? ',' : nil # CPU is little endian, so data will be stored # least-significant byte first. puts format("%<address>08x %<instruction>10s#{separator} %<arguments>s", { address: address, instruction: instruction, arguments: arguments.reverse.join('') }) end end rom.close end end
true
3c1d849e055b4ed2ddf454d414a0cacfd123a32a
Ruby
wpotratz/tealeaf
/2_ruby_workbook/quiz_2_3/exc_5.rb
UTF-8
322
3.71875
4
[]
no_license
## Original #def color_valid(color) # if color == "blue" || color == "green" # true # else # false # end #end ## Changed to: def color_valid(color) %w[blue green].any? { |c| c == color } #color == "blue" || color == "green" end puts color_valid("blue") puts color_valid("red") puts color_valid("green")
true
4c4c9dd838400ce93bdcc38b30caac984f0dde34
Ruby
svenfuchs/cl
/lib/cl/cast.rb
UTF-8
1,228
3.140625
3
[ "MIT" ]
permissive
class Cl module Cast class Cast < Struct.new(:type, :value, :opts) TRUE = /^(true|yes|on)$/ FALSE = /^(false|no|off)$/ def apply return send(type) if respond_to?(type, true) raise ArgumentError, "Unknown type: #{type}" rescue ::ArgumentError => e raise ArgumentError.new(:wrong_type, value.inspect, type) end private def array Array(value).compact.flatten.map { |value| split(value) }.flatten.compact end def string value.to_s unless value.to_s.empty? end alias str string def boolean return true if value.to_s =~ TRUE return false if value.to_s =~ FALSE !!value end alias bool boolean alias flag boolean def int Integer(value) if value end alias integer int def float Float(value) if value end def split(value) separator ? value.to_s.split(separator) : value end def separator opts[:separator] end end def cast(value) type ? Cast.new(type, value, separator: separator).apply : value end end end
true
f45e7543f969e4c9ccbb02ea3446801db6d281f9
Ruby
h4hany/leetcode
/solutions/108_convert_sorted_array_to_binary_search_tree.rb
UTF-8
1,103
4.46875
4
[]
no_license
# Given an array where elements are sorted in ascending order, convert it to a height balanced BST. # For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. # Example: # Given the sorted array: [-10,-3,0,5,9], # One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: # 0 # / \ # -3 9 # / / # -10 5 # # https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ class TreeNode attr_accessor :val, :left, :right def initialize(val) @val = val @left = nil @right = nil end end # @param {Integer[]} nums # @return {TreeNode} def sorted_array_to_bst(nums) return nil if nums.empty? return TreeNode.new(nums.first) if nums.size == 1 root = TreeNode.new(nums[nums.size / 2]) root.left = sorted_array_to_bst(nums[0..nums.size / 2 - 1]) if nums.size / 2 >= 1 root.right = sorted_array_to_bst(nums[nums.size / 2 + 1..-1]) root end nums = [-10,-3,0,5,9] p sorted_array_to_bst(nums)
true
d1f824ebb546f621c245397bc595ca23ed4eed3d
Ruby
Itsindigo/boris
/lib/bike.rb
UTF-8
263
3
3
[]
no_license
class Bike attr_reader :bike, :bike_status def initialize @bike @bike_status = "Working" end def working? @bike_status end def report_broken @bike_status = "Broken" end def in_transit @bike_status = "In Transit" end end
true
4390f24dd40f2d7113abf876caa388a05059ddc6
Ruby
kschumy/MediaRanker
/test/models/user_test.rb
UTF-8
1,572
2.859375
3
[]
no_license
require "test_helper" describe User do describe "valid" do it "must be valid" do users(:lovelace).must_be :valid? end it "must have a name of at least one char" do new_user = User.create(name: "") new_user.valid?.must_equal false new_user.errors.must_include :name new_user = User.create(name: " ") new_user.valid?.must_equal false new_user = User.create(name: "a") new_user.valid?.must_equal true end it "must have a unique name in same category" do new_user = User.create(name: users(:lovelace).name) new_user.valid?.must_equal false new_user.errors.must_include :name new_user.errors.messages[:name].must_equal ["has already been taken"] end it "removes strips white space from name" do valid_new_user = User.create(name: "Foo Bar") valid_new_user.valid?.must_equal true valid_new_user.name.must_equal "Foo Bar" invalid_new_user_one = User.create(name: "Foo Bar") invalid_new_user_one.valid?.must_equal false invalid_new_user_one.errors.must_include :name invalid_new_user_two = User.create(name: " Foo Bar") invalid_new_user_two.valid?.must_equal false invalid_new_user_one.errors.must_include :name end end it "must have a unique, case-insensitive name" do new_user_name = users(:lovelace).name new_user_name[0] = new_user_name.chr.swapcase new_user = User.create(name: new_user_name) new_user.valid?.must_equal false new_user.errors.must_include :name end end
true
5156a2ee8cf14b58ee2c9a0d3b7e2b9a66a67afb
Ruby
AlsaceDigitale/hacklechalet
/fetch_attendees.rb
UTF-8
1,651
2.578125
3
[]
no_license
require 'rubygems' require 'bundler/setup' require 'eventbrite-client' require 'digest/md5' require './env' def output(position, gravatar_hash, name, tags) gravatar_url = "http://www.gravatar.com/avatar/#{gravatar_hash}.png?size=48" str = "<tr>\n" str << " <td class='position'>#{position}</td>\n" str << " <td class='avatar'><img src='#{gravatar_url}'</td>\n" str << " <td class='name'>#{name}</td>\n" str << " <td>#{tags.join(", ")}</td>\n" str << "</tr>\n" end eb_auth_tokens = { app_key: APP_KEY, user_key: USER_KEY } eb_client = EventbriteClient.new(eb_auth_tokens) # response = eb_client.user_list_events() response = eb_client.event_list_attendees({id: 6377121141}) pos = 0 File.open("_includes/attendees.html", 'w') {|f| f.write(output("organizer", "139b66112d2e2b4efafac2aefed01c2f", "Yann Klis", %w(ruby rails nodejs))) f.write(output("organizer", "1c72bce95176cfcb37de816f5be59dd5", "Yannick Jost", %w(robot embedded python))) f.write(output("organizer", "10e11ddb56ddb2a5121a7678c76f9433", "Loïc Hoffmann", %w(community manager social))) f.write(output("jury", "840013d1ba6ddc409f2606cc3423cbeb", "Stéphane Becker", %w(Judge Dredd Here))) response["attendees"].sort_by{|hsh| hsh["attendee"]["created"] }.each{|hsh| attendee_hsh = hsh["attendee"] name = [attendee_hsh["first_name"], attendee_hsh["last_name"]].compact.join(" ") tags = attendee_hsh["answers"].find_all{|x| x["answer"]["question_id"] == 3959643}.first["answer"]["answer_text"].split(",") email = attendee_hsh["email"] gravatar_hash = Digest::MD5.hexdigest(email) pos+=1 f.write(output("#{pos}.", gravatar_hash, name, tags)) } }
true
8be43e78ee54edcf62ac66e8dec50765ccb4556a
Ruby
pt1988/logstash-filter-sanitize_mac
/spec/filters/sanitize_mac_spec.rb
UTF-8
3,460
2.6875
3
[ "Apache-2.0" ]
permissive
# encoding: utf-8 require_relative '../spec_helper' require "logstash/filters/sanitize_mac" describe LogStash::Filters::SanitizeMac do describe "Clean up a MAC address to hyphen and lowercase" do let(:config) do <<-CONFIG filter { sanitize_mac { match => { "client_mac" => "client_mac_sanitized" } separator => "-" fixcase => "lower" } } CONFIG end sample("client_mac" => "A98c.c2ff.fe37") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('a9-8c-c2-ff-fe-37') end sample("client_mac" => "11:23:4D:66:77:aB") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('11-23-4d-66-77-ab') end sample("client_mac" => "ad561297fEEd") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('ad-56-12-97-fe-ed') end end describe "Clean up a MAC address to colon and same case" do let(:config) do <<-CONFIG filter { sanitize_mac { match => { "client_mac" => "client_mac_sanitized" } separator => ":" fixcase => "" } } CONFIG end sample("client_mac" => "A98c.c2ff.fe37") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('A9:8c:c2:ff:fe:37') end sample("client_mac" => "11:23:4D:66:77:aB") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('11:23:4D:66:77:aB') end sample("client_mac" => "ad561297fEEd") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('ad:56:12:97:fE:Ed') end end describe "Clean up a MAC address to dots and uppercase" do let(:config) do <<-CONFIG filter { sanitize_mac { match => { "client_mac" => "client_mac_sanitized" } separator => "." fixcase => "upper" } } CONFIG end sample("client_mac" => "A98c.c2ff.fe37") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('A98C.C2FF.FE37') end sample("client_mac" => "11:23:4D:66:77:aB") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('1123.4D66.77AB') end sample("client_mac" => "ad561297fEEd") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('AD56.1297.FEED') end end describe "Clean up a MAC address to no separator and uppercase" do let(:config) do <<-CONFIG filter { sanitize_mac { match => { "client_mac" => "client_mac_sanitized" } separator => "" fixcase => "upper" } } CONFIG end sample("client_mac" => "A98c.c2ff.fe37") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('A98CC2FFFE37') end sample("client_mac" => "11:23:4D:66:77:aB") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('11234D6677AB') end sample("client_mac" => "ad561297fEEd") do expect(subject).to include("client_mac") expect(subject.get('client_mac_sanitized')).to eq('AD561297FEED') end end end
true
09dce9cd85381d2120ff187c23ed3ab407486128
Ruby
johnkerl/ruffl
/Factorization.rb
UTF-8
5,808
3.6875
4
[ "BSD-2-Clause" ]
permissive
# ================================================================ # Please see LICENSE.txt in the same directory as this file. # John Kerl # [email protected] # Copyright (c) 2004 # Ported to Ruby 2011-02-10 # ================================================================ class Factorization # ---------------------------------------------------------------- def initialize @factors_and_multiplicities = [] @trivial_factor = nil # E.g. -1, 0, 1. end attr_reader :trivial_factor attr_reader :factors_and_multiplicities def num_distinct_factors # Don't count trivial factors. @factors_and_multiplicities.length end def num_factors # Don't count trivial factors. @factors_and_multiplicities.inject(0) {|rv, fnm| rv += fnm[1]} end def get(i) @factors_and_multiplicities[i] end def get_factor(i) @factors_and_multiplicities[i][0] end def get_multiplicity(i) @factors_and_multiplicities[i][1] end # ---------------------------------------------------------------- def to_s s = "" num_printed = 0 if !@trivial_factor.nil? s << @trivial_factor.to_s num_printed += 1 end for factor, multiplicity in @factors_and_multiplicities if num_printed > 0 s << " " end s << factor.to_s if multiplicity != 1 s << "^" << multiplicity.to_s end num_printed+= 1 end s end # ---------------------------------------------------------------- def insert_trivial_factor(new_factor) if !new_factor.nil? if !@trivial_factor.nil? @trivial_factor *= new_factor else @trivial_factor = new_factor end end end # Inserts in sorted order. This makes it easier to unit-test the # factorization algorithm. def insert_factor(new_factor, new_multiplicity=1) m = @factors_and_multiplicities.length for i in 0..(m-1) factor, multiplicity = @factors_and_multiplicities[i] if new_factor == factor @factors_and_multiplicities[i][1] += new_multiplicity return elsif new_factor < factor @factors_and_multiplicities.insert(i, \ [new_factor, new_multiplicity]) return end end # Append to the end (or, new first element in the previously empty # list). @factors_and_multiplicities.push([new_factor, new_multiplicity]) end def merge(other) self.insert_trivial_factor(other.trivial_factor) other.factors_and_multiplicities.each do |fnm| f, m = fnm self.insert_factor(f, m) end end def exp_all(e) if !@trivial_factor.nil? @trivial_factor **= e end @factors_and_multiplicities.each {|fnm| fnm[1] *= e} end # ---------------------------------------------------------------- # Given the prime factorization p1^m1 ... pk^mk of n, how to enumerate all # factors of n? # # Example 72 = 2^3 * 3^2. Exponent on 2 is one of 0, 1, 2, 3. # Exponent on 3 is one of 0, 1, 2. Number of possibilities: product # over i of (mi + 1). Factors are: # # 2^0 3^0 1 # 2^0 3^1 3 # 2^0 3^2 9 # 2^1 3^0 2 # 2^1 3^1 6 # 2^1 3^2 18 # 2^2 3^0 4 # 2^2 3^1 12 # 2^2 3^2 36 # 2^3 3^0 8 # 2^3 3^1 24 # 2^3 3^2 72 def num_divisors ndf = self.num_distinct_factors if ndf <= 0 if @trivial_factor.nil? raise "Factorization.num_divisors: " \ "No factors have been inserted.\n" end end rv = 1 for i in (0..(ndf-1)) rv *= @factors_and_multiplicities[i][1] + 1 end return rv end # ---------------------------------------------------------------- # See comments to num_divisors. k is treated as a multibase # representation over the bases mi+1. (This may overflow a 32-bit # integer when factoring something large -- but if something really # has more than a billion factors, it is impractical to loop over all # its factors anyway.) def kth_divisor(k) ndf = self.num_distinct_factors if ndf <= 0 if !@trivial_factor.nil? return @trivial_factor / @trivial_factor # abstract one else raise << "Factorization.kth_divisor: " "No factors have been inserted.\n" end end x = @factors_and_multiplicities[0][0] rv = x / x # abstract one for i in (0..(ndf-1)) base = @factors_and_multiplicities[i][1] + 1 power = k % base k = k / base rv *= @factors_and_multiplicities[i][0] ** power end return rv end # ---------------------------------------------------------------- # Returns an array of divisors. The output is sorted from smallest to # largest. def all_divisors ndf = self.num_distinct_factors if ndf <= 0 if @trivial_factor.nil? raise "Factorization.all_divisors: " \ "No factors have been inserted.\n" end end nd = self.num_divisors rv = [0] * nd for k in (0..(nd-1)) rv[k] = self.kth_divisor(k) end rv.sort! return rv end # ---------------------------------------------------------------- # The output is sorted from smallest to largest. def maximal_proper_divisors ndf = self.num_distinct_factors if ndf <= 0 if @trivial_factor.nil? raise "Factorization.maximal_proper_divisors: " \ "No factors have been inserted.\n" else return [] end end save_trivial_factor = @trivial_factor @trivial_factor = nil n = self.unfactor rv = [0] * ndf for k in (0..(ndf-1)) rv[k] = n / @factors_and_multiplicities[k][0] end rv.sort! @trivial_factor = save_trivial_factor return rv end # ---------------------------------------------------------------- def unfactor ndf = self.num_distinct_factors if ndf <= 0 if @trivial_factor.nil? raise "Factorization.maximal_proper_divisors: " \ "No factors have been inserted.\n" else return @trivial_factor end end x = @factors_and_multiplicities[0][0] rv = x/x if !@trivial_factor.nil? rv *= @trivial_factor end for p,e in @factors_and_multiplicities rv *= p**e end return rv end end
true
67eae1fc1177f2b79d2bf9f5682c735c9107c96a
Ruby
izabellea/teacher-vacancy-service
/lib/base_dsi_exporter.rb
UTF-8
976
2.625
3
[ "MIT" ]
permissive
require 'dfe_sign_in_api' require 'google/cloud/bigquery' class BaseDsiExporter attr_reader :dataset def initialize(bigquery: Google::Cloud::Bigquery.new) @dataset = bigquery.dataset ENV.fetch('BIG_QUERY_DATASET') end private def delete_table(table_name) table = dataset.table table_name return if table.nil? dataset.reload! if table.delete end def insert_rows (1..number_of_pages).each do |page| response = api_response(page: page) raise error_message_for(response) if users_nil_or_empty?(response) insert_table_data(response['users']) end end def number_of_pages response = api_response raise (response['message'] || 'failed request') if response['numberOfPages'].nil? response['numberOfPages'] end def users_nil_or_empty?(response) response['users'].nil? || response['users'].first.empty? end def error_message_for(response) response['message'] || 'failed request' end end
true
424e22424f3afc94a6ea1aecb28f542b2360e3e5
Ruby
Wyattwicks/sweater_weather
/app/poros/route.rb
UTF-8
940
3.109375
3
[]
no_license
class Route attr_reader :id, :start_city, :end_city, :travel_time, :hours_to_arrival, :weather_at_eta, :conditions, :temperature def initialize(data, forecast) @id = nil @type = "roadtrip" @start_city = "#{data[:route][:locations][0][:adminArea5]}, #{data[:route][:locations][0][:adminArea3]}" @end_city = "#{data[:route][:locations][1][:adminArea5]}, #{data[:route][:locations][1][:adminArea3]}" @travel_time = "#{data[:route][:formattedTime].split(":")[0]} hour(s) and #{data[:route][:formattedTime].split(":")[1]} minutes" @hours_to_arrival = data[:route][:formattedTime].split(":").first.to_i @weather_at_eta = {} @weather_at_eta[:conditions] = forecast[@hours_to_arrival][:weather][0][:description] @weather_at_eta[:temperature] = forecast[@hours_to_arrival][:temp] end end
true
3677824ea6ca13ffb9f45ea08c2996f1acdaedc2
Ruby
ryan-jr/theodinproject
/webdev101/thebackend/Step4-RubyProject/tests.rb
UTF-8
2,718
4.4375
4
[]
no_license
#writing test code before running them in rspec #for testfirst live #http://testfirst.org/live/learn_ruby/calculator #Temp =begin What I learned: 1. Understand what formulas/equations you will need beforehand, it saves you time 2. I will probably need to go back and refactor the code especially conv1 =end =begin def ftoc(temp) temp = temp.to_f conv1 = 5.0/9.0 cel = ((temp - 32) * (conv1)) cel = cel.to_f return cel end def ctof(temp) temp = temp.to_f conv1 = 9.0/5.0 fahr = ((temp * conv1) + 32) return fahr end #Calculator def add (num1, num2) sum = num1 + num2 return sum end def subtract (num1, num2) sub = num1 - num2 return sub end def sum(array) array.inject(0, :+) end end def multiply(num1, num2) multip = num1 * num2 return multip end add (0,0) add (2,2) subtract(10,4) subtract([10, 10 , 10]) My explanation of the 'titlize' method/function: Titleize takes in a string of words and capitalizes them based upon a few rules 1. If it is the first word in a string 2. If the word is longer than or equal to 3 letters The method puts all of the words into the array 'split' and intializes the 'x' variable 'x' in this instance, checks our position in the array if the length of the string is 1 or less, we just take the first element in the array and capitalize it otherwise we iterate over each element in the array into the variable word and check to see if the length of the word in the string is less than or equal to 3 and make sure it's NOT the first word, if it's not we lowercase the word and add 1 to x. We then see if the lenght of the word in the variable word is greater than or equal to 3, if it is, then we capitalize it regardless, and add 1 to x we then join everything together at the end with a space we then end the method call, and get ready to start all over again def titleize (words) split = words.split x = 0 if (split.length <= 1) split.shift.to_s.capitalize else split.each do |word| if (word.length <= 3 and x !=0) word.downcase x = x+1 elsif word.length >= 3 word.capitalize! x = x+1 end split.join(" ") end end end puts(titleize("jaws")) puts(titleize("david copperfield")) puts(titleize("war and peace")) puts(titleize("the bridge over the river kwai")) =end =begin Steps: 1. put each character into an array and separate them with a comma 2. Test if the first letter is a vowel 3. If the first character is a vowel add it to the end and add ay 4. Otherwise do something else =end def translate(word) ary = Array.new ary << word.split("") puts "Hello World" puts word[0] puts "Hey there" if (ary[0] == "a") puts "hello world" puts "This word starts with a vowel" end end puts(translate("apple"))
true
39693e413f09d0530e622514edccdc5a88182fd4
Ruby
chrispyyy/ContactList
/contact_database.rb
UTF-8
1,356
3.234375
3
[]
no_license
## TODO: Implement CSV reading/writing require 'csv' class ContactDatabase def self.read_csv CSV.read('contacts.csv') end def self.read_contact_id(id) CSV.foreach('contacts.csv') do |line| return line if $. == id end end def self.read_contacts @@all_contacts = [] CSV.foreach('contacts.csv') do |row| @@all_contacts << row #turns it into an array end @@all_contacts end def self.add_contact(contact) CSV.open('contacts.csv', 'a') do |c| c << ["#{contact.name}", "#{contact.email}"] # data << "#{number}" , "#{contact.phonenumber}" end end def self.add_phone_number(id, number) match = false contacts = read_csv contacts.each do |contact| if (id-1) == contacts.index(contact) contact.concat [number] match = true end end puts "Contact not found" unless match == true CSV.open('contacts.csv', 'w') do |file| contacts.each do |contact| file << contact end end end def self. find(word) CSV.foreach('contacts.csv') do |l| return l if l.to_s.downcase.include? word.downcase end end # index def self.id index_lines = [] CSV.foreach('contacts.csv') do |line| index_lines << $. end index_lines.last end end
true
fdaf81bf011d5c313aaf8e6fb1c8878f94f11e17
Ruby
BooHooRor/family_tree
/app/models/user.rb
UTF-8
515
2.703125
3
[]
no_license
class User < ApplicationRecord attr_accessor :full_name validates :email, :first_name, :last_name, :birthdate, :address, :phone_number, presence: true validates :sex, presence: true, inclusion: { in: %w(male female), message: "%{value} is not a valid sex" } has_many :parents, class_name: "User", foreign_key: "parents_id" has_one :sibling, class_name: "User", foreign_key: "sibling_id" def full_name "#{first_name} #{last_name}" end def age age = Date.today.year - birthdate.year end end
true
88696b6806b71302bdd11a9b85e27ef4de356ee6
Ruby
aerostitch/bysas
/build_sitemap_xml.rb
UTF-8
2,254
2.640625
3
[]
no_license
#!/usr/bin/env ruby # require 'date' require 'time' require 'nokogiri' SiteUrl = 'http://aerostitch.github.io' # This is to ensure we are in the same directory as the script # to enable people to run the script from another directory script_path = File.dirname(File.expand_path($0)) # This function will get the content of the revdate in the html documents # Returns a date if a revdate tag is found, else returns nil. def get_revdate(doc_path) doc = Nokogiri::HTML(File.open(doc_path)) { |config| config.strict.nonet} revdate = doc.search('//span[@id="revdate"]').text.strip DateTime.strptime(revdate, '%Y-%m-%d') if /^\d{4}-\d{2}-\d{2}$/.match(revdate) end Dir.chdir(script_path) # Process starts here... # This gets all the html files and their modification date doc = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| xml.urlset('xmlns' => "http://www.sitemaps.org/schemas/sitemap/0.9", 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance", 'xsi:schemaLocation' => "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd") do Dir.glob('../**/*.html') .delete_if { |fname| /(\/|^)_/.match(fname) or /_(\/|$)/.match(fname) } .sort .each { |file| xml.url{ xml.loc(file.gsub(/\.\./,SiteUrl)) # For index.html files, use the description.inc file modification date # instead fdesc = file.gsub(/index\.html$/,'description.inc') if file != fdesc and File.exists?(fdesc) xml.lastmod((File.new(fdesc).mtime).iso8601) else # If a revision date is found in the doc, use it. # Else, use the file last modification date dte = get_revdate(file) if dte.nil? xml.lastmod((File.new(file).mtime).iso8601) else xml.lastmod((get_revdate(file)).iso8601) end end xml.changefreq('monthly') xml.priority('1.0') } } end end # Finally writing menu.xml file begin file = File.open("../sitemap.xml", "w") file.write(doc.to_xml) rescue IOError => e puts "[Error] Could not open file." puts e.message ensure file.close unless file == nil end
true
ac627d73e3efcda15a1eb6a0c22ec9f9aee7683e
Ruby
voostindie/topicz
/spec/command/note_command_spec.rb
UTF-8
1,873
2.59375
3
[ "MIT" ]
permissive
require 'spec_helper' require 'testdata' require 'topicz/commands/note_command' class DummyKernel def exec(*arguments) print arguments.join ' ' end end describe Topicz::Commands::NoteCommand do it 'creates a file with the proper heading when needed' do with_testdata do date = DateTime.now.strftime("%Y-%m-%d") filename = "/topics/topic1/Notes/#{date} Foo.md" expect { Topicz::Commands::NoteCommand.new(nil, %w(-s topic_1 Foo), DummyKernel.new).execute }.to output("foo-editor \"#{filename}\"").to_stdout expect(File.exist?(filename)).to be true expect(File.readlines(filename)[0]).to eq "# Special topic - Foo\n" end end it 'includes the hour and minute if no name is specified' do with_testdata do date = DateTime.now.strftime("%Y-%m-%d %H%M") filename = "/topics/topic1/Notes/#{date}.md" expect { Topicz::Commands::NoteCommand.new(nil, %w(-s topic_1), DummyKernel.new).execute }.to output("foo-editor \"#{filename}\"").to_stdout expect(File.exist?(filename)).to be true expect(File.readlines(filename)[0]).to eq "# Special topic - Unnamed note\n" end end it 'skips file creation when one already exists' do with_testdata do date = DateTime.now.strftime("%Y-%m-%d") filename = "/topics/topic1/Notes/#{date} Foo.md" FakeFS::FileSystem.add('/topics/topic1/Notes') File.write(filename, 'DUMMY FILE') expect { Topicz::Commands::NoteCommand.new(nil, %w(-s topic_1 Foo), DummyKernel.new).execute }.to output("foo-editor \"#{filename}\"").to_stdout expect(File.exist?(filename)).to be true expect(File.readlines(filename)[0]).to eq 'DUMMY FILE' end end it 'supports help' do expect(Topicz::Commands::NoteCommand.new.option_parser.to_s).to include 'Creates a new note' end end
true
77ee48ce44f2950eef67c939ddffd36a32460008
Ruby
t1h/uke_note
/app/helpers/chords_helper.rb
UTF-8
442
2.71875
3
[]
no_license
module ChordsHelper def chord_image(chord) if chord.nil? || chord == '' image_tag "chords/blank.png", alt: "" else image_tag "chords/" + chord.to_s.gsub('#', 's').gsub('/', 'on') + ".png", alt: chord end end def transpose_chord(chord, number) begin chords = TransposeChords::Chord.transpose([chord.to_s]).capo(number) chords[0] unless chords.nil? rescue => error nil end end end
true
d3adffef4adae6119bdbd1763c711c786388d2e1
Ruby
linyahu/collections_practice_vol_2-nyc-web-career-010719
/collections_practice.rb
UTF-8
1,939
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def begins_with_r(array) array.all? do |word| word.start_with?("r") end end def contain_a(array) array.select do |word| word.include?("a") end end def first_wa(array) array.find do |word| word.to_s.start_with?("wa") end end def remove_non_strings(array) array.delete_if do |word| word.class != String end end def count_elements(array) hash = Hash.new 0 new_array = [] array.each do |elements| elements.each do |key, value| hash[value] += 1 end end i = 0 while i < hash.length new_array.push(:count => hash.values[i], :name => hash.keys[i]) i += 1 end return new_array end def merge_data(keys, data) merged_array = [] m_hash_1 = {} m_hash_2 = {} keys.each do |elements| name_key = elements[:first_name] motto = elements[:motto] data.each do |hash| hash.each do |key, value| if key == name_key m_hash_1 = {elements.key(name_key) => name_key} m_hash_1[elements.key(motto)] = motto merged_array.push(m_hash_1.merge(value)) end end end end return merged_array end def find_cool(array) temperature = "" new_array = [] array.each do |data| temperature = data[:temperature] if temperature == "cool" new_array.push(:name => data[:name], :temperature => data[:temperature]) end end return new_array end def organize_schools(schools) cities = [] unique_cities = [] school_array = [] city_hash = {} schools.each do |school, location| location.each do |key, value| cities.push(value) end end unique_cities = cities.uniq unique_cities.each do |city| schools.each do |school, location| location.each do |key, value| if value == city school_array.push(school) end end end city_hash[city] = school_array school_array = [] end return city_hash end
true
d73f583229515076508b335b109f975b18c58c78
Ruby
jacob-brontes/file_storage
/test/bigger_pipe_test.rb
UTF-8
4,148
2.546875
3
[ "MIT" ]
permissive
require 'test/unit' require 'rubygems' require 'activerecord' require 'openssl' class BiggerPipeTest < Test::Unit::TestCase @@is_setup = false def setup_for_all unless @@is_setup #require this plugin require "#{File.dirname(__FILE__)}/../init" @@is_setup = true end end def setup setup_for_all end def test_write_all_then_read_all some_data = "abcdefghijklmnopqrstuvwxyz" r, w = BiggerPipe.pipe w.write(some_data) w.close result = r.read r.close assert_equal(some_data.size, result.size) assert_equal(some_data, result) end def test_reader_and_writer_thread some_data = File.read("#{File.dirname(__FILE__)}/initech_dms/TPSReport.doc") r, w = BiggerPipe.pipe write_from_this_string_io = StringIO.new(some_data) write_finished = false writer_thread = Thread.new do begin while write = write_from_this_string_io.read(1024) w.write(write) end rescue => e puts e.inspect puts e.backtrace.join("\n") ensure w.close write_finished = true end end read_into_this_buffer = "" read_finished = false reader_thread = Thread.new do begin while read = r.read(1024) read_into_this_buffer += read end rescue => e puts e.inspect puts e.backtrace.join("\n") ensure r.close read_finished = true end end while(!write_finished || !read_finished) do Thread.pass end assert_equal(some_data.size, read_into_this_buffer.size) assert_equal(some_data, read_into_this_buffer) end def test_write_faster_than_you_read some_data = "abcdefghijklmnopqrstuvwxyz" r, w = BiggerPipe.pipe write_from_this_string_io = StringIO.new(some_data) write_finished = false writer_thread = Thread.new do while write = write_from_this_string_io.read(5) w.write(write) end w.close write_finished = true end read_into_this_buffer = "" read_finished = false reader_thread = Thread.new do sleep(0.5) while read = r.read(1) sleep(0.02) read_into_this_buffer += read end r.close read_finished = true end while(!write_finished || !read_finished) do Thread.pass end assert_equal(some_data.size, read_into_this_buffer.size) assert_equal(some_data, read_into_this_buffer) end def test_read_faster_than_you_write some_data = "abcdefghijklmnopqrstuvwxyz" r, w = BiggerPipe.pipe write_from_this_string_io = StringIO.new(some_data) write_finished = false writer_thread = Thread.new do sleep(0.5) while write = write_from_this_string_io.read(5) sleep(0.02) w.write(write) end w.close write_finished = true end read_into_this_buffer = "" read_finished = false reader_thread = Thread.new do while read = r.read(5) read_into_this_buffer += read end r.close read_finished = true end while(!write_finished || !read_finished) do Thread.pass end assert_equal(some_data.size, read_into_this_buffer.size) assert_equal(some_data, read_into_this_buffer) end def test_read_all_before_you_write some_data = "abcdefghijklmnopqrstuvwxyz" r, w = BiggerPipe.pipe write_from_this_string_io = StringIO.new(some_data) write_finished = false writer_thread = Thread.new do while write = write_from_this_string_io.read(1) sleep(0.02) w.write(write) end w.close write_finished = true end read_into_this_buffer = "" read_finished = false reader_thread = Thread.new do read_into_this_buffer = r.read r.close read_finished = true end while(!write_finished || !read_finished) do Thread.pass end assert_equal(some_data.size, read_into_this_buffer.size) assert_equal(some_data, read_into_this_buffer) end end
true
f4b4a667c546efa36eecda40a9d04e3965b5e79e
Ruby
keritaf/labs-kidstv
/lab4/lib/scheme.rb
UTF-8
773
2.828125
3
[]
no_license
class Scheme INPUTS = 7 attr_writer :signals def initialize(mock: {}) @mock = mock end 0.upto(INPUTS) do |i| define_method "x#{i}".to_sym do @mock["x#{i}".to_sym] || @signals[i] end end def f1 @mock[:f1] || Function.new('and', x0, x1).value end def f2 @mock[:f2] || Function.new('not', x2).value end def f3 @mock[:f3] || Function.new('or', x4, x5).value end def f4 @mock[:f4] || Function.new('and', x3, x6, f3).value end def f5 @mock[:f5] || Function.new('nor', f2, f4).value end def f6 @mock[:f6] || Function.new('and', f1, f5).value end def process(signals) @signals = signals f6 end def state [x0, x1, x2, x3, x4, x5, x6, x6, f1, f2, f3, f4, f5, f6] end end
true
836fa41806d83abed4d162014d0c6bef469b522b
Ruby
oreno-tools/furikake
/lib/furikake/resources/kinesis.rb
UTF-8
1,347
2.53125
3
[ "MIT" ]
permissive
module Furikake module Resources module Kinesis def report resources = get_resources headers = ['Stream Name', 'Stream ARN', 'Stream Status', 'Shards'] if resources.empty? info = 'N/A' else info = MarkdownTables.make_table(headers, resources, is_rows: true, align: 'l') end documents = <<"EOS" ### Kinesis #{info} EOS documents end def get_resources kinesis = Aws::Kinesis::Client.new all_streams = [] loop do res = kinesis.list_streams all_streams.push(*res.stream_names) break unless res.has_more_streams end kinesis_infos = [] all_streams.each do |stream| keys = [:stream_name, :stream_arn, :stream_status] res = kinesis.describe_stream({ stream_name: stream }) resouces = [] res.stream_description.to_h.each do |k, v| if keys.include?(k) resouces << v end if k == :shards resouces << v.size end end kinesis_infos << resouces end kinesis_infos end module_function :report, :get_resources end end end
true
da059ff15b94dac3b2d4dbbadb5deebe6b0ca4b3
Ruby
chalmie/Random_Ruby
/thou_dij_fib.rb
UTF-8
174
3.109375
3
[]
no_license
def thou_dij_fib fibs = [1, 1] until fibs.last.to_s.length == 1000 nextfib = fibs[-1] + fibs[-2] fibs << nextfib end fibs.length end p thou_dij_fib
true
ecdb8956f8474b02f0313439bc2ee62c76a2a062
Ruby
greenglass/overseer
/lib/overseer/aws/wrappers/identity_access_management/iam_client.rb
UTF-8
2,363
2.5625
3
[ "MIT" ]
permissive
require 'overseer/helpers/dir_helper' require 'overseer/overseer_error' require 'aws-sdk' module Overseer module AWS module Wrappers # wrapper for aim client in amazon. class IamClient include Helpers # read the local credentials def initialize @iam_client = Aws::IAM::Client.new(region: AWS_REGION) end def all_instance_profiles profiles = [] marker = nil loop do options = marker ? { marker: marker } : {} resp = @iam_client.list_instance_profiles(options) marker = resp.marker profiles += resp.instance_profiles break unless resp.is_truncated end profiles end def all_roles roles = [] marker = nil loop do options = marker ? { marker: marker } : {} resp = @iam_client.list_roles(options) marker = resp.marker roles += resp.roles break unless resp.is_truncated end roles end def delete_instance_profiles(instance_profiles_to_delete) instance_profiles_to_delete.each do |profile| @iam_client.delete_instance_profile( instance_profile_name: profile.instance_profile_name) end end def delete_roles(roles_to_delete) roles_to_delete.each do |role| @iam_client.delete_role( role_name: role.role_name) end end def print_instance_profiles(instance_profiles) puts format(BASE_RESOURCE_FORMAT, 'Instance Profile Name', 'Age', 'Roles') instance_profiles.each do |profile| puts format( BASE_RESOURCE_FORMAT, profile.instance_profile_name, Wrappers.age_string_from_time(profile.create_date), profile.roles.map(&:role_name) ) end end def print_roles(roles) puts format(BASE_RESOURCE_FORMAT, 'Role Name', 'Age', '') roles.each do |role| puts format( BASE_RESOURCE_FORMAT, role.role_name, Wrappers.age_string_from_time(role.create_date), '' ) end end end end end end
true
f83d51461b65a144840465848b31bc0bd4ddb573
Ruby
thebravoman/software_engineering_2014
/class017_homework/homework1/Stefan_Iliev/results_writer.rb
UTF-8
755
3.1875
3
[]
no_license
class ResultsWriter def self.write( results ) results.to_hash html = File.open("results_Stefan_Iliev_B_28.html", "w") html.puts("<!DOCTYPE html>") html.puts("<html>") html.puts(" <table border=\"1\" style=\"width:100%\">") html.puts(" <tr>") html.puts(" <th> FirstName </th>") html.puts(" <th> LastName </th>") html.puts(" <th> Result </th>") html.puts(" <tr>") results.each do |name, result| first_name = name.split("_").first last_name = name.split("_")[1] html.puts(" <tr>") html.puts(" <th> #{first_name} </th>") html.puts(" <th> #{last_name} </th>") html.puts(" <th> #{result} </th>") html.puts(" <tr>") end html.puts(" </table>") html.puts("</html>") html.close end end
true
c99035b836e3e017b8cd1fd596332936bb50b3a3
Ruby
mathildathompson/wdi_sydney_feb
/students/kriss_heimanis/stock_exchange/cheats.rb
UTF-8
390
2.703125
3
[]
no_license
# gets the yahoo finance gem workign and connected? require 'yahoofinance' # this returns EVERYTHING for apple YahooFinance::get_quotes(YahooFinance::StandardQuote, 'AAPL') #this returns just the askign price YahooFinance::get_quotes(YahooFinance::StandardQuote, 'AAPL')['AAPL'].ask #returns the last price YahooFinance::get_quotes(YahooFinance::StandardQuote, 'AAPL')['AAPL'].lastTrade
true
f4fdef9a64b55cfb4fe5520c6af9aee394183fc4
Ruby
conyekwelu/rb101
/Easy Problems/Easy2/easy2.rb
UTF-8
3,325
4.34375
4
[]
no_license
# CORE CONCEPTS # - print allows user entry in same line as prompt unlike puts # ============================================================ # puts "Teddy is #{rand(20..199)} years old!" # # def age_declaration(name="Teddy") # puts "Enter your name: " # name = gets.chomp # name = "Teddy" if name.empty? # puts "#{name} is #{rand(20..199)} years old!" # end # # age_declaration() # ============================================================ # SQMETERS_TO_SQFEET = 10.7639 # puts "Enter the length of the room in meters: " # length = gets.chomp.to_f # puts "Enter the width of the room in meters: " # width = gets.chomp.to_f # area_sqm = (length * width).round(2) # area_sqf = (area_sqm * SQMETERS_TO_SQFEET).round(2) # puts "The area of the room is #{area_sqm} square meters (#{area_sqf} square feet)." # Tip Calculator ============================================================ print "What is the bill? " bill = gets.chomp.to_f print "what is the tip percentage? " tip_percentage = gets.chomp.to_f tip = (bill * tip_percentage / 100).round(1) total = (bill + tip).round(1) puts "the tip is #{tip}" puts "the total is #{total}" # When will I Retire? ========================================================= # print "What is your age? " # age = gets.chomp.to_i # # print "At what age would you like to retire? " # retirement_age = gets.chomp.to_i # # years_to_work = retirement_age - age # current_year = Time.now.year # retirement_year = current_year + (years_to_work) # # puts "It's #{current_year}. You will retire in #{retirement_year}." # puts "You have only #{years_to_work} years of work to go!" # # Greeting a user ============================================================ # print "What is your name? " # name = gets.chomp # # if name.end_with?("!") # can also use name[-1] == "!" # puts "HELLO #{name.chop.upcase}. WHY ARE WE SCREAMING?" # else # puts "Hello #{name}" # end # Odd Numbers ============================================================ # (1..99).each {|i| p i if i.odd?} # 1.upto(99) { |i| p i if i.odd? } # (1..99).step(2) { |n| puts n } # Even Numbers # (1..99).each {|i| puts i if i.even?} # # value = 1 # while value < 99 do # puts value if value % 2 == 0 # value += 1 # end # for i in (1..99) do # puts i if i.even? # end ===Create input validation for this piece of code === OPERATIONS = {"s" => "sum", "p" => "product"} puts ">> Please enter an integer greater than 0:" num = gets.chomp.to_i puts ">> Enter 's' to compute the sum, 'p' to compute the product." operator = gets.chomp result = case operator when "s" (1..num).reduce(:+) when "p" (1..num).reduce(:*) end puts "The #{OPERATIONS[operator]} of the integers between 1 and #{num} is #{result}." ============================================================ name = 'Bob' save_name = name name.upcase! puts name, save_name "BOB", "BOB" save_name points to the same object that name is pointing to we modify the object when we called the destructive method upcase! on it ============================================================= array1 = %w(Moe Larry Curly Shemp Harpo Chico Groucho Zeppo) array2 = [] array1.each { |value| array2 << value } array1.each { |value| value.upcase! if value.start_with?('C', 'S') } puts array2 both arrays reference the same objects.
true
a223dbee5015fe2e60322bae1f1e3bd7898e5b12
Ruby
capnregex/date-recurrence
/lib/date/recurrence/pay_period.rb
UTF-8
1,113
2.9375
3
[]
no_license
require 'date/recurrence/pay_period/calculations' class Date class Recurrence class PayPeriod # @NOTE: 01/07/2018 is the starting date for pay periods in 2018 # (https://www.nfc.usda.gov/Publications/Forms/pay_period_calendar.php has pay period dates) class_attribute :origin, default: Date.new(2018, 1, 7) class_attribute :duration, default: 14 # days delegate :origin, :duration, :new, to: :class attr_reader :starts def initialize(date=nil) @starts = (date.to_date || Time.zone.today).beginning_of_pay_period end def ends @ends ||= starts.days_since(duration - 1) end def range @range ||= starts..ends end def next new(day(duration)) end def prev new(starts.days_ago(duration)) end def day(index) if index.negative? ends.days_since(index + 1) else starts.days_since(index) end end def days range.to_a end def cover?(date) range.cover? date end end end end
true
c29c6e22e88529ea36f4d97aa5c442c8158008aa
Ruby
Sihan001/lbActions
/chmod.lbaction/Contents/Scripts/default.rb
UTF-8
1,399
2.84375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby # # LaunchBar Action Script # puts '<?xml version="1.0"?>' puts '<items>' def oct_to_sym(x) num = x.to_i(8).to_s(2) result = '' result << (num.slice(0, 1) == '1' ? 'r' : '-') result << (num.slice(1, 1) == '1' ? 'w' : '-') result << (num.slice(2, 1) == '1' ? 'x' : '-') result end def sym_to_oct(x) x.gsub(/[rwx]/, '1').gsub('-', '0').to_i(2).to_s(8) end input = ARGV.first if input =~ /[0-9]+/ input = input.slice 1, 3 if input.length >= 4 owner = oct_to_sym input.slice(0, 1) group = oct_to_sym input.slice(1, 1) others = oct_to_sym input.slice(2, 1) elsif input =~ /[drwx-]+/ input = input.slice 1, 9 if input.length >= 10 owner = input.slice 0, 3 group = input.slice 3, 3 others = input.slice 6, 3 end chmod = "chmod #{sym_to_oct(owner + group + others)}" puts " <item uid=\"octal\" valid=\"yes\" arg=\"#{chmod}\">" puts " <title>#{chmod}</title>" puts ' <subtitle>Copy to clipboard</subtitle>' puts ' <icon>icon.png</icon>' puts ' </item>' puts ' <item uid="owner">' puts " <title>Owner: #{owner}</title>" puts ' <icon>owner.png</icon>' puts ' </item>' puts ' <item uid="group">' puts " <title>Group: #{group}</title>" puts ' <icon>group.png</icon>' puts ' </item>' puts ' <item uid="others">' puts " <title>Others: #{others}</title>" puts ' <icon>others.png</icon>' puts ' </item>' puts '</items>'
true
49785e5d5247da9513beec21e2e7eee9a4b19d1c
Ruby
meyercm/git-issue
/src/git_issue/commands/close_command.rb
UTF-8
2,289
2.8125
3
[ "BSD-2-Clause" ]
permissive
require_relative 'base_command' module GitIssue class CloseCommand < BaseCommand def parse(args) options = OpenStruct.new() options.sha = validate_sha(args.shift) options.message = "" options.tags = {} parser = OptionParser.new do |opts| opts.on("-m", "--message MESSAGE", "notes on closing this issue") do |message| options.message = message end opts.on("-t", "--tag TAGS", "tags to place on this Issue") do |tags| options.tags = Tag.parse(tags) end opts.on("-e", "--editor", "opens an editor for a closing comment") do options.editor = true end end parser.parse!(args) options end def run(options) issue = get_issue(options.sha) title = "" message = options.message or "" message += @@default_message if options.editor then title, message = get_message_from_editor(message) end GitWorker.work_on_issues_branch do Tag.create(issue, {:status => "closed"}.merge(options.tags)) if message != "" Event.create(issue, {:event_type => :close, :title => title, :description => message}) end end write_output "#{issue.short_id} successfully closed" end @@default_message = ' #$# Add a reason for closing this issue. #$# Lines beginning with a "#$#"" are ignored, and an empty message aborts the #$# operation. ' @@help_message ='Closes an issue. Closed issues have a status of \"closed\", and do not appear in the query results of `git issue list`, unless `--all` is passed to that command. Currently, the only way to re-open an issue is with the `tag` command, e.g. `git issue tag <issue_id> status:open` Usage: git issue close <issue_id> [options] Options: -t, --tag TAGSTR applies the tags given in TAGSTR to the issue. This may be useful, for example, to tag an issue with a common reason for closure, like deferral. -m, --message, MESSAGE specifies a message for a closing comment. -e, --editor opens an editor to accept a closing comment. Examples: git issue close cc4 git issue close 3cf91 -t deferred:true git issue close a3e --editor ' end end
true
761f12c23eef354783d7a946322d272f59514f75
Ruby
tonymaibox/bringing-it-all-together-web-0716
/lib/dog.rb
UTF-8
1,741
3.46875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Dog attr_accessor :name, :breed, :id def initialize(name: nil, breed: nil, id: nil) @name = name @breed = breed @id = id end def self.create_table sql = <<-SQL CREATE TABLE IF NOT EXISTS dogs ( id INTEGER PRIMARY KEY, name TEXT, breed TEXT); SQL DB[:conn].execute(sql) end def self.drop_table sql = <<-SQL DROP TABLE dogs SQL DB[:conn].execute(sql) end def save if self.id self.update else sql = <<-SQL INSERT INTO dogs (name, breed) VALUES (?, ?); SQL DB[:conn].execute(sql, self.name, self.breed) sql = <<-SQL SELECT * FROM dogs ORDER BY id DESC LIMIT 1; SQL resultid = DB[:conn].execute(sql) @id = resultid.flatten.first self end end def self.create(name:, breed:) # binding.pry dog = Dog.new(name: name, breed: breed) dog.save # dog end def self.new_from_db(row) new_dog = self.new new_dog.id = row[0] new_dog.name = row[1] new_dog.breed = row[2] new_dog end def self.find_by_id(id) sql = <<-SQL SELECT * FROM dogs WHERE id = ? SQL row = DB[:conn].execute(sql,id).first self.new_from_db(row) end def self.find_by_name(name) sql = <<-SQL SELECT * FROM dogs WHERE name = ? SQL row = DB[:conn].execute(sql,name).first self.new_from_db(row) end def update sql = <<-SQL UPDATE dogs SET name = ?, breed = ? WHERE id = ?; SQL DB[:conn].execute(sql, self.name, self.breed, self.id) end def self.find_or_create_by(name:, breed:) # binding.pry if self.find_by_name(name).breed == breed self.find_by_name(name) else self.create(name: name, breed: breed) end end end
true
0f22cd69c71ad527ecf2790c43cc545bf2aa5c0f
Ruby
Graciexia/todo-csv
/lib/todo.rb
UTF-8
2,702
3.953125
4
[]
no_license
require 'csv' class Todo def initialize(file_name) @file_name = file_name @todos = CSV.read(@file_name, headers:true) # You will need to read from your CSV here and assign them to the @todos variable. make sure headers are set to true end def start loop do system('clear') puts "---- TODO.rb ----" view_todos puts puts "What would you like to do?" puts "1) Exit 2) Add Todo 3) Mark Todo As Complete" print " > " action = gets.chomp.to_i case action when 1 then exit when 2 then add_todo when 3 then mark_todo else puts "\a" puts "Not a valid choice" end end end def view_todos view_todos_by_status("Unfinished","no") view_todos_by_status("Completed","yes") end def view_todos_by_status(header,status) puts header arr_name = [] @todos.each do |x| if x["completed"] == status arr_name.push(x["name"]) end end arr_name.each_with_index do |element, index| puts "#{index+1}) #{element}" end end # def view_todos_by_status(header,status) # puts header # @todos.each_with_index do |x, index| # if x["completed"] == status # puts "#{index+1}) #{x['name']}" # end # end # end def add_todo puts "Name of Todo > " name_of_todo = get_input @todos << [name_of_todo, "no"] save! end def todos return @todos end # def mark_todo # # view_todos_by_status("Unfinished","no") # puts "Which todo have you finished?" # action = gets.chomp.to_i # puts "finish homework,yes\n" # if yes # save! # else # end # end # def mark_todo # puts "Which todo do you want to change? " # action = gets.chomp.to_i # # todo: check if input is in correct range # if action < 1 || action > @todos.count # puts "\aThat is not a valid number. Press <enter> to continue." # action = gets.chomp # else # if @todos[action-1]["completed"] == "yes" # puts "\aThat todo is already finished. Press <enter> to continue." # action = gets.chomp # else # @todos[action-1]["completed"] = "yes" # end # save! # end # end def mark_todo puts "Which todo have you finished?" action = get_input.to_i arr_index = 0 @todos.each do |x| if x["completed"] == "no" arr_index = arr_index + 1 if arr_index == action x["completed"] = "yes" save! break end end end end private def get_input gets.chomp end def save! File.write(@file_name, @todos.to_csv) end end
true
1e7422fb4589e3072ac7aa13b4f4faa9de0c38b5
Ruby
SamuelSacco/W4D2
/ClassWork/Pieces/king.rb
UTF-8
486
3.140625
3
[]
no_license
require_relative 'piece' require_relative 'stepable' class King < Piece include Stepable MOVES = [ [1,1], [1,0], [0,1], [-1,-1], [-1,1], [1,-1], [0,-1], [-1,0] ] def symbol '♚'.colorize(color) end protected def move_diffs MOVES # return an array of diffs representing where a King can step to end end [[1, 5], [1, 4], [-1, 3], [-1, 5], [1, 3], [-1, 4]]
true
05112ff7778e9adc7c0dda274228ad56c09e6ffb
Ruby
collabnix/dockerlabs
/vendor/bundle/ruby/2.6.0/gems/regexp_parser-2.4.0/lib/regexp_parser/expression/classes/group.rb
UTF-8
1,645
2.59375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Regexp::Expression module Group class Base < Regexp::Expression::Subexpression def parts [text.dup, *expressions, ')'] end def capturing?; false end def comment?; false end end class Passive < Group::Base attr_writer :implicit def initialize(*) @implicit = false super end def parts if implicit? expressions else super end end def implicit? @implicit end end class Absence < Group::Base; end class Atomic < Group::Base; end class Options < Group::Base attr_accessor :option_changes def initialize_copy(orig) self.option_changes = orig.option_changes.dup super end end class Capture < Group::Base attr_accessor :number, :number_at_level alias identifier number def capturing?; true end end class Named < Group::Capture attr_reader :name alias identifier name def initialize(token, options = {}) @name = token.text[3..-2] super end def initialize_copy(orig) @name = orig.name.dup super end end class Comment < Group::Base def parts [text.dup] end def comment?; true end end end module Assertion class Base < Regexp::Expression::Group::Base; end class Lookahead < Assertion::Base; end class NegativeLookahead < Assertion::Base; end class Lookbehind < Assertion::Base; end class NegativeLookbehind < Assertion::Base; end end end
true
e153cce67d2128be8e0183ed1fa719e21082e6c3
Ruby
nasa/Common-Metadata-Repository
/orbits-lib/resources/orbits/orbit.rb
UTF-8
28,776
3.265625
3
[ "Apache-2.0" ]
permissive
# This is a Ruby implementation of the Backtrack Orbit Search Algorithm (BOSA) # originally written in Java and maintained by [NSIDC](http://nsidc.org/). # References to "the Java code" or "the NSIDC spheres code" in the refer # to the original library which is available # [here](http://geospatialmethods.org/spheres/). Along with the original # code, geospatialmethods.org also has a [description of the algorithm] # (http://geospatialmethods.org/bosa/). # #### Overview # # Orbiting satellites have sensors that trace a circular path around the # Earth. It is difficult to express this ground track as a 2D polygon # with lat/lon coordinates. Most of the orbits we deal with have a # long, narrow, sinusoidal shape that would require hundreds of points # to describe. Further, their minimum bounding rectangle covers nearly # the whole Earth and some orbits have ground tracks that cross themselves # within a single granule of data. # # Instead of describing the orbit as a complex 2D polygon, we want to # answer a different question: # # *Where would the orbit need to cross the equator in order to see # a given point on the Earth?* # # Instead of using a complicated 2D polygon query, we could instead perform # a simple range query: "Find all data granules whose orbit crosses the # equator between longitudes `a` and `b`." # # This class contains the methods used to determine the equator crossing range # for a given orbit and point on the Earth. # # If we want to find data which intersects a more complicated area of the # Earth, we can decompose that area into points and perform a similar range # query. We add points along the perimiter of the shape so that any orbit # that intersects the shape will pass over points on the perimiter. This # process of adding points is called *densification*. # #### Conventions # # Where readability allows, we suffix variables with their units # # * _rad = radians (Earth radii) # * _deg = degrees # * _m = meters # * _s = seconds # # We use some default units where no suffix is present: # # * latitude and longitude: degrees # * other angles and distances: radians (Earth radii) # * time: seconds # # phi (`phi`) and theta (`theta`) are used to denote the radian counterparts # of latitude and longitude respectively, since the latter are almost always # expressed in degrees. # #### Definitions # # * **inclination**: Angle of the orbit from the equator. Numbers greater # than 90 degrees are common and indicate a retrograde orbit # * **prograde orbit**: An orbit that travels in the direction of the # Earth's rotation # * **retrograde orbit**: An orbit that travels in the direction opposite # the Earth's rotation # * **inflection point**: A point where the orbit reaches its highest # or lowest latitude # * **declination**: The angle between the orbits inflection points and the # nearest pole. Note that this definition is similar to magnetic # compass declination. Celestial declination is a different concept. # * **nadir**: The opposite of zenith - a vector pointing straight down at a # given point. # require 'orbits/longitude_coverage' require 'orbits/coordinate' require 'orbits/geometry_to_coordinates_converter' require 'orbits/geometry_backtracking' module Orbits ### Orbit class definition class Orbit include Math include GeometryBacktracking #### Attributes # The inclination angle of the orbit in radians attr_reader :inclination_rad # The number of seconds it takes to complete one orbit attr_reader :period_s # The width of the orbital track observed by the sensor, in Earth radians. # This width is perpendicular to the orbit's track, and runs along the # Earth's surface. It is measured at the equator, which only matters if # we use an ellipsoidal Earth at some point in the future. attr_reader :swath_width_rad # The starting circular latitude of each orbital pass. attr_reader :start_clat_rad # The number of orbits per granule of data (may be a fraction) attr_reader :count #### Constructor # We accept the parameters and units stored in ECHO but convert them to # units that are more useful internally. # # * **inclination_deg** - The number of degrees of inclination for the orbit # * **period_min** - The number of minutes it takes to complete one orbit # * **swath_width_km** - The width of the orbital track in kilometers # * **start_clat_deg** - The starting circular latitude in degrees # * **count** - The number of orbits per granule of data (may be a fraction) def initialize(inclination_deg, period_min, swath_width_km, start_clat_deg, count=0) @declination_rad = nil # lazy @inclination_rad = inclination_deg * PI / 180.0 @period_s = period_min * 60 @swath_width_rad = swath_width_km * 1000 / EARTH_RADIUS_M @start_clat_rad = start_clat_deg * PI / 180.0 @count = count end #### Accessors / Conversions ##### declination_rad # This declination is the angle between the top-most point of the orbit # and the north pole, similar to magnetic compass declination. This # should not be confused with celestial declination def declination_rad if @declination_rad.nil? @declination_rad = inclination_rad - PI / 2 @declination_rad -= PI / 2 while @declination_rad > PI / 2 end @declination_rad end ##### retrograde? # True if the orbit is a retrograde orbit (moves in the opposite direction # of the Earth's rotation), false if it is prograde (moves in the same direction # of the Earth's rotation). Note that all of the orbits in ECHO are retrograde, # so retrograde cases are more thoroughly tested. The Java code seems to # assume that orbits are retrograde. def retrograde? inclination_rad > PI / 2 end ##### max_orbit_phi # The maximum `phi` (latitude) the orbit is able to reach def max_orbit_phi PI / 2 - declination_rad end ##### min_orbit_phi # The minimum `phi` (latitude) the orbit is able to reach def min_orbit_phi -max_orbit_phi end ##### angular_velocity_rad_s # The angular velocity of the orbit, in radians per second. In other words, # the number of radians the orbiting satellite covers per second. def angular_velocity_rad_s 2 * PI / period_s end ##### full_coverage_phi # Some orbits have swaths that cross the poles. Every pass for these orbits # will observe the pole and surrounding points down to a certain latitude. # This method returns lowest positive `phi` (latitude) that every orbital # pass can see. If it's larger than `pi/2`, then the orbital swaths don't # pass over the poles. def full_coverage_phi PI - max_coverage_phi end ##### max_coverage_phi # The maximum `phi` (latitude) that the orbit can see. The orbital swath # can never observe points above this `phi` value. # # See: full_coverage_phi def max_coverage_phi max_orbit_phi + swath_width_rad / 2 end ##### to_s # The format of to_s appears strange, but its the same representation # used by the Java code, so it helps in debugging. def to_s inflection_diffs = [-swath_width_rad / 2, 0, swath_width_rad / 2] inflections = inflection_diffs.map {|d| ((max_orbit_phi + d) * 180 / PI).round(3)} "Orbit with inflections #{inflections.inspect}" end #### Core backtracking methods # This is slow and has accuracy problems. Do not use it for production. # It is here for reference and testing / validation. # Use area_crossing_range (defined in GeometryBacktracking) instead def densified_area_crossing_range(geometry, ascending) separation = swath_width_rad * 0.9 range = LongitudeCoverage.none GeometryToCoordinatesConverter.coordinates(geometry, separation).each do |coord| range << coord_crossing_range(coord, ascending) end range end # Use the faster area crossing range defined in GeometryBacktracking alias_method :area_crossing_range, :fast_area_crossing_range # Uncomment to cause really bad performance by swapping implementations # of area_crossing_range #alias_method :area_crossing_range, :densified_area_crossing_range ##### coord_crossing_range # # This method performs the Backtrack Orbit Search Algorithm. # # Given a coordinate, returns a range of longitudes. Orbital passes # which cross the equator within the returned range will cover the # given coordinate with their swath. # # Parameters: # * **coord** - The coordinate whose equator crossing range we're # interested in (Orbit::Coordinate) # * **ascending** - A boolean value. If true, we return ranges # where the orbit crosses the equator on its ascending pass. If # false, we return ranges where the orbit crosses the equator on # its descending pass. # # Returns an Orbit::LongitudeCoverage def coord_crossing_range(coord, ascending) # If the point is above the max coverage `phi`, there's no coverage return LongitudeCoverage.none if coord.phi.abs > max_coverage_phi # If the point is above the full coverage `phi`, it's covered by every pass return LongitudeCoverage.full if coord.phi.abs > full_coverage_phi # We start by figuring out how wide the swath is at the coordinate, # along the longitude lines. This is different from the orbit's # swath width parameter, because the measurement runs parallel to # the equator, not perpendicular to the orbit. west_edge, east_edge = *horizontal_swath_edges(coord, ascending) # If the swath has no edges at the coordinate, there's no coverage return LongitudeCoverage.none if west_edge.nil? || east_edge.nil? # TODO one edge may pass over the equator before the other, and the # Earth will rotate in the mean time, which will skew the # longitude range slightly. The NSIDC site mentions this, but # the Java code doesn't account for it. # This part is a little tricky. The swath area to the west of the point # is covered by a range of orbits to the east of the point, so we use # the west swath edge to calculate the range of orbits crossing to the # east and vice versa. west_width = west_edge.theta - coord.theta east_target = Coordinate.phi_theta(coord.phi, coord.theta - west_width) east_width = east_edge.theta - coord.theta west_target = Coordinate.phi_theta(coord.phi, coord.theta - east_width) # Figure out where the orbits through each of our targets cross the # equator, compensating for the Earth's rotation (the boolean true value). min_crossing = equator_crossing(west_target, ascending, true).theta max_crossing = equator_crossing(east_target, ascending, true).theta # Construct and return a coverage object LongitudeCoverage.new(min_crossing, max_crossing) end private ##### horizontal_swath_edges # # Given coord, a coordinate within the orbital swath, returns an array # of 2 points with the same latitude as coord which lie on the swath edges. # The first point lies on the edge to the west of coord, the second to the # east. # # If the coordinate cannot fall within the swath, returns an empty array # # Parameters: # * **coord** - A coordinate (Orbit::Coordinate) within the swath # * **ascending** - A boolean value. If true, we return edges for the # orbit's ascending pass. If false, we return edges for the descending # pass. # # Returns an array containing 0 or 2 Orbit::Coordinate instances def horizontal_swath_edges(coord, ascending) # Candidate solutions. We may end up finding more points than we need. # Before returning, we'll take the two points closest to the given # coordinate candidates = [] # We need to be able to assume the coordinate isn't on the equator, so # we'll return early if we find that it is. We know the swath width # from the orbit parameters. This calculation is slightly off, since # the swath width is measured perpendicular to the orbit, but the # Java code makes this assumption. This case should almost never # happen. When it does, the numbers are likely close enough. if coord.phi.abs <= EPSILON return [Coordinate.phi_theta(0, coord.theta - swath_width_rad / 2), Coordinate.phi_theta(0, coord.theta + swath_width_rad / 2)] end # We ignore the rotation of the Earth for the purposes of this method. # The values we return (the swath edges) are not influenced by the # Earth's rotation. Intermediate values are, but they're not visible # outside of this method. # # Ignoring the rotation of the Earth, we can imagine three circles # traced by the orbit. The first is the path on the ground directly # beneath the orbit. This is a great circle whose center is the origin. # The other two are the paths traced by the swath edges, which are not # great circles and not centered at the origin. # # These three circles each lie in a plane, and the three planes are # parallel to each other. # # There's another circle we're interested in, which is the circle # traced by the latitude line at coord. This circle lies in its own # plane which is not parallel to the other three. # # The four original circles are the intersections of their respective # planes and the sphere of the Earth. # # So, to find the swath's edge coordinates, we need to find the # intersection between three things: # # 1. `x^2 + y^2 + z^2 = 1` # # The sphere of the Earth. We've scaled everything so the Earth # has radius 1, and it's centered on the origin. Convenient. # # 2. `ax + by + cz = d` # # The swath's plane. `a`, `b`, `c` and `d` are constants which # we'll calculate. Since they're parallel, the swath edges share # `a`, `b`, and `c` with the orbital plane, but each edge has a # different `d` value. # # 3. `z = "coord.z"` # # The plane slicing through latitude = coord.lat # We already know z z = coord.z # We'll find `a`, `b`, and `c` for the orbit's plane, which are the same # constants for the swath's plane. To find them, we need 3 non-colinear # points in the orbit's plane. The origin is one, but we need two more. # First, we'll get a point that the orbit can pass over which is close # to coord. Usually we'll just use coord, but if coord's latitude is # above the orbit's inflection point, we need to find a point with a # lower latitude target_phi = coord.phi target_phi = max_orbit_phi if target_phi > max_orbit_phi target_phi = min_orbit_phi if target_phi < min_orbit_phi target = Coordinate.phi_theta(target_phi, coord.theta) # For the second point, we'll use the equatorial crossing of the orbit # through the target. This is safe, because we bailed earlier if # the target was on the equator. The "false" parameter tells the method # to ignore the Earth's rotation. cross = equator_crossing(target, ascending, false) # For a plane passing through the origin, `ax + by + cz = 0`. With our # two other points, we can solve for `a`, `b`, and `c`: a = target.y * cross.z - target.z * cross.y b = target.z * cross.x - target.x * cross.z c = target.x * cross.y - target.y * cross.x # If we can find a point on the swath edge, we can calculate `d`. We # can find a point on each edge by finding the orbit's inflection point # and adding/subtracting half the swath width from its latitude. inf = Coordinate.phi_theta(-inclination_rad, cross.theta - PI / 2) # Calculate solutions for the point p on each swath edge [Coordinate.phi_theta(inf.phi + swath_width_rad / 2, inf.theta), Coordinate.phi_theta(inf.phi - swath_width_rad / 2, inf.theta)].each do |p| # Calculate `d` from the plane equation d = a * p.x + b * p.y + c * p.z # The fact that `z` is constant is very handy. It means we really only # care about two dimensions. We're really trying to find the intersection # of a line (the edge's plane when `z = "coord.z"`) and a circle (the part # of the Earth intersecting `z = "coord.z"`). # # Note: that simplified math could make it easier to switch this # algorithm to use an ellipsoidal Earth (WGS84) in the future, since we # would just be intersecting a line with a slightly different circle. # # The swath plane's equation is: # # `ax + by + cz = d` # # `a`, `b`, `c`, `d`, and `z` are all known at this point, so we just # need to figure out `x` and `y`. Solve the equation for `y` # # `y = -a/b x + (d - cz) / b` # # Which is the line we need to intersect with the latitude circle. # We can't just compute constants for the line, because `b` could be near 0. # Let's deal with that special case first. if b.abs < 0.000001 # If `b = 0`, then the plane's equation is: # # `ax + 0y + cz = d` # # Solving for `x`: # # `x = (d - cz) / a` # Ok, another problem. It's possible that both `a` and `b` are 0. In that # case, we have an orbit that follows the equator. If coord lies within the # swath, then every orbit will cover the point, otherwise no orbits will. if a.abs < 0.000001 if coord.phi.abs < swath_width_rad / 2 return [Coordinate.phi_theta(0, -PI), Coordinate.phi_theta(0, PI)] else return [] end end # Now we can handle the case where `b` is 0 and `a` isn't x = (d - c * z) / a # We now know `x` and `z`, so we can use the sphere equation to solve for `y`. # # `y = +- sqrt(1 - z^2 - x^2)` # # In this case, `1 - z^2 - x^2` could be negative. This would indicate # that the latitude does not intersect the swath edge. Perhaps the point is # completely above one swath edge but below the other. We won't worry # about duplicate solutions (`y = +- 0`), since the LongitudeCoverage # class will combine them correctly. dis = 1 - z**2 - x**2 if dis >= 0 y = sqrt(dis) candidates << Coordinate.xyz(x, y, z) candidates << Coordinate.xyz(x, -y, z) end # Now the case when b is not 0. else # Recall, the line's equation is: # # `y = -a/b x + (d - cz) / b` # # We'll call those constants `m` and `k` m = -a / b k = (d - c * z) / b # Which means # # `y = mx + k` # # (We won't use the standard `b` as the `y`-intercept name, since # it means something different in the plane equation). # We need to find the intersection of that line with the latitude # circle at `z = "coord.z"`. Using the sphere equation with a # constant z, we get the latitude circle's equation: # # `x^2 + y^2 = 1 - z^2` # It's centered at the origin. `1 - z^2` is the radius squared. # # Taking the square root is safe because we calculated z from a # lat/lon coordinate. Further, a negative radius doesn't make sense. r = sqrt(1 - z**2) # So, # # `x^2 + y^2 = r^2` # # Substituting `y` with the value from our line equation: # # `x^2 + (mx + k)^2 = r^2` # # Multiplying out, we get: # # `x^2 + m^2x^2 + 2mkx + k^2 = r^2` # Grouping constants, we get: # # `(m^2 + 1)x^2 + (2mk)x + (k^2 - r^2) = 0` # # We call those constants `a_q`, `b_q`, and `c_q` a_q = m**2 + 1 b_q = 2 * m * k c_q = k**2 - r**2 # So: # # `a_q x^2 + b_qx + c_q = 0` # We can solve this using the quadratic equation: # # `x = (-b +- sqrt(b^2 - 4ac)) / (2a)` discriminant = b_q**2 - 4 * a_q * c_q # The discriminant could be negative if the line and circle do # not intersect if discriminant >= 0 # There are two possible `x` values [(-b_q + sqrt(discriminant)) / (2*a_q), (-b_q - sqrt(discriminant)) / (2*a_q)].each do |x2| # Now we need `y` y = m * x2 + k candidates << Coordinate.xyz(x2, y, z) end end end end # Return if we haven't found any valid points return [] if candidates.empty? # At this point, we have either 2 or 4 candidate points that are swath # edge intersections with the target latitude. Now we need to find # the two that are closest to the coordinate the caller passed. We # want them in west-to-east order to make things simpler for the caller. # Find the index of the first candidate to the east of the target candidates.sort_by!(&:theta) east_index = candidates.find_index { |c2| coord.theta < c2.theta } # Handle wrapping around the date line east_index = 0 if east_index.nil? # The west index is the one to the left of the east index, wrapping around # the date line if needed west_index = (east_index - 1) % candidates.size west_edge = candidates[west_index] east_edge = candidates[east_index] # There is a special case here. If we only found two candidates, that # indicates that the point is above one swath edge, but below the other, # which happens at latitudes near the inflection point. # # This method returns swath edges for either the ascending or descending # pass, not both. If both of our candidates are on the same edge, then # one is seen on the ascending pass and the other on the descending. We # solve this problem by moving one edge point to the inflection longitude. # # Note: the rest of this method will produce the same results regardless # of the value of "ascending." Factoring this out could slightly # improve performance. xprod = target * cross north_hemisphere = coord.phi > 0 if candidates.size == 2 inf_theta = north_hemisphere ? inf.theta + PI : inf.theta inflection = Coordinate.phi_theta(coord.phi, inf_theta) if north_hemisphere && retrograde? == ascending || !north_hemisphere && retrograde? != ascending west_edge = inflection else east_edge = inflection end end # Return the edges [west_edge, east_edge] end ##### equator_crossing # # Find the points at which the orbit passing through coord # crosses the equator on its ascending pass (if ascending # is true) or its descending pass (if ascending is false). # If corrected is true, we will correct for the rotation of # the Earth, otherwise we won't. def equator_crossing(coord, ascending, corrected=true) # [This page](http://mathworld.wolfram.com/SphericalTrigonometry.html) # has a good diagram and a summary of the math we'll need to use. # # [This image](http://geospatialmethods.org/bosa/triangles.gif) # is also helpful. (`Lat_p`, `Lon_p`) is what we call `C`. # `(0, Lon_p)` is what we call `B`. `(0, Lon_n)` is # what we call `A`. # # In order to figure out the crossing point, we need to # set up a spherical triangle formed by: # # point `C` - the given coordinate # point `B` - the point at (0, coord.theta) # point `A` - the (unknown) point where the orbit crosses the equator # # To remain consistent with the Wolfram and similar # references, we'll use A, B, and C notation. "`A`" will # denote the angle at point `A`. "`a`" will denote the arc-length # of the side across from point `A`. Our capital variable names will # use underscores to remain valid in Ruby, e.g. "_A_" # # We know two angles: # Because side `A` is on a latitude line and side `c` is on # the equator _B_ = PI / 2 # `A` is an angle between the orbit and the equator, which # is the inclination if it's a retrograde orbit in the # descending pass or a prograde orbit in the ascending # pass. Otherwise it's the complement of the inclination if retrograde? != ascending _A_ = inclination_rad else _A_ = PI - inclination_rad end # We also know one side's arc length: a = coord.phi # Coord could lie above or below the orbit. We find the nearest # inflection point in that case. a = max_orbit_phi if a > max_orbit_phi a = min_orbit_phi if a < min_orbit_phi # We need to find: # # 1. `c`, which we can add to coord's longitude to find # the crossing longitude # 2. `b`, which is the arc length traveled since crossing the # equator. We can use this to calculate the amount # the Earth has rotated since the satellite crossed # the equator and correct accordingly. # Since we know `A`, `a`, and `B`, we can use the law of sines # to calculate `b` # # `sin(A) / sin(a) = sin(B) / sin(b) = sin(\C) / sin(c)` sin_b = sin(_B_) * sin(a) / sin(_A_) b = asin(sin_b) # Finding `c` is trickier because we don't know `C`. We use [Napier's # first analogy](http://mathworld.wolfram.com/NapiersAnalogies.html): # # `sin((A - B)/2) / sin((A + B)/2) = tan((a - b)/2) / tan(c/2)` # # Rearranging: # # `tan(c/2) = (tan((a - b)/2) * sin((A + B)/2)) / sin((A - B)/2)` # # Since `sin((A - B)/2)` could be 0, we'll need to use atan2 and # keep the numerator and denominator separate numerator = tan((a - b) / 2) * sin(( _A_ + _B_ ) / 2) denominator = sin((_A_ - _B_) / 2) c = 2 * atan2(numerator, denominator) # We now know where the orbit crosses crossing_theta = coord.theta + c # For the descending pass, we ended up calculating the point half # way around the globe, so we need to correct crossing_theta -= PI unless ascending # Correct for the rotation of the Earth, if necessary if corrected # Recall, `b` is the angle of the orbit travelled since # crossing the equator on the ascending pass (in radians). # We can use this to calculate the angular distance covered # by the orbit on the requested pass. if ascending distance_rad = b else distance_rad = PI - b end # If the distance is below the starting latitude, the orbit will # need to make an additional pass before reaching the target point, # so we add `2pi` to the distance. distance_rad += 2 * PI while distance_rad < start_clat_rad distance_rad -= 2 * PI while distance_rad > start_clat_rad + 2 * PI # `"time" = "distance" / "rate"` # # We know distance from above and rate is given by the orbit parameters, # so we can calculate the time since crossing the equator. time_since_crossing_s = distance_rad / angular_velocity_rad_s # Now we want to know how far the Earth has rotated since we crossed # the equator. We know the Earth's rotation rate and the elapsed time earth_rotation_rad = EARTH_ANGULAR_VELOCITY_RAD_S * time_since_crossing_s # Since we're working with a unit sphere, we can make the # correction directly crossing_theta += earth_rotation_rad end # Return the coordinate Coordinate.phi_theta(0, crossing_theta) end end end
true
d462dd7e03ade2fed7883faac6f6982309a86744
Ruby
pjwl33/code_snippets
/missing_methods.rb
UTF-8
1,665
3.296875
3
[]
no_license
require 'delegate' #automatically delegate all method calls to local object unless delcared locally class School < SimpleDelegator DELEGATED_METHODS = [:username, :avatar] def initialize user super user end def method_missing method_name, *args if DELEGATED_METHODS.include?(method_name) #to check if the delegated and included methods have this name @user.send method_name, *args else super #default handling for all other methods end end end class Country def initialize name @nmae = name end def to_s @name end def method_missing method_name, *args # + in regex means one or more times, * is zero or more times, {n, } n or more times, {, m} m or less times, {n, m} at least n, less than m match = method_name.to_s.match(/^hash_(\w+)/) if match @name << "##{match[1]}" else super end end def respond_to? method_name # this operator will return 0 or nil if it works or not, for example: used with assigning varialbes with regex: /(?<a>\w+)\s*@\s*(?<b>\w+)/ =~ "hello@world", a = "hello", b ="world" method_name =~ /^hash_\w+/ || super end end america = Country.new("Amurrrica") america.respond_to?(:to_s) #==> true class Library SYSTEMS = ['arcade', 'atari', 'pc'] attr_accessor :games def method_missing(name, *args) system = name.to_s if SYSTEMS.include?(system) self.class.class_eval do defined_method system do find_by_system(system) end end send system else super end end private def find_by_system(system) games.select { |game| game.system == system } end end
true
c3bb2d4ef9db26b1e969c329e0fcc04d201d8da4
Ruby
zold-io/zold
/lib/zold/commands/routines/reconcile.rb
UTF-8
2,496
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true # Copyright (c) 2018 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'shellwords' require_relative '../routines' require_relative '../../log' require_relative '../../id' require_relative '../../copies' require_relative '../pull' # R # Author:: Yegor Bugayenko ([email protected]) # Copyright:: Copyright (c) 2018 Yegor Bugayenko # License:: MIT class Zold::Routines::Reconcile def initialize(opts, wallets, remotes, copies, address, log: Log::NULL) @opts = opts @wallets = wallets @remotes = remotes @copies = copies @address = address @log = log end def exec(_ = 0) sleep(20 * 60) unless @opts['routine-immediately'] @remotes.iterate(@log) do |r| next unless r.master? next if r.to_mnemo == @address res = r.http('/wallets').get r.assert_code(200, res) missing = res.body.strip.split("\n").compact .select { |i| /^[a-f0-9]{16}$/.match?(i) } .reject { |i| @wallets.acq(Zold::Id.new(i), &:exists?) } missing.each { |i| pull(i) } if missing.empty? log.info("Nothing to reconcile with #{r}, we are good at #{@address}") else @log.info("Reconcile routine pulled #{missing.count} wallets from #{r}") end end end private def pull(id) Zold::Pull.new(wallets: @wallets, remotes: @remotes, copies: @copies, log: @log).run( ['pull', "--network=#{Shellwords.escape(@opts['network'])}", id.to_s, '--quiet-if-absent'] ) end end
true
1d151b78e624921aa46da52a459fc39279e3abbf
Ruby
joshualat/study
/lib/study/tree_node.rb
UTF-8
6,659
2.921875
3
[ "MIT" ]
permissive
module Study class TreeNode attr_accessor :type, :value def initialize(type:, value:) @type = type @value = value end def ==(other) @type == other.type && @value == other.value end def highlight(left: nil, right: nil, nested: false, plain: false) colored_left = left.is_a?(Integer) ? TextHighlight.violet(left, plain: plain) : TextHighlight.cyan(left, plain: plain) if nested [ colored_left, TextHighlight.green(":", plain: plain), " ", TextHighlight.yellow(right, plain: plain) ].join("") else [ colored_left, TextHighlight.green(":", plain: plain), " ", TextHighlight.white(right, plain: plain) ].join("") end end def draw(indent: 0, tree_key: nil, branch_toggle: [], max_depth: 10, plain: false) return if indent > max_depth if indent == 0 if has_children? draw_line(indent: 0, text: TextHighlight.yellow(@type, plain: plain), branch_toggle: branch_toggle, root: true, max_depth: max_depth,) else draw_line(indent: 0, text: [TextHighlight.yellow(@type, plain: plain), TextHighlight.white(@value, plain: plain)].join(" "), branch_toggle: branch_toggle, root: true, max_depth: max_depth) return end end if has_children? if tree_key draw_line(indent: indent, text: highlight(left: tree_key, right: @type, nested: true, plain: plain), branch_toggle: branch_toggle, no_children: false, max_depth: max_depth, plain: plain) end each_child_with_last do |key, value, last| if value.is_a?(TreeNode) value.draw(indent: indent + 1, tree_key: key, branch_toggle: branch_toggle + [last], max_depth: max_depth, plain: plain) else draw_line(indent: indent + 1, text: highlight(left: key, right: value, plain: plain), branch_toggle: branch_toggle + [last], max_depth: max_depth, plain: plain) end end else draw_line(indent: indent, text: highlight(left: tree_key, right: @value, plain: plain), branch_toggle: branch_toggle, max_depth: max_depth, plain: plain) end nil end def each_child_with_last(&block) total_size = @value.size sorted_keys = @value.keys.sort sorted_number_keys = sorted_keys.select { |key| key.is_a?(Numeric) }.sort sorted_symbol_keys = sorted_keys.select { |key| key.is_a?(Symbol) }.sort sorted_string_keys = sorted_keys.select { |key| key.is_a?(String) }.sort remaining_keys = sorted_keys - sorted_number_keys - sorted_symbol_keys - sorted_string_keys remaining_keys = remaining_keys.sort rescue remaining_keys sorted_keys = sorted_number_keys + sorted_symbol_keys + sorted_string_keys + remaining_keys sorted_keys.each_with_index do |key, index| value = @value[key] block.call(key, value, total_size - 1 == index) end end def draw_line(indent: 0, text:, branch_toggle:, root: false, no_children: true, max_depth: 10, plain: false) if root puts text else previous, current = branch_toggle[0..-2], branch_toggle[-1] indent_lines = previous.map { |item| item ? " " : " │" }.join("") current_branch_line = current ? " └── " : " ├── " branch_lines = TextHighlight.green([indent_lines, current_branch_line].join(""), plain: plain) puts [branch_lines, text.force_encoding('UTF-8')].join("") if current && (no_children || (indent >= max_depth)) puts TextHighlight.green([indent_lines].join(""), plain: plain) end end end def has_children? ["Hash", "Array"].include?(@value.class.name) && @value.size > 0 end def self.convert(target, registered_objects: []) if registered_objects.include?(target.object_id) return TreeNode.new(type: target.class.name, value: "DUPLICATE #{ target.class.name }") else if target.is_a?(Array) || target.is_a?(Hash) || target.instance_variables.size > 0 registered_objects << target.object_id end end output = { type: nil, value: nil } target_class_name = target.class.name if target.is_a?(Hash) output_container = {} target.each do |hash_key, hash_value| output_container[hash_key] = convert(hash_value, registered_objects: registered_objects) end output[:value] = output_container elsif target.is_a?(Array) output_container = {} target.each_with_index do |array_value, index| output_container[index] = convert(array_value, registered_objects: registered_objects) end output[:value] = output_container elsif target.instance_variables.size > 0 output_container = {} target.instance_variables.each do |name| value = target.instance_variable_get(name) key = name.to_s.gsub('@', '').to_sym # use getter method instead if target.public_methods(false).include?(key.to_sym) begin output_container[key] = convert(target.send(key.to_sym), registered_objects: registered_objects) rescue output_container[key] = convert(value, registered_objects: registered_objects) end else output_container[key] = convert(value, registered_objects: registered_objects) end end output[:value] = output_container elsif target_class_name == "NilClass" output[:value] = "nil" elsif target_class_name == "IO" output[:value] = "<IO>" elsif target_class_name == "Thread::Mutex" output[:value] = "<Thread::Mutex>" elsif target_class_name == "Proc" output[:value] = "<Proc>" else output[:value] = target end output[:type] = target_class_name TreeNode.new(type: output[:type], value: output[:value]) end end end
true
3bc010f30306d647cc1075fbe02317e9662d2401
Ruby
johnquiwa/nyu
/qualtronics_format.rb
UTF-8
432
3
3
[]
no_license
def EditArray(array) i = 0 num = 1 while i < array.length if i == 0 array[i] = "[[Block]]" + "\n #{num}. " + array[i] + "\n\n" + "[[Block]]" puts array[i] elsif i == array.length - 1 array[i] = "#{num}. " + array[i] puts array[i] else array[i] = "#{num}. " + array[i] + "\n\n" + "[[Block]]" puts array[i] end i += 1 num += 1 end file = File.new("data.txt", "w") file.puts(array) file.close end EditArray(array)
true
c536092a37aaecd4eeb03e850b26cc1a8173b154
Ruby
abeger/advent-of-code-2019
/spec/functional/13/arcade_game_spec.rb
UTF-8
485
2.625
3
[]
no_license
# frozen_string_literal: true RSpec.describe ArcadeGame::Game do context 'puzzles' do let(:program_text) { File.read('13/input.txt') } it 'solves part 1' do game = described_class.new(program_text) game.run expect(game.screen.num_tiles(ArcadeGame::Screen::TILE_BLOCK)).to eq(236) end it 'solves part 2', :slow do game = ArcadeGame::Game.new(program_text, true, false) game.run expect(game.score).to eq(11_040) end end end
true
ed64aa827de5da840653964beb69c830ff854f77
Ruby
jcmorrow/wishing-well
/app/jobs/simulate_game.rb
UTF-8
1,061
2.8125
3
[]
no_license
class SimulateGame < ActiveJob::Base def perform(match:) @game = Game.create(match: match) @players ||= @game.match.strategies.map do |strategy| game_strategy = GameStrategy.create(game: game, strategy: strategy) Player.new(game_strategy) end run end private attr_accessor :game, :players def run turn_count = 0 until finished? turn_count += 1 players.each(&:take_turn) record_player_turns(turn_count) end finish_game end def record_player_turns(turn_number) players.each do |player| player.game_strategy.turns.build( points_gained: player.total_points, money_gained: player.total_money, number: turn_number, ) end end def finished? players.any? { |player| player.total_points >= 30 } end def finish_game game.update(winner: winning_strategy, finished_at: Time.current) players.each { |p| p.game_strategy.save } end def winning_strategy game.winner = players.max_by(&:total_points).game_strategy end end
true
3f90dc46be8f5d04610ec11752453287bc897559
Ruby
TomHoenderdos/stickler
/lib/stickler/spec_lite.rb
UTF-8
2,329
3.078125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "rubygems/platform" require "rubygems/version" module Stickler # # A lightweight version of a gemspec that only responds to name, version, # platform and full_name. Many of the items in the rubygems world # deal with the triplet [ name, verison, platform ] and this class # encapsulates that. # class SpecLite include Comparable attr_reader :name attr_reader :version attr_reader :platform attr_reader :platform_string def initialize(name, version, platform = Gem::Platform::RUBY) @name = name @version = Gem::Version.new(version) @platform_string = platform.to_s @platform = Gem::Platform.new(platform) end def full_name "#{name}-#{version_platform}" end alias to_s full_name def file_name full_name + ".gem" end def spec_file_name full_name + ".gemspec" end def name_version "#{name}-#{version}" end def version_platform if (platform == Gem::Platform::RUBY) || platform.nil? version.to_s else "#{version}-#{platform_string}" end end def prerelease? version.prerelease? end def to_a [name, version.to_s, platform_string] end # # Convert to the array format used by rubygems itself # def to_rubygems_a [name, version, platform_string] end # # Lets be comparable! # def <=>(other) return 0 if other.object_id == object_id other = coerce(other) %i[name version platform_string].each do |method| us = send(method) them = other.send(method) result = us.<=>(them) return result unless result == 0 end 0 end # # See if another Spec is the same as this spec # def =~(other) other = coerce(other) (other && (name == other.name) && (version.to_s == other.version.to_s) && (platform_string == other.platform_string)) end private def coerce(other) if self.class === other other elsif other.respond_to?(:name) && other.respond_to?(:version) && other.respond_to?(:platform_string) SpecLite.new(other.name, other.version, other.platform_string) else false end end end end
true
9c4545ac75cee25e47f24955d0169e33ea244137
Ruby
arnabsen1729/cef-projects
/Level-2/DNSResolver/lookup.rb
UTF-8
1,660
3.578125
4
[]
no_license
def get_command_line_argument # ARGV is an array that Ruby defines for us, # which contains all the arguments we passed to it # when invoking the script from the command line. # https://docs.ruby-lang.org/en/2.4.0/ARGF.html if ARGV.empty? puts "Usage: ruby lookup.rb <domain>" exit end ARGV.first end # `domain` contains the domain name we have to look up. domain = get_command_line_argument # File.readlines reads a file and returns an # array of string, where each element is a line # https://www.rubydoc.info/stdlib/core/IO:readlines dns_raw = File.readlines("zone") def parse_dns(dns_raw) records = {} dns_raw. reject { |line| line.empty? }. map { |line| line.strip.split(", ") }. reject { |record| record.length < 3 }. each { |record| records[record[1].to_sym] = { :type => record[0], :destination => record[2] } } return records end def resolve(dns_records, lookup_chain, domain) if dns_records[domain.to_sym] == nil lookup_chain.push("Domain #{domain} doesn't exist in records") else record = dns_records[domain.to_sym] if record[:type] == "A" lookup_chain.push(record[:destination]) elsif record[:type] == "CNAME" resolve(dns_records, lookup_chain, record[:destination]) else lookup_chain.push("Record Type invalid") end end end # To complete the assignment, implement `parse_dns` and `resolve`. # Remember to implement them above this line since in Ruby # you can invoke a function only after it is defined. dns_records = parse_dns(dns_raw) lookup_chain = [domain] lookup_chain = resolve(dns_records, lookup_chain, domain) puts lookup_chain.join(" => ")
true
0200059a6213ead659dd58c13799345f9e4ce052
Ruby
NeelAiyar/OOP-1
/save/OOP/ex05/main.rb
UTF-8
131
2.625
3
[]
no_license
require_relative "first.class" require_relative "second.class" Test = SecondClass.new("neelaiyar") puts "Your hobby is " + ##Test
true
bf5b69d3bde97569684296e53383a5a1a0035e74
Ruby
SwetaYamini/interpolation-super-power-ruby-intro-000
/lib/display_rainbow.rb
UTF-8
190
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your #display_rainbow method here def display_rainbow(colors) sep = "" for i in 0..6 print sep print "#{(colors[i])[0].upcase}: #{colors[i]}" sep = ", " end print "\n" end
true
87561dbc42fd35e459e17230cd45d22b5bf53ea8
Ruby
kellyarwine/t3
/spec/minimax_strategy_spec.rb
UTF-8
3,797
2.90625
3
[]
no_license
require 'spec_helper' describe T3::Player::MinimaxStrategy do let(:gamepiece) { "x" } let(:board) { T3::Board.new(3) } let(:game_rules) { T3::GameRules.new(board) } let(:subject) { T3::Player::MinimaxStrategy.new(gamepiece,game_rules) } it 'has a piece' do T3::Player::MinimaxStrategy.new("x",game_rules).piece.should == gamepiece end it "initializes game rules" do subject.game_rules.should be_kind_of(T3::GameRules) end it "should not be human" do subject.human?.should == false end it "gets the best move available from a board with 2 available spaces" do board.spaces = ["o","x","o","o","x","o","7","8","x"] # board.spaces = ["o","x","o", # "o","x","o", # "7","8","o"] subject.move(board,["x","o"]).should == 8 end it "gets the best move available from a board with 3 available spaces" do board.spaces = ["1","o","x","x","o","x","7","8","o"] # board.spaces = ["1","o","x", # "x","o","x", # "7","8","o"] subject.move(board,["x","o"]).should == 1 end it "gets the best move available from a board with 3 available spaces" do board.spaces = ["x","o","x","o","x","o","7","8","9"] # board.spaces = ["x","o","x", # "x","o","x", # "7","8","9"] subject.move(board,["x","o"]).should == 7 end it "gets the best move available from a board with 4 available spaces" do board.spaces = ["x","x","o","x","o","6","7","8","9"] # board.spaces = ["x","x","o", # "x","o","6", # "7","8","9"] subject.move(board,["x","o"]).should == 7 end it "gets the best move available from a board with 5 available spaces" do board.spaces = ["x","o","o","x","5","6","o","8","9"] # board.spaces = ["x","o","o", # "x","5","6", # "o","8","9"] subject.move(board,["x","o"]).should == 5 end it "gets the best move available from a board with 6 available spaces" do board.spaces = ["x","o","3","x","5","6","7","8","9"] # board.spaces = ["x","o","3", # "x","5","6", # "7","8","9"] subject.move(board,["x","o"]).should == 7 end it "gets the best move available from a board with 5 available spaces" do board.spaces = ["x","o","3","o","x","6","7","8","9"] # board.spaces = ["x","o","3", # "o","x","6", # "7","8","9"] subject.move(board,["x","o"]).should == 9 end it "gets the best move available from a board with 6 available spaces" do board.spaces = ["x","o","3","4","o","6","7","8","9"] # board.spaces = ["x","o","3", # "4","o","6", # "7","8","9"] subject.move(board,["x","o"]).should == 8 end it "gets the best move available from a board with 6 available spaces" do board.spaces = ["x","o","3","4","x","6","7","8","9"] # board.spaces = ["x","o","3", # "4","x","6", # "7","8","9"] subject.move(board,["x","o"]).should == 9 end it "gets the best move available from a board with 8 available spaces" do board.spaces = ["o","2","3","4","5","6","7","8","9"] # board.spaces = ["o","2","3", # "4","5","6", # "7","8","9"] subject.move(board,["x","o"]).should == 5 end it "gets the best move available from a board with 9 available spaces" do board.spaces = ["1","2","3","4","5","6","7","8","9"] # board.spaces = ["1","2","3", # "4","5","6", # "7","8","9"] subject.move(board,["x","o"]).should == 1 end end
true
7c519d8be91e3da0223432474f8ac50fda0f21f9
Ruby
avimoondra/mdapps
/parser.rb
UTF-8
3,111
2.96875
3
[]
no_license
require 'rubygems' require 'nokogiri' class Profile def initialize(index) @page = Nokogiri::HTML(open("profiles/#{index}.html")) @userMetadata = @page.css(".viewprofileheader div:contains('Application Cycles')").text.gsub!(/\t/,' ') @uGradQualitativeMetadata = @page.css('div.subpagecontent p')[0].text.gsub!(/\t/,' ') @uGradQuantitativeMetadata = @page.css('div.subpagecontent p')[1].text.gsub!(/\t/,' ') @profile = self.set_profile() end def show puts @profile end def set_profile profile = {} keys = [:username, :id, :applicationCycle, :demographics, :homeState, :uGradCollege, :uGradAreaOfStudy, :mcat, :overallGPA, :scienceGPA, :briefProfile, :amcasSubmitted, :schools] for key in keys profile[key] = cleaner(key) end return profile end def cleaner(method) self.send(method) rescue => e return nil end def username username = @page.css('.viewprofileheader h1').text end def id id = @page.css('.viewprofileheader div')[0].text[5..-2] end def applicationCycle applicationCycle = /Application\sCycles:\s(?<date>.+)\n/.match(@userMetadata)['date'].strip end def demographics demographics = /Demographics:(?<demo>\s(\w+,?\s){1,})/.match(@userMetadata)['demo'].strip end def homeState # split this into gender, age, and race homeState = /Home State: (?<state>(\w+\s)+)/.match(@userMetadata)['state'].strip end def uGradCollege uGradCollege = /Undergraduate College: (.+)\n\s/.match(@uGradQualitativeMetadata)[1].strip end def uGradAreaOfStudy uGradAreaOfStudy = /Undergraduate Area of Study: (.+)\n\s/.match(@uGradQualitativeMetadata)[1].strip end def mcat mcat = /MCAT: (.+)\n/.match(@uGradQuantitativeMetadata)[1] end def overallGPA overallGPA = /Overall GPA: (.+)\n/.match(@uGradQuantitativeMetadata)[1] end def scienceGPA scienceGPA = /Science GPA: (.+)\n/.match(@uGradQuantitativeMetadata)[1] end def briefProfile briefProfile = @page.css('div.subpagecontent p')[2].text.gsub!(/\t/,' ')[20..-1].strip end def amcasSubmitted amcasSubmitted = /AMCAS submitted: (?<date>.+)/.match(@page.css('div.subpagecontent p')[3].text.gsub!(/\t/,' ').strip)['date'].strip end def schools schools = [] for el in @page.css('div.subpagecontent a.arrow') school = {} school['name'] = el.text schoolId = el['id'][4..-1] schoolContent = @page.css('div#appspec_' + schoolId) school["Combined Phd/MSTP"] = /Combined PhD\/MSTP: (No|Yes)/.match(schoolContent.text)[1] for listel in schoolContent.css('li') key, value = listel.text.split(": ") school[key] = value end schools.push(school) end return schools end end for index in (0..1000).to_a p = Profile.new(index) puts p.show end
true
32e486ad2db573a2fe9de9f541024413717f1b7d
Ruby
Hack-Slash/sunday_afternoon
/fibon_recursive.rb
UTF-8
171
3.34375
3
[]
no_license
def fib_recursive(number) if number == 0 || number == 1 return number end return fib_recursive(number - 1) + fib_recursive(number - 2) end p fib_recursive(20)
true
bbefafeea29c49b4c5f7b5dd203799ab6eee844c
Ruby
ronakjain90/runeblog
/bin/blog
UTF-8
1,696
2.515625
3
[]
no_license
#!/usr/bin/env ruby # $LOAD_PATH << "./lib" require 'runeblog' require 'rubytext' require 'repl' include RuneBlog::REPL def get_started puts puts fx(<<-TEXT, :bold) Blog successfully created. You can create views with the command: new view Create a post within the current view: new post You can't publish until you set up the publish file via the config command. TEXT end def mainloop print fx("blog> ", Red, :bold) cmd = STDSCR.gets(history: @cmdhist, tab: @tabcom) cmd_quit(nil) if cmd.nil? # ^D cmd.chomp! return if cmd.empty? # CR does nothing meth, params = RuneBlog::REPL.choose_method(cmd) ret, str = send(meth, params) rescue => err puts err end ### major, minor = RUBY_VERSION.split(".").values_at(0,1) ver = major.to_i*10 + minor.to_i abort "Need Ruby 2.4 or greater" unless ver >= 24 include RuneBlog::Helpers # for try_read_config # read a .rubytext file here?? Call it something else? home = ENV['HOME'] @fg, @bg = try_read_config("#{home}/.rubytext", fg: Blue, bg: White) @fg = @fg.downcase.to_sym @bg = @bg.downcase.to_sym RubyText.start(:_echo, :keypad, scroll: true, log: "binblog.txt", fg: @fg, bg: @bg) if ! RuneBlog.exist? print fx("\n No blog found. Create new one? (y/n) ", :bold) resp = gets.chomp if resp.downcase == "y" RuneBlog.create_new_blog get_started else exit end end @blog = RuneBlog.new puts fx("\n RuneBlog", :bold), fx(" v #{RuneBlog::VERSION}\n", Red) @cmdhist = [] @tabcom = RuneBlog::REPL::Patterns.keys.uniq - RuneBlog::REPL::Abbr.keys @tabcom.map! {|x| x.sub(/ [\$\>].*/, "") + " " } @tabcom.sort! loop { mainloop } # sleep 0.2 # system("tput clear") puts
true
8cf95065997a811d8ee365bce904a9beed0c1a26
Ruby
copiousfreetime/launchy
/lib/launchy/cli.rb
UTF-8
2,265
2.734375
3
[ "ISC" ]
permissive
require 'optparse' module Launchy class Cli attr_reader :options def initialize @options = {} end def parser @parser ||= OptionParser.new do |op| op.banner = "Usage: launchy [options] thing-to-launch" op.separator "" op.separator "Launch Options:" op.on( "-a", "--application APPLICATION", "Explicitly specify the application class to use in the launch") do |app| @options[:application] = app end op.on( "-d", "--debug", "Force debug. Output lots of information.") do |d| @options[:debug] = true end op.on( "-e", "--engine RUBY_ENGINE", "Force launchy to behave as if it was on a particular ruby engine.") do |e| @options[:ruby_engine] = e end op.on( "-n", "--dry-run", "Don't launchy, print the command to be executed on stdout" ) do |x| @options[:dry_run] = true end op.on( "-o", "--host-os HOST_OS", "Force launchy to behave as if it was on a particular host os.") do |os| @options[:host_os] = os end op.separator "" op.separator "Standard Options:" op.on( "-h", "--help", "Print this message.") do |h| $stdout.puts op.to_s exit 0 end op.on( "-v", "--version", "Output the version of Launchy") do |v| $stdout.puts "Launchy version #{Launchy::VERSION}" exit 0 end end end def parse( argv, env ) parser.parse!( argv ) return true rescue ::OptionParser::ParseError => pe error_output( pe ) end def good_run( argv, env ) if parse( argv, env ) then Launchy.open( argv.shift, options ) { |e| error_output( e ) } return true else return false end end def error_output( error ) $stderr.puts "ERROR: #{error}" Launchy.log "ERROR: #{error}" error.backtrace.each do |bt| Launchy.log bt end $stderr.puts "Try `#{parser.program_name} --help' for more information." return false end def run( argv = ARGV, env = ENV ) exit 1 unless good_run( argv, env ) end end end
true
9599552eebd2ab0a0c4995f98097c696c9d0fb0b
Ruby
ged/mues
/lib/mues/client.rb
UTF-8
1,605
2.671875
3
[]
no_license
#!/usr/bin/env ruby require 'bunny' require 'mues' require 'mues/mixins' require 'mues/constants' # A reference implementation of a MUES client. class MUES::Client include MUES::Loggable, MUES::Constants ### Create a new client that will connect to the given +host+ using the specified ### +playername+ and +password+. def initialize( host, playername, password, vhost=DEFAULT_PLAYERS_VHOST ) @host = host @playername = playername @password = password @vhost = vhost @output = nil @input = nil @client = Bunny.new( :host => host, :vhost => vhost, :user => playername, :pass => password ) end ###### public ###### ### Connect to the server's player event bus. def connect @client.start # Set up our input and output exchange/queue @output = @client.exchange( @playername, :passive => false ) @queue = @client.queue @exchange = @client.exchange( @playername, :passive => false ) @queue = @client.queue( "#{@playername}_output", :exclusive => true ) login_exchange = @client.exchange( 'login', :type => :direct, :auto_delete => true ) # Set up the queue to handle incoming connections self.log.debug " setting up the connections queue..." @connect_queue = @playersbus.queue( 'connections', :exclusive => true ) @connect_queue.bind( @login_exch, :key => :character_name ) @connect_queue.subscribe( :header => true, :consumer_tag => 'engine', :exclusive => true, :no_ack => false, &self.method(:handle_connect_event) ) end end # class MUES::Client
true
fb4459a3120d1481c46c6a0b0dcaf0355700734f
Ruby
gkolan/CodeEval_Challenges
/sum_of_digits.rb
UTF-8
337
3.515625
4
[]
no_license
#Challenge Link - https://www.codeeval.com/open_challenges/21/ #Score - 100 def sum_of_digits value return [] if value.empty? split_number = value.scan(/./).map {|x| x.to_i} digits_sum = split_number.inject {|sum, el| sum + el} return digits_sum end File.open(ARGV[0]).each_line do |line| puts sum_of_digits(line) end
true