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
040fd428221834255ec4b60ce9e44db8ca00cbb2
Ruby
NcUltimate/BasicAlgos
/ruby/sorting_algos.rb
UTF-8
4,417
3.53125
4
[]
no_license
class Algorithms class Sorting class << self ############################ # RUBY SORT # The system O(nlogn) sort. def ruby_sort(ary) ary.sort end ############################ # BUBBLE SORT # Your textbook O(n^2) sort. def bubble_sort(ary) return ary if sorted?(ary) (1...ary.size).each do |j| (0...ary.size-j).each do |k| next if (ary[k] <=> ary[k+1]) < 1 swap(ary, k, k+1) end end ary end ############################ # INSERTION SORT # An intuitive O(n^2) sort. def insertion_sort(ary) return ary if sorted?(ary) (1...ary.size).each do |j| j.downto(1) do |k| break if (ary[k] <=> ary[k-1]) > -1 swap(ary, k, k-1) end end ary end ############################ # SELECTION SORT # Find n minimums for an O(n^2) sort. def selection_sort(ary) return ary if sorted?(ary) ary.size.times do |j| min, m = ary[j], j (j...ary.size).each do |k| if (ary[k] <=> min) == -1 min, m = ary[k], k end end swap(ary, j, m) end ary end ############################ # MERGE SORT # A fast, stable O(nlogn) sort. def merge_sort(ary, s=0, e=ary.size-1) return [ary[s]] if e <= s m = (s+e)/2 + 1 m1 = merge_sort(ary, s, m-1) m2 = merge_sort(ary, m, e) merge(m1, m2) end ############################ # HEAP SORT # A fast O(nlogn) sort. def heap_sort(ary) # TODO: implement heapsort ary.sort end ############################ # QUICK SORT # A fast, in-place O(nlogn) sort. # Redundant shuffle kills possibility of O(n^2). def quick_sort(ary, s=0, e=ary.size-1, d=0) return ary[s] if e == s piv = s s.upto(e) do |idx| if (ary[idx] <=> ary[e]) == -1 swap(ary, piv, idx) unless idx == piv piv += 1 end end swap(ary, piv, e) quick_sort(ary, s, piv - 1, 1) if piv > s quick_sort(ary, piv + 1, e, 1) if piv < e ary end ############################ # BUCKET SORT # An O(nlog(n/k)) sort, yay. def bucket_sort(ary, sort_algo = :merge_sort, num_buckets = 20) bucket_size = [ary.size / num_buckets, 5].max # I use merge_sort by default for sorting the buckets. buckets = ary.each_slice(bucket_size).map { |bucket| send(sort_algo, bucket) } # TODO: We need a Priority Queue for the k-way merge step. # I'm brute forcing it with a system sort & flatten for now. indices = (0..buckets.size-1).to_a indices.sort { |a,b| buckets[a][0] <=> buckets[b][0]} indices.map { |idx| buckets[idx] }.flatten end def swap(ary, a, b) ary[a], ary[b] = ary[b], ary[a] end def merge(m1, m2) merged, k, j = [], 0, 0 until j == m1.size || k == m2.size if (m1[j] <=> m2[k]) < 1 merged << m1[j] j += 1 end if (m2[k] <=> m1[j]) == -1 merged << m2[k] k += 1 end end merged << m1[j] and j += 1 until j == m1.size merged << m2[k] and k += 1 until k == m2.size merged end def sorted?(ary) asc = 0.upto(ary.size - 2).all? do |k| (ary[k] <=> ary[k + 1]) < 1 end return true if asc 0.upto(ary.size - 2).all? do |k| (ary[k] <=> ary[k + 1]) > -1 end end end end end def main array = (1..100).to_a.sample(20).shuffle puts "#{array}" puts "----------------------" algos = %i[ruby_sort quick_sort bubble_sort selection_sort insertion_sort merge_sort] algos.each do |algo| res = Algorithms::Sorting.send(algo, array.dup) puts "#{res} --> #{algo}" end puts puts "Benchmarking..." puts require 'benchmark' array = (1..50_000_000).to_a Benchmark.bm do |x| algos.each do |algo| x.report("#{algo}".ljust(20)) do Algorithms::Sorting.send(algo, array.dup) end end end end #main
true
e17db55856ddba42629553a2f31547e7d737259c
Ruby
yasslab/ruby-metaprogramming-tokyo
/quizzes/2.dynamic_methods/data_source.rb
UTF-8
733
3.3125
3
[]
no_license
# This is just the test for the Computer class. Don't modify this file! # Imagine that this is a class in a library that you cannot change. # Read the exercise instructions in computer.rb. class DS def initialize # connect to data source... end def get_cpu_info(workstation_id) "2.9 Ghz quad-core" end def get_cpu_price(workstation_id) 120 end def get_mouse_info(workstation_id) "Wireless Touch" end def get_mouse_price(workstation_id) 60 end def get_keyboard_info(workstation_id) "Standard US" end def get_keyboard_price(workstation_id) 20 end def get_display_info(workstation_id) "LED 1980x1024" end def get_display_price(workstation_id) 150 end end
true
1e9de08140e15e946192a91cd23b60b66ca2bd0b
Ruby
Day-101/scrap_crazy
/lib/03_cherdepute.rb
UTF-8
884
2.796875
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' a = [] def profile(url) begin page = Nokogiri::HTML(URI.open(url)) identity = {first_name: page.xpath("/html/body/div/div[3]/div/div/div/section[1]/div/article/div[2]/h1").text.split[1], last_name: page.xpath("/html/body/div/div[3]/div/div/div/section[1]/div/article/div[2]/h1").text.split[2..].join(" "), email: page.xpath("/html/body/div/div[3]/div/div/div/section[1]/div/article/div[3]/div/dl/dd[4]/ul/li[2]/a").text} return identity rescue RuntimeError return {error: "Data not found"} end end page = Nokogiri::HTML(URI.open("https://www2.assemblee-nationale.fr/deputes/liste/alphabetique")) liens = page.css("#deputes-list").css("a") liens.each_with_index do |lien, position| a << profile("https://www2.assemblee-nationale.fr#{(liens[position]["href"])}") end File.write("deputes.txt", a.join("\n")) puts a
true
af106cef1d4655346918733603c905a12069e2b2
Ruby
xtone/programming-contest
/20140602_MinesweeperMaster/take/main.rb
UTF-8
2,572
3.375
3
[]
no_license
require 'pp' casecount = 0 cases = [] open( ARGV[0] ) {|f| casecount = f.gets.to_i casecount.times { cases.push(f.gets.split(' ').map{|s| s.to_i }) } } def solve(r,c,m) cells = Array.new(r){Array.new(c){'.'}} # 地雷が無い場合はどこでもよい if m == 0 cells[0][0] = 'c' return cells end # 1つ以外地雷の場合は全て埋めてどこか一つだけクリック if m == r * c - 1 for i in 0..(r-1) for j in 0..(c-1) cells[i][j] = '*' end end cells[0][0] = 'c' return cells end # 一列の時は並べる if r == 1 if m >= c - 1 # pp 'aa0' return nil end (c-1).downto(c-1-m) do |j| cells[0][j] = '*' end cells[0][0] = 'c' return cells end if c == 1 if m >= r - 1 # pp 'aa1' return nil end (r-1).downto(r-1-m) do |j| cells[j][0] = '*' end cells[0][0] = 'c' return cells end # 一列以外の時は周りに3マス最低必要なのでそれ以外はエラー # if m >= r * c - 3 # return nil # end # 地雷のない数 s = r * c - m if r == 2 # 奇数はだめ if m % 2 == 1 || s == 2 # pp 'aa2' return nil end for i in 0..(r-1) for j in 0..( m / 2 - 1) cells[i][j] = '*' end end cells[0][c - 1] = 'c' return cells end if c == 2 # 奇数はだめ if m % 2 == 1 || s == 2 # pp 'aa4' return nil end for i in 0..(c-1) for j in 0..( m / 2 - 1) cells[j][i] = '*' end end cells[r-1][0] = 'c' return cells end # それ以外 # 一端地雷で埋めて動ける範囲を作る cells = Array.new(r){Array.new(c){'*'}} pp 'a2' # 空きの数が4, 6, 8以上必要、それ以外はだめ if s == 2 || s == 3 || s == 5 || s == 7 # pp 'aa5' return nil end for i in 0..(r-1) next if s == 3 # 一つ余ると条件を満たさない if s == 0 cells[0][0] = 'c' return cells end cells[i][0] = '.' cells[i][1] = '.' s -= 2 end for j in 2..(c-1) # 右端が1つになると開けなくなるので下に一つ残す if s == r + 1 for i in 0..(r-2) cells[i][j] = '.' end cells[0][j+1] = '.' cells[1][j+1] = '.' cells[0][0] = 'c' return cells end for i in 0..(r-1) if s == 0 cells[0][0] = 'c' return cells end cells[i][j] = '.' s -= 1 end end # pp 'aa6' return nil end i = 0 cases.each{|d| i+=1 r = d[0] c = d[1] m = d[2] puts "Case ##{i}:" cells = solve(r,c,m) if cells == nil puts "Impossible" next end cells.each {|row| puts row.join('') } }
true
1089433459aab8122ebb5de6ed8c3dd044a4a0a8
Ruby
fastlogin/funny-lol
/api-server/lib/external/riot.rb
UTF-8
3,822
2.609375
3
[]
no_license
require 'http' require 'json' require 'http_exceptions' ## # Riot API # # @author: George Ding (gd264) # @description: Ruby object to interface with and interact with the Riot API. This object was made # to abstract out API calls for ease of use. Also allows for easy modular implementation for any # part of the code that may need to make requests to the Riot API. ## class RiotApi ## # Static final variables for Riot API BASE_URL = "https://global.api.pvp.net/api/lol" BASE_URL_V2 = "https://na.api.pvp.net/api/lol/na" BASE_URL_V3 = "https://na.api.pvp.net/observer-mode/rest" # Currently only used for featured games API_KEY_EXT = "api_key=" + RIOT_KEY CURRENT_RANKED_QUEUES = ["TEAM_BUILDER_DRAFT_RANKED_5x5", "RANKED_TEAM_5x5"] CURRENT_SEASONS = ["SEASON2016"] ## # Endpoint versions, will update as Riot API updates STATIC_VERSION = "1.2" SUMMONER_VERSION = "1.4" MATCH_LIST_VERSION = "2.2" MATCH_VERSION = "2.2" # Append v to endpoint version def self.get_v(end_point) "v" + end_point end # Join all of the current ranked queues for use in url parameter def self.list_queues CURRENT_RANKED_QUEUES.join(",") end # Join all of the current seasons for use in url paramter def self.list_seasons CURRENT_SEASONS.join(",") end # (GET) featured-games-v1.0 def self.get_featured_games # Initialize url parameters and build url for request base = BASE_URL_V3 api_key = API_KEY_EXT url = "#{base}/featured/?#{api_key}" # Send request response = HTTP.get(url) begin raise Non200ResponseError.new(response.code, url) if response.code != 200 rescue Non200ResponseError => e return -1 end JSON.parse(response) end # (GET) summoner-v1.4 def self.get_summoner_by_name(summoner_name) # Initialize url parameters and build url for request base = BASE_URL_V2 version = RiotApi.get_v(SUMMONER_VERSION) api_key = API_KEY_EXT url = "#{base}/#{version}/summoner/by-name/#{summoner_name}?#{api_key}" # Send request response = HTTP.get(url) begin raise Non200ResponseError.new(response.code, url) if response.code != 200 rescue Non200ResponseError => e return -1 end JSON.parse(response) end # (GET) matchlist-v2.2 def self.get_match_list(summoner_id) # Initialize url parameters and build url for request base = BASE_URL_V2 version = RiotApi.get_v(MATCH_LIST_VERSION) id = summoner_id.to_s queues = RiotApi.list_queues seasons = RiotApi.list_seasons api_key = API_KEY_EXT url = "#{base}/#{version}/matchlist/by-summoner/#{id}?rankedQueues=#{queues}&#{seasons}&#{api_key}" # Send request response = HTTP.get(url) begin raise Non200ResponseError.new(response.code, url) if response.code != 200 rescue Non200ResponseError => e return -1 end JSON.parse(response) end # (GET) match-v2.2 def self.get_match(match_id) # Initialize url parameters and build url for request base = BASE_URL_V2 version = RiotApi.get_v(MATCH_VERSION) id = match_id.to_s api = API_KEY_EXT url = "#{base}/#{version}/match/#{id}?includeTimeline=true&#{api}" # Send request response = HTTP.get(url) begin raise Non200ResponseError.new(response.code, url) if response.code != 200 rescue Non200ResponseError => e return -1 end JSON.parse(response) end # (GET) lol-static-data-v1.2, get item with from data # @DEPRECATED def self.get_item(item_id) # Initialize url paramters and build url for request base = BASE_URL version = RiotApi.get_v(STATIC_VERSION) id = item_id.to_s api = API_KEY_EXT url = "#{base}/static-data/na/#{version}/item/#{id}?itemData=from&#{api}" # Send request response = HTTP.get(url) begin raise Non200ResponseError.new(response.code, url) if response.code != 200 rescue Non200ResponseError => e return -1 end JSON.parse(response) end end
true
29e01402760fa2db9f79098dbdb359ae453dcc81
Ruby
damaneice/-supermarket-pricing
/lib/checkout.rb
UTF-8
540
3.234375
3
[]
no_license
class Checkout def initialize rules @items = {} @rules = rules end def scan item if @items[item].nil? @items[item] = 0 end @items[item] = @items[item] + 1 end def total price = 0 @items.each_pair do | item, qty | (1..qty).each do | i | price = price + determinePrice(item, i) end end return price end private def determinePrice item, qty return @rules[item][:specialPrice] if qty % @rules[item][:quantity] == 0 @rules[item][:price] end end
true
030a8cd1ff2a7cc6726ea1944e0f6d6d43d109f2
Ruby
pturley/Setlist
/app/models/setlist_websocket_server.rb
UTF-8
1,116
2.75
3
[]
no_license
require 'eventmachine' require 'em-websocket' class SetlistWebsocketServer @@websocket_connections = [] def self.start(host, port=8080) @@pid ||= fork do EM.run { @@websocket_connections = [] EM::WebSocket.start( :host => host, :port => port ) do |socket| socket.onopen { open socket } socket.onmessage { |message| broadcast message } socket.onclose { destroy socket } end } end end def self.stop @@websocket_connections.clear `kill -9 #{@@pid}` end class << self private def open(socket) puts "New websocket connection opened" @@websocket_connections << socket puts "The current sockets are:" @@websocket_connections.each do |socket| puts socket.request["Origin"] end end def destroy(socket) puts "Websocket connection closed" @@websocket_connections.delete(socket) end def broadcast(message) @@websocket_connections.each do |socket| socket.send "#{message}" end end end end
true
84936be3850a9e38a7bbabf463eba90be47e5dd1
Ruby
Nabox68/Mardi13-projet
/exo_17.rb
UTF-8
285
3.703125
4
[]
no_license
puts "Quel est ton âge ?" age = gets.chomp age = age.to_i naissance = 0 age.times do naissance +=1 age -=1 if age < naissance || age > naissance puts "Il y #{age} ans, tu avais #{naissance} ans" else puts "Il y a #{age}ans, tu avais la moitié de l'âge que tu as aujourd'hui" end end
true
b02b3d56745b9f8dab22fcd9bb52c5fda4e78bc1
Ruby
chrisgonzgonz/student-orm
/app.rb
UTF-8
623
2.71875
3
[]
no_license
require 'sqlite3' require 'sinatra/base' require './lib/models/student.rb' # Why is it a good idea to wrap our App class in a module? module StudentSite class App < Sinatra::Base get '/' do "hello world!" end get '/students' do @students = Student.all erb :students end get '/students/:id' do @student = Student.find(params[:id]) erb :profile, :layout => false end # Student.all.each do |student| # get "/students/#{student.name.gsub(" ","")}" do # @student = student # erb :profile, :layout => false # end # end end end
true
21281dcb09ef5605d31f3669ebcb78d75262744a
Ruby
sachiko0811/React_on_Rails_Eats
/app/controllers/api/v1/line_foods_controller.rb
UTF-8
7,671
2.59375
3
[]
no_license
# --- ここから追加 --- module Api module V1 class LineFoodsController < ApplicationController before_action :set_food, only: %i[create replace] #before_actionではそのコントローラーのメインアクションに入る"前"に行う処理を挟める -> callback def index line_foods = LineFood.active # 全てのLineFoodモデルの中から、activeなものを取得し、line_foodsという変数に代入 if line_foods.exists? render json: { line_food_ids: line_foods.map{ |line_food| line_food.id }, # 登録されているLineFoodのidを配列形式にしている, インスタンスであるline_foodsそれぞれをline_foodという単数形の変数名でとって、line_food.idとして1つずつのidを取得, それが最終的にline_food_ids: ...のプロパティとなる restaurant: line_foods[0].restaurant, # 1つの仮注文につき1つの店舗という仕様のため、line_foodsの中にある先頭のline_foodインスタンスの店舗の情報を詰めている count: line_foods.sum { |line_food| line_food[:count] }, # 各line_foodインスタンスには数量を表す:countがある amount: line_foods.sum { |line_food| line_food.total_amount }, # amountには各line_foodがインスタンスメソッドtotal_amountを呼んで、その数値を合算, 「数量×単価」のさらに合計を計算(フロントエンドで必要) }, status: :ok else # activeなLineFoodが一つも存在しないcase render json: {}, status: :no_content # 空データとstatus: :no_contentを返す end end def create if LineFood.active.other_restaurant(@ordered_food.restaurant.id).exists? return render json: { existing_restaurant: LineFood.other_restaurant(@ordered_food.restaurant.id).first.restaurant.name, new_restaurant: Food.find(params[:food_id]).restaurant.name, }, status: :not_acceptable end set_line_food(@ordered_food) if @line_food.save render json: { line_food: @line_food }, status: :created else render json: {}, status: :internal_server_error end end def replace LineFood.active.other_restaurant(@ordered_food.restaurant.id).each do |line_food| #each ~ doについて下記 line_food.update_attribute(:active, false) #line_food.activeをfalseにする end set_line_food(@ordered_food) # line_foodインスタンス生成 if @line_food.save # DBに保存 render json: { line_food: @line_food }, status: :created # saveが成功した場合 -> status: :createdと保存したデータを返す else render json: {}, status: :internal_server_error # if @line_food.saveでfalseだった場合 -> render json~がreturn, もしフロントエンドでエラーの内容に応じて表示を変えるような場合にここでHTTPレスポンスステータスコードが500系になる end end private def set_food @ordered_food = Food.find(params[:food_id]) end def set_line_food(ordered_food) if ordered_food.line_food.present? # 新しくline_foodを生成するのか、既に同じfoodに関するline_foodが存在する場合を判断している @line_food = ordered_food.line_food @line_food.attributes = { count: ordered_food.line_food.count + params[:count], active: true } #present?がtrueの場合 -> 既存のline_foodインスタンスの既存の情報を更新(count, activeの2つをupdate) else @line_food = ordered_food.build_line_food( # 新しくインスタンスを作成 count: params[:count], restaurant: ordered_food.restaurant, active: true ) end end end end end # --- ここまで追加 --- # アクションの実行前にフィルタとして before_action : フィルタアクション名 を定義できる -> 今回の例だとcreateの実行前に、set_foodを実行することができる, :onlyオプションをつけることで、特定のアクションの実行前にだけ追加できる # set_foodはこのコントローラーの中でしか呼ばれないaction, そのためprivateにする # set_foodの中ではparams[:food_id]を受け取って、対応するFoodを1つ抽出し、@ordered_foodというインスタンス変数に代入 -> このあと実行されるcreateアクションの中でも@ordered_foodを参照可能 # !!注意 -> インスタンス変数(どこからでも参照できる)は便利だけどグローバルに定義するときのみ使うべき # ローカル変数(@をつけない変数)の場合、そのスコープでしか使われないため心配がない ## 例外パターン(他店舗での仮注文が既にある場合) ## # LineFood.active.other_restaurant(@ordered_food.restaurant.id)は複数のscope(active, other_resrtaurant)を組み合わせて「他店舗でアクティブなLineFood」をActiveRecord_Relationのかたちで取得 -> それが存在するかどうかをexists?で判断 -> if it's true, then return JSONデータ # JSONの中身にはexisting_restaurantで既に作成されている他店舗の情報と、new_restaurantでこのリクエストで作成しようとした新店舗の情報の2つをreturn, and return "406 Not Acceptable"HTTPレスポンスステータスコード # 「早期リターン」とは複雑あるいは重いメイン処理を実行する前に、この処理が不要なケースに当てはまるかどうかをifなどでチェックし、その場合にメイン処理に入らせないことを指す # active? -> models/line_food.rbのscope :active, モデル名.スコープ名 === active: trueなLineFoodの一覧がActiveRecord_Relationのかたちで取得可能 # .exists?メソッドは対象のインスタンスのデータがDBに存在するかどうか?をtrue/falseで返すメソッド # .map method -> 配列やハッシュオブジェクトなどを1つずつ取り出し、.mapより後ろのブロックをあてていく # 保守性の観点でなるべくデータの計算などはサーバーサイドで担当すべき, ビジネスロジックとしてモデル層ではなく、コントローラー層にベタ書きする ## まとめ # スコープはActiveRecord_Relationを返す # exists?でデータがあるかどうかをtrue/falseで判断できる -> 他に nil?/empty?/present?がある ## replace # before_actionで@ordered_foodをセット # 他店舗のactiveなLineFood一覧をLineFood.active.other_restaurant(@ordered_food.restaurant.id)で取得し、そのままeachに渡す。各要素に対し、do...end内の処理を実行 -> 他店舗のLineFood一つずつに対してupdate_attributeで更新している。更新内容は引数に渡された(:active, false)で、line_food.activeをfalseにするという意味 ## mapとeachのちがい # map: 最終的に配列をreturn, each: ただ繰り返し処理を行うだけで、そのままでは配列は返さない #範囲obj.eachの形で、範囲objの中身一つ一つを参照することができる。 ## まとめ # before_actionなどのcallbackには特定のアクションの場合のみ実行する、という指定ができる。 -> only: %i[メソッド名]
true
e88f94068fc4406f3bcbd297675ce9d21a031b10
Ruby
PLOS/rich_citations_processor
/lib/rich_citations_processor/uri_resolvers/uris_from_reference.rb
UTF-8
2,349
2.53125
3
[ "MIT" ]
permissive
# Copyright (c) 2014 Public Library of Science # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # This resolver attempts to find any type of parseable URI # From a reference href attributes and text # This could be split into two resolvers (from reference href and from reference text) module RichCitationsProcessor module URIResolvers class UrisFromReference < Base def resolve! filtered_references.each do |ref| resolve_reference(ref) end end protected def self.priority 10000 end def resolve_reference(ref) fragment = Nokogiri::HTML::DocumentFragment.parse(ref.original_citation) resolve_from_href(ref, fragment) resolve_from_text(ref, fragment.text) end private # Find URIs in href attributes def resolve_from_href(ref, fragment) href_nodes = fragment.xpath('.//*[@href]') href_nodes.each do |node| href_value = node['href'].to_s uri = URI.from_uri(href_value) ref.add_candidate_uri(uri, source:'reference-href') end end # Find URIs in the text def resolve_from_text(ref, text) uris = URI.from_text(text) uris.each do |uri| ref.add_candidate_uri(uri, source:'reference-text') end end end end end
true
ea8bf77a464aa4992000ed9ea9938ae89becbd5f
Ruby
md1961/ruby
/unit_test/lib/test_reverse_line_reader.rb
UTF-8
1,275
3.21875
3
[]
no_license
# vi: set fileencoding=utf-8 : require 'test/unit' require 'reverse_line_reader' require 'stringio' class TestReverseLineReader < Test::Unit::TestCase def test_empty_file data = '' actual_lines = read_lines_with_ReverseLineReader(data) assert_equal(0, actual_lines.size, "Number of lines") end def read_lines_with_ReverseLineReader(original_data) io = StringIO.new(original_data) lines = Array.new ReverseLineReader.new(io).each do |line| lines << line end return lines end private :read_lines_with_ReverseLineReader def test_one_line_file oneliner = "Just this line" + $/ actual_lines = read_lines_with_ReverseLineReader(oneliner) assert_equal(1, actual_lines.size, "Number of lines") assert_equal(oneliner, actual_lines[0], "Line #01") end def test_multiple_line_file original_lines = [ " 1: class Test", " 2: def test", " 3: # 何もしない", " 4: end", " 5: end", ].map { |line| line + $/ } actual_lines = read_lines_with_ReverseLineReader(original_lines.join('')) assert_equal(original_lines.size, actual_lines.size, "Number of lines") assert_equal(original_lines.reverse, actual_lines, "Contents") end end
true
065ca4ead10d796f2ec319541510b2289aa01cf3
Ruby
Bartlebyy/Iron_Yard_Projects
/Day_2/Hangman.rb
UTF-8
1,178
3.828125
4
[]
no_license
Hangman Design If the computer is creating, it needs a database, with a list of words or phrases that it can use as its word. Maybe a hint for each one. (Dictionary would be a good place to start). Maybe booktitles. And then use a random readline to get the word. Ideally it would have graphics. I would make a method where there will be a until_dead variable where it would start with number 6 and count down. When it reaches 0, player loses. I would use grep or select to see if our guess works, otherwise it would call above method. I would have a status method after each guess to show where the player stands. What is the current status of the hangman, how many letters we have and wrong guesses. the answer will be in the form of a string, and will be copied with an underscore substitution. while until_dead > 0 then guess = gets.chomp!.downcase If a guess is correct replace the string with underscores with the correct letter. That function will be pretty tricky. Have a method figure out where the correct letters are located. Then use answer[n]= "correct_guess_letter" to fill it in, and call the refresh method. Of course add taunts and words of praise.
true
d575af8dc53dd934a8ffe13148d0b39d9cee914c
Ruby
tiborh/ruby
/sort_words.rb
UTF-8
343
4.125
4
[]
no_license
#!/usr/bin/env ruby def sort_string(string) string.downcase.split.sort.join(" ") end def sort_string_by_length(string) string.split.sort{|a,b| a.length <=> b.length}.join(" ") end s1 = "Sort words in a sentence" puts sort_string(s1) puts sort_string_by_length(s1) s2 = 'Awesome I am' puts sort_string(s2) puts sort_string_by_length(s2)
true
4cfc5b22a4b32b282433e996f97522567ed46fbf
Ruby
theoluyi/ruby-project-alt-guidelines-dumbo-web-010620
/lib/command_line_interface.rb
UTF-8
489
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class CommandLineInterface attr_accessor :dev, :action, :result def run greet whats_your_name end def greet puts "Initializing new software developer... " sleep 1.5 puts "Wake up!!!" end def whats_your_name prompt = TTY::Prompt.new dev_name = prompt.ask("Hey new guy, what's your name?") puts "Nice to meet you #{dev_name}! 🤝" Dev.create(name: dev_name, cash: 100) end end
true
81a6299d5d7827b05bd5c307f56b424dc48bde4f
Ruby
wangjoc/betsy
/test/models/product_test.rb
UTF-8
5,370
2.78125
3
[]
no_license
require "test_helper" describe Product do describe "validations" do describe "name validation" do it "is invalid without a title" do product = products(:diaper) product.name = nil # Act result = product.valid? # Assert expect(result).must_equal false end it "is valid with a name" do product = products(:diaper) product.name = "Used Diaper" # Act result = product.valid? # Assert expect(result).must_equal true end end describe "price validation" do it "is invalid without a price" do product2 = products(:toilet) product2.price = nil # Act result = product2.valid? # Assert expect(result).must_equal false end it "is invalid with a non-numerical price" do product2 = products(:toilet) product2.price = "no price" # Act result = product2.valid? # Assert expect(result).must_equal false end it "is invalid with a price of 0" do product2 = products(:toilet) product2.price = 0 # Act result = product2.valid? # Assert expect(result).must_equal false end it "is invalid with a price less than 0" do product2 = products(:toilet) product2.price = -6.25 # Act result = product2.valid? # Assert expect(result).must_equal false end it "is valid with a numerical price greater than 0" do product2 = products(:toilet) product2.price = 1.09 # Act result = product2.valid? # Assert expect(result).must_equal true end end describe "photo_url valdation" do it "is invalid without a 'https' in the url" do product3 = products(:lion) product3.photo_url = "www.com" # Act result = product3.valid? # Assert expect(result).must_equal false end it "is valid with a 'https' in the url" do product3 = products(:lion) product3.photo_url = "https://www.com" # Act result = product3.valid? # Assert expect(result).must_equal true end end end describe "relations" do describe "product relationships" do it "can get the merchant through merchant" do current_product = products(:diaper) expect(current_product.merchant).must_be_instance_of Merchant end end it "has a merchant" do merchant = Merchant.first product = Product.create(name: "product", price: 599.99, photo_url: "https://i.imgur.com/JWfZcrG.jpg", stock: 5, merchant: merchant) expect(product).must_respond_to :merchant expect(product.merchant).must_be_kind_of Merchant end it "has a category" do product = products(:diaper) expect(product).must_respond_to :categories product.categories.each do |category| expect(category).must_be_kind_of Category end end it "contains many order items" do product = products(:lion) expect(product.order_items.count).must_equal 2 expect(product).must_respond_to :order_items product.order_items.each do |order_item| expect(order_item).must_be_kind_of OrderItem end end it "can contain many reviews" do product = products(:lion) expect(product.reviews.count).must_equal 1 expect(product).must_respond_to :reviews product.reviews.each do |review| expect(review).must_be_kind_of Review end end end describe "custom methods" do describe "list of products by category" do it "returns a list of products for each category" do category = categories(:indoor) product = products(:lion) product.categories << category products = Product.by_category(category.id) expect(products.count).must_equal 2 end end describe "in_stock?" do it "returns true if given a valid product that has items in stock" do product = products(:lion) expect(product.in_stock?).must_equal true end it "returns false if the current product is out of stock" do product = products(:toilet) product.stock = 0 expect(product.in_stock?).must_equal false end end it "calculate the average rating of a product with reviews" do product = products(:lion) expect(product.avg_rating).must_equal 3 end it "creates a list of featured products" do products = Product.featured_products expect(products).must_be_kind_of Array expect(products.first.name).must_equal products(:lion).name end end describe "decrease_stock" do it "decreases the given product's stock by the given quantity" do product = products(:toilet) expect(product.stock).must_equal 1 expect(product.decrease_stock(1)).must_equal true expect(product.stock).must_equal 0 end it "does not decrease the stock if it is already 0 and returns false" do product = products(:lion) product.stock = 0 expect(product.stock).must_equal 0 expect(product.decrease_stock(1)).must_equal false expect(product.stock).must_equal 0 end end end
true
cd0ae9b74db46a646cb906090c6409ee84938dfc
Ruby
jnikelski/beagle
/beagle_run_initialization
UTF-8
3,884
2.53125
3
[]
no_license
#!/usr/bin/env ruby # ============================================================================== # Purpose: # This is the first script in the Loris pipeline. Its purpose is to # set up all output directories, and initialize them with a smattering # of required files. # # ============================================================================== require 'optparse' require 'ostruct' require 'pathname' require 'fileutils' require 'tmpdir' # needed for Dir::tmpdir # load ruby gems require 'rubygems' require 'json' require 'pp' # these libs are pointed to by the RUBYLIB env variable require 'hclab_function_library' require 'beagle_function_library' require 'beagle_logger_classes' # start of main script begin opt = OpenStruct.new{} # store input options opt.verbose = false opt.debug = false opt.eraseLog = false opt.keyname = "" opt.settingsFile = "" # List of arguments. opts = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [Options]" opts.separator "" opts.separator "Options:" opts.on('-v', '--[no-]verbose', 'Run verbosely') { |v| opt.verbose = v } opts.on('-d', '--debug', 'Print pedantic debugging messages') { |d| opt.debug = d } opts.on('--eraseLog', 'Erase the subjects log file') { |l| opt.eraseLog = l } opts.on('--keyname subject_keyname', "Anonymizing keyname for this subject") do |keyname| opt.keyname = keyname puts "** keyname: " + opt.keyname if opt.verbose end opts.on('--settingsFile aggregated_settings_file', "Fullpath to the aggregated settings file ") do |settingsFile| opt.settingsFile = settingsFile.to_s puts "** Fullpath to the aggregated settings file: " + opt.settingsFile if opt.verbose end opts.on_tail("-h", "--help", "Show this very helpful help message") do puts opts exit end end # OptionParser # run parse!() method in the OptionParser object, passing ARGV # NB: the "!" in parse!() removes the switches from ARGV puts "Before OptionParser start ..." if opt.debug opts.parse!(ARGV) # = = = = = = = = M A I N P R O C E S S I N G S T A R T S H E R E = = = = = = = # # check for aggregated settings file, then read if all looks OK if ( opt.settingsFile.empty? || opt.settingsFile.empty? ) then puts "\n*** Error: Missing option(s) -- keyname or Loris aggregated settings file" puts opts exit end # if ( !File.exists?(opt.settingsFile) || !File.file?(opt.settingsFile) ) then puts sprintf("\n!!! Error: The specified Loris aggregated settings [%s] does not exist or is unreadable.", opt.settingsFile) exit end # settings = load_beagle_aggregated_settings(opt.settingsFile, verbose=false, debug=false) # init associated variables LORIS_LOGFILE_SUFFIX = settings['LORIS_LOGFILE_SUFFIX'] LORIS_ROOT_DIR = settings['LORIS_ROOT_DIR'] LORIS_LOGFILE_PREFIX = settings['LORIS_LOGFILE_PREFIX'] LORIS_LOGFILE_EXTENSION = settings['LORIS_LOGFILE_EXTENSION'] LORIS_RUN_IDENTIFIER = settings['LORIS_RUN_IDENTIFIER'] # set some useful values keyname_dir_fullPath = File.join(settings['LORIS_ROOT_DIR'], opt.keyname) # Create a few subject-common directories # # # filename = File.join(keyname_dir_fullPath, "tmp") if !File.exists?( filename ) then FileUtils.mkdir( filename ) end # create an empty logfile (unless asked not to) and log init message logger = BeagleLogger.new(opt.keyname, settings, eraseLog=true) logger.log_message('beagle_run_initialization', opt.keyname, 'NULL', 'NULL', 'init_message', 'Log file initialized') logger.save_to_file() rescue RuntimeError => e STDERR.puts e exit 1 end #main()
true
1db7e7538579445fe975ba9ce4e40a78bf57b702
Ruby
ohookins/pmacctstats
/lib/summarise.rb
UTF-8
11,218
2.765625
3
[ "MIT" ]
permissive
require 'rubygems' require 'active_record' require 'ipaddr' require 'bigdecimal' require 'inifile' require 'app/models/pmacct_entry' require 'app/models/usage_entry' require 'app/models/host' class NoConfFileError < Exception; end class UnreadableConfFileError < Exception; end class MissingConfSectionError < Exception; end class EmptyConfSectionError < Exception; end class MissingConfValueError < Exception; end class Summarise # define some constants used throughout the summarisation CONFIGFILE = '/etc/pmacctstats.conf' CONFIGPARTS = [:main, :source, :destination] STARTDATE = Date::civil(2010, 01, 01) attr_accessor :loglevel def initialize() @loglevel = 0 # Database and network settings @settings = {:sourcehost => nil, :sourcedb => nil, :sourceuser => nil, :sourcepass => nil, :desthost => nil, :destdb => nil, :destuser => nil, :destpass => nil, :localnets => nil } end # reasonably naive logging shortcut def log (msglevel, msg, loglevel = 0) if msglevel and msg and loglevel >= msglevel then puts msg end end # shortcut for outputting the current method call name def this_method_name caller[0] =~ /`([^']*)'/ and $1 end # Return path to configuration file. This makes testing easier. def config_file CONFIGFILE end # Parse configuration file def get_config # File must exist and at least be readable File.file?(config_file) or raise NoConfFileError File.readable?(config_file) or raise UnreadableConfFileError conf = IniFile.load(config_file) # Check all necessary sections exist CONFIGPARTS.each do |c| raise(MissingConfSectionError, c) unless conf.has_section?(c) raise(EmptyConfSectionError, c) if conf[c] == {} end # Populate our variables @settings[:sourcehost] = conf[:source]['host'] @settings[:sourcedb] = conf[:source]['database'] @settings[:sourceuser] = conf[:source]['username'] @settings[:sourcepass] = conf[:source]['password'] @settings[:desthost] = conf[:destination]['host'] @settings[:destdb] = conf[:destination]['database'] @settings[:destuser] = conf[:destination]['username'] @settings[:destpass] = conf[:destination]['password'] @settings[:localnets] = conf[:main]['networks'].delete(' ').split(',') # Check we have all values emptyvars = [] @settings.each_pair do |k,v| emptyvars.push(k) if v.nil? end unless emptyvars == [] then e = '' emptyvars.each { |v| e.concat("#{v} ") } raise MissingConfValueError, e.chomp(' ') end end # shortcut for matching an IP in one of our valid subnets def matches_subnets? (ip) if ! ip return false else ip_obj = nil begin ip_obj = IPAddr.new(ip) rescue ArgumentError log(0, "Invalid IP address #{ip} caught in #{self.this_method_name}") return false end @settings[:localnets].each do |n| IPAddr.new(n).include?(ip_obj) and return true end return false end end # adds an host object to the rails database def add_active_hosts(day) end # get usage for local IPs for a date from the pmacct database def get_daily_usage(day) # This is very inefficient. When the result set becomes too big to fit in memory # we may have to map/reduce or hack cursors into AR later. log(2, "Pulling out usage data for #{day}", @loglevel) usage = PmacctEntry.where('stamp_inserted > ? AND stamp_inserted < ?', day.strftime('%Y-%m-%d 00:00'), (day+1).strftime('%Y-%m-%d 00:00') ).all({:select => ['ip_src','ip_dst','bytes']}) log(2, "number of rows: #{usage.count()}", @loglevel) # Process each row in the result set and tally the bytes for each valid IP source_matched = 0 # purely diagnostic tracking dest_matched = 0 # ditto # keep a hash of our matched IPs and their byte counters like: # {IP => {:in => inbytes, :out => outbytes}} bytes_by_ip = {} usage.each do |row| # Egress bandwidth if matches_subnets?(row.ip_src) and not matches_subnets?(row.ip_dst) then source_matched += 1 bytes_by_ip[row.ip_src] or bytes_by_ip[row.ip_src] = {:in => 0, :out => 0} # create a record in the hash if missing bytes_by_ip[row.ip_src][:out] += row.bytes # Ingress bandwidth elsif matches_subnets?(row.ip_dst) and not matches_subnets?(row.ip_src) then dest_matched += 1 bytes_by_ip[row.ip_dst] or bytes_by_ip[row.ip_dst] = {:in => 0, :out => 0} # create a record in the hash if missing bytes_by_ip[row.ip_dst][:in] += row.bytes end end log(1, "source_matched: #{source_matched} for #{day}", @loglevel) log(1, "dest_matched: #{dest_matched} for #{day}", @loglevel) log(2, bytes_by_ip.each_pair { |host,usage| "#{host}: #{usage[:in]} in, #{usage[:out]} out" }, @loglevel) return bytes_by_ip end def insert_daily_usage(bytes_by_ip, day) # Loop over each valid host bytes_by_ip.each_pair do |ip,usage| # Find the object or create a new one for this host host_obj = Host.where(:ip => ip).first if host_obj.nil? then Host.new(:ip => ip).save host_obj = Host.where(:ip => ip).first log(2, "Created new host object with id #{host_obj.id} for #{ip}", @loglevel) else log(2, "Found host object with id #{host_obj.id} for #{ip}", @loglevel) end # Add usage data for this host. # We convert numbers from bytes to MB in fixed decimal inMB = (BigDecimal.new(usage[:in].to_s)/(1024**2)).round(2).to_f outMB = (BigDecimal.new(usage[:out].to_s)/(1024**2)).round(2).to_f UsageEntry.new(:host_id => host_obj.id, :in => inMB, :out => outMB, :date => day.strftime('%Y-%m-%d')).save end end # connect up the ruby on rails database to the default ActiveRecord::Base # adapter, and the source pmacct database to an adaptor specific to that # subclass def connect_activerecord() # FIXME: parameterise the adapter ActiveRecord::Base.establish_connection(:adapter => 'mysql2', :host => @settings[:desthost], :username => @settings[:destuser], :password => @settings[:destpass], :database => @settings[:destdb]) PmacctEntry.establish_connection(:adapter => 'mysql2', :host => @settings[:sourcehost], :username => @settings[:sourceuser], :password => @settings[:sourcepass], :database => @settings[:sourcedb]) end # Determine the most recently imported usage date def last_import_date() log(2, 'Calculating UsageEntry.maximum(:date)', @loglevel) # This is an arbitrary date cut-off in the case of no pre-existing stats. import_date = UsageEntry.maximum(:date) || STARTDATE log(1, "last import date: #{import_date}", @loglevel) return import_date end # Convenience method to facilitate testing def current_civil_date() Time.now.strftime('%Y-%m-%d') end # Determine list of days we have to process, given the last # successfully imported date. def find_unimported_days(import_date) # This will be expensive, but it should at least be DB agnostic. # Although, this DB should not be indexed anyway, so a row-scan is # inevitable. import_date += 1 # Need to look from the start of the next day. log(2, 'Retrieving unimported rows from database.', @loglevel) entries = PmacctEntry.where("stamp_inserted > ? AND stamp_inserted < ?", import_date.strftime('%Y-%m-%d'), current_civil_date()).all( {:select => 'stamp_inserted', :group => 'stamp_inserted', }) # List of days we have yet to import import_list = entries.map { |x| Date.parse(x.stamp_inserted.strftime('%Y-%m-%d')) }.uniq # Display what needs to be imported if import_list.empty? log(1, "Nothing to import", @loglevel) else log(1, import_list.map { |x| "need to import: #{x.strftime('%Y-%m-%d')}" }, @loglevel) end return import_list end # For a given date, pull all of the unique addresses seen in the accounting # data and match only the ones that we are interested in. # Sadly this is quite tricky to do in everything that isn't PostgreSQL def get_active_addresses(day) log(1, "Now importing from date: #{day.strftime('%Y-%m-%d')}", @loglevel) # Determine list of active IPs and check them against our local subnets. # This is all local IPs that were a source or destination of traffic. log(2, "Determining active IPs for #{day.strftime('%Y-%m-%d')}", @loglevel) sources = PmacctEntry.where('stamp_inserted > ? AND stamp_inserted < ?', day.strftime('%Y-%m-%d 00:00'), (day+1).strftime('%Y-%m-%d 00:00') ).uniq.pluck(:ip_src) destinations = PmacctEntry.where('stamp_inserted > ? AND stamp_inserted < ?', day.strftime('%Y-%m-%d 00:00'), (day+1).strftime('%Y-%m-%d 00:00') ).uniq.pluck(:ip_dst) # Pick out valid IP addresses from our array of sources and destinations on # this one day. return (sources + destinations).flatten.uniq.map do |address| if self.matches_subnets?(address) then log(1, "Found valid IP address: #{address}", @loglevel) address end end.compact end # the guts of the usage summarisation def run() get_config() # Establish the source and destination connections inside ActiveRecord connect_activerecord() # Determine our cut-off date for the latest stats. import_date = last_import_date() # Determine list of days we have to process. import_list = find_unimported_days(import_date) # Run import for each missing day of stats import_list.each do |day| start_time = Time.now() # We have to do a full table scan anyway, so determining active local # hosts and adding host objects for them separately to calculating # usage information is a pointless performance hit. # # find the active addresses for the day #active_addresses = get_active_addresses(day) # ensure each one has a host object #add_active_hosts(day) # Summarise traffic insert_daily_usage(get_daily_usage(day), day) log(1, "Stats for #{day} imported in #{(Time.now - start_time).to_i}s", @loglevel) end end end
true
fc8ab70c943c6b2d73ea45a1030d6066a0fa4d42
Ruby
ckennington/cs404
/src/ruby/no_return.rb
UTF-8
212
2.75
3
[]
no_license
def no_return # straight up expression, no variables or nothin'. 10 + 10 # notice there's no return statement. # 20 gets return automatically because it was the last eval'd expression end puts no_return
true
6219e60cc3c4dbc05b19d0c62c62d6fb7f9fd430
Ruby
acltc-the-el-ninos/whirlwind-ruby
/test.rb
UTF-8
470
3.765625
4
[]
no_license
class Song attr_reader :lyrics attr_writer :lyrics def initialize(input_lyrics) @lyrics = input_lyrics end def play `say "#{@lyrics}"` end # def set_lyrics(input_lyrics) # @lyrics = input_lyrics # end # def lyrics # @lyrics # end end song = Song.new("hello is it me you're looking for") # song.play # song.set_lyrics('start in the name of hate') # song.play p song.lyrics song.lyrics = 'happy birthday to you' p song.lyrics
true
c2f4a601fbd623e2eaa9d6e34b58530714a34c57
Ruby
mzsanford/twitter-search
/lib/trends.rb
UTF-8
718
2.84375
3
[ "MIT" ]
permissive
module TwitterSearch class Trend VARS = [ :query, :name ] attr_reader *VARS def initialize(opts) VARS.each { |each| instance_variable_set "@#{each}", opts[each.to_s] } end end class Trends VARS = [:date, :exclude_hashtags] attr_reader *VARS include Enumerable def initialize(opts) @exclude_hashtags = !!opts['exclude_hashtags'] @date = Time.at(opts['as_of']) time_key = opts['trends'].keys[0] @trends = opts['trends'][time_key].collect { |each| Trend.new(each) } end def each(&block) @trends.each(&block) end def size @trends.size end def [](index) @trends[index] end end end
true
393671ceabd4f6056cf164d329edfa98a2bf9e6c
Ruby
moranja/Cocktailor
/app/models/Ingredient.rb
UTF-8
1,205
2.90625
3
[]
no_license
class Ingredient < ActiveRecord::Base has_many :recipe_ingredients has_many :recipes, through: :recipe_ingredients has_many :user_ingredients has_many :users, through: :user_ingredients validates :name, uniqueness: true def amount self.recipe_ingredient.amount end def amount=(amt) self.recipe_ingredient.amount = amt end def self.main_ingredients Ingredient.all.select{|i| i.ingredient_type == "Main ingredient"} end def self.special_ingredients Ingredient.all.select{|i| i.ingredient_type == "Special ingredient"} end def recipe_count recipe_count = 0 ri_s = RecipeIngredient.all ri_s.each do |ri| if ri.ingredient_id == self.id recipe_count += 1 end end recipe_count end def self.all_names Ingredient.all.map{|i| [i, i.name.downcase]} end def self.search(search_term) results = [] Ingredient.all_names.each do |ing| if ing[1].include?(search_term) results << ing[0] end end results != [] ? ingredients = results : ingredients = Ingredient.all return ingredients end def self.popularity Ingredient.all.sort_by{|r| r.recipes.size}.reverse end end
true
9c516aeceddf01d977c38f06daa0f40ccde5e929
Ruby
vjdhama/twitchblade
/spec/twitter/timeline_model_spec.rb
UTF-8
935
2.5625
3
[]
no_license
require "spec_helper" module Twitter describe "TimelineModel" do def get_id(name) Connection.open.exec("select uid from users where username = '#{name}'").getvalue(0, 0) end before(:each) do name = "vjdhama" password = "password" Connection.open.exec("begin") Connection.open.exec("insert into users (username, password) values ($1, $2)", [name, password]) user_id = get_id(name) Connection.open.exec("insert into tweets (content, user_id) values ('Go home', $1)", [user_id]) Connection.open.exec("insert into tweets (content, user_id) values ('Call my phone', $1)", [user_id]) @timeline_model = TimelineModel.new(name) end after(:each) do Connection.open.exec("rollback") end it "should get tweets based on logged in user" do expect(@timeline_model.get_tweets).to eq(['Go home', 'Call my phone']) end end end
true
d71717fe86c7b11c9c15eb3d24e3c334bbf33f1d
Ruby
TeamGambit/Chessapp
/app/models/knight.rb
UTF-8
334
2.984375
3
[]
no_license
class Knight < Piece def valid_move?(x, y) # Knight has no concern for obstruction, only check required is valid move of spaces. return true if (self.x_position - x).abs == 2 && (self.y_position - y).abs == 1 return true if (self.x_position - x).abs == 1 && (self.y_position - y).abs == 2 return false end end
true
9a59eb0ae125b4786b94aa25b64e779d7345cab7
Ruby
IndianGuru/RPCFN10
/18_MichaelCramm/app.rb
UTF-8
1,204
3.359375
3
[]
no_license
require 'day' require 'business_hours' # renamed by ashbb require 'time' hours = BusinessHours.new("9:00 AM", "3:00 PM") hours.update :sun, "9:00 AM", "10:45 AM" hours.update :mon, "7:46 AM", "4:00 PM" hours.update :thu, "10:00 AM", "12:01 PM" hours.update "Dec 24, 2009", "11:00 AM", "2:00 PM" hours.closed :tue, :wed, "Jan 21 2010", :fri, "Jan 23 2010" hours.update "Dec 24, 2009", "2:00 AM", "2:30 PM" hours.update "01/25/2010", "7:46 AM", "9:00 AM" hours.update 'something', "7:46 AM", "9:00 AM" # will be parsed as 'today' hours.update 1, "7:46 AM", "9:00 AM" hours.update :mon, "7:46 AM", "4:00 PM" # hours.display # => Used to display currently set business hours & special cases hours.closed :tue puts hours.calculate_deadline(2*60*60, "Jan 20, 2010 6:01 PM") puts hours.calculate_deadline(60*60, "Jan 20, 2010 6:01 PM") puts hours.calculate_deadline(15*60, "Jan 20, 2010 6:01 PM") puts hours.calculate_deadline(2*60*60, "Jan 19, 2011 17:55 PM") hours = BusinessHours.new("9:00 AM", "3:00 PM") hours.closed :sun, :wed, "Dec 25 2010" hours.update :fri, "10:00 AM", "5:00 PM" hours.update "Dec 24, 2010", "8:00 AM", "1:00 PM" puts hours.calculate_deadline(7*60*60, "Dec 24, 2010 6:45 AM")
true
08c7205d85567f15ab5a921c84b53f93da9bf466
Ruby
Turzhanskyi/thoughtbot
/fundamentals-of-TDD/step-02/calculator.rb
UTF-8
677
3.75
4
[]
no_license
# frozen_string_literal: true require 'rspec/autorun' class Calculator def add(first_number, second_number) first_number + second_number end def factorial(number) if number.zero? 1 else (1..number).reduce(:*) end end end describe Calculator do describe '#add' do it 'returns the sum of its two arguments' do calc = Calculator.new expect(calc.add(5, 10)).to eq(15) end end it 'returns 1 when given 0 (0! = 1)' do calc = Calculator.new expect(calc.factorial(0)).to eq(1) end it 'returns 120 when given 5 (5! = 120)' do calc = Calculator.new expect(calc.factorial(5)).to eq(120) end end
true
1ffa21255765e2b4b99cf54ddb02eeea3c8556e6
Ruby
t-mangoe/get_favorite_tweets
/get_favorite_tweets.rb
UTF-8
2,798
2.953125
3
[]
no_license
#!/usr/bin/env ruby require './twitter_client.rb' require 'open-uri' class GetFavoriteTweets def initialize @client = TwitterClient.new @picture_counter_hash end def fetch(url) p url html = open(url) body = html.read mime = html.content_type return body, mime end def check_picture_extension(mime) ext = '' if mime.include?('jpeg') ext = '.jpg' elsif mime.include?('png') ext = '.png' elsif mime.include?('gif') ext = '.gif' end ext end def download_tweet_picture(tweet) p tweet.text #p tweet.user.name #p tweet.user.screen_name return if tweet.media.empty? media_urls = tweet.media.map{|media| media.media_url.to_s} media_urls.each do |url| img,mime = fetch url next if mime.nil? or img.nil? ext = check_picture_extension(mime) next if ext == '' @picture_counter_hash[tweet.user.screen_name] = 0 unless @picture_counter_hash.has_key?(tweet.user.screen_name) file_name = tweet.user.screen_name + "-" + @picture_counter_hash[tweet.user.screen_name].to_s result_file_path = picture_dir + file_name + ext @picture_counter_hash[tweet.user.screen_name] += 1 File.open(result_file_path, 'w') do |file| file.puts(img) end sleep(1) end # exit if picture_counter > 5 # 画像をダウンロードしたら、終了。デバッグ用 end def start_download_picture #p client.show_my_profile # picture_counter = 1 #画像の名前をつけるための、暫定的なカウンター @picture_counter_hash = {} # 画像の名前をつけるためのカウンター。アカウント毎にカウントする picture_dir = 'favorite_picture/' Dir.mkdir(picture_dir) unless File.exist?(picture_dir) # フォルダの作成 page = 1 until (favorites = @client.favorite(20,page)).nil? do favorites.each do |tweet| download_tweet_picture tweet end page += 1 end end def output_tweet page = 1 until (favorites = @client.favorite(20,page)).nil? do favorites.each do |tweet| File.open("favorite_tweets.md", 'a') do |file| file.print("###" + tweet.user.name) file.puts('(@' + tweet.user.screen_name + ')') text = tweet.text text = text.gsub(/#/,"\\#") file.puts(text) unless tweet.media.empty? file.puts(" ") media_urls = tweet.media.map{|media| media.media_url.to_s} media_urls.each do |url| file.puts("![](#{url}) ") end end file.puts("") end end page += 1 break # for debug end end end a = GetFavoriteTweets.new # a.start_download_picture a.output_tweet
true
e27b6e2c54ffd83e535e7a94c34933e216ddcd26
Ruby
kbrock/benchmark-sweet
/lib/benchmark/sweet.rb
UTF-8
3,805
2.875
3
[ "MIT" ]
permissive
require "benchmark/sweet/version" require "benchmark/sweet/ips" require "benchmark/sweet/memory" require "benchmark/sweet/queries" require "benchmark/sweet/job" require "benchmark/sweet/comparison" require "benchmark/sweet/item" require "benchmark/ips" module Benchmark module Sweet def items(options = {memory: true, ips: true}) job = ::Benchmark::Sweet::Job.new(options) yield job job.load_entries job.run job.save_entries job.run_report job # both items and entries are useful end # report helper methods # these are the building blocks for the reports printed. # These can be used to create different tables # @param base [Array<Comparison>}] array of comparisons # @param grouping [Symbol|Array<Symbol>|Proc] Proc passed to group_by to partition records. # Accepts Comparison, returns an object to partition. returns nil to filter from the list # @keyword sort [Boolean] true to sort by the grouping value (default false) # Proc accepts the label to generate custom summary text def self.group(base, grouping, sort: false, &block) if grouping.nil? yield nil, base return end grouping = symbol_to_proc(grouping) label_records = base.group_by(&grouping).select { |value, _comparisons| !value.nil? } label_records = label_records.sort_by(&:first) if sort label_records.each(&block) end def self.table(base, grouping: nil, sort: false, row: :label, column: :metric, value: :comp_short) header_name = grouping.respond_to?(:call) ? "grouping" : grouping column = symbol_to_proc(column) value = symbol_to_proc(value) group(base, grouping, sort: true) do |header_value, table_comparisons| row_key = row.kind_of?(Symbol) || row.kind_of?(String) ? row : "label" table_rows = group(table_comparisons, row, sort: sort).map do |row_header, row_comparisons| row_comparisons.each_with_object({row_key => row_header}) do |comparison, row_data| row_data[column.call(comparison)] = value.call(comparison) end end if block_given? yield header_value, table_rows else print_table(header_name, header_value, table_rows) end end end # proc produced: -> (comparison) { comparison.method } def self.symbol_to_proc(field, join: "_") if field.kind_of?(Symbol) || field.kind_of?(String) field_name = field -> v { v[field_name] } elsif field.kind_of?(Array) field_names = field if join -> v { field_names.map { |gn| v[gn].to_s }.join(join) } else -> v { field_names.map { |gn| v[gn] } } end else field end end def self.print_table(header_name, header_value, table_rows) puts "", "#{header_name} #{header_value}", "" if header_value to_table(table_rows) end def self.to_table(arr) field_sizes = Hash.new arr.each { |row| field_sizes.merge!(row => row.map { |iterand| iterand[1].to_s.gsub(/\e\[[^m]+m/, '').length } ) } column_sizes = arr.reduce([]) do |lengths, row| row.each_with_index.map { |_iterand, index| [lengths[index] || 0, field_sizes[row][index]].max } end format = column_sizes.collect {|n| "%#{n}s" }.join(" | ") format += "\n" printf format, *arr[0].each_with_index.map { |el, i| " "*(column_sizes[i].to_i - field_sizes[arr[0]][i].to_i ) + el[0].to_s } printf format, *column_sizes.collect { |w| "-" * w } arr[0..arr.count].each do |line| printf format, *line.each_with_index.map { |el, i| " "*(column_sizes[i] - field_sizes[line][i] ) + el[1].to_s } end end end extend Benchmark::Sweet end
true
6125c3ffa57f41c4f88f8502234f6121402721db
Ruby
Sadeshakur/dev
/kilos_to_pounds.rb
UTF-8
594
4.03125
4
[]
no_license
# Read in a weight from Standard input (in kilos) $stdout.puts("Please input the weight of your puppy, in kilos?") # weight in kilos weight_in_kilos=$stdin.gets.to_i # print out puppy's weight in kilos weight_in_lbs = 2.20462 * weight_in_kilos # convert in pounds # data type comes in as string so need to turn weight into a float # get user input and assign it to variable $stdout.puts (weight_in_lbs.round(2)) $stdout.puts("Your puppy is " + weight_in_kilos.to_s + "lbs") # Print to Standard output the weight # converted to pounds # only to the second decimal place $stderr.puts("oh crap!")
true
2f0dcf6475562e3efd710b3b594d3c6284a0c9f2
Ruby
ytorii/cyclepark_rails
/app/models/multi_seals_update.rb
UTF-8
1,398
2.640625
3
[]
no_license
# Model for updating multiple seals. class MultiSealsUpdate include ActiveModel::Model include StaffsExist attr_accessor :sealed_date attr_accessor :sealsid_list attr_accessor :staff_nickname date_format = %r(\A20[0-9]{2}(/|-)(0[1-9]|1[0-2])(/|-)(0[1-9]|(1|2)[0-9]|3[01])\z) # All parameters are required for update action. validates :sealed_date, presence: true, format: { with: date_format, allow_blank: true } validate :valid_array? validate :staff_exists? def update_selected_seals # Check all params exist. return false if invalid? # If unexist id is contained, all update is cancelled Seal.transaction do Seal.update(sealsid_list, set_seals_attributes) end # Successed all update, return true true end private # If no number is selected, [""] array is sent from client. def valid_array? sealsid_list = self.sealsid_list if sealsid_list.blank? errors.add(:sealsid_list, 'が選択されていません。') return false elsif !sealsid_list.is_a?(Array) || !sealsid_list.all? { |id| id =~ /^\d+/ } errors.add(:sealsid_list, 'は不正な形式です') return false end end def set_seals_attributes Array.new( sealsid_list.size, sealed_flag: true, sealed_date: sealed_date, staff_nickname: staff_nickname ) end end
true
6656c135c05d41ec31741dbbecc27f3cb1892b88
Ruby
leedu708/assignment_toh
/procedural_ToH.rb
UTF-8
3,127
4.21875
4
[]
no_license
class TowerOfHanoi def initialize(num_disks) @disks = num_disks end def start_game # introductory message puts "Welcome to Tower of Hanoi" puts "Instructions:" puts "Enter where you'd like to move disks from a column and to another column in the format [1,3]. Enter 'q' to quit." end def init_board # sets up board where first column contains initial number of disks first_column = [] # fills first column as necessary @disks.times do |disk| first_column.push(disk + 1) end # array returned to render [ # disks are doubled to center visually later on first_column.reverse.map{|num| num * 2}, [], [] ] end # check to see if user input valid columns def valid_input?(input) # make sure input only contains 2 columns if input.length == 2 input.each do |column| # check to see if column choices are between 1 and 3 if column < 1 || column > 3 puts "Enter numbers between 1 and 3" return false end end return true else puts "\nEnter only two numbers separated by a comma\n" return false end end # check if disk being moved can be placed in new column def valid_move?(board, from, to) # check if 'from' column is empty if board[from - 1].last == nil puts "\nThere is no disk in that column\n" return false # check that disk being moved is smaller than disk in new column elsif (board[to - 1].last != nil) && (board[to - 1].last < board [from - 1].last) puts "\nA bigger disk cannot be placed on a smaller disk\n" return false else return true end end # prints board with disks centered to column def render(board) puts "\nCurrent Board:" (@disks - 1).downto(0) do |column| 3.times do |row| print ("o" * board[row][column].to_i).center((@disks*2) + 2) end print "\n" end print "-C1-".center((@disks*2) + 2) print "-C2-".center((@disks*2) + 2) print "-C3-".center((@disks*2) + 2) print "\n" end # defines move method def move(board, from, to) board[to - 1].push(board[from - 1].last) board[from - 1].pop return board end def play start_game board = init_board render(init_board) # checks to see if top disk in column 3 at the last index is the smallest disk until board[2][@disks - 1] == 2 valid_input = false until valid_input puts "Enter Move (type 'q' to quit) >" input = gets.chomp # ends program if user inputs 'q' exit if input == "q" # properly formats user input for necessary methods user_move = input.split(",").map(&:to_i) valid_input = valid_input?(user_move) end # check to see if input move is valid valid_move = valid_move?(board, user_move[0], user_move[1]) unless valid_move == false move(board, user_move[0], user_move[1]) render(board) end end puts "\nCongratulations! You have successfully solved the Tower of Hanoi" end end
true
95e5c81ce748ea47bd4d537db5eedf7091c12dac
Ruby
sandiks/Trader_bot
/lib/arr_helper.rb
UTF-8
471
3.09375
3
[]
no_license
class Array def sum inject(0.0) { |result, el| result + el } end def mean sum / size end end class Time def to_datetime # Convert seconds + microseconds into a fractional number of seconds seconds = sec + Rational(usec, 10**6) # Convert a UTC offset measured in minutes to one measured in a # fraction of a day. offset = Rational(utc_offset, 60 * 60 * 24) DateTime.new(year, month, day, hour, min, seconds, 0/24.0) end end
true
22b4c013d6a2b607752b0c5cf0c1cd892ac3b796
Ruby
Ecthelion3/codaisseur-week1
/day3/exercise3.rb
UTF-8
106
2.984375
3
[]
no_license
loop do puts "Got all ingredients you need?" all_ingredients = gets.chomp if all_ingredients == "Y" end
true
2bfa1f9cd6226116b5c296d27f742875dd62ac30
Ruby
gavdaly/Deleted-Appointment-Finder
/find_patient.rb
UTF-8
501
2.78125
3
[]
no_license
#!/usr/bin/env ruby require 'fileutils' include FileUtils # A quick little ruby script that # goes through every file in the log/'subdirectory' # and matches the arguments for each patient ID def find_id(value) Dir['logs/**/*'].each do |name| unless File.directory?(name) File.open(name, 'r').each_line do |line| puts line if /APPOINTMENT DELETED~[0-9]+#{value}/.match(line) end end end end ARGV.each do |value| puts 'Matches for #{value}:' find_id value end
true
51859286e0ed6109a03917ebccc8bd1751c30342
Ruby
tchryssos/reverse-each-word-001-prework-web
/reverse_each_word.rb
UTF-8
346
3.53125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# def reverse_each_word(sentence) # split_array=sentence.split(" ") # reverse_array=[] # split_array.each do |word| # reverse_array<<word.reverse! # end # reverse_array.join(" ") # end def reverse_each_word(sentence) split_array=sentence.split(" ") split_array.collect { |word| word.reverse! } split_array.join(" ") end
true
0a2dab9463392ecaf584078432be9290d6549720
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/series/76960f2a39c846bd894ce9a08d3ed491.rb
UTF-8
298
3.390625
3
[]
no_license
class Series def initialize(digits) @digits = digits.split(//).map { |d| d.to_i } end def slices(length) raise ArgumentError if length > @digits.length 0.upto(@digits.length - length).each_with_object([]) do |index, array| array << @digits[index, length] end end end
true
34c631af5b1ac8fed11d1838a2bee6fb4c1df9bb
Ruby
keatongreve/modiflow_bots
/notification-checker/notif.rb
UTF-8
2,303
2.859375
3
[]
no_license
#!/usr/bin/env ruby # Corrects the names (and values) of NSNotification names to match the format Notif[UniqueIdentifer], # which adheres to the modi style guide. Encoding.default_external = Encoding::UTF_8 Encoding.default_internal = Encoding::UTF_8 source_extensions = [".h", ".m", ".c", ".swift", ".cpp"] path = ARGV[0] unless path puts "please specify a directory" exit 1 end unless File.directory? path puts "#{path} is not a directory" exit 2 end source_files = Dir.glob("#{path}/**/*").keep_if { |f| source_extensions.include? File.extname(f) } notification_names = [] source_files.each do |path| File.read(path).each_line do |line| match = line.match /postNotificationName:(\w*)/ if match captures = match.captures notification_names << captures[0] unless notification_names.include? captures[0] || captures[0] == "" end end end incorrect_notification_names = notification_names.select { |notif| !notif.match /^notif/i and notif != '' } corrections = [] incorrect_notification_names.each do |notif| if notif.start_with? "k" corrected_notif = "Notif" + notif[1..-1] elsif notif.end_with? "Notification" corrected_notif = "Notif" + notif[0..-13] else corrected_notif = "Notif" + notif end puts "#{notif} should be #{corrected_notif}" corrections << { original: notif, corrected: corrected_notif } end puts "There are #{incorrect_notification_names.length} incorrect notification names" puts "#{corrections.length} have been corrected" puts corrections corrections.each do |correction| original = correction[:original] corrected = correction[:corrected] puts "Correcting #{original} to #{corrected}" source_files.each do |path| puts "\tIn file #{path}" File.write( path, File.open(path, &:read).gsub(original, corrected) ) end end # Correct the values of the notification names to ensure consistency # Example: NSString *const NotifMyNotification = @"NotifMyNotification"; source_files.each do |path| text = File.read(path) new_text = "" text.each_line do |line| match = line.match /\ (Notif\w*)\s*=\s*@"(\w*)";/ if match && match.captures[0] != match.captures[1] puts line line = line.gsub("@\"#{match.captures[1]}\"", "@\"#{match.captures[0]}\"") end new_text = new_text + line end File.write(path, new_text) end
true
eadf99c98783350614d16787cd43b341ed00e33b
Ruby
simonoff/bank
/spec/bic_spec.rb
UTF-8
1,235
2.578125
3
[ "MIT" ]
permissive
require 'spec_helper' RSpec.describe Bank::BIC do let(:bic) { ::Bank::BIC.new('ABNACHZ8XXX') } it 'returns the right bank code' do expect(bic.bank_code).to eq 'ABNA' end it 'returns the right country code' do expect(bic.country_code).to eq 'CH' end it 'returns the right location code' do expect(bic.location_code).to eq 'Z8' end it 'returns the right branch code' do expect(bic.branch_code).to eq 'XXX' end [8, 11].each do |len| context 'x' * len do it 'has a valid length' do expect(::Bank::BIC.new('x' * len).valid_length?).to be_truthy end end end 1.upto(20) do |len| if len != 8 && len != 11 context 'x' * len do it 'has a valid length' do expect(::Bank::BIC.new('x' * len).valid_length?).to be_falsey end end end end %w(UCJAES2MXXX ABAGATWWXXX UCJAES2MXXX).each do |code| context code do it 'has a valid format' do expect(::Bank::BIC.new(code).valid_format?).to be_truthy end end end [ '12341234' ].each do |code| context code do it 'has an invalid format' do expect(::Bank::BIC.new(code).valid_format?).to be_falsey end end end end
true
aab1cb21804065a7a650c089c0811a1bbbfb3e67
Ruby
joviane/streaming
/app/models/fila.rb
UTF-8
335
2.734375
3
[]
no_license
require 'observer' class Fila include Singleton def initialize @observers = [] end def notifica(noticia) notify_observers(noticia) end def notify_observers(noticia) @observers.each do |observer| observer.update(noticia) end end def add_observer(observer) @observers << observer end end
true
fbc910e482b40779309a51ba909c38a9eef14d8b
Ruby
little-chi-mai/seic43-homework
/Priyanka Patel/week_4/accounts/main.rb
UTF-8
3,915
2.609375
3
[]
no_license
require 'sinatra' require 'sinatra/reloader' require 'active_record' require 'sqlite3' require 'pry' # Rails will do all this for you automatically: ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => 'database.sqlite3' ) # Optional bonus: ActiveRecord::Base.logger = Logger.new(STDERR) # Model class Account < ActiveRecord::Base belongs_to :customer end class Customer < ActiveRecord::Base has_many :accounts end get '/' do erb :home #:layout => :home //to direct layout to home.erb end #INDEX get '/customers' do @customers = Customer.all erb :customers_index end #NEW get '/customers/new' do erb :customers_new end #CREATE post '/customers' do customer = Customer.new customer.first_name = params[:first_name] customer.last_name = params[:last_name] customer.gender = params[:gender] customer.contact_detail = params[:contact_detail] customer.email = params[:email] customer.address = params[:address] customer.save redirect to("/customers") end #SHOW get '/customers/:id' do @customer = Customer.find params[:id] erb :customers_show end #EDIT get '/customers/:id/edit' do @customer = Customer.find params[:id] erb :customers_edit end #UPDATE post '/customers/:id' do customer = Customer.find params[:id] customer.first_name = params[:first_name] customer.last_name = params[:last_name] customer.gender = params[:gender] customer.contact_detail = params[:contact_detail] customer.email = params[:email] customer.address = params[:address] customer.save redirect to("/customers/#{ params[:id] }") end #DELETE get '/customers/:id/delete' do customer = Customer.find params[:id] accounts = Account.where(["customer_id = ?", params[:id]]) accounts.destroy_all customer.destroy redirect to('/customers') end ####################################################################################################### #ACCOUNTS# #Get all accounts Index of customer get '/accounts' do @accounts = Account.all erb :accounts_index end #NEW ACCOUNT get '/customers/:id/accounts/new' do @customer_id = params[:id]; erb :accounts_new end #CREATE ACCOUNT INSIDE CUSTOMER post '/customers/:id/accounts' do account = Account.new account.customer_id = params[:id] account.account_type = params[:account_type] account.balance = params[:balance] account.account_status = params[:account_status] account.save redirect to("/customers/#{account.customer_id}/accounts") end #SHOW ALL ACCOUNTS OF SELECTED CUSTOMER get '/customers/:id/accounts' do @accounts = Account.where(["customer_id = ?", params[:id]]) erb :accounts_index end #SHOW PARTICULAR ACCOUNT DETAIL OF SELECTED CUSTOMER get '/customers/:id/accounts/:account_number' do @account = Account.find params[:account_number] @customer = Customer.find @account.customer_id erb :accounts_show end #CREATE NEW ACCOUNT post '/accounts/accounts_number' do account = Account.new account.customer_id = params[:id] account.account_type = params[:account_type] account.balance = params[:balance] account.account_status = params[:account_status] account.save redirect to("/accounts/") end #EDIT ACCOUNTS DETAILS get '/customers/:id/accounts/:account_number/edit' do @account = Account.find params[:account_number] erb :accounts_edit end #UPDATE EDITED DETAILS post '/customers/:id/accounts/:account_number' do account = Account.find params[:account_number] account.account_type = params[:account_type] account.balance = params[:balance] account.account_status = params[:account_status] account.save redirect to("customers/#{ account.customer_id }/accounts/#{ account.account_number }") end #DELETE ACCOUNT get '/customers/:id/accounts/:account_number/delete' do account = Account.where(["account_number = ?", params[:account_number]]) account.destroy_all redirect to("/customers/#{params[:id]}/accounts") end
true
bba400b93fcf949138f53a6c5e17972f9e93c954
Ruby
pjmorse/mbta-api
/lib/mbta/mode.rb
UTF-8
361
2.734375
3
[ "MIT" ]
permissive
module Mbta class Mode attr_accessor :route_type, :mode_name, :routes def initialize(data_hash) @raw_data = data_hash @route_type = data_hash["route_type"] @mode_name = data_hash["mode_name"] @routes = data_hash["route"] end def show_routes @routes.map { |route| Mbta::Route.new(route) } end end end
true
454619a6e807f7502507c29af49315d16eb2c1de
Ruby
ondreian/Olib
/lib/Olib/combat/metadata.rb
UTF-8
436
2.671875
3
[]
no_license
class Creatures module Metadata @repo = JSON.parse File.read File.join(__dir__, "creatures.json") def self.put(name:, level:, tags: []) @repo[name.downcase] = {name: name, level: level, tags: tags} end def self.get(name) @repo.fetch(name.downcase) do {name: name, level: Char.level, tags: []} end end def self.repo() @repo.values.map {|creature| OpenStruct.new(creature)} end end end
true
84353012a6ebdb257aeffa16102eaa36467c181e
Ruby
mmanousos/ruby-small-problems
/challenges/advanced1/02_pythagorean_triplet/triplet.rb
UTF-8
714
3.609375
4
[]
no_license
class Triplet attr_reader :numbers def self.where(min_factor:1, max_factor:, sum:nil) triplets = create_triplet_objects(min_factor, max_factor) if sum triplets.select { |trio| trio.pythagorean? && trio.sum == sum } else triplets.select { |trio| trio.pythagorean? } end end def self.create_triplet_objects(min, max) [*min..max].combination(3).to_a.map { |trio| self.new(trio) } end def initialize(val1, val2=nil, val3=nil) @numbers = val1.class == Array ? val1 : [val1, val2, val3] end def sum @numbers.sum end def product @numbers.reduce(&:*) end def pythagorean? (@numbers[0] ** 2) + (@numbers[1] ** 2) == @numbers[2] ** 2 end end
true
f5f8e62de25c70d8923961734a39f68fa05e92a5
Ruby
ianderse/roguelike
/lib/fov.rb
UTF-8
7,560
3.125
3
[]
no_license
#Shamelessly copied from: http://www.roguebasin.com/index.php?title=Ruby_precise_permissive_FOV_implementation #Because math module PermissiveFieldOfView # Determines which co-ordinates on a 2D grid are visible # from a particular co-ordinate. # start_x, start_y: center of view # radius: how far field of view extends def do_fov(start_x, start_y, radius) @start_x, @start_y = start_x, start_y @radius_sq = radius * radius # We always see the center light @start_x, @start_y # Restrict scan dimensions to map borders and within the radius min_extent_x = [@start_x, radius].min max_extent_x = [@width - @start_x - 1, radius].min min_extent_y = [@start_y, radius].min max_extent_y = [@height - @start_y - 1, radius].min # Check quadrants: NE, SE, SW, NW check_quadrant 1, 1, max_extent_x, max_extent_y check_quadrant 1, -1, max_extent_x, min_extent_y check_quadrant -1, -1, min_extent_x, min_extent_y check_quadrant -1, 1, min_extent_x, max_extent_y end private # Represents a line (duh) class Line < Struct.new(:xi, :yi, :xf, :yf) # Macros to make slope comparisons clearer {:below => '>', :below_or_collinear => '>=', :above => '<', :above_or_collinear => '<=', :collinear => '=='}.each do |name, fn| eval "def #{name.to_s}?(x, y) relative_slope(x, y) #{fn} 0 end" end def dx; xf - xi end def dy; yf - yi end def line_collinear?(line) collinear?(line.xi, line.yi) and collinear?(line.xf, line.yf) end def relative_slope(x, y) (dy * (xf - x)) - (dx * (yf - y)) end end class ViewBump < Struct.new(:x, :y, :parent) def deep_copy ViewBump.new(x, y, parent.nil? ? nil : parent.deep_copy) end end class View < Struct.new(:shallow_line, :steep_line) attr_accessor :shallow_bump, :steep_bump def deep_copy copy = View.new(shallow_line.dup, steep_line.dup) copy.shallow_bump = shallow_bump.nil? ? nil : shallow_bump.deep_copy copy.steep_bump = steep_bump.nil? ? nil : steep_bump.deep_copy return copy end end # Check a quadrant of the FOV field for visible tiles def check_quadrant(dx, dy, extent_x, extent_y) active_views = [] shallow_line = Line.new(0, 1, extent_x, 0) steep_line = Line.new(1, 0, 0, extent_y) active_views << View.new(shallow_line, steep_line) view_index = 0 # Visit the tiles diagonally and going outwards i, max_i = 1, extent_x + extent_y while i != max_i + 1 and active_views.size > 0 start_j = [0, i - extent_x].max max_j = [i, extent_y].min j = start_j while j != max_j + 1 and view_index < active_views.size x, y = i - j, j visit_coord x, y, dx, dy, view_index, active_views j += 1 end i += 1 end end def visit_coord(x, y, dx, dy, view_index, active_views) # The top left and bottom right corners of the current coordinate top_left, bottom_right = [x, y + 1], [x + 1, y] while view_index < active_views.size and active_views[view_index].steep_line.below_or_collinear?(*bottom_right) # Co-ord is above the current view and can be ignored (steeper fields may need it though) view_index += 1 end if view_index == active_views.size or active_views[view_index].shallow_line.above_or_collinear?(*top_left) # Either current co-ord is above all the fields, or it is below all the fields return end # Current co-ord must be between the steep and shallow lines of the current view # The real quadrant co-ordinates: real_x, real_y = x * dx, y * dy coord = [@start_x + real_x, @start_y + real_y] light *coord # Don't go beyond circular radius specified #if (real_x * real_x + real_y * real_y) > @radius_sq # active_views.delete_at(view_index) # return #end # If this co-ord does not block sight, it has no effect on the view return unless blocked?(*coord) view = active_views[view_index] if view.shallow_line.above?(*bottom_right) and view.steep_line.below?(*top_left) # Co-ord is intersected by both lines in current view, and is completely blocked active_views.delete(view) elsif view.shallow_line.above?(*bottom_right) # Co-ord is intersected by shallow line; raise the line add_shallow_bump top_left[0], top_left[1], view check_view active_views, view_index elsif view.steep_line.below?(*top_left) # Co-ord is intersected by steep line; lower the line add_steep_bump bottom_right[0], bottom_right[1], view check_view active_views, view_index else # Co-ord is completely between the two lines of the current view. Split the # current view into two views above and below the current co-ord. shallow_view_index, steep_view_index = view_index, view_index += 1 active_views.insert(shallow_view_index, active_views[shallow_view_index].deep_copy) add_steep_bump bottom_right[0], bottom_right[1], active_views[shallow_view_index] unless check_view(active_views, shallow_view_index) view_index -= 1 steep_view_index -= 1 end add_shallow_bump top_left[0], top_left[1], active_views[steep_view_index] check_view active_views, steep_view_index end end def add_shallow_bump(x, y, view) view.shallow_line.xf = x view.shallow_line.yf = y view.shallow_bump = ViewBump.new(x, y, view.shallow_bump) cur_bump = view.steep_bump while not cur_bump.nil? if view.shallow_line.above?(cur_bump.x, cur_bump.y) view.shallow_line.xi = cur_bump.x view.shallow_line.yi = cur_bump.y end cur_bump = cur_bump.parent end end def add_steep_bump(x, y, view) view.steep_line.xf = x view.steep_line.yf = y view.steep_bump = ViewBump.new(x, y, view.steep_bump) cur_bump = view.shallow_bump while not cur_bump.nil? if view.steep_line.below?(cur_bump.x, cur_bump.y) view.steep_line.xi = cur_bump.x view.steep_line.yi = cur_bump.y end cur_bump = cur_bump.parent end end # Removes the view in active_views at index view_index if: # * The two lines are collinear # * The lines pass through either extremity def check_view(active_views, view_index) shallow_line = active_views[view_index].shallow_line steep_line = active_views[view_index].steep_line if shallow_line.line_collinear?(steep_line) and (shallow_line.collinear?(0, 1) or shallow_line.collinear?(1, 0)) active_views.delete_at view_index return false end return true end end
true
f186c6ca868779d672a8929df826dc9f847c96d6
Ruby
EulaConstellar/greentusk
/app/actions.rb
UTF-8
3,721
2.515625
3
[]
no_license
## # Copyright 2012 Evernote Corporation. All rights reserved. ## require 'shotgun' require 'sinatra' require 'byebug' require_relative "../evernote_config" require_relative 'helpers' before "/editor/?" do redirect '/' unless session[:access_token] end get '/editor/?' do erb :'editor' end ## # Index page ## get '/' do if session[:access_token] redirect '/editor' else erb :index, layout: false end end ## # Reset the session ## get '/reset/?' do session.clear redirect '/' end ## # Obtain temporary credentials ## get '/requesttoken' do callback_url = request.url.chomp("requesttoken").concat("callback") begin session[:request_token] = client.request_token(:oauth_callback => callback_url) redirect '/authorize' rescue => e @last_error = "Error obtaining temporary credentials: #{e.message}" erb :'errors/oauth_error' end end ## # Redirect the user to Evernote for authoriation ## get '/authorize' do if session[:request_token] redirect session[:request_token].authorize_url else # You shouldn't be invoking this if you don't have a request token @last_error = "Request token not set." erb :'errors/oauth_error' end end ## # Receive callback from the Evernote authorization page ## get '/callback' do unless params['oauth_verifier'] || session['request_token'] @last_error = "Content owner did not authorize the temporary credentials" halt erb :'errors/oauth_error' end session[:oauth_verifier] = params['oauth_verifier'] begin session[:access_token] = session[:request_token].get_access_token(:oauth_verifier => session[:oauth_verifier]) redirect '/editor' rescue @last_error = 'Error extracting access token' erb :'errors/oauth_error' end end get '/notes' do check_login notebook_guid = params['notebook_guid'] if tags = params['tags'] tags = tags.split(',') end @notes = notes(notebook_guid: notebook_guid, tags: tags) erb :'/notes/index' end get '/notes/new' do check_login erb :'notes/new' end get '/notes/:guid' do check_login if @note = note(params[:guid]) # if(request.xhr?) content_type :json return strip_content(@note.content).to_json # end # erb :'notes/show' else erb :'errors/no_note_error' end end get '/notes/:guid/edit' do check_login @note = note(params[:guid]) erb :'notes/edit' end post '/notes' do new_note = Evernote::EDAM::Type::Note.new new_note.title = params[:title] new_note.notebookGuid = params[:notebook_guid] new_note.tagNames = ["markdown"] new_note.content = format_content(params[:content]) created_note = note_store.createNote(auth_token, new_note) unless (request.xhr?) redirect '/editor' end # TODO: error message handling # content_type :json hash = {guid: created_note.guid, title: created_note.title, notebook_guid: created_note.notebookGuid} hash.to_json end put '/notes' do # TODO: check if note exists first edited_note = Evernote::EDAM::Type::Note.new edited_note.guid = params[:guid] edited_note.content = format_content(params[:content]) edited_note.title = params[:title] # @edited_note.notebookGuid = params[:notebook_guid] # edit_note.tagNames = [params[:tags]] updated_note = note_store.updateNote(auth_token, edited_note) unless (request.xhr?) redirect '/editor' end hash = {guid: updated_note.guid, title: updated_note.title, notebook_guid: updated_note.notebookGuid} hash.to_json end get '/html/:title/?:base64?' do check_login if params[:base64] send_file(create_file(params[:title], params[:base64]), disposition: "attachment", filename: html_filename(params[:title])) else redirect '/editor' end end
true
319521563a498f4d844f8389e8e7fa8cc67c50f1
Ruby
afide26/studio_game
/lib/berserk_player_spec.rb
UTF-8
644
3.015625
3
[]
no_license
require_relative "berserk_player" describe "BerserkPlayer" do before do initial_health = 50 @player = BerserkPlayer.new("berserker", @initial_health) end it "does not go berserk when wooted upto 5 times" do 1.upto(5) {@player.w00t} expect(@player.berserk?).to be_falsey end it "goes berserk when w00ted more than 5 times" do 1.upto(6) {@player.w00t} expect(@player.berserk?).to be_truthy end it "gets w00ted instead of blammed when it's gone berserk'" do 1.upto(6) {@player.w00t} 1.upto(2) {@player.blam} expect(@player.health).to be(@initial_health.to_i+(8*15)) end end
true
a07c45e2c2d829c2b33facb381abc648efc6f145
Ruby
gabriel376/exercism
/ruby/boutique-inventory/boutique_inventory.rb
UTF-8
503
3.3125
3
[]
no_license
class BoutiqueInventory def initialize(items) @items = items end def item_names @items.map{|item| item[:name]}.sort end def cheap @items.filter{|item| item[:price] < 30} end def out_of_stock @items.filter{|item| item[:quantity_by_size].empty?} end def stock_for_item(name) @items.find{|item| item[:name] == name}[:quantity_by_size] end def total_stock @items.map{|item| item[:quantity_by_size].values.sum}.sum end private attr_reader :items end
true
56ab2c5470463b165c57b76166d7ee7ff5effeb5
Ruby
Miel2000/pyramide
/exo_07_c.rb
UTF-8
386
3.171875
3
[]
no_license
user_name = gets.chomp puts user_name # a) dit bonjour, prend l'information qui suit et la stock dans user_name puis la renvoi dans le terminal # b) dit bonjour, demande l'information avec un >, prend l'information et la stock dans user_name puis la renvoi dans le terminal # c) dit pas bonjour (...), prends la prochaine information ecrite par l'utilisateur et la stock dans user_name
true
42eec7056f6bd8c82d4fd7864f892b0f34bf38d4
Ruby
sometimesfood/ldumbd
/db/migrations/005_set_uid_and_gid_start_value.rb
UTF-8
1,838
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def set_min_max_value_commands(dbtype, min, max) case dbtype when :postgres options = "start #{min} restart #{min} minvalue #{min} maxvalue #{max}" ["alter sequence users_id_seq #{options};", "alter sequence groups_id_seq #{options};"] when :sqlite id = min-1 name = '#dummyname#' dir = '#dummydir#' ["insert into users(id, name, homedir) values(#{id}, '#{name}', '#{dir}');", "delete from users where id = #{id};", "insert into groups(id, name) values(#{id}, '#{name}');", "delete from groups where id = #{id};"] when :mysql ["alter table users auto_increment = #{min};", "alter table groups auto_increment = #{min};"] else raise Sequel::Error, "database type '#{dbtype}' not supported" end end def reset_min_max_value_commands(dbtype, next_uid, next_gid) case dbtype when :postgres ["alter sequence users_id_seq start #{next_uid} restart #{next_uid} \ no minvalue no maxvalue;", "alter sequence groups_id_seq start #{next_gid} restart #{next_gid} \ no minvalue no maxvalue;"] when :sqlite ["delete from sqlite_sequence where name = 'users';", "delete from sqlite_sequence where name = 'groups';"] when :mysql ["alter table users auto_increment = #{next_uid};", "alter table groups auto_increment = #{next_gid};"] else raise Sequel::Error, "database type '#{dbtype}' not supported" end end Sequel.migration do dbtype = DB.database_type min_id = 100_000 max_id = 200_000 up do set_min_max_value_commands(dbtype, min_id, max_id).each do |command| run command end end down do next_uid = self[:users].max(:id).to_i + 1 next_gid = self[:groups].max(:id).to_i + 1 reset_min_max_value_commands(dbtype, next_uid, next_gid).each do |command| run command end end end
true
004e179ef80deed191bae13ed29fac85d65f9907
Ruby
marklombardinelson/user-input-statistics
/hello_world.rb
UTF-8
498
4.4375
4
[]
no_license
# keep track of to numbers , one is total, and the other is count. both are now 0. total = 0 count = 0 # ask for a number. loop do puts "give me a number" input = gets.chomp # If that nuber is blank, stop asking for numbers. if input == "" break end # add that number to total total += input.to_f # add 1 to count count += 1 # go back and ask for another number end # if done, print total and average. puts "The total is #{total}" puts "The average is #{total /= count}"
true
eb1f466c1738c60bd00cf5a3e7b4c22d9c0110ba
Ruby
possumtale/ruby-challenges
/hello_world_spec.rb
UTF-8
698
2.765625
3
[]
no_license
# we need to tell Rack (remember what Rack is?) that we are just testing. # normally this is 'development' ENV['RACK_ENV'] = 'test' # look in this directory! $:.unshift File.join(File.dirname(__FILE__)) require 'index' # <-- your sinatra app # require testing gems require 'rspec' require 'rack/test' describe 'Our Hello World App' do include Rack::Test::Methods # Rack::Test looks for this app variable def app Sinatra::Application end it "responds with success" do get '/' # This is an HTTP status - we'll talk about these later! expect(last_response).to be_ok end it "says hello" do get '/' expect(last_response.body).to eq('Hello World') end end
true
e1449b06d715729f75e067f48ff733b48d027338
Ruby
Gues1211/rack-responses-lab-v-000
/app/application.rb
UTF-8
259
2.828125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Application def call(env) resp = Rack::Response.new time = Time.now.hour # time2 = Time.new(2017, 10, 16, 12, 00, 00) if time < 12 resp.write "Morning" else resp.write "Afternoon" end resp.finish end end
true
e98de1064549198be87a7dff50b5fbc8a93205ff
Ruby
joshuawootonn/caesar_cipher
/caesar_cipher.rb
UTF-8
574
2.8125
3
[]
no_license
require 'sinatra' #require 'sinatra/reloader' if development? get '/' do erb :index end get '/submit' do post = params[:post] @word = params['word'] @shift = params['shift'] @shifted_word = caesar_cipher(@word,@shift.to_i) erb :index end def caesar_cipher( words , shift ) encoded_msg = "" words.each_char do |char| num_ciphered = char.ord + shift unless num_ciphered > 122 char_ciphered = num_ciphered.chr else char_ciphered = (num_ciphered-26).chr end encoded_msg += char_ciphered end encoded_msg end
true
54f0deab5ef1ae673c7a30d4f10f870a7d696a13
Ruby
ericfirth/app_academy_projects
/checkers/player.rb
UTF-8
910
3.75
4
[]
no_license
class HumanPlayer attr_reader :color def initialize(color) @color = color end def play_turn(board) board.display puts "It's your turn #{color.to_s.capitalize}" from = get_input("Which Piece do you want to move?") to = to_input("Where to? If its multiple moves, seperate them by a space") board[*from].perform_moves(to) rescue InvalidMoveError => e puts "Error: #{e.message}" retry end end def get_input(prompt) puts prompt gets.chomp.split(',').map {|coord_s| Integer(coord_s) } end def to_input(prompt) puts prompt answer = gets.chomp if answer.length == 3 [answer.split(',').map {|coord_s| Integer(coord_s) }] else answers = answer.split(' ') [].tap do |final| answers.each do |answer| final << answer.split(',').map {|coord_s| Integer(coord_s) } end end end end
true
e685d1588d05fef42275edf774af8b9ee7b9e055
Ruby
dmalyuta/config-public
/.my_scripts/tmux/tmux-list-words
UTF-8
2,663
2.890625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # frozen_string_literal: true # Copied from # https://github.com/junegunn/dotfiles/blob/master/bin/tmuxwords.rb require 'optparse' require 'set' require 'English' # NOTE(infokiller): splitting by \W will also split by dashes and dots which are # often part of valid identifiers, so we also do splits without them. WORD_SPLIT_REGEX = /[\/\\!@#$%^&*()\[\]|,?{}]/ opts = { panes: :visible } op = OptionParser.new do |o| o.banner = "usage: #{$PROGRAM_NAME} [OPTIONS]" o.separator '' o.on('-A', '--all', 'All panes') { |_v| opts[:panes] = :all } o.on('-a', '--all-but-current', 'All panes but the active one') { |_v| opts[:panes] = :others } o.on('-s NUM', '--scroll NUM', 'Scroll back') { |v| opts[:scroll] = v } o.on('-p STR', '--prefix STR', 'Prefix') { |v| opts[:prefix] = v } o.on('-m NUM', '--min NUM', 'Minimum length') { |v| opts[:min] = v.to_i } o.separator '' o.on('-h', '--help', 'Show this message') do puts o exit end o.separator '' end begin op.parse! rescue OptionParser::InvalidOption => x warn x warn op exit 1 end def list_panes(cond) command = %q(tmux list-panes -a -F '#{window_active}#{pane_active} #{pane_id}') `#{command}`.split($INPUT_RECORD_SEPARATOR).map(&:split).select do |pair| status = pair.first case cond when :all then true when :visible then status =~ /^1/ when :others then status !~ /^11/ end end.map(&:last) end system 'tmux capture-pane -p &> /dev/null' if $CHILD_STATUS.exitstatus.zero? def capture_pane(pane_id, scroll) `tmux capture-pane #{"-S -#{scroll}" if scroll} -t #{pane_id} -p` end else def capture_pane(pane_id, scroll) `tmux capture-pane #{"-S -#{scroll}" if scroll} -t #{pane_id} && tmux show-buffer && tmux delete-buffer` end end def tokenize(str, prefix, min) set = Set.new set.merge(chunks = str.split(/\s+/)) set.merge(_strip_chunks = chunks.map { |t| t.gsub(/^\W+|\W+$/, '') }) set.merge(_lines = str.split($INPUT_RECORD_SEPARATOR).map(&:strip)) set.merge(_words = str.gsub(WORD_SPLIT_REGEX, ' ').split(/\s+/)) set.merge(_words_granular = str.gsub(/\W/, ' ').split(/\s+/)) prefix &&= /^#{Regexp.escape prefix}/ if prefix && min set.select { |t| t =~ prefix && t.length >= min } elsif prefix set.select { |t| t =~ prefix } elsif min set.select { |t| t.length >= min } else set end rescue StandardError [] end tokens = list_panes(opts[:panes]).inject(Set.new) do |set, pane_id| tokens = tokenize(capture_pane(pane_id, opts[:scroll]), opts[:prefix], opts[:min]) set.merge tokens end puts tokens.to_a
true
201f16e9659fb9330a9f582d3750c8fef2492990
Ruby
crupar/secretsanta
/secretsanta.rb
UTF-8
1,324
3.234375
3
[]
no_license
require 'yaml' class Person attr_accessor :name, :household, :santa def initialize(attrs) self.name = attrs["name"] self.household = attrs["household"] self.santa = attrs["santa"] end def can_be_santa_of?(other) @household != other.household end def already_santa_of?(other) @name != other.person.santa.name end def self.santaize(filename) people_config = YAML.load_file(filename) people = people_config['people'].map do |attrs| Person.new(attrs) end santas = people.dup people.each do |person| person.santa = santas.delete_at(rand(santas.size)) end people.each do |person| unless person.santa.can_be_santa_of? person candidates = people.select do |p| p.santa.can_be_santa_of?(person) && person.santa.can_be_santa_of?(p) end raise if candidates.empty? other = candidates[rand(candidates.size)] temp = person.santa person.santa = other.santa other.santa = temp finished = false end end puts "Secret Santa List:" people.each do |person| puts "#{person.name} (of clan #{person.household}) is secret santa for #{person.santa.name} (of clan #{person.santa.household})." end end end Person.santaize('data/people.yml') $end
true
13734ace7c0cac7112db4d99f99d2fdbbde57bbc
Ruby
apoorvparijat/ruby-example-code
/profiler.rb
UTF-8
282
3.578125
4
[]
no_license
require 'profile' class Peter def initialize amt @value = amt end def rob amt @value -= amt end end class Paul def initialize @value = 0 end def pay amt @value += amt amt end end peter = Peter.new 1000 paul = Paul.new 1000.times do paul.pay(peter.rob 10) end
true
29d1cca4d6c50b2d898a5c5c762b0906fef1f2e6
Ruby
dan5/rec_game
/app/models/user.rb
UTF-8
1,167
2.578125
3
[]
no_license
class User < ActiveRecord::Base class UnAuthorized < Exception ; end attr_accessible :description, :mail, :url, :name, :summary, :categorys_text, :teams_text has_many :results, dependent: :destroy, :order => ['date desc', 'created_at desc'] validates :name, :presence => true, :length => { :maximum => 32} validates :mail, :length => { :maximum => 128} validates :summary, :length => { :maximum => 140} validates :description, :length => { :maximum => 2048} validates :categorys_text, :presence => true, :length => { :maximum => 512} validates :teams_text, :presence => true, :length => { :maximum => 512} def categorys categorys_text.split end def teams(category = nil) a = teams_text.split if category hash = {} a.each do |e| if e =~ /([^\s]+)::([^\s]+)/ hash[$1] ||= [] hash[$1] << $2 end end a = hash[category] if hash[category] end a.map {|e| e.sub(/[^\s]+::/, '') } end def category_results(category) if category.nil? or category == 'ALL' results else results.where(:category => category) end end end
true
531076f1b6b3b792239d471be647fdadb6fd4f74
Ruby
wwilco/week08
/d01/server.rb
UTF-8
1,423
2.953125
3
[]
no_license
require 'pry' require 'sinatra' require 'json' require 'httparty' get '/' do url = "http://api.randomuser.me/" response = HTTParty.get(url) person = response["results"][0]["user"] person_json = { first: person["name"]["first"], last: person["name"]["last"], email: person["email"], username: person["username"] } content_type :json person_json.to_json end # require 'sinatra' # require 'httparty' # require 'pry' # # get '/' do # url = "http://api.randomuser.me/" # response = HTTParty.get(url) # console.log(response) # person = response["results"][0]["user"] #could also use ["results"].first # # person_json = { # first: person["name"]["first"], # last: person["name"]["last"], # email: person["email"], # username: person["username"] # } # content_type :json # person_json.to_json # # end # binding.pry # #your first API! # require 'pry' # require 'sinatra' # require 'json' #depends on the sinatra server # # get '/' do # content_type :json #lets the computer know what type of file you'll be working with # data = {msg: "hello worldz"} # data.to_json # end # # get '/top_theatres' do # content_type :json # data = ["Ace Ventura", "Dumb and Dumber", "The Mask"] # data.to_json # end # # get '/top_dvd' do # content_type :json # data = { "results"=> [ {"Jurassic Park"=> 9}, {"Superman"=> 2}, {"Inception"=> 8} ]} # data.to_json # end
true
116d08e6f9280b21c660f7bb6f5207a147c15488
Ruby
bbuchalter/tictactoe_core
/test/tictactoe/board_test.rb
UTF-8
3,253
3.109375
3
[]
no_license
require_relative '../test_helper' require 'tictactoe/board' class BoardTest < Minitest::Test def test_new_board_is_empty board = new_board assert_board_empty(board) end def test_position_index board = new_board assert_equal 1, board.at(1).position assert_equal 9, board.at(9).position end def test_new_move_for board = new_board assert board.at(1).empty? board.new_move_for(1, 'X') assert !board.at(1).empty? end def test_duplicate_moves board = new_board board.new_move_for(1, 'X') assert_raises(::TicTacToe::Board::PositionTaken) do board.new_move_for(1, 'X') end end def test_invalid_moves board = new_board assert_raises(::TicTacToe::Board::InvalidPosition) do board.new_move_for(10, 'X') end end def test_board_has_all_tuples board = new_board assert_board_has_all_tuples(board) end def test_corners board = new_board corners = board.corners assert_equal 4, corners.length assert_equal 1, corners[0].position assert_equal 3, corners[1].position assert_equal 7, corners[2].position assert_equal 9, corners[3].position end def test_sides board = new_board sides = board.sides assert_equal 4, sides.length assert_equal 2, sides[0].position assert_equal 4, sides[1].position assert_equal 6, sides[2].position assert_equal 8, sides[3].position end private include ::TicTacToe::ObjectCreationMethods def assert_board_empty(board) assert_equal 9, board.length board.each_with_index do |position, i| assert_equal i + 1, position.at assert_nil position.player end end def assert_board_has_all_tuples(board) assert_board_has_all_row_tuples(board) assert_board_has_all_column_tuples(board) assert_board_has_all_diagonal_tuples(board) assert_equal 8, board.tuples.length end def assert_board_has_all_diagonal_tuples(board) assert_equal board.at(1), board.tuples[6][0] assert_equal board.at(5), board.tuples[6][1] assert_equal board.at(9), board.tuples[6][2] assert_equal board.at(3), board.tuples[7][0] assert_equal board.at(5), board.tuples[7][1] assert_equal board.at(7), board.tuples[7][2] end def assert_board_has_all_column_tuples(board) assert_equal board.at(1), board.tuples[3][0] assert_equal board.at(4), board.tuples[3][1] assert_equal board.at(7), board.tuples[3][2] assert_equal board.at(2), board.tuples[4][0] assert_equal board.at(5), board.tuples[4][1] assert_equal board.at(8), board.tuples[4][2] assert_equal board.at(3), board.tuples[5][0] assert_equal board.at(6), board.tuples[5][1] assert_equal board.at(9), board.tuples[5][2] end def assert_board_has_all_row_tuples(board) assert_equal board.at(1), board.tuples[0][0] assert_equal board.at(2), board.tuples[0][1] assert_equal board.at(3), board.tuples[0][2] assert_equal board.at(4), board.tuples[1][0] assert_equal board.at(5), board.tuples[1][1] assert_equal board.at(6), board.tuples[1][2] assert_equal board.at(7), board.tuples[2][0] assert_equal board.at(8), board.tuples[2][1] assert_equal board.at(9), board.tuples[2][2] end end
true
0b1a73a19bafeaf81cd603019551fa129ba5f171
Ruby
WhatsARanjit/controlrepo_gem
/lib/controlrepo/node.rb
UTF-8
857
2.703125
3
[]
no_license
require 'controlrepo' class Controlrepo class Node @@all = [] attr_accessor :name attr_accessor :beaker_node attr_accessor :fact_set def initialize(name) @name = name @beaker_node = nil # If we can't find the factset it will fail, so just catch that error and ignore it begin @fact_set = Controlrepo.facts[(Controlrepo.facts_files.index{|facts_file| File.basename(facts_file,'.json') == name})] rescue TypeError @fact_set = nil end @@all << self end def self.find(node_name) @@all.each do |node| if node_name.is_a?(Controlrepo::Node) if node = node_name return node end elsif node.name == node_name return node end end nil end def self.all @@all end end end
true
ba6ae7fd0cdc69872bcb71b4d78b9d044d47320d
Ruby
pyrocat101/hackerrank
/discrete-math/minimum-draws.rb
UTF-8
47
3.09375
3
[ "MIT" ]
permissive
Integer(gets).times { puts Integer(gets) + 1 }
true
15082003df5f56f48a435ef1a447b6d448be006b
Ruby
mbj/substation
/lib/substation/utils.rb
UTF-8
1,733
3.140625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Substation # A collection of utility methods module Utils # Get the constant for the given FQN # # @param [#to_s] name # the FQN denoting a constant # # @return [Class, nil] # # @api private def self.const_get(name) list = name.to_s.split("::") list.shift if list.first.empty? obj = Object list.each do |const| # This is required because const_get tries to look for constants in the # ancestor chain, but we only want constants that are HERE obj = if obj.const_defined?(const) obj.const_get(const) else obj.const_missing(const) end end obj end # Converts string keys into symbol keys # # @param [Hash<#to_sym, Object>] hash # a hash with keys that respond to `#to_sym` # # @return [Hash<Symbol, Object>] # a hash with symbol keys # # @api private def self.symbolize_keys(hash) hash.each_with_object({}) { |(key, value), normalized_hash| normalized_value = value.is_a?(Hash) ? symbolize_keys(value) : value normalized_hash[key.to_sym] = normalized_value } end # Coerce the given +handler+ object # # @param [Symbol, String, Proc] handler # a name denoting a const that responds to `#call(object)`, or a proc # # @return [Class, Proc] # the callable action handler # # @api private def self.coerce_callable(handler) case handler when Symbol, String Utils.const_get(handler) when Proc, Class, Chain handler else raise(ArgumentError) end end end # module Utils end # module Substation
true
c86568fde5aaa3eeb71adb524b5ce3a6837353f2
Ruby
jschoolcraft/urlagg
/vendor/plugins/typus/lib/support/array.rb
UTF-8
293
3.25
3
[ "MIT" ]
permissive
class Array #-- # Taken from http://snippets.dzone.com/posts/show/302 # # >> %W{ a b c }.to_hash_with( %W{ 1 2 3 } ) # => {"a"=>"1", "b"=>"2", "c"=>"3"} #++ def to_hash_with(other) Hash[ *(0...self.size()).inject([]) { |arr, ix| arr.push(self[ix], other[ix]) } ] end end
true
7ca63672adde2e19defcb9e9cdb72d2573cfa581
Ruby
dasstoni/algorithms
/linked_list2_iterative.rb
UTF-8
939
4.25
4
[]
no_license
class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node=nil) @value = value @next_node = next_node end end def print_values(list_node) if list_node print "#{list_node.value} --> " print_values(list_node.next_node) else print "nil\n" return end end # Store the current next node # Change the next node to equal previous # Set previous to list to store the values of the current loop # Set list to equal current so the loop will continue until it reaches nil # Return the value of list which is set to previous def reverse_list(list, previous=nil) while list current = list.next_node list.next_node = previous previous = list list = current end list = previous end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) print_values(node3) revlist = reverse_list(node3) print_values(revlist)
true
05b58f9ae90a775503a30c8ab034825417752112
Ruby
micaelbergeron/backend-coding-challenge
/app/engine/geo.rb
UTF-8
1,876
2.640625
3
[]
no_license
require 'engine' require 'model/geoname' include SinCity::Model module SinCity::Engine class GeoEngine < Base include SinCity::Engine @@defaults = { radius: 10000, distance_unit: 'km', result_count: 100, input_file: INPUT_FILE, } def initialize(**args) super(@@defaults.merge(args)) end def startup super() #NOTE: This is slow @redis.flushall if DB_FLUSH import_count = 0 if DB_LOAD TSV[INPUT_FILE].each do |row| geo = Geoname.from_a row.to_a #TODO: keybuilder geokey = build_key(geo) @redis.mapped_hmset geokey, geo.to_h @redis.sadd "city:names:#{geo.asciiname.downcase}", geokey @redis.geoadd "city:geopos", geo.longitude, geo.latitude, geokey import_count += 1 end end puts "Imported #{import_count} rows." end def pre_process(input) return SKIP unless input.latitude && input.longitude input end def process(input) byebug keys = @redis.georadius("city:geopos", input[:longitude], input[:latitude], @config[:radius], @config[:distance_unit], "WITHDIST", "COUNT", @config[:result_count]) keys end def post_process(input) Hash[ input.map {|k,v| [k.split(':')[1], v.to_f]} ] end private def build_key(geoname) "city:#{geoname.geonameid}" end end end if ENV['RACK_ENV'] == 'cli' engine = SinCity::Engine::GeoEngine.new engine.startup() puts "Awaiting request...\n" while STDIN.gets.chomp long, lat = $_.split(' ') puts "Searching for #{$_}..." puts engine.run(SinCity::Engine::Query.new(nil, long.to_i, lat.to_i)) end end
true
b76ff8ca8f582ba1688cde6cf2fe72ecda9e4fda
Ruby
ariel-alvear/desafios-arrays-primerasesion
/filtro_procesos.rb
UTF-8
366
3.015625
3
[]
no_license
def process_filter(file) data = open(file).readlines lines = data.count array = [] lines.times do |i| array << data[i].to_i end n = ARGV[0].to_i new_array = array.select{ |x| x > n} File.new("procesos_filtrados.data", "w") File.write('procesos_filtrados.data', new_array.join("\n")) end process_filter('procesos.data')
true
415360e4e841014e44bb00eafac3556599091bc9
Ruby
RocketRobC/exercism
/ruby/rail-fence-cipher/rail_fence_cipher_3.rb
UTF-8
1,408
3.09375
3
[]
no_license
class RailFenceCipher VERSION = 1 def self.encode(string, rails) new(string, rails).encode end def self.decode(string, rails) new(string, rails).decode end def encode puts sequence.inspect puts code_map(sequence).inspect cypher(string, code_map(sequence)) end def decode puts string puts sequence.inspect puts code_map(sequence).inspect puts code_map(sequence).invert.inspect cypher(string, code_map(sequence).invert) end private attr_reader :string, :rails, :length def initialize(string, rails) @string = string @rails = rails @length = @string.size end def cypher(string, mapped_sequence) mapped_sequence.sort.to_h.values.map { |value| string[value] }.join end def code_map(seq) (0...length).zip(seq).to_h end def sequence (0...rails).flat_map do |rail| (0...number_of_cycles).flat_map do |cycle_number| start_of_cycle = cycle_number * full_cycle if rail == 0 start_of_cycle elsif rail == half_cycle start_of_cycle + half_cycle else [start_of_cycle + rail, start_of_cycle + full_cycle - rail] end end end.select { |i| i < length } end def half_cycle rails - 1 end def full_cycle half_cycle > 0 ? half_cycle * 2 : 1 end def number_of_cycles (length.to_f / full_cycle).ceil end end
true
4ed18fcb0021af6156306ff01b39e8faa28d9cfe
Ruby
marcosfparreiras/10-days-of-statistics-hacker-rank
/app/src/d3t2_cards_of_the_same_suit.rb
UTF-8
1,765
3.890625
4
[]
no_license
############################### # Task: # You draw 2 cards from a standard 52-card deck without replacing them. # What is the probability that both cards are of the same suit? # # ANSWER by calculus # # P = ( (4)C(1) * (13)C(2) ) / (52)C(2) # => (4)C(1) => combination for 1 out of the 4 suits # => (13)C(2) => combination for 2 cards out the 13 available for the suit # => (52)C(2) => combination for 2 cards out the 52 available for the deck # # P = ( (4! / (1! * 3!)) * (13! / (2! / 11!)) ) / (52! / (2! * 50!)) # P = 12 / 51 = 4 / 17 (=~ 0.23529) # ############################### # ANSWER by code # 1 million samples for the experiment. # It was expected to get 4/17 (0.235) as probability # After running the experiment, we got the 0.235, what comproves the calculus def build_deck suits = %i[hearts clubs diamonds spades] suits.inject([]) { |deck, suit| deck + [suit] * 13 } end def pick_card_position(deck) rand(deck.size) end def format_number(number) number.to_s.chars.to_a.reverse.each_slice(3).map(&:join).join(',').reverse end puts 'Running experiment...' n = 2_000_000 favorable_outcomes = 0 n.times do |i| puts "Experiment #{format_number(i)}" if (i % 200_000).zero? deck = build_deck first_card_position = pick_card_position(deck) first_suit = deck.delete_at(first_card_position) second_card_position = pick_card_position(deck) second_suit = deck.delete_at(second_card_position) favorable_outcomes += 1 if first_suit == second_suit end probability = (favorable_outcomes / n.to_f).round(3) puts '' puts 'Answer Report:' puts "Number of favorable outcomes: #{favorable_outcomes}" puts "Number of samples: #{n}" puts "Probability as ratio: #{Rational(favorable_outcomes, n)}" puts "Probability as number: #{probability}"
true
80f27bbcb603a137ec002bca0844140f93c44c40
Ruby
Mia-J-Russell/LaunchSchool
/RB101/small_problems/easy_7/combine.rb
UTF-8
389
3.8125
4
[]
no_license
def interleave(array1, array2) # newarr = [] # counter = 0 # loop do # break if counter >= array1.size # newarr << array1[counter] # newarr << array2[counter] # counter += 1 # end # newarr #Further Exploration array1.zip(array2).flatten end puts interleave([1, 2, 3], ['a', 'b', 'c']) puts interleave([1, 2, 3], ['a', 'b', 'c']) == [1, 'a', 2, 'b', 3, 'c']
true
0de3f090cfd665a2206b0bd8073abfa3b3e6c7ef
Ruby
radu-constantin/small-problems
/reverseit1.rb
UTF-8
207
3.34375
3
[]
no_license
def reverse_sentence (string) string.split.reverse.join('') end puts reverse_sentence('') == '' puts reverse_sentence('Hello World') puts reverse_sentence('Reverse these words') == 'words these Reverse'
true
037324e79985183bb0c076ef2b6765d025e9c7bd
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/rna-transcription/461686df714848eaae495b4151020472.rb
UTF-8
366
3.203125
3
[]
no_license
class Complement def self.of_dna(dna) replace(dna) return dna.gsub("A","U").gsub("T","A") end def self.of_rna(rna) replace(rna) return rna.gsub("A","T").gsub("U","A") end def self.replace(str) for i in 0..str.length if str[i] == "C" str[i] = "G" elsif str[i] == "G" str[i]="C" end end end end
true
913661f25da81f47fa7dfdc1b0ac105b1f129422
Ruby
natevenn/enigma
/lib/encryptor.rb
UTF-8
993
3.359375
3
[]
no_license
require_relative 'number_generator' require_relative 'cipher' class Encryptor attr_reader :rotation, :message, :character_map def initialize(message, key = nil, date = nil) @message = message @rotation = NumberGenerator.new(key, date).rotation @character_map = Cipher.new.character_map end def encrypt encryption_index.map { |i| character_map[i] }.join end def index_message message.downcase.chars.map do |char| character_map.index(char) end end def rotation_multiplier index_message if index_message.length % 4 == 0 m = index_message.length / 4 rotation * m elsif index_message.length / 4 == 0 r = index_message.length % 4 rotation[0,r] else m = index_message.length / 4 r = index_message.length % 4 rotation * m + rotation[0,r] end end def encryption_index merge = rotation_multiplier.zip(index_message) merge.map do |nums| nums.reduce(:+) % 39 end end end
true
79eddb4b94b22e95a9cc876ad22b67ac42d3219f
Ruby
manageyp/grape_demo
/app/models/error_code.rb
UTF-8
943
2.75
3
[]
no_license
# -*- coding: utf-8 -*- class ErrorCode SUCCESS = '0000' CODES = { success: [SUCCESS, '成功'], invalid_parameters: ['1001', '参数不完整'], default_system_error: ['1002', '系统内部错误'], invalid_user_token: ['1003', '验证信息无效,请重新登录'], expired_user_token: ['1004', '验证信息过期,请重新登录'] } class << self def default_error CODES[:default_system_error] end def error_content(code) if CODES.has_key?(code) [false, CODES[code]] else [false, default_error] end end def error_words(code) if CODES.has_key?(code) CODES[code].last else default_error.last end end def error_value(code) if CODES.has_key?(code) CODES[code] else default_error end end end end
true
8986b32ec5b5ea407908ee63c1c324234b9e111c
Ruby
flyptkarsh/Cracking-The-Coding-Interview-Ruby-Solutions
/recursion_and_dynamic_programing/kadanes_algorithm.rb
UTF-8
1,337
4
4
[]
no_license
# frozen_string_literal: true # Dynamic Programming – Kadane’s Algorithm # Find the maximum max contiguous sub array # brute force # check every combination # too slow :( def max_subarray(arr) max_so_far = -1.0 / 0 # this is negative INFINITY max_ending_here = -1.0 / 0 # this is negative INFINITY arr.each do |i| max_ending_here = [i, max_ending_here + i].max max_so_far = [max_so_far, max_ending_here].max end max_so_far end arr = [1, -3, 2, 1, -1] max_subarray(arr) # slightly different Kadane's Algorithm def maximum_subarray_sum(array) max_ending_here = 0 max_so_far = 0 array.each do |ele| max_ending_here = [0, max_ending_here + ele].max max_so_far = [max_so_far, max_ending_here].max end max_so_far end # Best Time to Buy and Sell Stock # dynamic programing and kadane's algorithm # brute force # check every combination # too slow :( def max_profit(prices) return 0 if prices.count < 2 profit = 0 min_price = prices[0] (1..prices.count - 1).each do |k| # profit represents the max profit between day 0 and day k # min_price represents minimum prices from day 0 to day k - 1 profit = prices[k] - min_price if profit < prices[k] - min_price min_price = prices[k] if prices[k] < min_price end profit end prices = [7, 1, 5, 3, 6, 4] p max_profit(prices)
true
f60f6196f3863a1f23c9b75eef03a04610588453
Ruby
timcharper/bond
/lib/bond/missions/object_mission.rb
UTF-8
1,604
2.90625
3
[ "MIT" ]
permissive
# A mission which completes an object's methods. For this mission to match, # the condition must match and the current object must have an ancestor that matches :object. # Note: To access to the current object being completed on within an action, use the input's # object attribute. # # ==== Bond.complete Options: # [*:object*] String representing a module/class of object whose methods are completed. # [*:action*] If an action is not specified, the default action is to complete an object's # non-operator methods. # # ===== Example: # Bond.complete(:object=>ActiveRecord::Base) {|input| input.object.class.instance_methods(false) } class Bond::ObjectMission < Bond::Mission #:stopdoc: OBJECTS = %w<\S+> + Bond::Mission::OBJECTS CONDITION = '(OBJECTS)\.(\w*(?:\?|!)?)$' def initialize(options={}) @object_condition = /^#{options[:object]}$/ options[:on] ||= Regexp.new condition_with_objects super end def unique_id "#{@object_condition.inspect}+#{@on.inspect}" end def do_match(input) super && eval_object(@matched[1]) && @evaled_object.class.respond_to?(:ancestors) && @evaled_object.class.ancestors.any? {|e| e.to_s =~ @object_condition } end def after_match(input) @completion_prefix = @matched[1] + "." @action ||= lambda {|e| default_action(e.object) } create_input @matched[2], :object=>@evaled_object end def default_action(obj) obj.methods.map {|e| e.to_s} - OPERATORS end def match_message "Matches completion for object with ancestor matching #{@object_condition.inspect}." end #:startdoc: end
true
b75818aef5db41719f2c23ce712bcbcb32c99cc1
Ruby
jepetersohn/basic-OO-Orange-Trees
/source/orange_tree.rb
UTF-8
593
3.703125
4
[]
no_license
# This is how you define your own custom exception classes class NoOrangesError < StandardError end class OrangeTree # Ages the tree one year def age! end # Returns +true+ if there are any oranges on the tree, +false+ otherwise def any_oranges? end # Returns an Orange if there are any # Raises a NoOrangesError otherwise def pick_an_orange! raise NoOrangesError, "This tree has no oranges" unless self.any_oranges? # orange-picking logic goes here end end class Orange # Initializes a new Orange with diameter +diameter+ def initialize(diameter) end end
true
dc574ba2134459589b9e1ecd40d0eb19f5a09a12
Ruby
GregPK/cv-from-ruby
/src/model/competence.rb
UTF-8
538
2.5625
3
[ "MIT" ]
permissive
class Competence attr_accessor :overall, :specific_hash def initialize(overall, complex_commercial = true,simple_commercial = true,personal_complex = true, edu_projects_or_simple = true,simple_scripts = true) @overall = overall @specific_hash = { simple_scripts: simple_scripts, edu_projects_or_simple: edu_projects_or_simple, personal_complex: personal_complex, simple_commercial: simple_commercial, complex_commercial: complex_commercial, } end def overall_max 10 end end
true
e93a2c179cccac593cb0586d80347bd1a8969254
Ruby
PeterTucker/ruby_learning
/ProgrammingRuby/to_test.rb
UTF-8
105
3.375
3
[]
no_license
class Multiplier def initialize num1, num2 @value = num1 * num2 + 0 end def to_i @value end end
true
2917753d18697f57bc3591209d7d8a87b50e0d93
Ruby
imranansari/platesurfer-web-landing
/api.rb
UTF-8
1,654
2.546875
3
[]
no_license
require 'sinatra' require 'json' #require 'mongoid' class API < Sinatra::Base # MongoDB configuration =begin Mongoid.configure do |config| if ENV['MONGOHQ_URL'] conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']) uri = URI.parse(ENV['MONGOHQ_URL']) config.master = conn.db(uri.path.gsub(/^\//, '')) else config.master = Mongo::Connection.from_uri("mongodb://localhost:27017").db('test') end end =end # Models =begin class Counter include Mongoid::Document field :count_yes, :type => Integer field :count_no, :type => Integer def self.increment_yes c = first || new({:count_yes => 0}) c.inc(:count_yes, 1) c.save c.count end def self.increment_no c = first || new({:count_no => 0}) c.inc(:count_no, 1) c.save c.count end end =end =begin get '/sushi.json' do content_type :json {:sushi => ["Maguro", "Hamachi", "Uni", "Saba", "Ebi", "Sake", "Tai"]}.to_json end get '/report' do counter = Counter.first() #content_type 'application/json' yesCount =counter.count_yes noCount =counter.count_no resp = "yes:" + yesCount.to_s + ", no:"+ noCount.to_s end post '/action' do #response = JSON.parse(request.body.read) response = request.body.read if response == "yes" Counter.increment_yes else Counter.increment_no end 'sucess' end =end get '/sass_css/:name.css' do content_type 'text/css', :charset => 'utf-8' scss(:"/stylesheets/#{params[:name]}") end get '/' do erb :index end get '/signup' do erb :signup end end
true
64219aaa09063e3fd57538ff0d07c37ccf9700e3
Ruby
buzzy-rental-cars/website
/app/helpers/application_helper.rb
UTF-8
3,200
2.546875
3
[]
no_license
module ApplicationHelper def title(page_title) content_for(:title) { page_title } end def description(page_description) content_for(:description) { page_description } end def markdown_to_html(markdown_text) # Converts remaining Markdown syntax to html tags using Kramdown. require 'kramdown' html = Kramdown::Document.new(markdown_text, auto_ids: false).to_html # Sets up whitelist of allowed html elements, attributes, and protocols. allowed_elements = ['h2', 'h3', 'a', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'cite', 'blockquote', 'code', 'pre', 'dl', 'dt', 'dd', 'br', 'hr', 'sup'] allowed_attributes = { 'a' => ['href', 'rel', 'rev', 'class'], 'sup' => ['id'], 'li' => ['id'], 'h2' => ['id'], 'h3' => ['id'] } allowed_protocols = { 'a' => {'href' => ['#fn', '#fnref', 'http', 'https', 'mailto', :relative]}} # Cleans the text of any unwanted html tags. require 'sanitize' Sanitize.clean(html, elements: allowed_elements, attributes: allowed_attributes, protocols: allowed_protocols) end def illustrated_markdown_to_html(illustratable_type, illustratable, markdown_text) require 'kramdown' require 'sanitize' require 'nokogiri' # Converts Markdown syntax to html tags using Kramdown. html = Kramdown::Document.new(markdown_text, auto_ids: true).to_html # Sets up whitelist of allowed html elements, attributes, and protocols. allowed_elements = ['h2', 'h3', 'a', 'img', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'cite', 'blockquote', 'code', 'pre', 'dl', 'dt', 'dd', 'br', 'hr', 'sup', 'div'] allowed_attributes = {'a' => ['href', 'rel', 'rev', 'class'], 'img' => ['src', 'alt'], 'sup' => ['id'], 'div' => ['class'], 'li' => ['id'], 'h2' => ['id'], 'h3' => ['id']} allowed_protocols = {'a' => {'href' => ['#fn', '#fnref', 'http', 'https', 'mailto', :relative]}} # Clean text of any unwanted html tags. html = Sanitize.clean(html, elements: allowed_elements, attributes: allowed_attributes, protocols: allowed_protocols) html = Nokogiri::HTML.parse(html) # Sets correct src, width, and height attributes for the illustration. html.css('img').each do |img| file_name = img.get_attribute('src') if illustration = Illustration.where(illustratable_id: illustratable.id, illustratable_type: illustratable_type, illustration_file_name: file_name).first img.set_attribute('src', illustration.illustration.url(:embedded)) image_file = Paperclip::Geometry.from_file(illustration.illustration.path(:embedded)) img.set_attribute('width', image_file.width.to_i.to_s) img.set_attribute('height', image_file.height.to_i.to_s) img.set_attribute('class', 'illustration') else img.set_attribute('src', '') end end # Converts nokogiri variable to html. html = html.to_html # Sanitize html of extra markup that Nokogiri adds. allowed_attributes['img'] += ['id', 'width', 'height', 'class'] Sanitize.clean(html, elements: allowed_elements, attributes: allowed_attributes, protocols: allowed_protocols) end end
true
1d75b60cfc8a6b9b6f3851103cc51cc28d300dca
Ruby
muminovic/cs61aPrepCourse
/ch9/modern_roman_numerals.rb
UTF-8
1,146
4.03125
4
[]
no_license
def modern_roman_numeral num new = '' #see how many I,X,C,M we have (V, L, D are in-between symbols of themselves) #similar pattern to ORN, but this time using only 1,10,100,1000 ones = num % 10 tens = (num % 100)/10 hundreds = (num % 1000)/100 thousands = num/1000 new += 'M' * thousands #take care of the special cases, 400 500 900 CD L CM if hundreds == 9 new += 'CD' elsif hundreds == 4 new += 'CM' elsif hundreds == 5 new += 'D' else #all other possible combos using code from ORN new += 'C' * ((num % 500)/100) new += 'D' * ((num % 1000)/500) end #take care of special cases, 40 50 90 XL L XC if tens == 9 new += 'XC' elsif tens == 4 new += 'XL' elsif tens == 5 new += 'L' else #all other possible combos using code from ORN new += 'X' * ((num % 50)/10) new += 'L' * ((num % 100)/50) end #take care of special cases 4 5 9 IV V IX if ones == 9 new += 'IX' elsif ones == 4 new += 'IV' elsif ones == 5 new += 'V' else #ORN new += 'V' * ((num % 10)/5) new += 'I' * ((num % 5)/1) end puts new end puts modern_roman_numeral 4 puts modern_roman_numeral 49 puts modern_roman_numeral 48 puts modern_roman_numeral 254
true
70a3525633462c335a5c7f5c00d28c650583ad0b
Ruby
mecampbellsoup/flatiron
/take_a_number.rb
UTF-8
568
3.859375
4
[]
no_license
def take_a_number(current_line, name) current_line << name puts current_line.index(name)+1 end def now_serving(current_line) puts "Currently serving #{current_line.first}" current_line.shift end def line(current_line) current_line.each_with_index do |p,i| print "#{i+1}. #{p.capitalize}" if i < current_line.size-1 print " " else puts "" end end end katz_deli = [] take_a_number(katz_deli, "Matt") take_a_number(katz_deli, "Logan") take_a_number(katz_deli, "Manuel") line(katz_deli) now_serving(katz_deli) line(katz_deli)
true
7baefc1929d598a1b2c64b62fb2ede43bc975286
Ruby
littlegustv/redemption
/affects/affects_b.rb
UTF-8
10,757
2.75
3
[]
no_license
require_relative 'affect.rb' class AffectBarkSkin < Affect def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 300, # duration { resist_bash: 5 }, # modifiers: nil nil, # period: nil false, # permanent: false :normal, # visibility true # savable ) end def self.affect_info return @info || @info = { name: "bark skin", keywords: ["barkskin", "armor"], existing_affect_selection: :keywords, application_type: :overwrite, } end def send_start_messages @target.output "You are as mighty as an oak." (@target.room.occupants - [@target]).each_output "0<N> looks as mighty as an oak", [@target] end def send_complete_messages @target.output "The bark on your skin flakes off." (@target.room.occupants - [@target]).each_output "The bark on 0<n>'s skin flakes off.", [@target] end end class AffectBerserk < Affect def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 60, # duration { damage_roll: level / 10, hit_roll: level / 10 }, # modifiers: nil nil, # period: nil false, # permanent: false :normal, # visibility true # savable ) @healing_left = 3 * level if @healing_left > 0 toggle_periodic(1) end end def self.affect_info return @info || @info = { name: "berserk", keywords: ["berserk"], existing_affect_selection: :affect_id, application_type: :overwrite, } end def send_start_messages @target.output "Your pulse races as you are consumed by rage!" (@target.room.occupants - [@target]).each_output("0<N> gets a wild look in 0<p> eyes!", @target) end def periodic heal = [@healing_left, 3].min @healing_left -= heal @target.regen heal, 0, 0 if @healing_left == 0 toggle_periodic(nil) end end def complete @target.output "You feel your pulse slow down." end def summary super + "\n" + (" " * 24) + " : regenerating #{ ( 10 * @duration / @period ).floor } hitpoints" end end class AffectBladeRune < Affect @@TYPES = [ [ "The weapon begins to move faster.", { attack_speed: 1 } ], [ "The weapon becomes armor-piercing.", { hitroll: 20 } ], # [ "The weapon will deflect incoming attacks.", { none: 0 } ], # [ "The weapon becomes more accurate.", { none: 0 } ], [ "The weapon surrounds you with a glowing aura.", { armor_class: -30 } ], [ "The weapon is endowed with killing dweomers.", { damroll: 10 } ] ] def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 60, # duration nil, # modifiers: nil nil, # period: nil false, # permanent: false :normal, # visibility true # savable ) @message, @modifiers = @@TYPES.sample end def self.affect_info return @info || @info = { name: "blade rune", keywords: ["blade rune", "rune"], existing_affect_selection: :affect_id, application_type: :single, } end def send_start_messages @source.room.occupants.each_output("0<N> empower0<,s> 1<n> with a blade rune0<!,.>", [@source, @target]) @source.output @message end def send_complete_messages @source.output "The blade rune on %n fades away.", [@target] end end class AffectBless < Affect def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 300, # duration { hit_roll: 5, saves: -5 }, # modifiers: nil nil, # period: nil false, # permanent: false :normal, # visibility true # savable ) end def self.affect_info return @info || @info = { name: "bless", keywords: ["bless"], existing_affect_selection: :affect_id, application_type: :overwrite, } end def send_start_messages @target.output "You feel righteous." (@target.room.occupants - [@target]).each_output "0<N> glows with a holy aura.", [@target] end def send_complete_messages @target.output "You feel less righteous." (@target.room.occupants - [@target]).each_output "0<N>'s holy aura fades.", [@target] end end class AffectBlind < Affect def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 30, # duration { hit_roll: -5 }, # modifiers: nil nil, # period: nil false, # permanent: false :normal, # visibility true # savable ) end def self.affect_info return @info || @info = { name: "blind", keywords: ["blind"], existing_affect_selection: :keywords, application_type: :single, } end def start add_event_listener(@target, :try_can_see, :do_blindness) end def send_start_messages (@target.room.occupants - [@target]).each_output "0<N> is blinded!", [@target] @target.output "You can't see a thing!" end def send_complete_messages @target.output "You can see again." end def do_blindness(data) data[:chance] *= 0 end end class AffectBlur < Affect def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 300, # duration { resist_slash: 5 }, # modifiers: nil nil, # period: nil false, # permanent: false :normal, # visibility true # savable ) end def self.affect_info return @info || @info = { name: "blur", keywords: ["blur", "armor"], existing_affect_selection: :keywords, application_type: :overwrite, } end def send_start_messages @target.room.occupants.each_output "0<N>'s outline turns blurry.", [@target] end def send_complete_messages @target.room.occupants.each_output "0<N> comes into focus.", [@target] end end class AffectBolster < Affect def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 60, # duration nil, # modifiers: nil 3, # period: nil false, # permanent: false :normal, # visibility true # savable ) end def self.affect_info return @info || @info = { name: "bolster", keywords: ["bolster"], existing_affect_selection: :affect_id, application_type: :single, } end def send_complete_messages @target.room.occupants.each_output "0<N> 0<are,is> no longer so resolutely holy.", @target end def start old_hp = @target.health @target.room.occupants.each_output "0<N> 0<bolster,bolsters> 0<p> faith!", @target @target.regen( 3 * @target.level + 25, 0, 0 ) @healed = @target.health - old_hp end def periodic @target.output "Some divine protection leaves you." @target.receive_damage( @target, 1.5 * @healed / 20, :divine_power ) end end class AffectBurstRune < Affect @@NOUN_NAME = "elemental charged strike" def initialize(target, source = nil, level = 0) super( target, # target source, # source level, # level 60, # duration nil, # modifiers: nil nil, # period: nil false, # permanent: false :normal, # visibility true # savable ) @ELEMENTS = [ ["flooding", "Your weapon carries the {Dstrength{x of the {Btides!{x", "A {Dblack{x and {Bblue{x rune appears.",:hurricane], ["corrosive", "Your attack explodes into {Gcorrosive {Bacid{x!", "A {Ggreen{x and {Bblue{x rune appears.", :acid_blast], ["frost", "The air is {Wtinged{x with {Bfrost{x as you strike!", "A {Bblue{x and {Wwhite{x rune appears.", :ice_bolt], ["poison", "Your weapon discharges a {Gvirulent {Dspray!{x", "A {Ggreen{x and {Dblack{x rune appears.", :blast_of_rot], ["shocking", "You strike with the force of a {Ythunder {Bbolt!{x", "A {Ygold{x and {Bblue{x rune appears.", :lightning_bolt], ["flaming", "A {Wblast{x of {Rflames{x explodes from your weapon!", "A {Rred{x and {Wwhite{x rune appears.", :fireball] ] overwrite_data(Hash.new) end def self.affect_info return @info || @info = { name: "burst rune", keywords: ["burst rune", "rune"], existing_affect_selection: :affect_id, application_type: :single, } end def overwrite_data(data) super(data) @data[:index] = rand(@ELEMENTS.length) if !@data[:index] @element_string, @hit_message, @apply_message, @noun = @ELEMENTS[@data[:index]] end def start add_event_listener(@target, :override_hit, :do_burst_rune) end def do_burst_rune(data) if data[:confirm] == false && data[:target] && rand(1..100) <= 125 data[:source].output @hit_message data[:target].receive_damage(data[:source], 100, @noun, false, false, @@NOUN_NAME) data[:confirm] = true end end def send_start_messages @source.room.occupants.each_output("0<N> empower0<,s> 1<n> with a burst rune0<!,.>", [@source, @target]) @source.output @apply_message end def send_complete_messages @source.output "The burst rune on 0<n> fades away.", [@target] end def summary "Spell: burst rune adds #{@element_string} elemental charged strike for #{@duration.to_i} seconds" end end
true
dbcc8bbc2db09615c8e686144b4145fb6933870c
Ruby
imac18078/advanced-hashes-hashketball-001-prework-web
/hashketball.rb
UTF-8
7,591
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here! require 'pry' def game_hash game_hash = { home: { team_name: "Brooklyn Nets", colors: ["Black", "White"], players: [ {"Alan Anderson" => {player_name: "Alan Anderson", number: 0, shoe: 16, points: 22, rebounds: 12, assists: 12, steals: 3, blocks: 1, slam_dunks: 1} }, {"Reggie Evans" => {player_name: "Reggie Evans", number: 30, shoe: 14, points: 12, rebounds: 12, assists: 12, steals: 12, blocks: 12, slam_dunks: 7} }, {"Brook Lopez" => {player_name: "Brook Lopez", number: 11, shoe: 17, points: 17, rebounds: 19, assists: 10, steals: 3, blocks: 1, slam_dunks: 15} }, {"Mason Plumlee" => {player_name: "Mason Plumlee", number: 1, shoe: 19, points: 26, rebounds: 12, assists: 6, steals: 3, blocks: 8, slam_dunks: 5} }, {"Jason Terry" => {player_name: "Jason Terry", number: 31, shoe: 15, points: 19, rebounds: 2, assists: 2, steals: 4, blocks: 11, slam_dunks: 1} } ] }, away: { team_name: "Charlotte Hornets", colors: ["Turquoise", "Purple"], players: [ {"Jeff Adrien" => {player_name: "Jeff Adrien", number: 4, shoe: 18, points: 10, rebounds: 1, assists: 1, steals: 2, blocks: 7, slam_dunks: 2} }, {"Bismak Biyombo" => {player_name: "Bismak Biyombo", number: 0, shoe: 16, points: 12, rebounds: 4, assists: 7, steals: 7, blocks: 15, slam_dunks: 10} }, {"DeSagna Diop" => {player_name: "DeSagna Diop", number: 2, shoe: 14, points: 24, rebounds: 12, assists: 12, steals: 4, blocks: 5, slam_dunks: 5} }, {"Ben Gordon" => {player_name: "Ben Gordon", number: 8, shoe: 15, points: 33, rebounds: 3, assists: 2, steals: 1, blocks: 1, slam_dunks: 0} }, {"Brendan Haywood" => {player_name: "Brendan Haywood", number: 33, shoe: 15, points: 6, rebounds: 12, assists: 12, steals: 22, blocks: 5, slam_dunks: 12} } ] } } end def num_points_scored(name) points = 0 game_hash.each do |location, data| data[:players].each do |player| player.each do |player_name, attributes| if player_name == name points = attributes[:points] end end end end points end def shoe_size(name) size = 0 game_hash.each do |location, data| data[:players].each do |player| player.each do |player_name, attributes| if player_name == name size = attributes[:shoe] end end end end size end def team_colors(team) colors = [] game_hash.each do |location, data| if data[:team_name] == team colors = data[:colors] end end colors end def team_names names = [] names = game_hash.collect do |location, data| data[:team_name] end names end def player_numbers(team) numbers = [] game_hash.each do |location, data| if data[:team_name] == team numbers = data[:players].collect do |player| player.collect do |player_name, attributes| attributes[:number] end end end end numbers.flatten.sort end def player_stats(name) stats = {} game_hash.each do |location, data| data[:players].each do |player| player.each do |player_name, attributes| if player_name == name stats = attributes end end end end new_stats = stats.delete_if do |k, v| k == :player_name end new_stats end def big_shoe_rebounds shoe_sizes = [] game_hash.each do |location, data| data[:players].each do |player| shoe_sizes = player.collect do |player_name, attributes| attributes[:shoe] end end end big_shoes = shoe_sizes.max rebounds = 0 game_hash.each do |location, data| data[:players].each do |player| player.each do |player_name, attributes| if attributes[:shoe] == big_shoes rebounds = attributes[:rebounds] end end end end rebounds end def most_points_scored points = [] most_points = 0 game_hash.each do |location, data| points = data[:players].collect do |player| player.collect do |player_name, attributes| attributes[:points] end end end most_points = points.flatten.max highest_scorer = "" game_hash.each do |location, data| data[:players].each do |player| player.each do |player_name, attributes| if attributes[:points] == most_points highest_scorer = attributes[:player_name] end end end end highest_scorer end def winning_team points_home = [] points_away = [] points_home = game_hash[:home][:players].collect do |player| player.collect do |player_name, attributes| attributes[:points] end end points_away = game_hash[:away][:players].collect do |player| player.collect do |player_name, attributes| attributes[:points] end end points_home = points_home.flatten points_away = points_away.flatten idx = 0 total_points_home = 0 while idx < points_home.size total_points_home += points_home[idx] idx += 1 end idx = 0 total_points_away = 0 while idx < points_away.size total_points_away += points_away[idx] idx += 1 end if total_points_home > total_points_away game_hash[:home][:team_name] else game_hash[:away][:team_name] end end def player_with_longest_name name_lengths = [] name_lengths = game_hash.collect do |location, data| data[:players].collect do |player| player.collect do |player_name, attributes| player_name end end end name_lengths = name_lengths.flatten name_lengths.sort! {|a, b| b.length <=> a.length} name_lengths[0] end def long_name_steals_a_ton? name_lengths = [] name_lengths = game_hash.collect do |location, data| data[:players].collect do |player| player.collect do |player_name, attributes| player_name end end end name_lengths = name_lengths.flatten name_lengths.sort! {|a, b| b.length <=> a.length} name_lengths[0] steals = [] steals = game_hash.collect do |location, data| data[:players].collect do |player| player.collect do |player_name, attributes| attributes[:steals] end end end steals = steals.flatten most_steals = steals.max most_steals_name = "" game_hash.each {|location, data| data[:players].each {|player| player.each {|player_name, attributes| if attributes[:steals] == most_steals most_steals_name = attributes[:player_name] end } } } if name_lengths[0] == most_steals_name true else false end end
true
936bbfcda1037eacdecf0cb5424e74059dadba31
Ruby
hambrice/ruby-music-library-cli-v-000
/lib/musiclibrarycontroller.rb
UTF-8
2,390
3.578125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class MusicLibraryController attr_accessor :path def initialize(path = "./db/mp3s") @path = path MusicImporter.new(path).import end def call puts "Welcome to your music library!" puts "To list all of your songs, enter 'list songs'." puts "To list all of the artists in your library, enter 'list artists'." puts "To list all of the genres in your library, enter 'list genres'." puts "To list all of the songs by a particular artist, enter 'list artist'." puts "To list all of the songs of a particular genre, enter 'list genre'." puts "To play a song, enter 'play song'." puts "To quit, type 'exit'." puts "What would you like to do?" input = "" while input != "exit" input = gets.strip if input == "list songs" self.list_songs elsif input == "list artists" self.list_artists elsif input == "list genres" self.list_genres elsif input == "list artist" self.list_songs_by_artist elsif input == "list genre" self.list_songs_by_genre elsif input == "play song" self.play_song end end end def list_songs songs = Song.all.sort_by!{|s| s.name} songs.each.with_index do |s,i| puts "#{i+1}. #{s.artist.name} - #{s.name} - #{s.genre.name}" end end def list_artists Artist.all.sort_by!{|s| s.name}.each.with_index(1) do |s,i| puts "#{i}. #{s.name}" end end def list_genres Genre.all.sort_by!{|s| s.name}.each.with_index(1) do |s,i| puts "#{i}. #{s.name}" end end def list_songs_by_artist puts "Please enter the name of an artist:" input = gets artist = Artist.find_by_name(input) #binding.pry if artist != nil artist.songs.sort_by!{|s| s.name}.each.with_index(1) do |s, i| puts "#{i}. #{s.name} - #{s.genre.name}" end end end def list_songs_by_genre puts "Please enter the name of a genre:" input = gets genre = Genre.find_by_name(input) #binding.pry if genre != nil genre.songs.sort_by!{|s| s.name}.each.with_index(1) do |s, i| puts "#{i}. #{s.artist.name} - #{s.name}" end end end def play_song songs = Song.all.sort_by!{|s| s.name} range = (1..songs.length).to_a puts "Which song number would you like to play?" input = gets if range.include? (input.to_i) puts "Playing #{songs[input.to_i-1].name} by #{songs[input.to_i-1].artist.name}" end end end
true
b64d7abc5b730655a9f165f3b5e13e8d73fd4929
Ruby
carbonfive/raygun
/lib/raygun/template_repo.rb
UTF-8
2,360
2.859375
3
[ "MIT" ]
permissive
module Raygun class TemplateRepo attr_reader :name, :branch, :tarball, :sha def initialize(repo) @name, @branch = repo.split("#").map(&:strip) fetch end private def fetch return if @branch && @sha @branch ? fetch_branches : fetch_tags end def handle_github_error(response) puts "" print "Whoops - need to try again!".colorize(:red) puts "" print "We could not find (".colorize(:light_red) print name.to_s.colorize(:white) print "##{branch}".colorize(:white) if @branch print ") on github.".colorize(:light_red) puts "" print "The response from github was a (".colorize(:light_red) print response.code.to_s.colorize(:white) puts ") which I'm sure you can fix right up!".colorize(:light_red) puts "" exit 1 end def handle_missing_tag_error puts "" print "Whoops - need to try again!".colorize(:red) puts "" print "We could not find any tags in the repo (".colorize(:light_red) print name.to_s.colorize(:white) print ") on github.".colorize(:light_red) puts "" print "Raygun uses the 'largest' tag in a repository, " \ "where tags are sorted alphanumerically.".colorize(:light_red) puts "" print "E.g., tag 'v.0.10.0' > 'v.0.9.9' and 'x' > 'a'.".colorize(:light_red) print "" puts "" exit 1 end def fetch_branches response = http_get("https://api.github.com/repos/#{name}/branches/#{branch}") handle_github_error(response) unless response.code == "200" result = JSON.parse(response.body) @sha = result["commit"]["sha"] @tarball = result["_links"]["html"].gsub(%r{/tree/#{branch}}, "/archive/#{branch}.tar.gz") end def fetch_tags response = http_get("https://api.github.com/repos/#{name}/tags") handle_github_error(response) unless response.code == "200" result = JSON.parse(response.body).first handle_missing_tag_error unless result @sha = result["commit"]["sha"] @tarball = result["tarball_url"] end def http_get(url) uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri) http.request(request) end end end
true
7c35a1fc854b2222a9c8deceee0e97e1a9a09d32
Ruby
dhanesana/sea-c21-ruby
/lib/class4/exercise3.rb
UTF-8
2,338
4.6875
5
[ "MIT" ]
permissive
#!/usr/bin/env ruby # # 5 points # # Write a program that asks whether or not you like tacos: # # If you reply with 'y', then we're friends: # # $ ruby exercise3.rb # Do you like eating tacos? (y or n) # y # We can be friends! # # If you reply with 'n', then we're enemies: # # $ ruby exercise3.rb # Do you like eating tacos? (y or n) # n # Get out of my sight! # # And if you reply with **anything** else, you have to try again: # # $ ruby exercise3.rb # Do you like eating tacos? (y or n) # maybe # Try again # Do you like eating tacos? (y or n) # y # We can be friends! # # TIP #1: You only need to change the `ask` method. # # TIP #2: Use `return` to preemptively exit the `ask` method. =begin # only change the method: the question change me # following is a method def ask(question) # question is a variable and also a parameter loop do puts question # outputting question to the terminal answer = gets.chomp # get user input # put answer in an if statement if answer == 'y' # puts 'We can be friends' doesn't work because puts returns nil # puts nil will basically just put a blank line # so get rid of the puts return 'We can be friends!' # return breaks out loop and returns string elsif answer == 'n' return 'Get out of my sight!' else puts 'Try again' # puts because it's not outputting anything without it end end end =end # shorten above method like a pro rubyguy # question is a variable and also a parameter def ask(question) loop do puts question # outputting question to the terminal answer = gets.chomp # get user input # put answer in an if statement # puts 'We can be friends' doesn't work because puts returns nil # puts nil will basically just put a blank line # so get rid of the puts return 'We can be friends!' if answer == 'y' # return breaks out loop and returns string return 'Get out of my sight!' if answer == 'n' puts 'Try again' # puts because it's not outputting anything without it end end # puts method ask puts ask('Do you like eating tacos? (y or n)') # the string is an argument # the string argument goes into the parameter 'question' # it only exists within the scope of the ask method # can't just have 'puts ask' because it needs an argument or crash
true
060958dc03cc5ce8c631e4217fcd773a30a77547
Ruby
adbasner/code_snippets
/job_training/interview.rb
UTF-8
1,025
4.125
4
[]
no_license
# def print_odds(max_number) # odd_numbers = [] # number = 1 # max_number.times do # if number % 2 != 0 # odd_numbers << number # end # number += 1 # end # return odd_numbers # end # loop_until = gets.chomp.to_i # p print_odds(loop_until) # Question 2 def is_palindrome(string) string_array = string.downcase.split('') # remove space and non letter characters p string_array first_char_index = 0 last_char_index = string_array.length - 1 first_char = string_array[first_char_index] last_char = string_array[last_char_index] if first_char != last_char return "not a palindrome" end # repeat this until something until first_char_index == string_array.length/2 first_char_index += 1 last_char_index -= 1 first_char = string_array[first_char_index] last_char = string_array[last_char_index] if first_char != last_char return "not a palindrome" end end return "must be a palindrome" end p is_palindrome('Amanaplanacanalpanama')
true
1ed597da05445f3ac43a0b2ce9c29b34d16c63f7
Ruby
YumaInaura/YumaInaura
/ruby/keyword-args-hash-args.rb
UTF-8
596
3.828125
4
[]
no_license
# receive keyword args method def foo(x:, y:) p x p y end # OK # Pass keyword args foo(x: "x", y: "y") # OK # Pass hash but convert as keyword args explicity foo(**{x: "x", y: "y"}) # OK # Pass hash but convert as keyword args explicity hash = {x: "x", y: "y"} foo(**hash) # NG # Pass Hash Args # warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call foo({x: "x", y: "y"}) # Receive hash method def bar(h = {}) p h[:x] p h[:y] end # OK bar({ x: "x", y: "y" }) # OK # Call with keyword argus but NO ERROR! bar(x: "x", y: "y")
true
dae006b0f02ed2a538c364125a901122bf9f1bf0
Ruby
cdlib/cedilla_service_commons
/lib/cedilla/author.rb
UTF-8
7,937
2.921875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Cedilla class Author # Author attributes attr_accessor :corporate_author attr_accessor :full_name, :last_name, :first_name, :suffix attr_accessor :middle_initial, :first_initial, :initials attr_accessor :dates, :authority attr_accessor :extras # -------------------------------------------------------------------------------------------------------------------- def initialize(params) if params.is_a?(Hash) @extras = {} # Assign the appropriate params to their attributes, place everything else in others params.each do |key,val| key = key.id2name if key.is_a?(Symbol) if self.respond_to?("#{key}=") self.method("#{key}=").call(val) else if @extras["#{key}"].nil? @extras["#{key}"] = [] end @extras["#{key}"] << val end end else raise Error.new("You must supply an attribute hash!") end end # -------------------------------------------------------------------------------------------------------------------- def self.from_arbitrary_string(value) params = {} params[:dates] = value.slice(/[0-9\-]+/) unless value.slice(/[0-9\-]+/).nil? # Last Name, First Name Initial if 0 == (value =~ /[a-zA-Z\s\-]+,\s?[a-zA-Z\s\-]+\s[a-zA-Z]{1}\.?/) params[:last_name] = value.slice(/[a-zA-Z\s\-]+,/).gsub(',', '') params[:middle_initial] = value.slice(/[a-zA-Z]{1}\./) params[:first_name] = value.gsub("#{params[:last_name]}, ", '').gsub(" #{params[:middle_initial]}", '') # Last Name, Initial Initial elsif 0 == (value =~ /[a-zA-Z\s\-]+,\s?[a-zA-Z]{1}\.?\s[a-zA-Z]{1}\.?/) params[:last_name] = value.slice(/[a-zA-Z\s\-]+,/).gsub(',', '') inits = value.split('.') inits.each do |init| params[:middle_initial] = "#{inits[1].gsub(' ', '')}." unless inits[1].include?(params[:last_name]) params[:first_initial] = "#{inits[0].gsub(' ', '').gsub(',', '').gsub(params[:last_name], '')}." if inits[0].include?(params[:last_name]) end # Initial Initial Last Name elsif 0 == (value =~ /[a-zA-Z]{1}\.?\s+[a-zA-Z]{1}\.?\s+[a-zA-Z\s\-]+/) inits = value.split('.') params[:first_initial] = "#{inits[0].gsub(' ', '')}." params[:middle_initial] = "#{inits[1].gsub(' ', '')}." params[:last_name] = "#{inits[2].gsub(' ', '')}" # First Name Initial Last Name elsif 0 == (value =~ /[a-zA-Z\s\-]+\s+[a-zA-Z]{1}\.?\s+[a-zA-Z\s\-]+/) inits = value.split('.') params[:middle_initial] = "#{inits[0][-1]}." params[:first_name] = "#{inits[0][0..inits[0].size - 3]}" params[:last_name] = "#{inits[1]}" # Last Name, First Name elsif 0 == (value =~ /[a-zA-Z\s\-]+,\s?[a-zA-Z\s\-]+/) names = value.split(', ') params[:last_name] = names[0] params[:first_name] = names[1] # First Name Last Name elsif 0 == (value =~ /[a-zA-Z\s\-]+\s+[a-zA-Z\s\-]+/) names = value.gsub(' ', ' ').split(' ') params[:first_name] = names[0..(names.size / 2) - 1].join(' ') params[:last_name] = names[(names.size / 2)..names.size].join(' ') else params[:last_name] = value end self.new(params) end # -------------------------------------------------------------------------------------------------------------------- def ==(object) return false unless object.is_a?(self.class) ret = @full_name == object.full_name ret = (@last_name == object.last_name and (@first_name == object.first_name or @first_initial == object.first_initial)) unless ret or @last_name.nil? ret = @corporate_author = object.corporate_author unless ret or @corporate_author.nil? ret end # -------------------------------------------------------------------------------------------------------------------- def last_name_first if @last_name.nil? if @first_name.nil? and @first_initial.nil? @corporate_author else "#{@first_name.nil? ? @first_initial : @first_name} #{@middle_initial}".strip end else if @first_name.nil? and @first_initial.nil? @last_name else "#{@last_name}, #{@first_name.nil? ? @first_initial : @first_name} #{@middle_initial}".strip end end end # -------------------------------------------------------------------------------------------------------------------- def first_name=(val) @first_name = val.nil? ? '' : val.strip @first_initial = "#{val[0].gsub(' ', '').upcase}." @initials = "#{@first_initial} #{@middle_initial}".strip end # -------------------------------------------------------------------------------------------------------------------- def first_initial=(val) @first_initial = val.nil? ? '' : val.strip @first_name = @first_initial if @first_name.nil? @initials = "#{@first_initial} #{@middle_initial.nil? ? '' : @middle_initial}".strip end # -------------------------------------------------------------------------------------------------------------------- def middle_initial=(val) @middle_initial = val.nil? ? '' : val.strip @initials = "#{@first_initial.nil? ? '' : "#{@first_initial} "}#{@middle_initial}" end # -------------------------------------------------------------------------------------------------------------------- def initials=(val) @initials = val.nil? ? '' : val.strip unless val.nil? inits = val.split('. ') @first_initial = "#{inits[0]}." if @first_name.nil? @middle_initial = inits[1] end end # -------------------------------------------------------------------------------------------------------------------- def last_name=(val) @last_name = val.nil? ? '' : val.strip end # -------------------------------------------------------------------------------------------------------------------- def full_name=(val) auth = Cedilla::Author.from_arbitrary_string(val) @dates = auth.dates unless auth.dates.nil? @first_name = auth.first_name unless auth.first_name.nil? @last_name = auth.last_name unless auth.last_name.nil? @middle_initial = auth.middle_initial unless auth.middle_initial.nil? @first_initial = auth.first_initial unless auth.first_initial.nil? @intials = auth.initials unless auth.initials.nil? end # -------------------------------------------------------------------------------------------------------------------- def full_name if @full_name.nil? if @corporate_author.nil? "#{@first_name.nil? ? @first_initial : @first_name} #{@middle_initial} #{@last_name}".gsub(' ', ' ').strip else @corporate_author end else @full_name end end # -------------------------------------------------------------------------------------------------------------------- def to_s "#{self.full_name}" end # -------------------------------------------------------------------------------------------------------------------- def to_hash ret = {} self.methods.each do |method| name = method.id2name.gsub('=', '') val = self.method(name).call if method.id2name[-1] == '=' and self.respond_to?(name) ret["#{name}"] = val unless val.nil? or ['!', 'others'].include?(name) end ret['extras'] = @extras unless @extras.empty? ret end end end
true
18b7a10711d8ad85eef37660c7d0ddca8a367a05
Ruby
guragt/bugsnag_to_webex_teams
/app/models/webex_teams/message.rb
UTF-8
601
2.609375
3
[]
no_license
module WebexTeams class Message WEBEX_URL='https://api.ciscospark.com/v1/messages' def initialize(markdown:) @markdown = markdown end def deliver(room_id) response = Net::Hippie::Client.new.post(URI.parse(WEBEX_URL), body: {roomId: room_id, markdown: @markdown}, headers: {'Authorization' => "Bearer #{ENV['WEBEX_ACCESS_CODE']}"} ) raise 'Failed to publish to WebexTeams' unless response.is_a?(Net::HTTPOK) end end end
true
44bd7fd0a05c486e61d58a0519576dc668b8e007
Ruby
Noah2610/TextAdventure_v2
/src/Test/rb/Tests/InputConversationMode.rb
UTF-8
1,299
2.921875
3
[]
no_license
### Tests for user input in conversation mode class TestInputConversationMode < MiniTest::Test include TestInputHelpers def reset args = {} super PLAYER.talk_to @persons[:Parsley] unless (args[:no_talk] == true) end ## CONVERSATION MODE ## def test_talk_to_unknown_person reset no_talk: true @persons[:Parsley].unknown! output = process_line 'Talk to Friend' assert_equal :conversation, PLAYER.mode, "Player should talk to unknown Person: #{output}" end def test_talk_to_known_person reset no_talk: true @persons[:Parsley].known! output = process_line 'Talk to Parsley' assert_equal :conversation, PLAYER.mode, "Player should talk to known Person: #{output}" end def test_leave_conversation reset output = process_line 'Good Bye friend!' GAME.tick_increase GAME.handle_queue assert_equal :normal, PLAYER.mode, "Player should have left conversation mode: #{output}" end ## TERMS ## def test_give_item_to_person reset item = @items[:Apple] PLAYER.item_add item output = process_line 'Take this Apple, friend!' assert_equal false, PLAYER.has_item?(item), "Player should not have Item anymore: #{output}" assert_equal true, @persons[:Parsley].has_item?(item), "Player should have given Item to Person #{output}" end end
true
be295f4bee7b4a96792a140a4bdd315a144ce163
Ruby
itdddjulius/bitmap_editor
/spec/command_spec.rb
UTF-8
9,542
2.640625
3
[]
no_license
# frozen_string_literal: true describe Command do let(:command) { Command.new(input) } describe '#initialize' do context 'invalid input format' do let(:input) { 'I A' } it 'should raise an invalid format error' do expect { command }.to raise_error(Command::InvalidFormatError) end end context 'valid input format' do let(:should_not_raise_error) do expect { command }.to_not raise_error end context '`I M N`' do let(:input) { 'I 5 5' } it 'should not raise an invalid format error' do should_not_raise_error end end context '`C`' do let(:input) { 'C' } it 'should not raise an invalid format error' do should_not_raise_error end end context '`L X Y C`' do let(:input) { 'L 2 3 C' } it 'should not raise an invalid format error' do should_not_raise_error end end context '`F X Y C`' do let(:input) { 'F 2 3 C' } it 'should not raise an invalid format error' do should_not_raise_error end end context '`V X Y1 Y2 C`' do let(:input) { 'V 1 2 4 C' } it 'should not raise an invalid format error' do should_not_raise_error end end context '`H X1 X2 Y C`' do let(:input) { 'H 1 2 4 C' } it 'should not raise an invalid format error' do should_not_raise_error end end context '`S`' do let(:input) { 'S' } it 'should not raise an invalid format error' do should_not_raise_error end end context '`?`' do let(:input) { '?' } it 'should not raise an error' do should_not_raise_error end end context '`X`' do let(:input) { 'X' } it 'should not raise an error' do should_not_raise_error end end end context 'invalid command' do let(:input) { 'A' } it 'should raise an invalid command error' do expect { command }.to raise_error(Command::InvalidCommandError) end end context 'valid command' do let(:should_raise_invalid_params_error) do expect { command }.to raise_error(Command::InvalidFormatError) end context '`I`' do context 'with invalid params' do context '(missing params)' do let(:input) { 'I 2' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context '(extra params)' do let(:input) { 'I 2 3 4' } it 'should raise invalid params error' do should_raise_invalid_params_error end end end context 'with valid params' do let(:input) { 'I 5 6' } it 'should set type, x, and y values' do expect(command.type).to eq('I') expect(command.x).to eq(5) expect(command.y).to eq(6) expect(command.x_range).to be_nil expect(command.y_range).to be_nil expect(command.colour).to be_nil end end end context '`C`' do context 'with invalid extra params' do let(:input) { 'C 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context 'with valid params' do let(:input) { 'C' } it 'should set type value' do expect(command.type).to eq('C') expect(command.x).to be_nil expect(command.y).to be_nil expect(command.x_range).to be_nil expect(command.y_range).to be_nil expect(command.colour).to be_nil end end end context '`F`' do context 'with invalid params' do context '(missing params)' do let(:input) { 'F 1 2' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context '(extra params)' do let(:input) { 'F 1 2 C 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end end context 'with valid params' do let(:input) { 'F 1 2 C' } it 'should set type, x, y and colour values' do expect(command.type).to eq('F') expect(command.x).to eq(1) expect(command.y).to eq(2) expect(command.x_range).to be_nil expect(command.y_range).to be_nil expect(command.colour).to eq('C') end end end context '`L`' do context 'with invalid params' do context '(missing params)' do let(:input) { 'L 1 2' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context '(extra params)' do let(:input) { 'L 1 2 C 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end end context 'with valid params' do let(:input) { 'L 1 2 C' } it 'should set type, x, y and colour values' do expect(command.type).to eq('L') expect(command.x).to eq(1) expect(command.y).to eq(2) expect(command.x_range).to be_nil expect(command.y_range).to be_nil expect(command.colour).to eq('C') end end end context '`V`' do context 'with invalid params' do context '(missing params)' do let(:input) { 'V 1 1 2' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context '(extra params)' do let(:input) { 'V 1 1 2 C 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end end context 'with valid params' do let(:input) { 'V 1 1 2 C' } it 'should set type, x, y_range and colour values' do expect(command.type).to eq('V') expect(command.x).to eq(1) expect(command.y).to be_nil expect(command.x_range).to be_nil expect(command.y_range).to eq(1..2) expect(command.colour).to eq('C') end end end context '`H`' do context 'with invalid params' do context '(missing params)' do let(:input) { 'H 1 2 2' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context '(extra params)' do let(:input) { 'H 1 2 2 C 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end end context 'with valid params' do let(:input) { 'H 1 2 2 C' } it 'should set type, x_range, y and colour values' do expect(command.type).to eq('H') expect(command.x_range).to eq(1..2) expect(command.y).to eq(2) expect(command.x).to be_nil expect(command.y_range).to be_nil expect(command.colour).to eq('C') end end end context '`S`' do context 'with invalid extra params' do let(:input) { 'S 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context 'with valid params' do let(:input) { 'S' } it 'should set type value' do expect(command.type).to eq('S') expect(command.x).to be_nil expect(command.y).to be_nil expect(command.x_range).to be_nil expect(command.y_range).to be_nil expect(command.colour).to be_nil end end end context '`?`' do context 'with invalid extra params' do let(:input) { '? 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context 'with valid params' do let(:input) { '?' } it 'should set type value' do expect(command.type).to eq('?') expect(command.x).to be_nil expect(command.y).to be_nil expect(command.x_range).to be_nil expect(command.y_range).to be_nil expect(command.colour).to be_nil end end end context '`X`' do context 'with invalid extra params' do let(:input) { 'X 1' } it 'should raise invalid params error' do should_raise_invalid_params_error end end context 'with valid params' do let(:input) { 'X' } it 'should set type value' do expect(command.type).to eq('X') expect(command.x).to be_nil expect(command.y).to be_nil expect(command.x_range).to be_nil expect(command.y_range).to be_nil expect(command.colour).to be_nil end end end end end end
true
04869564d71201b2c31f71414de882795d89a3d9
Ruby
jordanhudgens/exercism
/ruby/raindrops/raindrops.rb
UTF-8
254
3.046875
3
[]
no_license
class Raindrops FACTORS = { 'Pling': 3, 'Plang': 5, 'Plong': 7 }.freeze def self.convert(num) sounds = FACTORS.map do |sound, factor| sound if (num % factor).zero? end.join sounds.empty? ? num.to_s : sounds end end
true
ad14e2e53ea3446aed718da51e183ff177ae8a5c
Ruby
amateharu/homework
/HW03/Volodymyr Larkin/HW3/lib/mentor.rb
UTF-8
813
2.75
3
[]
no_license
# frozen_string_literal: true require_relative 'person.rb' require_relative 'student.rb' class Mentor < Person attr_accessor :student def initialize(name:, surname:) super(name: name, surname: surname) @student end def subscribe_to!(student) @student = student student.mentor = self end def add_homework(title:, description:, student:) student.notifications << "New hw #{title} was added for you by #{name}" homework = Homework.new(title, description) student.homeworks << homework homework end def reject_to_work!(homework) homework.status = 'Rejected' @student.notifications << "#{homework.title} was rejected" end def accept!(homework) homework.status = 'Accepted' @student.notifications << "#{homework.title} was accepted" end end
true
c5829ac4a3eb1634405e8fe314b5a095c7ff97e2
Ruby
cyber-dojo-retired/ragger
/test/client/test_base.rb
UTF-8
926
2.5625
3
[ "BSD-2-Clause" ]
permissive
require_relative '../id58_test_base' require_relative '../require_src' require_src 'externals' require_src 'ragger_service' class TestBase < Id58TestBase def externals @externals ||= Externals.new end def ragger RaggerService.new(externals) end # - - - - - - - - - - - - - - - - - - - - - - - - - - def sha ragger.sha end def alive? ragger.alive? end def ready? ragger.ready? end def colour(image_name, id, stdout, stderr, status) @colour = ragger.colour(image_name, id, stdout, stderr, status) end # - - - - - - - - - - - - - - - - - - - - - - - - - - def assert_sha(string) assert_equal 40, string.size string.each_char do |ch| assert '0123456789abcdef'.include?(ch) end end def assert_colour(expected) assert_equal expected, @colour end # - - - - - - - - - - - - - - - - - - - - - - - - - - def id id58[0..5] end end
true
a8e973b2ddfbb131ac6572edcebf76ef9ffbb60a
Ruby
sawangupta92/VTAPP
/Ruby_exercise/customer/lib/customer.rb
UTF-8
748
4.03125
4
[]
no_license
class Customer @@count = 0 def initialize(name) @name = name @balance = 1000.0 @@count += 1 @account_number = @@count end def to_s "name is #{ @name }, balance is #{ @balance }, account number is #{ @account_number }" end def deposit(balance) # minimum balance you can add in your account is 1 rupee balance = balance.to_f if(balance >= 1) @balance += balance else 'minimum balance you can add in your account is 1 rupee' end end def withdraw(balance) # you can not withdraw more amount than in your account balance = balance.to_f if(balance <= @balance) @balance -= balance else 'you can not withdraw more amount than in your account' end end end
true
c129c2007393748ac3895efab80741f3dc3a0d47
Ruby
ReseauEntourage/entourage-ror
/config/initializers/json_validator.rb
UTF-8
504
2.53125
3
[ "MIT" ]
permissive
# Accepts ISO 8601, then converts it to RFC 3339 (JSON Schema standard) # # derived from # https://github.com/ruby-json-schema/json-schema/blob/v2.6.2/lib/json-schema/attributes/formats/date_time_v4.rb JSON::Validator.register_format_validator("date-time-iso8601", -> (data) { begin return unless data.is_a?(String) data.replace DateTime.iso8601(data).rfc3339(3) rescue TypeError, ArgumentError raise JSON::Schema::CustomFormatError, "must be a valid ISO 8601 date/time string" end })
true
1a6ffa87cb74d4446b4bdd36031f45771f2cba6e
Ruby
erikbenton/connect_four
/spec/connect_four_spec.rb
UTF-8
5,142
3.109375
3
[]
no_license
require "connect_four.rb" describe "ConnectFour" do subject(:game) {ConnectFour.new()} let(:empty_board) {Hash[(0..5).map { |row| [row, [".",".",".",".",".",".","."]]}]} let(:full_board) {Hash[(0..5).map { |row| [row, ["O","O","O","O","O","O","O"]]}]} let(:horizontal_win_board) {{0 => ["O", "O", "O", "X", "O", ".", "."], 1 => ["O", "X", "O", "X", "O", ".", "."], 2 => ["O", "O", "O", "O", "X", ".", "."], 3 => [".", ".", ".", ".", ".", ".", "."], 4 => [".", ".", ".", ".", ".", ".", "."], 5 => [".", ".", ".", ".", ".", ".", "."]}} let(:vertical_win_board) {{0 => ["O", "O", "X", "X", "O", "O", "."], 1 => ["O", "O", "X", "X", "O", "X", "."], 2 => ["O", "O", "X", ".", "O", ".", "."], 3 => ["X", "O", ".", ".", "X", ".", "."], 4 => [".", ".", ".", ".", ".", ".", "."], 5 => [".", ".", ".", ".", ".", ".", "."]}} let(:diagonal_r2l_win_board) {{0 => ["O", "X", "O", "X", "X", ".", "."], 1 => ["O", "X", "X", "O", "O", ".", "."], 2 => [".", ".", ".", "X", "O", ".", "."], 3 => [".", ".", ".", ".", "X", ".", "."], 4 => [".", ".", ".", ".", ".", ".", "."], 5 => [".", ".", ".", ".", ".", ".", "."]}} let(:diagonal_l2r_win_board) {{0 => [".", ".", ".", "X", "O", "X", "O"], 1 => [".", ".", ".", "O", "X", "O", "."], 2 => [".", ".", ".", "X", "O", ".", "."], 3 => [".", ".", ".", "O", ".", ".", "."], 4 => [".", ".", ".", ".", ".", ".", "."], 5 => [".", ".", ".", ".", ".", ".", "."]}} let(:empty_board_string) {". . . . . . .\n. . . . . . .\n. . . . . . .\n. . . . . . .\n. . . . . . .\n. . . . . . .\n1 2 3 4 5 6\n"} let(:full_board_string) {"O O O O O O O\nO O O O O O O\nO O O O O O O\nO O O O O O O\nO O O O O O O\nO O O O O O O\n1 2 3 4 5 6\n"} describe ".initialize" do it "it sets up an empty board" do expect(game.board).to eql(empty_board) end end describe ".write_instructions" do it "writes instructions for the game" do expect(game.write_instructions).to be_is_a(String) end end describe ".check_coord" do context "given a valid coordinate" do it "returns true" do expect(game.check_coord(3)).to eql(true) end end context "given an invalid, positive coordinate" do it "returns false" do expect(game.check_coord(10)).to eql(false) end end context "given an invalid, negative coordinate" do it "returns false" do expect(game.check_coord(-5)).to eql(false) end end end describe ".check_if_free" do context "with an empty board" do it "returns true" do game.board = empty_board expect(game.check_if_free(3)).to eql(true) end end context "with a full column" do it "returns false" do game.board = Hash[(0..5).map { |row| [row, ["O","","","","",""]]}] expect(game.check_if_free(0)).to eql(false) end end end describe ".make_move" do context "add piece to empty board" do it "returns the position of the piece" do game.board = empty_board expect(game.make_move(4)).to eql([0,4]) end end context "add piece to non-empty board with empty space" do it "returns the position of the piece" do game.board[0] = ["O", "O", ".", ".", "O", ".", "."] game.board[1] = ["O", "O", ".", ".", "O", ".", "."] game.board[2] = ["O", "O", ".", ".", "O", ".", "."] game.board[3] = [".", "O", ".", ".", ".", ".", "."] expect(game.make_move(3)).to eql([0,3]) end end context "add piece to full board" do it "returns false" do game.board = full_board expect(game.make_move(4)).to eql(false) end end end describe ".draw_board" do context "given an empty board" do it "returns a string of an empty board" do game.board = empty_board expect(game.draw_board).to eql(empty_board_string) end end context "given a full board" do it "returns a string of a full board" do game.board = full_board expect(game.draw_board).to eql(full_board_string) end end end describe ".check_for_win" do context "given an empty board" do it "returns false" do game.board = empty_board expect(game.check_for_win).to eql(false) end end context "given a board with four connected horizontally" do it "returns true" do game.board = horizontal_win_board expect(game.check_for_win).to eql(true) end end context "given a board with four connected vertically" do it "returns true" do game.board = vertical_win_board expect(game.check_for_win).to eql(true) end end context "given a board with four connected diagonally top left to right" do it "returns true" do game.board = diagonal_l2r_win_board expect(game.check_for_win).to eql(true) end end context "given a board with four connected diagonally top right to left" do it "returns true" do game.board = diagonal_r2l_win_board expect(game.check_for_win).to eql(true) end end end end
true