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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
70bfe5388fa629279139b405b0d252e81123889a | Ruby | mdimannyit/shopify-snippets-2 | /line-item-scripts/buy-more-save-more/no-discount-code.rb | UTF-8 | 1,523 | 2.65625 | 3 | [] | no_license | # Tier One Threshold, Discount, and Percentage
TIER_ONE_THRESHOLD = 0
TIER_ONE_DISCOUNT = Decimal.new(10) / 100.0
TIER_ONE_MESSAGE = "10% Off"
# Tier Two Threshold, Discount, and Percentage
TIER_TWO_THRESHOLD = 51
TIER_TWO_DISCOUNT = Decimal.new(15) / 100.0
TIER_TWO_MESSAGE = "15% Off"
# Tier Three Threshold, Discount, and Percentage
TIER_THREE_THRESHOLD = 101
TIER_THREE_DISCOUNT = Decimal.new(20) / 100.0
TIER_THREE_MESSAGE = "20% Off"
# Variables
categoryTotal = 0
# Adds up total cart value of X Category
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next if product.gift_card?
# Fix to convert decimal to string then to integer
a = line_item.line_price_was
a_int = Integer(a.cents.to_s)
end
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next if product.gift_card?
if categoryTotal >= TIER_THREE_THRESHOLD * 100
line_discount = line_item.line_price * TIER_THREE_DISCOUNT
line_item.change_line_price(line_item.line_price - line_discount, message: TIER_THREE_MESSAGE)
elsif categoryTotal >= TIER_TWO_THRESHOLD * 100
line_discount = line_item.line_price * TIER_TWO_DISCOUNT
line_item.change_line_price(line_item.line_price - line_discount, message: TIER_TWO_MESSAGE)
elsif categoryTotal >= TIER_ONE_THRESHOLD * 100
line_discount = line_item.line_price * TIER_ONE_DISCOUNT
line_item.change_line_price(line_item.line_price - line_discount, message: TIER_ONE_MESSAGE)
end
end
Output.cart = Input.cart
| true |
35251f43234360505027974ac8bfe6519efc04fc | Ruby | ryuchan00/ruby_for_beginners | /sample/ensure.rb | UTF-8 | 372 | 3.015625 | 3 | [] | no_license | # 9.6.2 ensureの代わりにブロックを使う
# ブロック付きでオープンすると、メソッドの実行後に自動的にクローズされる
File.open('some.txt', 'w') do |file|
file << 'Hello'
1 / 0
end
# 例外は発生するものの、openメソッドによってクローズ処理自体は必ず行われる
# => ZeroDivisionError: divided by 0
| true |
08b2be6c4b4e36fa4c9b845fdd61d59973837931 | Ruby | MicFin/ga-twitter-stock-sinatra-lab | /main1.rb | UTF-8 | 731 | 2.546875 | 3 | [] | no_license |
require 'twitter'
require 'pry'
require 'dotenv'
require 'stock_quote'
require 'sinatra'
require 'sinatra/reloader' if development?
Dotenv.load
set :server, 'webrick'
def twitter(company)
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["CONSUMER_KEY"]
config.consumer_secret = ENV["CONSUMER_SECRET"]
config.access_token = ENV["ACCESS_TOKEN"]
config.access_token_secret = ENV["ACCESS_SECRET"]
end
client.search("$#{company}".take(15).collect {|tweet|
"#{tweet.user.screen_name}: #{tweet.text}" }
end
get '/info/:stock' do
@stock = StockQuote::Stock.quote(params[:stock].to_s)
@tweets = twitter(params[:stock].to_s)
erb :twitter_and_stock
end
| true |
4d85f8e1eda359ac7d3c66658d6ddbe728897300 | Ruby | danielcpan/tic_tac_toe | /tic_tac_toe.rb | UTF-8 | 894 | 3.890625 | 4 | [] | no_license | class TicTacToe
def initialize(game_mode)
@game_mode = game_mode
start_game
end
def start_game
display_instructions
draw_board
end
def display_instructions
puts "Enter 1-9 to place on that tile (Q to quit game)"
end
def draw_board
tile = [1, 2, 3, 4, 5, 6, 7, 8, 9]
puts (" #{tile[0]} | #{tile[1]} | #{tile[2]}\n---+---+---\n #{tile[3]} | #{tile[4]} | #{tile[5]}\n---+---+---\n #{tile[6]} | #{tile[7]} | #{tile[8]}\n")
end
end
def display_menu
puts "1 - Play with Friend"
puts "2 - Play with AI"
end
user_input = nil
while (user_input != "Q" || user_input != "q")
display_menu
user_input = gets.chomp.to_i
case user_input
when 1 then new_game = TicTacToe.new("friend")
when 2 then new_game = TicTacToe.new("ai")
else
puts "Please choose either '1' or '2'"
end
# new_game.draw_board()
# new_game.display_menu
# user_input = gets.chomp
# break
end | true |
d03aa89ae6e774a0653b03ebc92ca06672ade90f | Ruby | oscaralbertoag/ruby-practice-excercises | /chatroom-status/spec/chatroom_status_spec.rb | UTF-8 | 834 | 2.578125 | 3 | [] | no_license | require "rspec/autorun"
require_relative "../lib/chatroom_status_solution.rb"
describe "chatroom_status()" do
test_cases = [[[], "no one online"],
[["becky325"], "becky325 online"],
[["becky325", "malcolm888"], "becky325 and malcolm888 online"],
[["becky325", "malcolm888", "fah32fa"], "becky325, malcolm888 and 1 more online"],
[["paRIE_to"], "paRIE_to online"],
[["s234f", "mailbox2"], "s234f and mailbox2 online"],
[["pap_ier44", "townieBOY", "panda321", "motor_bike5", "sandwichmaker833", "violinist91"], "pap_ier44, townieBOY and 4 more online"]]
test_cases.each do |test_case|
it "Returns \"#{test_case[1]}\" for users: #{test_case[0]}" do
expect(chatroom_status(test_case[0])).to eq(test_case[1])
end
end
end
| true |
7872b84ce696672d3261282d54d2ce300d876e24 | Ruby | hiroyuki-sato/pgroonga_like_test | /sample_gen.rb | UTF-8 | 460 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'csv'
require 'securerandom'
require 'uri'
urls = %w[
http://aa.yahoo.co.jp/
http://ab.yahoo.co.jp/
http://ac.yahoo.co.jp/
http://ad.yahoo.co.jp/
http://ae.yahoo.co.jp/
]
idx = 1
urls.each do |url|
%w[ aa bb cc dd ee ].each do |p|
1.upto(1000).each do |n|
# print [idx,URI.join(urls,p,SecureRandom.hex(15))].to_csv
puts [idx,File.join(url,p,SecureRandom.hex(15))].to_csv
idx += 1
end
end
end
| true |
461127b6aab6caaf7fb879ef7501c3ac8e095a7c | Ruby | AbbyJonesDev/AJAX_Puppy_HQ | /spec/controllers/puppies_controller_spec.rb | UTF-8 | 7,573 | 2.578125 | 3 | [] | no_license | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
RSpec.describe PuppiesController, :type => :controller do
# This should return the minimal set of attributes required to create a valid
# Puppy. As you add validations to Puppy, be sure to
# adjust the attributes here as well.
let!(:breed) { FactoryGirl.create(:breed) }
let(:valid_attributes) {
{ name: "Buddy", breed_id: breed.id }
}
let(:invalid_attributes) {
{ name: "" }
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# PuppiesController. Be sure to keep this updated too.
let(:valid_session) { {} }
# API TESTS
######################################################
describe "via API calls" do
let(:json) { JSON.parse(response.body) }
render_views
describe "GET /puppies.json" do
before do
duke = FactoryGirl.create(:puppy, name: "Duke")
spot = FactoryGirl.create(:puppy, name: "Spot")
get :index, format: :json
end
it "returns success code" do
expect(response.status).to eq(200)
end
it "returns puppies" do
names = json.collect { |n| n["name"] }
expect(names).to eq(["Duke", "Spot"])
end
end
describe "POST /puppies.json" do
context "successful puppy listing" do
before { post :create, format: :json, :puppy => { name: "Sadie", breed_id: "#{breed.id}"} }
it "returns success code" do
expect(response.status).to eq(201)
end
it "adds new puppy" do
expect(Puppy.last.name).to eq("Sadie")
end
it "returns puppy url" do
expect(response.location).to eq(puppy_url(Puppy.last))
end
end
context "invalid puppy - no breed" do
before { post :create, format: :json, :puppy => { name: "Elmo" } }
it "returns failure code" do
expect(response.status).to eq(422)
end
end
context "invalid puppy - nonexistant breed" do
before do
bad_id = Breed.last.id + 5
post :create, format: :json, :puppy => { name: "Mutt", breed_id: bad_id }
end
it "returns failure code" do
expect(response.status).to eq(422)
end
end
end
describe 'DELETE (ADOPT) /puppies/:id.json' do
let!(:adoptee) { FactoryGirl.create(:puppy) }
context 'successful adoption' do
it 'removes the puppy from the db' do
delete :destroy, format: :json, id: "#{adoptee.id}"
expect(Puppy.where(id: "#{adoptee.id}")).to be_empty
end
end
end
end
# STANDARD TESTS
######################################################
describe "GET index" do
it "assigns all puppies as @puppies" do
puppy = Puppy.create! valid_attributes
get :index, {}, valid_session
expect(assigns(:puppies)).to eq([puppy])
end
end
describe "GET show" do
it "assigns the requested puppy as @puppy" do
puppy = Puppy.create! valid_attributes
get :show, {:id => puppy.to_param}, valid_session
expect(assigns(:puppy)).to eq(puppy)
end
end
describe "GET new" do
it "assigns a new puppy as @puppy" do
get :new, {}, valid_session
expect(assigns(:puppy)).to be_a_new(Puppy)
end
end
describe "GET edit" do
it "assigns the requested puppy as @puppy" do
puppy = Puppy.create! valid_attributes
get :edit, {:id => puppy.to_param}, valid_session
expect(assigns(:puppy)).to eq(puppy)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new Puppy" do
expect {
post :create, {:puppy => valid_attributes}, valid_session
}.to change(Puppy, :count).by(1)
end
it "assigns a newly created puppy as @puppy" do
post :create, {:puppy => valid_attributes}, valid_session
expect(assigns(:puppy)).to be_a(Puppy)
expect(assigns(:puppy)).to be_persisted
end
it "redirects to the created puppy" do
post :create, {:puppy => valid_attributes}, valid_session
expect(response).to redirect_to(Puppy.last)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved puppy as @puppy" do
post :create, {:puppy => invalid_attributes}, valid_session
expect(assigns(:puppy)).to be_a_new(Puppy)
end
it "re-renders the 'new' template" do
post :create, {:puppy => invalid_attributes}, valid_session
expect(response).to render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested puppy" do
puppy = Puppy.create! valid_attributes
put :update, {:id => puppy.to_param, :puppy => new_attributes}, valid_session
puppy.reload
skip("Add assertions for updated state")
end
it "assigns the requested puppy as @puppy" do
puppy = Puppy.create! valid_attributes
put :update, {:id => puppy.to_param, :puppy => valid_attributes}, valid_session
expect(assigns(:puppy)).to eq(puppy)
end
it "redirects to the puppy" do
puppy = Puppy.create! valid_attributes
put :update, {:id => puppy.to_param, :puppy => valid_attributes}, valid_session
expect(response).to redirect_to(puppy)
end
end
describe "with invalid params" do
it "assigns the puppy as @puppy" do
puppy = Puppy.create! valid_attributes
put :update, {:id => puppy.to_param, :puppy => invalid_attributes}, valid_session
expect(assigns(:puppy)).to eq(puppy)
end
it "re-renders the 'edit' template" do
puppy = Puppy.create! valid_attributes
put :update, {:id => puppy.to_param, :puppy => invalid_attributes}, valid_session
expect(response).to render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested puppy" do
puppy = Puppy.create! valid_attributes
expect {
delete :destroy, {:id => puppy.to_param}, valid_session
}.to change(Puppy, :count).by(-1)
end
it "redirects to the puppies list" do
puppy = Puppy.create! valid_attributes
delete :destroy, {:id => puppy.to_param}, valid_session
expect(response).to redirect_to(puppies_url)
end
end
end
| true |
bf101626442f0699b4e3f5832dc1794231165322 | Ruby | ekearm/budgiet_finance | /Budgiet/budgietv1.rb | UTF-8 | 808 | 3.765625 | 4 | [] | no_license | class Paycheck
def initialize
attr_accessor :name, :last_amnt
end
puts "Hello, I am Budgiet your personal finance and budget assistant. Lets start by getting your name."
p1 = gets.chomp
puts "Nice to meet you #{p1}"
puts "First to get started with how many jobs with pay checks do you have?"
num_pychks = gets.to_i
if num_pychks > 1
puts"Wow. You work alot"
#Will create a pay check object for each pay check entered
num_pychks.times do |i|
pay_numb = i + 1
puts"Enter the name of the pay check #{pay_numb}:"
chck_name = gets.chomp.to_s
puts"Enter the last amount you recivied#{pay_numb}:"
lst_amount = gets.chomp.to_i
check = Paycheck.new
check.chck_name = name
check.lst_amount = last_amnt
end
else
puts "Wow this will be easy."
end
end | true |
f6b02d9ee5ced880804374ff22b09dff14e826f3 | Ruby | howclf/RubyCode | /simple_grep.rb | UTF-8 | 186 | 3.328125 | 3 | [] | no_license | # simple example to grep files
pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
file = open(filename)
while text = file.gets do
if pattern =~ text
print(text)
end
end
file.close
| true |
d9c748c211f2de316b4cff563d8ec3763d6f07c1 | Ruby | bryanstearns/fest2 | /config/initializers/basic_type_extensions.rb | UTF-8 | 2,573 | 3.296875 | 3 | [] | no_license | module TimeExtensions
# Add step() to times, too
def step(limit, step)
v = self
while v < limit
yield v
v += step
end
end
def date
# Get the date corresponding to this time
Date.civil(self.year, self.month, self.day)
end
def parts(include_zero_minutes=true)
# Get the parts for formatting this time, with niceties like
# "noon" & "midnight"
if min == 0
if hour == 0
return "midnight", "", ""
elsif hour == 12
return "noon", "", ""
end
end
if hour >= 12
suffix = " pm"
h = hour - (hour > 12 ? 12 : 0)
else
suffix = " am"
h = hour == 0 ? 12 : hour
end
m = ":#{strftime("%M")}" if min != 0 or include_zero_minutes
[h, m, suffix]
end
def to_time_label(include_zero_minutes=true)
return parts(include_zero_minutes).join("")
end
def round_down
# Return ourself, rounded down to next hour
return self if min % 60 == 0 # already at an hour boundary
self - ((60 * min) + sec)
end
def round_up
# Return ourself, rounded up to next hour
down = round_down
return self if self == down # already at an hour boundary
down + (60 * 60)
end
def to_minutes
# Return the number of minutes since the start of today
(self.hour * 60) + self.min
end
end
class Time
include TimeExtensions
end
class ActiveSupport::TimeWithZone
include TimeExtensions
end
class Float
def to_minutes
(self / 60.0).to_i
end
end
class String
def quote(end_punctuation=nil)
"“#{self}#{end_punctuation}”"
end
end
class Numeric
WORDS = %w[no one two three four five six seven eight nine ten]
def in_words
# five, six, 11 (and uses "no" for the zero case)
WORDS.fetch(self, self.to_s)
end
def counted(name)
# five fish, no octopi, one weasel
name = name.pluralize if self != 1
"#{self.in_words} #{name}"
end
def to_duration
# Format a duration (in seconds) meaningfully: "0.100ms", "3s", "4.05m"
return sprintf("%0.3gd", self / 1.0.day) if self > 2.days
return sprintf("%0.3gh", self / 1.0.hour) if self > 2.hours
return sprintf("%0.3gm", self / 1.0.minute) if self > 2.minutes
return sprintf("%0.3gms", self * 1000.0) if self < 0.1.seconds
(self.truncate == self) ? "#{self}s" : sprintf("%0.3fs", self)
end
end
class Array
def average
sum.to_f / count
end
end
class Hash
def without(*excludees)
# Return a copy of this hash with these keys removed
reject {|k, v| excludees.include?(k) }
end
end
| true |
cbec435fb8e5c86d3f337ec312b9a88f8b5c215c | Ruby | ualbertalib/sufia_migrate | /lib/sufia_migrate/export/versions_from_graph.rb | UTF-8 | 1,394 | 2.984375 | 3 | [] | no_license | # frozen_string_literal: true
module Export
class VersionsFromGraph
attr_accessor :versions
class Version
attr_accessor :uri, :label, :created
def initialize(uri, label, created)
@uri = uri
@label = label
@created = created
end
end
# Converts a graph with version information to an array of Version objects
def self.parse(graph)
versions = []
find_uris(graph).each do |uri|
created = find_created(uri, graph)
label = find_label(uri, graph)
version = Version.new(uri, label, created)
versions << version
end
versions
end
def self.find_uris(graph)
uris = []
graph.each do |triple|
if triple.predicate.to_s == "http://fedora.info/definitions/v4/repository#hasVersion"
uris << triple.object.to_s
end
end
uris
end
def self.find_created(uri, graph)
predicate = "http://fedora.info/definitions/v4/repository#created"
find_triple(uri, predicate, graph)
end
def self.find_label(uri, graph)
predicate = "http://fedora.info/definitions/v4/repository#hasVersionLabel"
find_triple(uri, predicate, graph)
end
def self.find_triple(uri, predicate, graph)
triple = graph.find { |t| t.subject == uri && t.predicate == predicate }
triple.object.to_s
end
end
end
| true |
159292ade12b835dd0d560a5ad09fd149a6dd222 | Ruby | jonashermann/a_real_web_server_and_browser | /server.rb | UTF-8 | 1,227 | 2.984375 | 3 | [] | no_license | require 'socket'
require 'json'
server = TCPServer.open(3000)
loop{
Thread.start(server.accept)do |client|
#REVIEW: short-term fix solution
#for reading request from client
#research others solutions.
#read_nonblock(256)?
request = client.read_nonblock(256)
request_headers, request_body = request.split("\r\n\r\n", 2)#Parse the Http request
path = request_headers.split[1][1..-1]
method = request_headers.split[0]
if File.exist?(path)
response_body = File.read(path)
client.puts "HTTP/1.0 200 OK\r\nContent-type:text/html\r\n\r\n"
client.puts"size: #{File.size(response_body)} KO\r\n\r\n"
if method == "GET"
client.puts response_body
elsif method == "POST"
params = JSON.parse(response_body)#deserialize:json=>ruby with JSON.parse method
user_data = "<li>name: #{params["person"]["name"]}</li><li>email: #{params["person"]["email"]}</li>"
client.puts response_body.gsub("<%=yield%>", user_data)
end
else
client.puts"HTTP/1.0 404 Not found \r\n\r\n"
client.puts "404 Error File Could not be Found"
end
client.close
end
}
| true |
046582c0b0f329eb852cef4a5f4ffd238c86d176 | Ruby | monicamendesmontanha/warmup | /06_scrabbleScore/scrabble_score.rb | UTF-8 | 1,840 | 4.65625 | 5 | [] | no_license | # Write a program that, given a word, computes the scrabble score for that word.
# scrabble("cabbage")
# # => 14
# Your program should be in a file named scrabble.rb. You should be able to compute the score for any word entered by the user.
# Letter Values
# Letter Value
# A, E, I, O, U, L, N, R, S, T 1
# D, G 2
# B, C, M, P 3
# F, H, V, W, Y 4
# K 5
# J, X 8
# Q, Z 10
# Extensions
# You can play a :double or a :triple letter.
# You can play a :double or a :triple word.
# Version 1
# def calc_score word
# scrabble_letters = {
# 1 => ["A", "E", "I", "O", "U", "L", "N", "R", "S", "T"],
# 2 => %w{D G},
# 3 => %w{B C M P},
# 4 => %w{F H V W Y},
# 5 => %w{K},
# 8 => %w{J X},
# 10 => %w{Q Z}
# }
# score = 0
# word.upcase.each_char do |letter|
# scrabble_letters.each do |key, value|
# if scrabble_letters[key].include? letter
# score += key
# end
# end
# end
# score
# end
# puts "Please enter a word"
# input = gets.chomp
# output = calc_score input
# puts "Your Word: #{input}"
# puts "Your Word Score: #{output}"
# Version 2
def calc_score word
scrabble_letters = {
"A"=>1, "E"=>1, "I"=>1, "O"=>1, "U"=>1, "L"=>1, "N"=>1, "R"=>1, "S"=>1, "T"=>1,
"D"=>2, "G"=>2,
"B"=>3, "C"=>3, "M"=>3, "P"=>3,
"F"=>4, "H"=>4, "V"=>4, "W"=>4, "Y"=>4,
"K"=>5,
"J"=>8, "X"=>8,
"Q"=>10, "Z"=>10
}
score = 0
word.upcase.each_char do |letter|
score += scrabble_letters[letter]
end
score
end
puts "Please enter a word"
input = gets.chomp
output = calc_score input
puts "Your Word: #{input}"
puts "Your Word Score: #{output}" | true |
5825e8f778d9416ff470a95d88cc3059bca0c800 | Ruby | matttproud/ruby_quantile_estimation | /profile/quantile.rb | UTF-8 | 608 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | require 'ruby-prof'
require 'time'
require_relative '../lib/quantile'
runs = 2 ** 12
time = Time.now.strftime('%Y-%m-%d-%H-%M-%S')
estimator = Quantile::Estimator.new
{
:observe => lambda { |_| estimator.observe(rand) },
:query => lambda { |_| estimator.query(0.5) },
}.each do |report, test|
profile = RubyProf.profile do
runs.times(&test)
end
profile.eliminate_methods!([/Integer#times/, /Kernel#rand/])
filename = File.expand_path("#{report}-#{time}.html", File.dirname(__FILE__))
File.open(filename, 'w') do |file|
RubyProf::GraphHtmlPrinter.new(profile).print(file)
end
end
| true |
ddec34535b56b8a11dc5cb0a35b7626bb1e5c5ee | Ruby | aliashafi/W4D3 | /chess/modules/stepable.rb | UTF-8 | 311 | 2.734375 | 3 | [] | no_license | module Stepable
def moves
dirs = self.move_diffs # give us offsets for piece
current_pos = self.pos #current_pos
all_moves = []
dirs.each do |offset|
all_moves << [current_pos[0] + offset[0], current_pos[1] + offset[1]]
end
all_moves
end
private
def move_diffs
end
end | true |
b309477243b286f4ae6cf41a1d0e370f24f0b3d0 | Ruby | Nerajno/many-to-many-through-event-ticket-attendee | /many-to-many-through-event-ticket-attendee/tools/console.rb | UTF-8 | 1,088 | 3.109375 | 3 | [] | no_license | require_relative '../config/environment.rb'
def reload
load 'config/environment.rb'
end
# Insert code here to run before hitting the binding.pry
# This is a convenient place to define variables and/or set up new object instances,
# so they will be available to test and play around with in your console
#Example of a variable definition that will be available in your Pry session once you've built out the model:
event1 = Event.new("Party 1", 7000, 50)
event2 = Event.new("Party 2", 6000, 70)
event3 = Event.new("Party 3", 5500, 65)
Event.all
lucy = Attendee.new("Lucy", 22)
frank = Attendee.new("Frank", 19)
mary = Attendee.new("Mary", 44)
marshall = Attendee.new("M&M", 43)
Attendee.all
ticket1 = Ticket.new(lucy,event1)
ticket2 = Ticket.new(lucy,event3)
ticket3 = Ticket.new(mary, event2)
ticket4 = Ticket.new(marshall,event1)
Ticket.all
lucy.events #// lucy.my_events
lucy.money_spent
event1.average_age
#extra attendee & ticket
#The variable `lucy` will point to an instance of a new attendee
binding.pry
0 #leave this here to ensure binding.pry isn't the last line
| true |
99c25504444f405cfddf00b75a6455e503bbd26d | Ruby | ppibburr/GirFFISugar | /lib/GObject/lib/payload.rb | UTF-8 | 1,779 | 2.59375 | 3 | [] | no_license | require File.join(File.dirname(__FILE__),"ffi.rb")
require File.join(File.dirname(__FILE__),"subclass_normalize.rb")
module GObject
load_class :Object
class Object
# set's up the farthest ancestor's method
# q, method name, String|Symbol
# b method body, optional, if passed, defines method q
def self.overide q,&b
a = ancestors.find_all do |a|
a.instance_methods.index(q)
end.last
a._setup_instance_method(q.to_s)
define_method(q,&b) if b
end
end
end
module ConstructorOveride
def self.included cls
cls.class_eval do
def self.add_constructor *signature,&b
@constructors << [signature,b]
end
@constructors = []
def self.constructors
@constructors
end
def self.use_constructor_overides
_setup_method :new.to_s
def self.print_constructs
possibles = @constructors.map do |c| c[0] end
buff = ["possible constructors are:\n"]
possibles.each do |pc|
buff << "#{self}.new(#{pc.join(", ")})"
end
buff.join("\n")
end
class << self
alias :new__ :new
end
def self.new *o
ca = @constructors.find_all do |cs|
cs[0].length == o.length
end
c = ca.find do |cs|
a = []
cs[0].each_with_index do |q,i|
a << o[i].is_a?(q)
end
!a.index(false)
end
if c
instance_exec(*o,&c[1])
else
raise "no constructor for signature found\n#{print_constructs}"
end
end
end
end
end
end
module GObject
load_class :Object
class Object
class << self
alias :inherited_ :inherited
end
def self.inherited cls
result = inherited_(cls)
cls.class_eval do
include ConstructorOveride
end
result
end
end
end
| true |
3552f28dcbfebd55c601d08b30ed0effa925b2ed | Ruby | calb3ars/aa2 | /w2/w2d1/exercises/lib/00_rpn_calculator.rb | UTF-8 | 1,166 | 3.953125 | 4 | [
"MIT"
] | permissive | class RPNCalculator
OPERATORS = [:+, :-, :*, :/]
def initialize
@stack = []
end
def push(el)
@stack << el
end
def evaluate(string)
tokens(string).each do |char|
case char
when Integer
push(char)
when Symbol
perform_op(char)
end
end
value
end
def plus
perform_op(:+)
end
def minus
perform_op(:-)
end
def divide
perform_op(:/)
end
def times
perform_op(:*)
end
def tokens(string)
results = string.split(" ")
results.map { |el| OPERATORS.include?(el.to_sym) ? el.to_sym : Integer(el) }
end
def value
@stack.last
end
private
def perform_op(op_sym)
raise "calculator is empty" unless @stack.count >= 2
right_value = @stack.pop
left_value = @stack.pop
case op_sym
when :+
@stack << left_value + right_value
when :-
@stack << left_value - right_value
when :*
@stack << left_value * right_value
when :/
@stack << left_value.fdiv(right_value)
else
@stack << left_value < right_value
raise ArgumentError.new("No operation #{op_sym}")
end
self
end
end
| true |
f2c93a62dd3345b0feec19b3b4edc7044c5b1e45 | Ruby | nkelton/wik-wak | /app/services/factories/vote_factory.rb | UTF-8 | 1,150 | 2.640625 | 3 | [] | no_license | module Factories
class VoteFactory < Factory
Result = Struct.new(:response, :errors, :code, keyword_init: true)
SUCCESS = "success"
ERROR = "error"
POST_NOT_FOUND_ERROR = "Post Not Found"
POST_NOT_CREATED = "Post Could Not Be Created"
def initialize
super
@result = Result.new(response: nil, errors: [], code: SUCCESS)
end
def create(vote_attributes:)
vote = Vote.new(vote_attributes)
if vote.save
@result.response = vote
_queue_summary_vote(vote: vote)
else
@result.code = ERROR
@result.errors = vote.errors
end
@result
end
private
def _queue_summary_vote(vote:)
if vote.is_post?
PostSummaryVoteWorker.perform_async({ value: vote.value, post_id: vote.post_id })
elsif vote.is_comment?
CommentSummaryVoteWorker.perform_async({ value: vote.value, comment_id: vote.comment_id })
end
end
end
end
| true |
0ae6f0f6ea4cb854f914aaefd77f52d2202701f2 | Ruby | indepat/Intro-Programming | /6_Arrays/Arrays_Exercise3.rb | UTF-8 | 164 | 3.078125 | 3 | [] | no_license | #How do you return the word "example"
#from the following array?
arr = [["test", "hello", "world"],["example", "mem"]]
arr.last.include?("example")
#Returned True
| true |
1658b127c37073c5cd4c25bce2cd8171287bea2e | Ruby | brentgreeff/acts_as_human | /spec/acts_as_human_spec.rb | UTF-8 | 5,014 | 2.6875 | 3 | [
"MIT"
] | permissive | class Model < ActiveRecord::Base
end
RSpec.describe ActsAsHuman do
context 'A Model that acts as a human' do
before do
Model.class_eval do
acts_as_human
end
end
context 'when the user is new' do
let(:user) { Model.new }
it 'has an empty full_name' do
expect( user.full_name ).to eq ''
end
end
context 'A name assiged through first_name and last_name' do
let(:user) { Model.new first_name: 'Nelson', last_name: 'Mandela' }
it 'has a full_name' do
expect( user.full_name ).to eq 'Nelson Mandela'
end
end
context 'A name assiged through first_name, middle_names and last_name' do
let(:user) do
Model.new first_name: 'Nelson',
middle_names: 'Madiba Rolihlahla', last_name: 'Mandela'
end
it 'has a full_name' do
expect( user.full_name ).to eq 'Nelson Madiba Rolihlahla Mandela'
end
end
context 'A name assigned through full_name' do
let(:user) { Model.new full_name: 'Nelson Mandela' }
it 'has a first_name and last_name' do
expect( user.first_name ).to eq 'Nelson'
expect( user.last_name ).to eq 'Mandela'
end
end
context 'A name assigned through full_name with middle_names' do
let(:user) { Model.new full_name: 'Nelson Madiba Rolihlahla Mandela' }
it 'has a first_name and last_name' do
expect( user.first_name ).to eq 'Nelson'
expect( user.middle_names ).to eq 'Madiba Rolihlahla'
expect( user.last_name ).to eq 'Mandela'
end
end
context 'assigned a Scottish name' do
let(:user) { Model.new full_name: 'Ewan Mc Greggor' }
it 'is split up correctly' do
expect( user.first_name ).to eq 'Ewan'
expect( user.last_name ).to eq 'Mc Greggor'
end
end
context 'assigned another Scottish name' do
let(:user) { Model.new full_name: 'Jade Frances Roseanne Mc Cracken' }
it 'is split up correctly' do
expect( user.first_name ).to eq 'Jade'
expect( user.middle_names ).to eq 'Frances Roseanne'
expect( user.last_name ).to eq 'Mc Cracken'
end
end
context 'without a first_name' do
let(:user) { user = Model.new }
before { user.first_name = '' }
it "is invalid" do
expect(user.valid?).not_to be
expect(
user.errors[:first_name]
).to include 'first name is required'
end
end
context 'without a last_name' do
let(:user) { Model.new first_name: 'Brent', last_name: '' }
it "is invalid" do
expect(user.valid?).not_to be
expect(
user.errors[:last_name]
).to include 'last name is required'
end
end
context 'when the first name is assigned through full_name' do
let(:user) { Model.new full_name: 'Brent' }
it 'requires a last_name' do
expect(user.valid?).not_to be
expect(
user.errors[:last_name]
).to include 'last name is required'
end
end
context 'with invalid characters' do
let(:user) { Model.new full_name: '<Brent> Middle >< Names Gre&eff' }
it 'is invalid' do
expect(user.valid?).not_to be
expect(
user.errors[:first_name]
).to include 'some characters in your name are not allowed'
expect(
user.errors[:last_name]
).to include 'some characters in your name are not allowed'
expect(
user.errors[:middle_names]
).to include 'some characters in your name are not allowed'
end
end
context 'with a first_name that is over 40 characters' do
let(:user) do
Model.new first_name: 'over 40 characters----over 40 characters*'
end
it 'is invalid' do
expect(user.valid?).not_to be
expect(
user.errors[:first_name]
).to include 'first name is too long (max 40 characters)'
end
end
context 'with a last_name that is over 40 characters' do
let(:user) do
Model.new last_name: 'over 40 characters----over 40 characters*'
end
it 'is invalid' do
expect(user.valid?).not_to be
expect(
user.errors[:last_name]
).to include 'last name is too long (max 40 characters)'
end
end
context 'with middle_names that are over 40 characters' do
let(:user) do
Model.new middle_names: 'over 40 characters----over 40 characters*'
end
it 'is invalid' do
expect(user.valid?).not_to be
expect(
user.errors[:middle_names]
).to include 'middle names are too long (max 40 characters)'
end
end
end
context 'A Model that acts as a human' do
context 'and doesnt require a last_name' do
before do
Model.class_eval do
acts_as_human require_last_name: false
end
end
context 'without a last_name' do
let(:user) { Model.new first_name: 'Brent', last_name: '' }
it "is valid" do
expect(user.valid?).to be
end
end
end
end
end
| true |
636ac7e3f60ae35fe9535c12505c38c2e543db0e | Ruby | iazigit/thp-homework | /rubyDay1/exo_19.rb | UTF-8 | 210 | 2.5625 | 3 | [] | no_license | fake_emails = []
for i in 1..100
fake_emails << "jean.mouloud#{i.to_s.rjust(3,'0')}@yahoo.fr"
end
puts fake_emails
fake_emails.each_with_index do |email, index|
if index %2 == 0
puts email
end
end
| true |
2ad4dd8fb488c1fa66b9c9deeced9ea7e47f366b | Ruby | david50407/eatwhat | /dict.rb | UTF-8 | 294 | 2.84375 | 3 | [] | no_license | #!/usr/bin/env ruby
# encoding: utf-8
class EatWhatDict
attr_reader :foods
attr_reader :ops
@foods = []
@ops = []
def initialize
@foods = []
@ops = []
end
def foods=(val)
puts "dict here!"
@foods = val.uniq
end
def ops=(val)
@ops = val.uniq
end
end
| true |
dede35ff36694bf100f438e6b9d12d5a97ecadde | Ruby | fcarlosdev/the_odin_project | /tdd/caesar_cipher/spec/caesar_cipher_spec.rb | UTF-8 | 1,130 | 3.375 | 3 | [] | no_license | require './caesar_cipher'
describe "Caesar Cipher" do
def load_cipher(word,key)
ciphred_characteres = cipher(word,key)
ciphred_characteres
end
context "with the word or a letter and a key provided" do
it "cipher the given word by a key" do
expect(load_cipher("tomorrow",7)).to eq("avtvyyvd")
end
it "cipher the given letter by a key" do
expect(load_cipher("m",7)).to eq("t")
end
it "cipher the word preserving punctuation characters" do
expect(load_cipher("hello!",7)).to eq("olssv!")
end
it "cipher the word preserving the others characters" do
expect(load_cipher("hello world!",7)).to eq("olssv dvysk!")
end
it "cipher the word preserving the uppercase" do
expect(load_cipher("HELLO WORLD!",7)).to eq("OLSSV DVYSK!")
end
it "cipher the word wrapping the letters from z to a" do
expect(load_cipher("zeus",1)).to eq("afvt")
end
it "cipher the word preserving uppercase and dowcase" do
expect(load_cipher("Ruby on Rails!",7)).to eql("Ybif vu Yhpsz!")
end
end
end
| true |
286cd518bf61ed6d65fa27528b17a65ee2b179a2 | Ruby | amittauro/BorisBikes | /test_framework.rb | UTF-8 | 281 | 3.625 | 4 | [] | no_license | require 'colorize'
def assert_equals(val1, val2)
val1 == val2
end
def it(description, &block)
result = block.call # return a boolean (hopefully)
if result == true
puts "#{description}: Yeah, Great!".green
else
puts "#{description}: Try again... :(".red
end
end
| true |
3d41fb828cfa4f11da2b202e642ba4887a7cf597 | Ruby | mikechau/edx | /cs-169.1x/Week 2/hw1/part1.rb | UTF-8 | 621 | 3.5625 | 4 | [] | no_license | #For those just starting out, one suggested way to work on your code is to have a command window open and a text editor with this
#file loaded. Make changes to this file and then run 'ruby part1.rb' at the command line, this will run your program. Once you're
#satisfied with your work, save your file and upload it to the checker.
def palindrome?(str)
scrub_str = str.gsub(/[^a-zA-Z]/, "").downcase
scrub_str.reverse == scrub_str
end
def count_words(str)
word_count = Hash.new(0)
scrub_str = str.gsub(/[^a-zA-Z ]/, "").downcase
scrub_str.split(" ").each { |word| word_count[word] += 1 }
word_count
end
| true |
e2953db2e01a3595ca30c54a3b98ea8fd2147d0e | Ruby | zhisme/notes_backend | /app/services/collection_builder.rb | UTF-8 | 1,396 | 2.78125 | 3 | [] | no_license | class CollectionBuilder
attr_reader :params, :collection
DEFAULT_SORT_DIR = :desc
class CollectionNotBuilded < StandardError; end
def self.call(params, collection)
new(params, collection).call
end
def call
return search if SqlCommandDefiner.search?(params)
return sort if SqlCommandDefiner.sort?(params)
return group if SqlCommandDefiner.group?(params)
return group_by_story if SqlCommandDefiner.group_by_story?(params)
raise CollectionNotBuilded
end
private
def initialize(params, collection)
@params = params
@collection = collection
end
def search
collection.where('LOWER(name) LIKE :term OR LOWER(text) LIKE :term', term: "%#{params[:term].downcase}%")
end
def sort
sort_by = params[:sort_by].to_s
sort_direction = params[:sort_direction].to_s.presence || DEFAULT_SORT_DIR
collection.order(sort_by => sort_direction)
end
def group
collection.group_by { |ar| ar[params[:group_by]].to_s }
end
def group_by_story
return group_by_story_articles_count if params[:group_by_story] == 'articles_count'
group_by_story_articles_kind_count
end
def group_by_story_articles_count
Story.includes(:articles).order(articles_count: :desc).map(&:articles)
end
def group_by_story_articles_kind_count
Story.includes(:articles).order(articles_kind_count: :desc).map(&:articles)
end
end
| true |
d1093128887ae698e8d82503352705c5ee139369 | Ruby | TomYang1993/OOP_easy_example | /store_item.rb | UTF-8 | 603 | 3.625 | 4 | [] | no_license | # item1 = {name: "apple",price: 40, weight: 3}
# item2 = {name: "peach",price: 30, weight: 2}
# item3 = {name: "kiwi" ,price: 20, weight: 1}
module Storefont
class Store
attr_reader :name, :price, :weight
def initialize(input)
@name = input[:name]
@price = input[:price]
@weight = input[:weight]
end
end
end
item_1 = Storefont::Store.new({price: 40, weight: 3, name: "apple"})
item_2 = Storefont::Store.new({price: 40, weight: 3, name: "apple"})
item_3 = Storefont::Store.new({price: 40, weight: 3, name: "apple"})
puts item_1.price
puts item_2.name
puts item_3.weight
| true |
9cede565fb636b1f98f7f17407adf6f6e9758212 | Ruby | spraints/t | /lib/t/commands/since.rb | UTF-8 | 877 | 2.765625 | 3 | [
"MIT"
] | permissive | require 't'
require 't/data'
module T
module Commands
class Since
def initialize(options = {})
@stdout = options.fetch(:out) { $stdout }
@file = options.fetch(:file) { T::DATA_FILE }
@time = options.fetch(:time) { Time }
@act = options.fetch(:act) { T.activity_words }
end
def run
if total == 0
@stdout.puts "You have not #{@act.past_participle} #{period_description}."
else
@stdout.puts "You have #{@act.past_participle} for #{total} minutes #{period_description}."
end
end
def total
return @total if @total
data = Data.new(@file)
now = @time.now.strftime(T::TIME_FORMAT)
@total = data.entries.each { |e| e.stop ||= now }.inject(0) { |sum, e| sum + e.minutes_between(range_start, range_stop) }
end
end
end
end
| true |
3e625939605dd4807378b8a99f4fb0de4dd0657d | Ruby | NUOCW-Project/ocw-design-en | /scripts/mb_check.rb | UTF-8 | 2,170 | 2.84375 | 3 | [] | no_license | # In ruby 1.6.8, 'open-uri' and 'optparse' library can not be used...
require 'getoptlong'
require 'net/http'
Net::HTTP.version_1_2
# Regular Expressions for a multibyte character
shift_jis = /[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc]/n
euc_jp = /[\xa1-\xfe][\xa1-\xfe]/n
utf8 = / [\xc0-\xdf][\x80-\xbf] | [\xe0-\xef][\x80-\xbf]{2}
| [\xf0-\xf7][\x80-\xbf]{3} | [\xf8-\xfb][\x80-\xbf]{4}
| [\xfc-\xfd][\x80-\xbf]{5} /xn
# Flags
local = false
no_mb = true
# Options
def usage
puts "Usage: ruby #{$0}"
puts "\t or: ruby #{$0} FILE... --local "
exit 0
end
parser = GetoptLong.new(
["--local", GetoptLong::OPTIONAL_ARGUMENT],
["--help", "-h", GetoptLong::NO_ARGUMENT])
parser.each{|opt, arg|
case opt
when "--local" then local = true
when "--help" then usage
end
} rescue exit 1
# main
if (!local) then
host = "ocw.media.nagoya-u.ac.jp"
dir = "/preview/"
first_page = "index.php?lang=en"
# breadth first search
open_list = Array[first_page]
closed_list = Array.new
# HTTP Request
Net::HTTP.start(host){|http|
while !open_list.empty?
page = open_list.shift
closed_list.push(page) unless closed_list.include?(page)
res = http.get(dir + page)
res.body.split("\n").each_with_index{|line, i|
# detect a multibyte character
if (line =~ shift_jis || line =~ euc_jp || line =~ utf8) then
no_mb = false
puts "> file: #{page} line: #{i+1}"
puts "\t" + line.strip
end
# push all unvisited links in the page into open_list
links = line.scan(/<a href="(?:\.\/)?(index\.php\?lang=en.*?)(?!#)">/).flatten.uniq
links = links.delete_if{|l| l =~ /page_type=feedback/}
if (!links.empty?) then
open_list |= links - closed_list
end
}
end
}
else
# process local file(s)
while line = ARGF.gets
if (line =~ shift_jis || line =~ euc_jp || line =~ utf8) then
no_mb = false
puts "> file: #{ARGF.filename} line: #{ARGF.file.lineno}"
puts "\t" + line
end
end
end
if (no_mb) then
puts "No multibyte character was found."
end
| true |
d5c078bfd4ac6cb4abb199d34454567f1bf54bcb | Ruby | HNH12/Design-Pattern | /Ruby/Седьмая_лаба/WorkWithDB.rb | UTF-8 | 4,186 | 2.78125 | 3 | [] | no_license | require_relative 'Employee.rb'
require_relative 'Post'
require 'mysql2'
class DB_work
@@DB_connection = nil
# private_class_method :new
def initialize
@client = Mysql2::Client.new(
:host => 'localhost',
:username => 'root',
:database => 'stuff'
)
end
def self.DB_connection
if @@DB_connection == nil
@@DB_connection = DB_work.new
end
end
def add_to_DB(emp)
emp_previous_work = emp.previous_work == 'Поле не указано' ? nil : emp.previous_work
emp_previous_post = emp.previous_post == 'Поле не указано' ? nil : emp.previous_post
emp_previous_salary = emp.previous_salary == 'Поле не указано' ? nil : emp.previous_salary
if emp_previous_salary == nil || emp_previous_post == nil || emp_previous_work == nil
@client.query("INSERT INTO `stuff`.`employees` (`Name` ,`Birthday` ,`PhoneNumber` ,`Address` ,`Email` ,
`Passport` ,`Specialty` ,`WorkExperience`)
VALUES ('#{emp.name}', '#{emp.birthday}', '#{emp.phone_number}', '#{emp.address}', '#{emp.email}',
'#{emp.passport}', '#{emp.specialty}', #{emp.work_experience.to_i})")
else
@client.query("INSERT INTO `stuff`.`employees` (`Name` ,`Birthday` ,`PhoneNumber` ,`Address` ,`Email` ,
`Passport` ,`Specialty` ,`WorkExperience`, `PreviousWork` ,`PreviousPost` ,`PreviousSalary`)
VALUES ('#{emp.name}', '#{emp.birthday}', '#{emp.phone_number}', '#{emp.address}', '#{emp.email}',
'#{emp.passport}', '#{emp.specialty}', #{emp.work_experience.to_i},
'#{emp_previous_work}', '#{emp_previous_post}', #{emp_previous_salary})")
end
end
def change_node(all_emp)
all_emp.each { |emp|
emp_previous_work = emp.previous_work == 'Поле не указано' ? nil : emp.previous_work
emp_previous_post = emp.previous_post == 'Поле не указано' ? nil : emp.previous_post
emp_previous_salary = emp.previous_salary == 'Поле не указано' ? nil : emp.previous_salary
emp.name = 'Толстиков Илья Вадимович'
if emp_previous_salary == nil || emp_previous_post == nil || emp_previous_work == nil
@client.query("UPDATE employees SET Name = '#{emp.name}'
WHERE Passport = '#{emp.passport}'")
else
@client.query("UPDATE employees SET Name = '#{emp.name}'
WHERE Passport = '#{emp.passport}'")
end
}
end
def delete_from_db(all_emp)
all_emp.each { |emp| emp
@client.query("DELETE FROM employees WHERE Passport = '#{emp.passport}'")
}
end
def read_db
new_list = []
@client.query("SELECT * FROM employees").each do |row|
new_list.append(Employee.new(row['Name'], row['Birthday'].to_s, row['PhoneNumber'], row['Address'],
row['Email'], row['Passport'].to_s, row['Specialty'], row['WorkExperience'],
row['PreviousWork'], row['PreviousPost'], row['PreviousSalary']))
end
new_list
end
def post_list_read_db(department_name)
new_list= []
if department_name != nil
department_id = @client.query("SELECT DepartmentID FROM departments WHERE DepartmentName = '#{department_name}'")
results = []
department_id.each do |field|
results = @client.query("SELECT * FROM post WHERE DepartmentID = #{field['DepartmentID']}")
end
results.each do |row|
fixed_premium = row['FixedPremiumSize']
quarterly_award = row['QuarterlyAwardSize']
possible_bonus = row['PossibleBonusPercent']
new_list << Post.new(row['PostName'], row['FixedSalary'], fixed_premium, quarterly_award, possible_bonus)
end
else
results = @client.query("SELECT * FROM post")
results.each do |row|
fixed_premium = row['FixedPremiumSize']
quarterly_award = row['QuarterlyAwardSize']
possible_bonus = row['PossibleBonusPercent']
new_list << Post.new(row['PostName'], row['FixedSalary'], fixed_premium, quarterly_award, possible_bonus)
end
end
new_list
end
def post_id_read_db(post)
results = @client.query("SELECT PostID FROM post WHERE PostName = #{post}")
end
end | true |
d92ad1ff01f809548ad449713e76694df67c627d | Ruby | Whapow/overlord-shovel-backend | /spec/models/stack_spec.rb | UTF-8 | 2,262 | 2.6875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Stack do
let (:inventory) { create :inventory }
let (:item1) { create :item }
let (:item2) { create :item }
let (:stack1) { create :stack, inventory: inventory, item: item1, position: 1 }
let (:stack2a) { create :stack, inventory: inventory, item: item2, position: 2 }
let (:stack2b) { create :stack, inventory: inventory, item: item2, position: 3 }
before do
@inventory = create :inventory
@item1 = create :item
@item2 = create :item
end
it 'cannot be placed on top of an existing stack' do
stack1 = create :stack, inventory: @inventory, position: 1
stack2 = create :stack, inventory: @inventory, position: 2
expect {stack1.update!(position: stack2.position)}.to raise_error(ActiveRecord::RecordInvalid,'Validation failed: Position There is already a stack of items in that spot.')
end
context "combination" do
it 'is prevented when item_id does not match' do
stack1 = create :stack, inventory: @inventory, item: @item1
stack2 = create :stack, inventory: @inventory, item: @item2
expect(stack1.combine(stack2)).to eq false
expect(stack1.errors.messages[:item_id]).to include 'mismatch'
end
it 'updates both stacks' do
stack1 = create :stack, inventory: @inventory, item: @item1
stack2 = create :stack, inventory: @inventory, item: @item1
initial_quantity = stack1.quantity
stack2.combine(stack1)
expect(stack1.quantity).to eq(initial_quantity + stack2.quantity)
expect(stack2.discarded_at).not_to be_nil
end
end
context "split" do
before(:each) do
@stack = create :stack
end
it 'fails when requested stack size exceed quantity' do
expect(@stack.split(@stack.quantity + 10)).to eq false
expect(@stack.errors.messages[:quantity]).to include 'insufficient quantity'
end
it 'reduces the quantity by the requested stack size' do
initial_quantity = @stack.quantity
@stack.split(5)
expect(@stack.quantity).to eq(initial_quantity - 5)
end
it 'creates a new stack of the requested size' do
# expect(Stack).to receive(:create!)
# expect { new_stack = @stack.split(5) }.to change { Stack.count }.by(1)
end
end
end
| true |
23b6bfb29f3e9daef41d57527cc6f56dbaf99271 | Ruby | awesome-academy/naitei-ruby-2020-airport-workspace-management | /awm-api/lib/helpers/password_reset_helper.rb | UTF-8 | 718 | 2.515625 | 3 | [] | no_license | module PasswordResetHelper
def check_expiration user
is_expired = user.password_reset_expired?
error!(I18n.t("errors.expired_reset_password_token"), :bad_request) if is_expired
end
def check_blank_password
error!(I18n.t("errors.blank_password"), :bad_request) if params[:password].blank?
end
def check_password_confirmation
is_equal = params[:password] == params[:password_confirmation]
error!(I18n.t("errors.incorrect_password_confirm"), :bad_request) unless is_equal
end
def valid_reset_password_token user
activated_value = user&.valid_reset_password?(params[:token])
error!(I18n.t("errors.invalid_reset_password_token"), :unauthorized) unless activated_value
end
end
| true |
e55bd5f8e416f7b47587ff96048a29fd8da26625 | Ruby | TylerTaylor/reverse-each-word-v-000 | /reverse_each_word.rb | UTF-8 | 410 | 3.53125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | #def reverse_each_word(string)
# reversed_words = []
# new_string = string.split(" ")
# new_string.each do |word|
# reversed_words << word.reverse
# end
# reversed_words.join(" ")
#end
def reverse_each_word(string)
new_string = string.split(" ")
reversed_words = []
new_string.collect do |word|
reversed_words << word.reverse
end
reversed_words.join(" ")
end | true |
2f4c4387c7fb593bc94f35b0d711cfbba7020bec | Ruby | liberatus/insightexchange_gem | /spec/insightexchange_spec.rb | UTF-8 | 3,231 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe InsightExchange do
let(:api_token) { 'abc123' }
let(:exchange) { InsightExchange.new(api_token) }
describe 'reading options from ENV variables' do
before { ENV['INSIGHT_EXCHANGE_TOKEN'] = api_token }
after { ENV['INSIGHT_EXCHANGE_TOKEN'] = nil }
it 'reads INSIGHT_EXCHANGE_TOKEN' do
client = InsightExchange.new
expect(client.api_token).to eql(api_token)
end
end
describe '#publish' do
let(:request_body) { 'api_token=abc123&insight[email]=this_email%40that_address.com&insight[name]=CreatedPopularPoem' }
describe 'when valid inputs' do
it 'POSTS to InsightExchange api' do
stub_request(:post, 'https://secure.insightexchange.co/sellers/api/insights.json').
with(:body => request_body).
to_return(:status => 200, :body => "", :headers => {})
exchange.publish 'this_email@that_address.com', 'CreatedPopularPoem'
assert_requested(:post, 'https://secure.insightexchange.co/sellers/api/insights.json') do
request_body
end
end
it 'POSTS arbitrary data' do
request_body = 'api_token=abc123&insight[email]=this_email%40that_address.com&insight[name]=CreatedPopularPoem&insight[data][arbitrary]=data'
stub_request(:post, 'https://secure.insightexchange.co/sellers/api/insights.json').
with(:body => request_body).
to_return(:status => 200, :body => "", :headers => {})
exchange.publish 'this_email@that_address.com', 'CreatedPopularPoem', arbitrary: 'data'
assert_requested(:post, 'https://secure.insightexchange.co/sellers/api/insights.json') do
request_body
end
end
end
describe 'when invalid inputs' do
it 'raises when missing api_token' do
expect {
InsightExchange.new.publish 'this_email@that_address.com', 'CreatedPopularPoem'
}.to raise_error(InsightExchange::MissingTokenError)
end
it 'raises when missing email_address' do
expect {
exchange.publish '', 'SomeInsight'
}.to raise_error(ArgumentError)
end
it 'raises when missing insight_name' do
expect {
exchange.publish 'this_email@that_address.com', ''
}.to raise_error(ArgumentError)
end
end
end
describe '#identify' do
describe 'when valid inputs' do
let(:request_body) { 'api_token=abc123&user[email]=this_email%40that_address.com' }
it 'POSTS to InsightExchange api' do
stub_request(:post, 'https://secure.insightexchange.co/sellers/api/users.json').
with(:body => request_body).
to_return(:status => 200, :body => "", :headers => {})
exchange.identify 'this_email@that_address.com'
assert_requested(:post, 'https://secure.insightexchange.co/sellers/api/users.json') do
request_body
end
end
end
describe 'when invalid inputs' do
it 'raises when missing api_token' do
expect {
InsightExchange.new.identify 'this_email@that_address.com'
}.to raise_error(InsightExchange::MissingTokenError)
end
it 'raises when missing email_address' do
expect {
exchange.identify ''
}.to raise_error(ArgumentError)
end
end
end
end
| true |
137e0f1f4995df7c5e46d896b9324b1788ad6ef9 | Ruby | inesikhlef/Pair-Programming | /exo_11.rb | UTF-8 | 177 | 3.5625 | 4 | [] | no_license | puts "Donne moi un nombre !"
number = gets.chomp.to_i
number.times do
puts "Salut, ca farte ?"
end
#l'utilisateur va rentrer un nombre, la phrase va s'afficher au meme nombre | true |
7c50bdcaacdef53288e7800eb68a90b2a7c2fdc7 | Ruby | geekdreamzz/epiphany | /app/models/epiphany/config.rb | UTF-8 | 393 | 2.71875 | 3 | [
"MIT"
] | permissive | module Epiphany
class Config
def auth_handler
@auth
end
def auth=(method_name)
@auth = method_name
end
class << self
def set
yield config
end
def has_auth?
config.auth_handler.present?
end
def auth
config.auth_handler
end
def config
@config ||= new
end
end
end
end
| true |
20e9e63cda152da2da958422ef9d501a8c8d228b | Ruby | bibikovilya/summer-2019 | /3485/3/app/models/comment.rb | UTF-8 | 431 | 2.515625 | 3 | [] | no_license | class Comment < ActiveRecord::Base
validates :raiting, presence: { message: 'Rate it!' }
validates :text, presence: { message: 'Write a review!' }, if: :too_low_raiting
belongs_to :user
belongs_to :restaurant
after_save :update_raiting
def too_low_raiting
raiting ? raiting < 3 : false
end
private
def update_raiting
restaurant.update(raiting: restaurant.comments.average(:raiting).round(2))
end
end
| true |
53efdae3b96d90eb7ce1a8ca6b43a4592d89d22b | Ruby | Code4PuertoRico/suministrospr-web-scraper | /suministrospr_web_scraper.rb | UTF-8 | 2,424 | 2.53125 | 3 | [] | no_license | # encoding: UTF-8
require 'i18n'
require 'kimurai'
require 'mechanize'
require 'sanitize'
class SuministrosPR < Kimurai::Base
DATA_DIR = File.expand_path('data', __dir__).freeze
ALL_DATA_FILES_PATH = File.join(DATA_DIR, '*.json').freeze
@name = "suministrospr-web-scraper"
@engine = :mechanize
@start_urls = ["https://suministrospr.com/"]
@config = {
user_agent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36",
before_request: { delay: 1 }
}
def parse(response, url:, data: {})
# Go to the main page, find all links related to a 'sector' page and parse each one individually.
response.xpath("//a[starts-with(@href, 'https://suministrospr.com/sectores/')]").each do |a|
request_to :parse_sector_page, url: a[:href]
end
end
def parse_sector_page(response, url:, data: {})
# Parse elements.
municipio = response.xpath("//div[@class='breadcrumbs pauple_helpie_breadcrumbs']/a[@class='mainpage-link'][starts-with(@href, 'https://suministrospr.com/municipios/')][position()=1]").text.strip
title = response.xpath("//h1").text.strip
content = Sanitize.fragment(response.xpath("//div[@class='article-content']").to_html, Sanitize::Config::BASIC).strip
# Create hash that will be serialized to JSON.
sector_data = {}
sector_data[:url] = url
sector_data[:municipio] = municipio.empty? ? 'EMPTY_MUNICIPIO' : municipio
sector_data[:title] = title.empty? ? 'EMPTY_TITLE' : title
sector_data[:content] = content
# Get current time and use in filename if sector has no title or file already exists.
timestamp = Time.now.to_i
# Construct filename.
json_filename = if title.empty?
# Using timestamp in filename if title is empty.
"#{I18n.transliterate(municipio)}-EMPTY_TITLE-#{timestamp}.json"
else
# Transliterating title to ASCII and using as filename.
"#{I18n.transliterate(municipio)}-#{I18n.transliterate(title).slice(0,100)}.json"
end
# Adding timestamp to filename if a file with that name already exists.
if File.exist?(File.join(DATA_DIR, json_filename))
json_filename = "#{File.basename(json_filename, ".json")}-DUPLICATE-#{timestamp}.json"
end
# Saving parsed data to JSON file.
json_filepath = File.join(DATA_DIR, json_filename)
save_to json_filepath, sector_data, format: :pretty_json
end
end
| true |
7ac058697bc43d7d2f1debfdcef0bc314cb5c4fb | Ruby | ilyafaybisovich/LRTHW | /ex19.rb | UTF-8 | 983 | 4.59375 | 5 | [] | no_license | def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket.\n"
end
puts "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
puts "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
puts "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
puts "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
def man(height, weight, age)
puts "The man's height is #{height}\nHis weight is #{weight}\nand his age is #{age}"
end
man(180, 80, 35)
man(172 - 10, 50 + 20, 15 * 2)
height = 175
weight = 78
age = 85
man(height, weight, age)
man(height - 5, weight / 2, height - (2 * weight))
man(155 + 3, weight + 2, 27)
| true |
321e56483b79f8c1e66bdf3bf2286ef88822bf49 | Ruby | nkinney/rrobots | /LCF/destination_setter.rb | UTF-8 | 769 | 3.078125 | 3 | [] | no_license | class DestinationSetter
attr_reader(:damage_taken)
attr_reader(:ticks_used)
def initialize battlefield_width, battlefield_height, clipping_offset
@damage_taken = 0
@ticks_used = 0
@battlefield_width = battlefield_width
@battlefield_height = battlefield_height
@clipping_offset = clipping_offset
end
def get_name
return "base setter"
end
def add_damage_for_this_tick damage
@damage_taken += damage
end
def add_tick
@ticks_used += 1
end
def average_damage_per_tick
if @ticks_used == 0
return 0
else
return @damage_taken.to_f/@ticks_used.to_f
end
end
def calculate_destination bot
#all child classes need to implement this
return bot.x_destination, bot.y_destination
end
end | true |
75f7fde453b2f9f9caa3bf06e6e34d73a9d22b57 | Ruby | toshinori/flms | /app/models/member.rb | UTF-8 | 1,540 | 2.796875 | 3 | [] | no_license | class Member < ActiveRecord::Base
acts_as_paranoid
validates_as_paranoid
belongs_to :position
has_one :team_member, dependent: :destroy
has_one :team, through: :team_member
has_many :game_members
validates :first_name,
presence: true,
length: { maximum: 10 }
validates :last_name,
presence: true,
length: { maximum: 10 }
validates :player_number,
allow_blank: true,
format: {with: %r(^\d{10}$)i},
uniqueness: true
# 論理削除も考慮してユニークチェックするなら下記を使用する
# その際、通常のuniqueness: trueは削除
# validates_uniqueness_of_without_deleted :player_number
validates :member_type,
inclusion: { in: (Constants.member_type.values) }
validates :uniform_number,
allow_blank: true,
numericality: {
only_integer: true,
greater_than_or_equal_to: Constants.uniform_number.min,
less_than_or_equal_to: Constants.uniform_number.max
}
# validates_with DateFormatValidator,
# allow_nil: true,
# field: :birth_day
# validates_each :birth_day, allow_nil: true do |record, atr, value|
# Date.parse(value) rescue record.errors[attr] << 'invalid format.'
# end
def player?
self.member_type == Constants.member_type[:player]
end
def manager?
self.member_type == Constants.member_type[:manager]
end
def full_name
"#{self.last_name} #{self.first_name}"
end
def self.uniform_number_range
(Constants.uniform_number.min..Constants.uniform_number.max)
end
end
| true |
30207e3ffacb95da6340d1ac0c02e2079ae10f53 | Ruby | ajith-u/R2 | /r2.rb | UTF-8 | 109 | 2.84375 | 3 | [] | no_license | r,s=gets.chomp.split.map(&:to_i)
if s.between?(-1000,1000) and r.between?(-1000,1000)
puts (s*2)-r
end
| true |
c6e2e3354429a837edfa49a5dadbfff0057a3cb6 | Ruby | risanto/connect-four | /sandbox.rb | UTF-8 | 115 | 2.65625 | 3 | [] | no_license | arr = [
['O', 'O'],
['X', 'O']
]
results = arr.select.with_index do |val, i|
val[i][1]
end
pp results | true |
9d58e2a98d2a950b63c603338e3a31a912cfd2f3 | Ruby | TomCrypto/Comet | /lib/comet/parser.rb | UTF-8 | 2,721 | 2.703125 | 3 | [
"MIT"
] | permissive | module Comet
class Parser
include Comet::DSL::Helpers
alias inject instance_exec
def software(name, depends:, &block)
raise "software `#{name}' redefined" if @software.key? name
@software[name] = DSL::Software.new(name, depends: depends, &block)
end
def hardware(name, targets:, &block)
if hardware_defined? name, targets
raise "hardware `#{name}' redefined for `#{targets}'"
end
raise "`#{name}' already used by software" if @software.key? name
@hardware[name].push DSL::Hardware.new(name, targets: targets, &block)
end
def firmware(name, imports:, &block)
raise "firmware `#{name}' redefined" if firmware_defined? name
@firmware.push DSL::Firmware.new(name, imports: imports, &block)
end
def array_hash
Hash.new { |h, k| h[k] = [] }
end
def plain_hash
{}
end
def initialize(filename)
@software = plain_hash
@hardware = array_hash
@firmware = []
@filename = filename
end
attr_reader :filename
def targets
parse_file! if @targets.nil?
@targets ||= compute_targets
end
def compute_targets
@firmware.flat_map do |firmware|
firmware.validate!
firmware.targets.map do |device|
[firmware, device]
end
end
end
private
def resolve_dependencies!(firmware)
seen = {}
firmware.imports = firmware.imports.flat_map do |name|
resolve! name, seen
end
end
def resolve!(name, seen)
if seen[name] == :temporary
raise "circular dependency involving `#{name}' detected"
end
object = object_by_name name
return object if seen[name] == :permanent
resolve_software! name, object, seen if @software.key? name
seen[name] = :permanent
object
end
def resolve_software!(name, software, seen)
seen[name] = :temporary
software.depends = software.depends.flat_map do |dependency|
resolve! dependency, seen
end
end
def object_by_name(name)
if @software[name].nil? && @hardware[name].empty?
raise "software or hardware `#{name}' undefined"
end
@software[name] || @hardware[name]
end
def resolve_all_dependencies!
@firmware.each do |firmware|
resolve_dependencies! firmware
end
end
def parse_file!
instance_eval File.read(@filename)
resolve_all_dependencies!
end
def hardware_defined?(name, targets)
@hardware[name].any? do |hardware|
hardware.targets == targets
end
end
def firmware_defined?(name)
@firmware.map(&:name).include? name
end
end
end
| true |
b225bec5a223520978fead603076fee2c9e13591 | Ruby | Lix311/ruby-oo-self-cash-register-lab-nyc-web-021720 | /lib/cash_register.rb | UTF-8 | 960 | 3.5 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class CashRegister
attr_accessor :total, :discount, :last_item
items = []
def initialize(empl_discount=nil) #initializer
@total = 0
@discount = empl_discount
@items = []
@last_item = 0
end
def add_item(title, price, quantity=1) #instance method
@total += price * quantity
@last_item = price * quantity
until quantity == 0
@items << title
quantity -= 1
end
end
def apply_discount
if @discount == nil
"There is no discount to apply."
else
discount = @total * (@discount / 100.00)
discounted_total = @total -= discount
"After the discount, the total comes to $#{discounted_total.to_i}."
end
end
def items
@items
end
def void_last_transaction
@total = self.total - self.last_item
end
end | true |
74e98887d0995e3c8276919d9c524e2e7de1fa99 | Ruby | Bor1s/chargen | /app/services/data_extractor_service.rb | UTF-8 | 636 | 2.953125 | 3 | [
"MIT"
] | permissive | class DataExtractorService
def initialize(character_sheet)
@character_sheet = character_sheet
end
def extract
@character_sheet.class.stored_attributes[:data_fields].map do |field_name|
field_name_as_defined_in_sheet = @character_sheet.class.fields_map[field_name]
field_value = escape_unsafe(@character_sheet.data_fields[field_name].to_s)
"#{field_name_as_defined_in_sheet} #{field_value}"
end
end
private
def escape_unsafe(string)
# TODO: convert true/false to 'Yes'/'Off'
string&.gsub!(/\\/, '\\\\\\')
string&.gsub!(/(\r\n)|(\r)/, '\n')
string
end
end
| true |
be0dcb953607b590a51851c7c4db6e4962dbc9dc | Ruby | govaniso/phidgets-ffi | /lib/phidgets-ffi/analog.rb | UTF-8 | 2,885 | 2.5625 | 3 | [] | no_license | module Phidgets
# This class represents a PhidgetAnalog.
class Analog
Klass = Phidgets::FFI::CPhidgetAnalog
include Phidgets::Common
# Collection of analog outputs
# @return [AnalogOutputs]
attr_reader :outputs
attr_reader :attributes
# The attributes of a PhidgetAnalog
def attributes
super.merge({
:outputs => outputs.size
})
end
private
def load_device_attributes
load_outputs
end
def load_outputs
ptr = ::FFI::MemoryPointer.new(:int)
Klass.getOutputCount(@handle, ptr)
@outputs = []
ptr.get_int(0).times do |i|
@outputs << AnalogOutputs.new(@handle, i)
end
end
def remove_specific_event_handlers
end
# This class represents an analog output for a PhidgetAnalog. All the properties of an output are stored and modified in this class.
class AnalogOutputs
Klass = Phidgets::FFI::CPhidgetAnalog
private
def initialize(handle, index)
@handle, @index = handle, index.to_i
end
public
# Displays data for the analog output
def inspect
"#<#{self.class} @index=#{index}, @enabled=#{enabled}, @voltage=#{voltage}, @voltage_min=#{voltage_min}, @voltage_max=#{voltage_max}>"
end
# @return [Integer] returns the index of an output, or raises an error.
def index
@index
end
# @return [Boolean] returns the enabled state of an output, or raises an error.
def enabled
ptr = ::FFI::MemoryPointer.new(:int)
Klass.getEnabled(@handle, @index, ptr)
(ptr.get_int(0) == 0) ? false : true
end
# Sets the enabled state of an output, or raises an error.
# @param [Boolean] new_state new state
# @return [Boolean] returns the enabled state of an output, or raises an error.
def enabled=(new_state)
tmp = new_state ? 1 : 0
Klass.setEnabled(@handle, @index, tmp)
new_state
end
# @return [Float] returns the voltage of an output, in V, or raises an error.
def voltage
ptr = ::FFI::MemoryPointer.new(:double)
Klass.getVoltage(@handle, @index, ptr)
ptr.get_double(0)
end
# Sets the voltage of an output, in V, or raises an error.
# @param [Float] new_voltage new voltage
# @return [Float] returns the voltage of an output, in V, or raises an error.
def voltage=(new_voltage)
Klass.setVoltage(@handle, @index, new_voltage.to_f)
new_voltage
end
# @return [Float] returns the minimum supported output voltage, or raises an error.
def voltage_min
ptr = ::FFI::MemoryPointer.new(:double)
Klass.getVoltageMin(@handle, @index, ptr)
ptr.get_double(0)
end
# @return [Float] returns the maximum supported output voltage, or raises an error.
def voltage_max
ptr = ::FFI::MemoryPointer.new(:double)
Klass.getVoltageMax(@handle, @index, ptr)
ptr.get_double(0)
end
end
end
end
| true |
6bfe40a67faaf3d24eb0954dee3b0e1bb0afad34 | Ruby | y5f/Projects | /Mini comp /lexer.rb | UTF-8 | 1,467 | 3.25 | 3 | [] | no_license | require 'pp'
Token=Struct.new(:kind,:value,:pos)
class Lexer
attr_accessor :stream
def initialize token_hash
@token_def=token_hash
end
def tokenize str
stream=[]
str.split(/\n/).each_with_index do |str,numline|
stream << tokenize_line(1+numline,str)
end
@stream=stream.flatten
@current=0
end
def eof?
@stream.size == 0
end
def lookahead k
@stream[k]
end
def show_next
@stream.first
end
def get_next
@stream.shift
end
def print_stream n=5
footer=@stream.size>0 ? "..." : "<EMPTY STREAM>"
puts "token stream (pos[#{@stream.first.pos}]): "+@stream.collect{|tok| tok.kind}[0..n-1].join(',')+footer
end
def pos
@stream.first.pos
end
private
def next_token str
@token_def.each do |name,rex|
str.match /\A#{rex}/
return Token.new(name,$&) if $&
end
raise "Lexing error. no match for #{str}"
end
def strip_and_count str
init=str.size
ret=str.strip || str
final=ret.size
[ret,init-final]
end
def tokenize_line numline,str
begin
stream=[]
col=1
while str.size>0
str,length=strip_and_count(str)
col+=length
if str.size>0
stream << tok=next_token(str)
tok.pos=[numline,col]
col+= tok.value.size
str=str.slice(tok.value.size..-1)
end
end
rescue Exception =>e
puts e
end
return stream
end
end
| true |
f1b5601d747ae9297ed9c7647217690f2e6be3ee | Ruby | jamesdconklin/ORM-Practice | /lib/user.rb | UTF-8 | 1,504 | 2.796875 | 3 | [] | no_license | require_relative 'questionrelation'
require_relative 'model'
class User < ModelBase
attr_reader :id
attr_accessor :f_name, :l_name
def initialize(options)
@id = options['id']
@l_name = options['l_name']
@f_name = options['f_name']
end
def followed_questions
QuestionFollow.followed_questions_for_user_id(@id)
end
def liked_questions
QuestionLike.liked_questions_for_user_id(@id)
end
def average_karma
data = QuestionDBConnection.instance.execute(<<-SQL, @id)
SELECT
count(DISTINCT questions.id) as num_questions,
count(question_likes.question_id) as num_likes
FROM
questions
LEFT OUTER JOIN
question_likes ON questions.id = question_likes.question_id
WHERE
questions.user_id = ?
SQL
data = data.first
num_questions = data['num_questions']
num_likes = data['num_likes']
return 0 if num_questions == 0
num_likes.to_f/num_questions
end
# def create
# QuestionDBConnection.instance.execute(<<-SQL, @f_name, @l_name)
# INSERT INTO
# users(f_name, l_name)
# VALUES
# (?,?)
# SQL
# @id = QuestionDBConnection.instance.last_insert_row_id
# end
#
# def update
# QuestionDBConnection.instance.execute(<<-SQL, @f_name, @l_name, @id)
# UPDATE
# users
# SET
# f_name = ?, l_name = ?
# WHERE
# id = ?
# SQL
# @id = QuestionDBConnection.instance.last_insert_row_id
# end
end
| true |
ffd6feab492e909e5ac71265ae94fab522f01046 | Ruby | PhilHuangSW/Leetcode | /integer_to_roman.rb | UTF-8 | 3,111 | 4.65625 | 5 | [] | no_license | #################### INTEGER TO ROMAN ####################
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
# ```
# Symbol Value
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
# ```
# For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
# Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
# - I can be placed before V (5) and X (10) to make 4 and 9.
# - X can be placed before L (50) and C (100) to make 40 and 90.
# - C can be placed before D (500) and M (1000) to make 400 and 900.
# Given an integer, convert it to a roman numeral.
# **Example 1:**
# ```
# Input: num = 3
# Output: "III"
# ```
# **Example 2:**
# ```
# Input: num = 4
# Output: "IV"
# ```
# **Example 3:**
# ```
# Input: num = 9
# Output: "IX"
# ```
# **Example 4:**
# ```
# Input: num = 58
# Output: "LVIII"
# Explanation: L = 50, V = 5, III = 3.
# ```
# **Example 5:**
# ```
# Input: num = 1994
# Output: "MCMXCIV"
# Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
# ```
# **Constraints:**
# - 1 <= num <= 3999
#################### SOLUTION ####################
# @param {Integer} num
# @return {String}
# TIME: O(1) -- SPACE: O(1)
def int_to_roman(num)
roman = ""
if num >= 1000
m = num/1000
num = num%1000
roman += "M" * m
end
if num >= 900
cm = num/900
num = num%900
roman += "CM" * cm
end
if num >= 500
d = num/500
num = num%500
roman += "D" * d
end
if num >= 400
cd = num/400
num = num%400
roman += "CD" * cd
end
if num >= 100
c = num/100
num = num%100
roman += "C" * c
end
if num >= 90
xc = num/90
num = num%90
roman += "XC" * xc
end
if num >= 50
l = num/50
num = num%50
roman += "L" * l
end
if num >= 40
xl = num/40
num = num%40
roman += "XL" * xl
end
if num >= 10
x = num/10
num = num%10
roman += "X" * x
end
if num >= 9
ix = num/9
num = num%9
roman += "IX" * ix
end
if num >= 5
v = num/5
num = num%5
roman += "V" * v
end
if num >= 4
iv = num/4
num = num%4
roman += "IV" * iv
end
if num >= 1
i = num/1
num = num%1
roman += "I" * i
end
roman
end
num1 = 3
num2 = 4
num3 = 9
num4 = 58
num5 = 1994
num6 = 3999
puts "Expected: III -- Actual: #{int_to_roman(num1)}"
puts "Expected: IV -- Actual: #{int_to_roman(num2)}"
puts "Expected: IX -- Actual: #{int_to_roman(num3)}"
puts "Expected: LVIII -- Actual: #{int_to_roman(num4)}"
puts "Expected: MCMXCIV -- Actual: #{int_to_roman(num5)}"
puts "Expected: MMMCMXCIX -- Actual: #{int_to_roman(num6)}" | true |
6f18fc8748571203bcd973152972f2fd2229045c | Ruby | redding/sanford-protocol | /lib/sanford-protocol/request.rb | UTF-8 | 1,118 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'sanford-protocol'
module Sanford; end
module Sanford::Protocol
class Request
def self.parse(body)
self.new(body['name'], body['params'])
end
attr_reader :name, :params
def initialize(name, params)
self.validate!(name, params)
@name = name.to_s
@params = params
end
def to_hash
{ 'name' => name,
'params' => Sanford::Protocol::StringifyParams.new(params)
}
end
def to_s; name; end
def inspect
reference = '0x0%x' % (self.object_id << 1)
"#<#{self.class}:#{reference}"\
" @name=#{name.inspect}"\
" @params=#{params.inspect}>"
end
def ==(other)
if other.kind_of?(self.class)
self.to_hash == other.to_hash
else
super
end
end
protected
def validate!(name, params)
problem = if !name
"The request doesn't contain a name."
elsif !params.kind_of?(::Hash)
"The request's params are not valid."
end
raise(InvalidError, problem) if problem
end
InvalidError = Class.new(ArgumentError)
end
end
| true |
a35e25f8362ca2f98924d68c8dc791300b496544 | Ruby | simplificator/conversions | /test/conversions_test.rb | UTF-8 | 989 | 2.71875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'test_helper'
class ConversionsTest < Test::Unit::TestCase
should 'convert from grams to tons' do
assert_equal 1, 1000000.g_to_t
assert_equal 1.234567, 1234567.g_to_t
assert_equal 0.001, 1000.g_to_t
assert_equal 0.000001, 1.g_to_t
end
should 'convert from grams to kg' do
assert_equal 1, 1000.g_to_kg
assert_equal 0.001, 1.g_to_kg
end
should 'convert from t to grams' do
assert_equal 1000000, 1.t_to_g
assert_equal 1234, (0.001234).t_to_g
end
should 'convert from kg to grams' do
assert_equal 1000, 1.kg_to_g
assert_equal 12, 0.012.kg_to_g
end
should 'convert from mm2 to m2' do
assert_equal 1, (1000 * 1000).mm2_to_m2
assert_equal 0.025, (100 * 250).mm2_to_m2
end
should 'convert from m2 to mm2' do
assert_equal 1000, (0.01 * 0.1).m2_to_mm2
end
should 'raise if source or target unit can not be found' do
assert_raises(NoMethodError) do
1000.kg_to_m
end
end
end
| true |
d44477487d83a99fff72fbfe7ec82af7e9cbd254 | Ruby | susano/ppsn2012 | /evaluators/pattern_matching_evaluator.rb | UTF-8 | 1,977 | 3.0625 | 3 | [
"MIT"
] | permissive | require 'utils/assert'
class PatternMatchingEvaluator
# ctor
def initialize(patterns)
assert{ !patterns.empty? }
@patterns =
patterns.collect do |p|
p.collect do |v|
if (v == true || v == 1)
true
elsif (v == false || v == 0)
false
else
raise ArgumentError
end
end
end
@pattern_size = @patterns[0].size
@check_edges = false
end
# set check edges
def check_edges=(check_edges)
@check_edges = check_edges
@pattern_edges = @check_edges ? @patterns.collect{ |p| count_edges(p) } : nil
end
def evaluate(genome)
controller = genome.newController(0, @patterns.size, :beginning, :boolean)
values = Array.new(@patterns.size){ Array.new }
@pattern_size.times do |i|
controller.update
@patterns.size.times{ |j| values[j] << controller.outputs[j] }
end
difference = 0
@patterns.size.times do |i|
@pattern_size.times do |j|
# $stdout << "debug #{i} #{j}\n"
difference += 1 if @patterns[i][j] != values[i][j]
end
end
fitness = -difference
# $stdout << "debug fitness before edges #{fitness}\n"
if @check_edges
# $stdout << "debug checking edges count_edges(values[0]) #{count_edges(values[0])} @pattern_edges[0] #{@pattern_edges[0]} \n"
fitness -= Array.new(@patterns.size){ |i| (count_edges(values[i]) - @pattern_edges[i]).abs }.inject(&:+)
end
display_patterns(values, fitness)
# $stderr << controller.to_s
genome.fitness = fitness
end
def phenotype_evaluations;
0
end
private
def display_patterns(patterns, fitness)
output = ''
patterns.each_with_index do |p, i|
output << 'pattern ' + (i + 1).to_s + ': '
p.each do |v|
output << ((v) ? 'X' : '_')
end
output << " : " + fitness.to_s + "\n"
end
puts output
end
def count_edges(pattern)
edge_sum = 0
previous = nil
pattern.each do |v|
edge_sum += 1 if !previous.nil? && (previous != v)
previous = v
end
edge_sum
end
end # PatternMatchingEvaluator
| true |
1b9f36a74007e1a1237166a6181cbb6658f12374 | Ruby | littlemighty/test_first | /02_calculator/calculator.rb | UTF-8 | 269 | 3.703125 | 4 | [] | no_license | def add(x, y)
x + y
end
def subtract(x, y)
x - y
end
def sum(x)
x.inject(0){|total, number| total+number}
end
def multiply(*nums)
nums.inject(:*)
end
def power(x, y)
x ** y
end
def factorial(x)
if x < 1
x = 1
else
x * factorial(x-1)
end
end | true |
ef1b2d900a61efee7839f934937d51e53cf7173f | Ruby | atheiman/knife-ansible-inventory | /lib/chef/knife/ansible_inventory.rb | UTF-8 | 2,466 | 2.515625 | 3 | [
"MIT"
] | permissive | class Chef::Knife::AnsibleInventory < Chef::Knife
banner 'knife ansible inventory'
deps do
require 'chef/search/query'
end
option :group_by_attribute,
long: '--group-by-attribute ATTRIBUTE',
description: "Attribute to group hosts by"
option :host_attribute,
long: '--host-attribute ATTRIBUTE',
description: "Attribute to identify hosts by",
default: 'ipaddress'
option :hostvars,
long: '--hostvars RETURNED_KEY=ATTRIBUTE.PATH[,RETURNED_KEY=ATTRIBUTE.PATH]',
description: "Comma-delimited mapping of returned hostvars to Chef attribute paths",
default: 'ipaddress=ipaddress'
option :query,
long: '--query QUERY',
description: 'Chef node search query'
def validate_options
missing = []
%i(group_by_attribute host_attribute hostvars query).each do |opt|
missing << opt unless config[opt]
end
raise ArgumentError, "Missing option(s): #{missing}" unless missing.empty?
end
def str_to_attr_path(str)
str.split('.')
end
# limit node query results to the group_by_attribute and the hostvars
def filter_result
filter_result = {}
config[:hostvars].split(',').each do |attr|
key, value = attr.split('=')
filter_result[key] = str_to_attr_path(value)
end
filter_result.merge(
config[:group_by_attribute] => str_to_attr_path(config[:group_by_attribute]),
config[:host_attribute] => str_to_attr_path(config[:host_attribute])
)
end
# get all the nodes matching the given query
def nodes_search
nodes = []
Chef::Search::Query.new.search(
:node,
config[:query],
filter_result: filter_result
) { |n| nodes << n }
nodes
end
def run
validate_options
nodes = nodes_search
inventory = {}
until nodes.empty?
# TODO: currently this doesnt handle nodes that should exist in multiple groups
# organize nodes into groups based on matching group_by_attribute values
match_value = str_to_attr_path(config[:group_by_attribute]).inject(nodes.first, &:[])
group_name = match_value.join(',')
inventory[group_name] = { 'hosts' => [], 'vars' => {} }
filtered_nodes = nodes.select do |n|
n[config[:group_by_attribute]] == match_value
end
filtered_nodes.each do |n|
inventory[group_name]['hosts'] << n
nodes.delete(n)
end
# TODO: fill out group vars with
end
require 'pp'
pp inventory
end
end
| true |
7f43ae012b934ab8dac61997d13eda48d78c133f | Ruby | genki/wormhole | /test/wormhole_test.rb | UTF-8 | 1,623 | 2.796875 | 3 | [
"MIT"
] | permissive | require File.dirname(__FILE__) + '/test_helper.rb'
require "test/unit"
class WormholeTest < Test::Unit::TestCase
def setup
@result = []
end
def foo
@result << "foo"
data = Wormhole.throw :bar => 'hello'
@result << data[:bar]
@result << "bar"
end
def test_wormhole
Wormhole.catch do
foo
end.return do |data|
@result << data[:bar]
data[:bar] = 'world!'
end
assert !@result.empty?
assert_equal ['foo', 'hello', 'world!', 'bar'], @result
end
def test_wormhole_without_throw
result = Wormhole.catch do
"test"
end.return
assert_equal "test", result
end
def test_nested_wormhole
array = []
result = Wormhole.catch(:foo) do
Wormhole.catch(:bar) do
Wormhole.throw :foo, 1
Wormhole.throw :bar, 2
"test"
end.return do |value|
array << value
end
end.return do |value|
array << value
end
assert_equal [1, 2], array
assert_equal 'test', result
end
def test_wormhole_without_trailing_return
assert_raise Wormhole::LateReturnError do
w = Wormhole.catch do
"test"
end
w.return
end
end
def test_wormhole_without_symbol
result = Wormhole.catch do
@result << "foo"
Wormhole.throw :bar => 'hello' do |data|
@result << data[:bar]
end
@result << "bar"
'result'
end.return do |data|
@result << data[:bar]
data[:bar] = 'world!'
end
assert_equal 'result', result
assert !@result.empty?
assert_equal ['foo', 'hello', 'world!', 'bar'], @result
end
end
| true |
88ec28e75638497309414be3e176d89ce3f1a5dd | Ruby | kelseyde/hogwarts | /db/seeds.rb | UTF-8 | 1,906 | 2.71875 | 3 | [] | no_license | require_relative('../models/student')
require_relative('../models/house')
require_relative('sql_runner')
require('pry')
gryffindor = House.new({
"name" => "Gryffindor",
"logo" => "http://vignette1.wikia.nocookie.net/harrypotter/images/8/8e/0.31_Gryffindor_Crest_Transparent.png/revision/latest?cb=20161124074004"})
hufflepuff = House.new({
"name" => "Hufflepuff",
"logo" => "https://vignette2.wikia.nocookie.net/harrypotter/images/5/50/0.51_Hufflepuff_Crest_Transparent.png/revision/latest?cb=20161020182518"})
ravenclaw = House.new({
"name" => "Ravenclaw",
"logo" => "http://vignette2.wikia.nocookie.net/harrypotter/images/2/29/0.41_Ravenclaw_Crest_Transparent.png/revision/latest?cb=20161020182442"})
slytherin = House.new({
"name" => "Slytherin",
"logo" => "http://vignette4.wikia.nocookie.net/harrypotter/images/d/d3/0.61_Slytherin_Crest_Transparent.png/revision/latest?cb=20161020182557"})
gryffindor.save
hufflepuff.save
ravenclaw.save
slytherin.save
harry_potter = Student.new ({
"first_name" => "Harry",
"second_name" => "Potter",
"house" => gryffindor.id,
"age" => 11
})
harry_potter.save
hermione_granger = Student.new ({
"first_name" => "Hermione",
"second_name" => "Granger",
"house" => gryffindor.id,
"age" => 11
})
hermione_granger.save
draco_malfoy = Student.new ({
"first_name" => "Draco",
"second_name" => "Malfoy",
"house" => slytherin.id,
"age" => 11
})
draco_malfoy.save
luna_lovegood = Student.new ({
"first_name" => "Luna",
"second_name" => "Lovegood",
"house" => ravenclaw.id,
"age" => 12
})
luna_lovegood.save
ron_weasley = Student.new ({
"first_name" => "Ron",
"second_name" => "Weasley",
"house" => gryffindor.id,
"age" => 11
})
ron_weasley.save
cedric_diggory = Student.new ({
"first_name" => "Cedric",
"second_name" => "Diggory",
"house" => hufflepuff.id,
"age" => 14
})
cedric_diggory.save
binding.pry
nil
| true |
9095e099b0a515934bcf270aa44b021a1118133a | Ruby | svoboda-jan/opal-browser | /opal/browser/window/view.rb | UTF-8 | 225 | 2.59375 | 3 | [] | no_license | module Browser; class Window
class View
def initialize(window)
@window = window
@native = window.to_n
end
def width
`#@native.innerWidth`
end
def height
`#@native.innerHeight`
end
end
end; end
| true |
06fd0debd48ab05be139d98dd24d0250dc00b6a4 | Ruby | jhbadger/scripts | /alertTime | UTF-8 | 218 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env ruby
x = Time.now.to_i
diff = 1618033989 - x
hours = diff / 3600
min = diff - hours*3600
secs = diff - 60*min
printf("Currently %d. %d hours %d minutes, %d seconds to target\n", x, hours, min, secs)
| true |
250141d3531eac91b7a4d08865017471313ef091 | Ruby | bbensky/launch_school | /intro_to_ruby/methods/ex1_greeting.rb | UTF-8 | 102 | 3.46875 | 3 | [] | no_license | def greeting(name)
"Hi " + name + "! I hope you're having a swell day!"
end
puts greeting("Brian") | true |
be7db50a792d7879fbf15ed3415e70592a51bd05 | Ruby | CodeMonkeySteve/object-schema | /lib/object_schema/param.rb | UTF-8 | 1,036 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'object_schema/buildable'
# Function Parameter
class ObjectSchema::Param
include ObjectSchema::Buildable
attr_reader :option
def initialize(parent: nil, schema: nil, option: false, &defn)
@required = false
@option = false
super(parent: parent, schema: schema, &defn)
end
def required?
@required
end
def required=( state )
@required = !!state
end
def required(state = true)
self.required = state
end
def optional?
!@required
end
def optional=( state )
@required = !state
end
def optional(state = true)
self.optional = state
end
# aka ENUM
def values(*values)
return @values if values.empty?
@values = values
end
alias_method :values=, :values
def default(*value)
return @default if value.empty?
default = value[0]
@default = default
end
alias_method :default=, :default
def as_json(**opts)
schema.as_json(**opts).update(
option: option || nil,
).reject { |_, v| v.blank? }.as_json(**opts)
end
end
| true |
1d215e9042840f53c8dcd325bb783a021c84806a | Ruby | greeneca/AdventOfCode2019 | /lib/day14-2.rb | UTF-8 | 2,524 | 3.171875 | 3 | [] | no_license | module P142
class P142
def run(input)
@reactions = {}
input.each do |reaction|
inputs, output = reaction.strip.split("=>")
inputs = inputs.strip.split(",").map{|ingredient| process_ingredient(ingredient)}
output = process_ingredient(output)
@reactions[output[1]] = Reaction.new(output, inputs)
end
total_ore = 1000000000000
ore_requirement = 0
fuel = total_ore/get_ore_requirement(1)
[1000, 100, 10, 1].each do |increment|
while (ore_requirement < total_ore)
fuel += increment
ore_requirement = get_ore_requirement(fuel)
end
fuel -= increment
ore_requirement = 0
end
#Off by one error on final input for some reason but not on sample input
puts "Fuel: #{fuel-1}"
end
def get_ore_requirement(fuel)
requirements = [[fuel, :FUEL]]
while not done(requirements)
requirements = requirements.inject([]) do |new_requirements,requirement|
if @reactions[requirement[1]]
new_requirements += @reactions[requirement[1]].get_requirements(requirement[0])
else
new_requirements.push(requirement)
end
end
requirements = combine(requirements)
end
requirements.first.first
end
def done(requirements)
requirements.count == 1 and requirements[0][1] == :ORE
end
def process_ingredient(ingredient_string)
ingredient = ingredient_string.strip.split(" ")
ingredient[0] = ingredient[0].to_i
ingredient[1] = ingredient[1].to_sym
ingredient
end
def combine(requirements)
new_requirements = Marshal.load(Marshal.dump(requirements.uniq{|req| req.last}))
new_requirements.map! do |requirement|
matching_requirements = requirements.select{|req| req[1] == requirement[1]}
requirement[0] = matching_requirements.inject(0) {|sum,req| sum += req[0]}
requirement
end
new_requirements
end
end
class Reaction
def initialize(creates, inputs)
@creates = creates[1]
@create_count = creates[0]
@inputs = inputs
@extra = 0
end
def get_requirements(count)
count -= @extra
reaction_count = (count.to_f/@create_count).ceil
@extra = (@create_count*reaction_count) - count
requirements = Marshal.load(Marshal.dump(@inputs))
requirements.map do |input|
input[0] *= reaction_count
input
end
end
end
end
| true |
f35a6ff73cd5c99b77370f0b5e5c4902a1d1387f | Ruby | AustinJuliusKim/AustinK_WDI | /08_week/beer_pong_emporium/spec/models/product_spec.rb | UTF-8 | 2,043 | 2.703125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Product, type: :model do
describe "product attributes required?" do
it "returns name" do
product = FactoryGirl.build_stubbed(:product, name: nil)
p product
expect(product).to be_invalid
end
it "returns sku" do
product = FactoryGirl.build_stubbed(:product, sku: nil)
p product
expect(product).to be_invalid
end
it "has sku that is exactly 9 characters" do
product = FactoryGirl.build_stubbed(:product, sku: "12345678")
expect(product.sku.length).to_not eq(9)
end
it "returns wholesale_price" do
product = FactoryGirl.build_stubbed(:product, wholesale_price: nil)
p product
expect(product).to be_invalid
end
it "returns quantity" do
product = FactoryGirl.build_stubbed(:product, quantity: nil)
p product
expect(product).to be_invalid
end
end
describe "product is?" do
it "is in stock?" do
product = FactoryGirl.build_stubbed(:product, quantity: 0)
expect(product.in_stock?).to eq(false)
end
it "has a margin of?" do
product = FactoryGirl.build_stubbed(:product, wholesale_price: 500.99, retail_price: 599.99)
expect(product.margin?).to eq(99.00)
end
it "sells(qty) or declines sale based on insufficient stock" do
product = FactoryGirl.build_stubbed(:product, quantity: 49)
expect(product.sell(50)).to eq("Cannot fulfill this order.")
end
end
describe "if product" do
it "is in stock" do
product = FactoryGirl.create(:product, name: "Ping Pong Balls", quantity: 50)
product1 = FactoryGirl.create(:product, name: "Table", quantity: 0)
product2 = FactoryGirl.create(:product, name: "Red Cups", quantity: 20)
expect(Product.in_stock).to eq([product, product2])
end
it "is not in stock" do
product = FactoryGirl.create(:product, name: "Ping Pong Balls", quantity: 50)
product1 = FactoryGirl.create(:product, name: "Table", quantity: 0)
product2 = FactoryGirl.create(:product, name: "Red Cups", quantity: 20)
expect(Product.out_of_stock).to eq([product1])
end
end
end
| true |
493fa9e982b6f056511f224fce3a7999ed38a149 | Ruby | VoChrisK/aA-classwork | /W4D1/knights-travails/knightpathfinder.rb | UTF-8 | 2,617 | 3.484375 | 3 | [] | no_license | require_relative "./polytreenode/skeleton/lib/00_tree_node.rb"
class KnightPathFinder
attr_reader :root_node
def self.valid_moves(current_pos)
row, col = current_pos
row >= 0 && row < 8 && col >= 0 && col < 8
end
def initialize(start_pos)
@root_node = PolyTreeNode.new(start_pos)
@considered_positions = [start_pos]
self.build_move_tree
end
def build_move_tree
queue = [@root_node]
until queue.empty?
current_pos = queue.pop
next_pos = new_move_positions(current_pos.value)
next_pos.each do |pos|
child = PolyTreeNode.new(pos)
child.parent = current_pos
queue.unshift(child)
end
end
end
def generate_positions(pos)
positions = []
row, col = pos
positions << [(row + 1), (col + 2)]
positions << [(row + 1), (col - 2)]
positions << [(row - 1), (col + 2)]
positions << [(row - 1), (col - 2)]
positions << [(row + 2), (col + 1)]
positions << [(row + 2), (col - 1)]
positions << [(row - 2), (col + 1)]
positions << [(row - 2), (col - 1)]
return positions
end
def new_move_positions(current_pos)
positions = generate_positions(current_pos)
positions = positions.select do |pos|
!@considered_positions.include?(pos) && KnightPathFinder.valid_moves(pos)
end
@considered_positions.concat(positions)
positions
end
def find_path_bfs(end_pos)
queue = [@root_node]
until queue.empty?
current_pos = queue.pop
return trace_path_back(current_pos) if current_pos.value == end_pos
current_pos.children.each do |child|
queue.unshift(child)
end
end
nil
end
# def find_path_dfs(starting_pos, end_pos)
# return end_pos if starting_pos.value == end_pos
# starting_pos.children.each do |child|
# res = []
# res.concat(find_path_dfs(child, end_pos))
# return res unless res.empty?
# end
# nil
# end
def trace_path_back(pos)
return [@root_node.value] if @root_node.value == pos.value
trace_path_back(pos.parent) << pos.value
end
end
kpf = KnightPathFinder.new([0, 0])
p kpf.find_path_bfs([7, 6]) # => [[0, 0], [1, 2], [2, 4], [3, 6], [5, 5], [7, 6]]
p kpf.find_path_bfs([6, 2]) # => [[0, 0], [1, 2], [2, 0], [4, 1], [6, 2]]
# p kpf.find_path_dfs(kpf.root_node, [7, 6]) | true |
eefcb64e0503e948c42675f61c1ae5cfcba56acd | Ruby | averysoren/ls-core-curriculum | /ruby_book/the_basics/exercise3.rb | UTF-8 | 177 | 3 | 3 | [] | no_license | movies = {fight_club: 1999,
braveheart: 1995,
lucky_number_slevin: 2006}
puts movies[:fight_club]
puts movies[:braveheart]
puts movies[:lucky_number_slevin] | true |
f9a849efe9aacbd3e80b66f2fb1f2633adf31243 | Ruby | EricRicketts/LaunchSchool | /exercises/Ruby/small_problems/easy/one/third_exercise.rb | UTF-8 | 2,719 | 4.125 | 4 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require 'byebug'
class ThirdExercise < Minitest::Test
=begin
List Of Digits
Write a method that takes one argument, a positive integer, and returns a list of the digits in the number.
Examples:
puts digit_list(12345) == [1, 2, 3, 4, 5] # => true
puts digit_list(7) == [7] # => true
puts digit_list(375290) == [3, 7, 5, 2, 9, 0] # => true
puts digit_list(444) == [4, 4, 4] # => true
Input: Integer
Questions: no negative?
Output: an array of numbers where each element corresponds to each digit in the number
numbers in the array are ordered as they appear in the digit
Algorithm:
- convert the number into a string to_s
- all chars on the string to return an array of chars
- use map to convert each string to a number
Another way to do it is to pick off each digit using div and subtraction
- have an empty array
- find the highest power of 10 represented by the. number power = number.to_s.length - 1
- digit, remainder = number.divmod(10**power)
- push the digit onto the array
- set the number equal to the remainder, repeat the process
- we should be able use a times iterator
4.downto(0) do |power|
digit, remainder = num.divmod(10**power)
digit_ary.push(digit)
num = remainder
end
=end
def digit_list(number)
number.to_s.chars.map {|char| char.to_i}
end
def digit_list_v2(number)
# I keep forgetting to use the proc to shorten
# the map or inject code!!
number.to_s.chars.map(&:to_i)
end
def digit_list_v3(number)
"#{number}".split(//).map(&:to_i)
end
def digit_list_v4(number)
number.digits.reverse
end
def digit_list_v5(number)
num = number
digit_ary = []
high_power = number.to_s.length - 1
high_power.downto(0) do |power|
digit, remainder = num.divmod(10**power)
digit_ary.push(digit)
num = remainder
end
digit_ary
end
def test_12345
expected = (1..5).to_a
assert_equal(expected, digit_list(12345))
end
def test_7
assert_equal([7], digit_list(7))
end
def test_375290
expected = [3, 7, 5, 2, 9, 0]
assert_equal(expected, digit_list(375290))
end
def test_444
assert_equal(Array.new(3, 4), digit_list(444))
end
def test_v2
expected = (1..5).to_a
assert_equal(expected, digit_list_v2(12345))
end
def test_v3
expected = (1..5).to_a
assert_equal(expected, digit_list_v3(12345))
end
def test_v4
expected = (1..5).to_a
assert_equal(expected, digit_list_v4(12345))
end
def test_v5
expected = (1..5).to_a
assert_equal(expected, digit_list_v5(12345))
end
end | true |
3f058e7e0facbe9f52c2903b081cf3d7d82443b9 | Ruby | DrYaR/EXO_RUBY | /exo_20.rb | UTF-8 | 152 | 3.1875 | 3 | [] | no_license | puts "Un nombre s'il vous plait"
print "> "
number = gets.chomp.to_i
i = 0
block = "#"
number.times do puts i = block
block = block + "#"
end
| true |
ebde0575921a57b499d54d541eeecab559915f7f | Ruby | chaplonglau/product_searcher | /service_objects/process_products.rb | UTF-8 | 761 | 2.96875 | 3 | [] | no_license | module ServiceObjects
class ProcessProducts
attr_accessor :products, :store, :value_to_attribute_map
def initialize(products)
@products = products
@store = {}
@value_to_attribute_map = {}
end
def call
products.each do |product|
type = product["product_type"]
store[type] = {} if store[type] == nil
product["options"].each do |attribute,value|
store[type][attribute] = [value] if store[type][attribute] == nil
store[type][attribute] << value unless store[type][attribute].include?(value)
value_to_attribute_map[value] = attribute if value_to_attribute_map[value] == nil
end
end
[store,value_to_attribute_map]
end
end
end | true |
95d11aaf25d8d60b3d8ab39519bf79efffac9e1f | Ruby | MisterMur/nyc-web-010719 | /06-intro-to-inheritance/lib/dog.rb | UTF-8 | 179 | 3.109375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Dog < Pet
include ModuleName::InstanceMethods
def initialize(name, num_walks)
@num_walks
super(name)
end
# def walk
# puts "I am walking."
# end
end
| true |
9e8ca4ad4629aaae81141c21bb79bb6b680693f5 | Ruby | lissdy/CODEWARS | /Valid_Parentheses.rb | UTF-8 | 889 | 3.78125 | 4 | [] | no_license | #https://www.codewars.com/kata/52774a314c2333f0a7000688/train/ruby
#MY SOLUTION
def valid_parentheses(string)
return true if string.empty?
left_num = string.size - string.gsub('(','').size
right_num = string.size - string.gsub(')','').size
return false if left_num != right_num
stack = []
string.chars.each do |char|
if char == "("
stack.push("(")
elsif char == ")"
return false unless stack.pop
end
end
if stack.empty?
return true
else
return false
end
end
#BEST PRACTICE
def valid_parentheses(string)
open = 0
string.chars.each do |c|
open += 1 if c == "("
open -= 1 if c == ")"
return false if open < 0
end
open == 0
end
def valid_parentheses(string)
string.chars.each_with_object([]) do |c, stack|
if c == '('
stack.push(c)
elsif c == ')'
stack.pop or return(false)
end
end.empty?
end | true |
e317d8b49b5952c28f4ca46e3923845009a8f3e0 | Ruby | sarahabimay/TicTacToe_Gem | /lib/tictactoe/beatable_ai_player.rb | UTF-8 | 436 | 2.984375 | 3 | [] | no_license | require "tictactoe/player"
module TicTacToe
class BeatableAIPlayer
include Player
def initialize(mark, display)
@mark = mark
@display = display
end
def get_next_move(board)
move = randomized_move(board)
display.announce_player_move(mark, move)
move
end
def randomized_move(board)
rand(1..board.board_size)
end
private
attr_reader :mark, :display
end
end
| true |
18b83db2c88035c6b0c852a0e1f6dfbfead9b74a | Ruby | byzantinist/phase-0-tracks | /ruby/game.rb | UTF-8 | 3,596 | 4.125 | 4 | [] | no_license | # Class declaration
class Game
attr_reader :secret, :length, :secret_array
attr_accessor :guesses, :history, :display
def initialize
# Welcome message
puts "Welcome to Hangunicorn, a game where you need to correctly guess a word or phrase to save the life of an innocent baby unicorn!"
# Player 1: Enters a word or phrase
puts "Player 1, please enter your secret word or phrase:"
# For Ruby, we use gets.chomp
# For RSpec purposes, we assume the user will input "unicorn"
@secret = gets.chomp.downcase
#@secret = "unicorn"
# This clears the screen so Player 2 cannot see what Player 1 entered
puts "\e[H\e[2J"
puts "Player 1 has entered the secret word or phrase!"
# Establishes variable for number of guesses remaining, based on the length of the word
@length = @secret.length
@guesses = 2 * @length
puts "Since the secret word or phrase is #{@length} characters long (including possible spaces), you will get #{guesses} guesses!"
# An array to store the history of past guesses
@history = []
# Breaks the secret word into an array and creates the display for the user
# It is also possible to do this with hashes. One of the values could be a boolean
# true (revealed) or false (not revealed) and display the character or the "_" accordingly
@secret_array = @secret.split('')
@display = []
@secret_array.each {@display.push("_")}
end
# Player 2: Attempts to guess the word
def guessing
# Feedback on the current state of the word
puts "Here is your secret word or phrase: #{@display.join(' ')}"
puts "Here are your previous guesses: #{@history.join(' ')}"
puts "You have #{guesses} guesses left! Please save the unicorn!"
# Some additional taunting
if @guesses == 1
puts "Uh oh! You only have a single guess left. This is the unicorn's last chance!"
elsif @guesses == @length
puts "Uh oh! You are halfway through your guesses. The unicorn is in trouble!"
end
puts "Player 2, please guess a letter, character, or space:"
character = gets.chomp.downcase
#Test code for RSpec
#character = 'o'
# If the character has not been previously guessed, then you decrement the number
# of guesses. And for each index/character in the secret_array that matches the
# guessed character, you copy over its value into the display.
if !@history.include?(character)
@history << character
@guesses += -1
count = 0
if secret_array.include?(character)
puts "Good work! There are #{secret_array.count(character)} instance(s) of '#{character}'!"
while count < @length
if @secret_array[count] == character
@display[count] = character
end
count += 1
end
else
puts "Sorry, there is no '#{character}' in the secret word or phrase!"
end
else
# Repeated guesses do not count: @guesses does not decrement in this case
puts "You have already guessed the letter, character, or space: '#{character}'!"
end
# Congratulatory message or taunting message
if @display == @secret_array
puts "Congratulations! You have successfully saved the unicorn by guessing the secret word/phrase: '#{@secret}'! You still had #{guesses} guesses left!"
@guesses = 0
elsif @guesses == 0
puts "Oh noes! You have failed to guess the secret word or phrase, which was: '#{@secret}'! The unicorn is dead and it is all YOUR FAULT! :'("
puts "Better luck next time!"
end
end
end
# Driver code
lets_play = Game.new
while lets_play.guesses > 0
lets_play.guessing
end | true |
34799192f9c520e8f5fe63b61174fe9739686bef | Ruby | JustinData/GA-WDI-Work | /w04/d03/Erica/crypt.rb | UTF-8 | 98 | 2.53125 | 3 | [] | no_license | def encode(string)
encode = string.tr!('A-Za-z', 'N-ZA-Mn-za-m')
return encode
end
end
| true |
c81b216ecfb077979c3400a3388c7ba226ab220f | Ruby | msmiller/redbus | /backburner/pubsub.rb | UTF-8 | 1,515 | 2.546875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/ruby
# @Author: msmiller
# @Date: 2019-09-16 13:24:00
# @Last Modified by: msmiller
# @Last Modified time: 2019-10-31 10:43:43
#
# Copyright (c) Sharp Stone Codewerks / Mark S. Miller
# This is for pub/sub and wait with specific messages
# NOTE: This was the first incarnation. But it wouldn't work well with a deployment
# where there were multiple instances per process type (i.e. event would get published
# to every instance, not just one per process type). It will later be resurrected for
# cases where people may want a simpler configuration.
module Redbus
class Pubsub
# Fire-and-forget publish
def self.publish(channels, data)
channels.gsub(/\s+/, "").split(',').each do |c|
$pubredis.publish c, data.to_json
end
end
# Synchronous subscribe
def self.subscribe(channels, callback=nil)
$subredis.subscribe(channels) do |on|
on.message do |channel, msg|
data = JSON.parse(msg)
if callback.nil?
dump_message(channel, msg)
else
eval("#{callback}(channel, msg)")
end
end
end
end
# Synchronous psubscribe
def self.psubscribe(pattern, callback=nil)
$subredis.psubscribe(pattern) do |on|
on.pmessage do |pattern, channel, msg|
data = JSON.parse(msg)
if callback.nil?
dump_message(channel, msg)
else
eval("#{callback}(channel, msg)")
end
end
end
end
end
end
| true |
00900d1b8a63b7aae7dfe777d654bb615b845d87 | Ruby | Sigwings/Ruby | /bin/RubyLogger.rb | UTF-8 | 1,052 | 2.609375 | 3 | [] | no_license | require_relative 'Directory'
require_relative 'RegistryTools'
class RubyLogger
include Directory
extend RegistryTools
DEFAULT_FILE = "#{ documents_path }\\Ruby Logs\\#{ File.basename( $0, '.*' ) }.log".freeze
attr_accessor :filename, :orig_std_out
def initialize( filename = DEFAULT_FILE )
self.filename = check_dir_path(filename)
clear
end
def sync
self.orig_std_out = STDOUT.clone #Make a record of the default console output to return to it later
$stdout.reopen( filename, 'w' ) #Create / overwrite logfile
$stdout.sync = true #Allow interception of console output
$stderr.reopen( filename ) #Pass errors to logfile
self
end
def unsync
$stdout.reopen( orig_std_out )
$stdout.sync = true
$stderr.reopen( orig_std_out )
self
end
def log( msg )
File.open( filename, 'a') { |f| f.puts msg }
end
alias puts log
def path
File.dirname( filename )
end
def clear
File.write( filename, '' )
end
end | true |
0481d1a39df0da2c020526e407226c069ac5f819 | Ruby | iain/miniture-ninja | /lib/collada.rb | UTF-8 | 2,451 | 2.796875 | 3 | [] | no_license | class Collada
attr_reader :doc, :filename
def initialize(filename, doc)
@filename = filename
@doc = doc
end
def dir
Pathname(File.dirname(filename))
end
def as_json
{
geometries: geometries,
textures: Hash[textures]
}
end
def geometries
doc.css("instance_geometry").select { |in_geo|
url = in_geo[:url]
doc.css("#{url} triangles input[semantic=TEXCOORD]").first
}.map do |in_geo|
url = in_geo[:url]
{
indices: indices(url),
vertices: vertices(url),
texcoords: texcoords(url),
material: material(in_geo)
}
end
end
def indices(url)
indices_count = doc.css("#{url} triangles").first[:count].to_i * 3
doc.css("#{url} triangles p").first.content.split(/\s+/).select.with_index { |p, i| i.even? }.map(&:to_i)[(0..indices_count)]
end
def vertices(url)
vertex_url = doc.css("#{url} triangles input[semantic=VERTEX]").first[:source]
{
positions: positions(vertex_url),
normals: normals(vertex_url)
}
end
def positions(url)
get_vertex(url, "POSITION")
end
def normals(url)
get_vertex(url, "NORMAL")
end
def get_vertex(url, semantic)
source_url = doc.css("#{url} input[semantic=#{semantic}]").first[:source]
doc.css("#{source_url} float_array").first.content.split(/\s+/).map(&:to_f)
end
def texcoords(url)
source = doc.css("#{url} triangles input[semantic=TEXCOORD]").first
if source
source_url = source[:source]
doc.css("#{source_url} float_array").first.content.split(/\s+/).map(&:to_f)
end
end
def material(in_geo)
material_id = in_geo.css("bind_material instance_material").first[:target]
effect_id = doc.css("#{material_id} instance_effect").first[:url]
color_doc = doc.css("#{effect_id} color")
if color_doc.any?
{
color: color_doc.first.content.split(/\s+/).map(&:to_f),
texture: nil
}
else
image_id = doc.css("#{effect_id} init_from").first.content
filename = doc.css("##{image_id} init_from").first.content
{
texture: md5(filename),
color: [1,1,1,1]
}
end
end
def textures
doc.css("library_images image init_from").map do |init_from|
[md5(init_from.content), init_from.content ]
end
end
def md5(filename)
data = File.open(dir.join(filename), 'rb').read
Digest::MD5.hexdigest(data)
end
end
| true |
0ad7d18c27aa9b23987d5a89a5b1ced3f64d71ac | Ruby | enzo9214/E8CP2A1 | /prueba.rb | UTF-8 | 1,737 | 3.296875 | 3 | [] | no_license | alumnos = {}
alumnos_promedios = {}
def abrir_archivo(hash)
data = File.open('notas.csv','r') { |archivo| archivo.readlines }
data = data.map{ |data| data.chomp.split(', ') }
data.each do |info|
hash[info[0]] = [info[1], info[2], info[3], info[4], info[5]]
end
hash.each do |nombre,array_notas|
hash[nombre] = array_notas.map{ |nota|
if nota != 'A'
nota.to_i
else
nota = 0
end
}
end
hash
end
def comprobar_aprobacion(hash, nota_minima)
hash.each do |nombre, promedio|
puts "#{nombre} aprobo con promedio #{promedio}" if promedio >= nota_minima
end
end
## cargando data en init
abrir_archivo(alumnos)
#print alumnos
alumnos.each do |nombre, array_notas|
alumnos_promedios.store(nombre, array_notas.inject(0) { |acc, valor| acc + valor } / array_notas.length)
end
##print alumnos_promedios
while true
puts "\nIngrese opcion"
opcion = gets.chomp.to_i
case opcion
when 1 ##promedio de notas
File.open( "alumnos/Promedios.txt",'w') do |archivo|
alumnos_promedios.each do |nombre, promedio|
archivo.puts "#{nombre} #{promedio}"
end
end
puts "Archivo creado!"
print alumnos_promedios
when 2 ##mostrar total inasistencias
suma = 0
alumnos.values.each do
|nota_alumno| suma += nota_alumno.count(0)
end
puts "Hay #{suma} inasistencias"
when 3 ##comprobar si alumnos aprueban
puts "Ingresa nota minima de aprobacion"
nota_minima = gets.chomp.to_i
if nota_minima == 0
nota_minima = 5
end
comprobar_aprobacion(alumnos_promedios, nota_minima)
when 4
break
else
puts 'Opcion invalida'
end
end
| true |
71b8121884e9273fc0559ae521ceac968d4a1a67 | Ruby | tainarareis/DesignPatterns | /strategy/en_us/ruby/celsius_fahrenheit.rb | UTF-8 | 160 | 2.953125 | 3 | [] | no_license | class CelsiusFahrenheit
# Makes the convertion of Celsius to Fahrenheit
def convert(value)
converted_measure = (value * (9.0 / 5.0)) + 32.0
end
end
| true |
3c7a977bd95341fe63d00ca13c9b4c610e87714c | Ruby | AlexanderCode/Practice_Problems | /practice20.rb | UTF-8 | 364 | 4.34375 | 4 | [] | no_license | # practice20.rb
# Write a method that takes a String of digits, and returns the appropriate number as an integer.
def string_to_integer(string)
string.gsub('1', 1).gsub('2', 2).gsub('3', 3).gsub('4', 4).gsub('5', 5).gsub('6', 6).gsub('7', 7).gsub('8', 8).gsub('9', 9).gsub('0', 0)
end
p string_to_integer('4321') # => 4321
p string_to_integer('570') # => 570 | true |
930169a0b846c0fecec626a68b05abaf74f2b12c | Ruby | MastersAcademy/ruby-course-2018 | /objects/taras.turchenko/colorized_string.rb | UTF-8 | 318 | 3.265625 | 3 | [] | no_license | class String
COLORS = {
black: 30,
red: 31,
green: 32,
brown: 33,
blue: 34,
magenta: 35,
cyan: 36,
gray: 37
}.freeze
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
COLORS.each do |name, color_code|
define_method(name) { colorize color_code }
end
end
| true |
8a51028b670b44dfcd9ec53279aba5837030e74c | Ruby | joeplyr/pandata | /spec/parser_spec.rb | UTF-8 | 10,940 | 2.53125 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
require 'pandata/parser'
describe Pandata::Parser do
let(:liked_albums_html) { read_path('fixtures/ajax/show_more/liked_albums.html') }
let(:liked_tracks_html) { read_path('fixtures/ajax/show_more/mobile/liked_tracks.html') }
let(:liked_artists_html) { read_path('fixtures/ajax/show_more/liked_artists.html') }
let(:liked_stations_html) { read_path('fixtures/ajax/show_more/liked_stations.html') }
let(:liked_albums_html) { read_path('fixtures/ajax/show_more/liked_albums.html') }
let(:parser) { Pandata::Parser.new }
describe '#get_webnames_from_search' do
let(:html) { read_path('fixtures/ajax/show_more/search_results_for_joe.html') }
it 'returns an array of webnames' do
webnames = parser.get_webnames_from_search(html)
expect(webnames).to eq [
'joe',
'joe_maas',
'joe_m_reyes',
'joe_rybicki',
'joe_biear',
'batman-joe',
'jedi_joe',
'joe_carpenito',
'joe_old',
'rustin_joe',
'joe_slavin',
'explosivo_joe',
'joe_tonda',
'joe-phat'
]
end
end
describe '#get_next_data_indices' do
context 'when more data exists on the server' do
let(:followers) { read_path('fixtures/ajax/show_more/followers.html') }
let(:following) { read_path('fixtures/ajax/show_more/following.html') }
it 'returns the indices to use in the next request to get the next set of data' do
result = parser.get_next_data_indices(liked_tracks_html)
expect(result).to eq({ nextLikeStartIndex: 0, nextThumbStartIndex: 20 })
result = parser.get_next_data_indices(liked_artists_html)
expect(result).to eq({ nextStartIndex: 5 })
result = parser.get_next_data_indices(liked_stations_html)
expect(result).to eq({ nextStartIndex: 5 })
result = parser.get_next_data_indices(liked_albums_html)
expect(result).to eq({ nextStartIndex: 5 })
result = parser.get_next_data_indices(followers)
expect(result).to eq({ nextStartIndex: 50 })
result = parser.get_next_data_indices(following)
expect(result).to eq({ nextStartIndex: 50 })
end
end
context 'when no more data exists' do
let(:html) { read_path('fixtures/ajax/no_more/mobile/liked_tracks.html') }
it 'returns false' do
result = parser.get_next_data_indices(html)
expect(result).to eq false
end
end
end
describe '#infobox_each_link' do
it 'accepts a block passing the title link and the subtitle link text' do
albums = liked_albums_html
all_titles = []
parser.instance_eval do
infobox_each_link(albums) do |title, subtitle|
all_titles.push(title, subtitle)
end
end
expect(all_titles).to eq [
'Sweet Talk EP',
'Kito & Reija Lee',
'Audio, Video, Disco.',
'Justice',
'All Eternals Deck',
'The Mountain Goats',
'All Of A Sudden I Miss Everyone',
'Explosions In The Sky',
'Attack & Release',
'The Black Keys'
]
end
end
describe '#doublelink_each_link' do
it 'accepts a block passing the title link and the subtitle link text' do
tracks = liked_tracks_html
all_titles = []
parser.instance_eval do
doublelink_each_link(tracks) do |title, subtitle|
all_titles.push(title, subtitle)
end
end
expect(all_titles).to eq [
"Chitlins Con Carne",
"by Stevie Ray Vaughan",
"Rock You Like A Hurricane (Live)",
"by Scorpions",
"Evil",
"by William Clarke",
"Blues For Lost Days (Live)",
"by John Mayall",
"As The Years Go Passing By (Live)",
"by The Mannish Boys",
"Let's Cool One (1958)",
"by Thelonious Monk",
"Breathe",
"by Bjorn Akesson",
"Greatest DJ (Radio Edit)",
"by twoloud",
"Nobody's Fault But My Own",
"by Lil' Ed & The Blues Imperials",
"Dog House Blues",
"by Larry Garner"
]
end
end
describe '#get_recent_activity' do
let(:xml) { read_path('fixtures/feeds/recent_activity.xml') }
it 'returns an array of activity names' do
activity = parser.get_recent_activity(xml)
expect(activity).to eq [
'Drake',
'George Strait',
'Future',
'Ssion',
'Gucci Mane',
'Frank Ocean',
'Rage Against The Machine',
'Lady Gaga',
'Loverboy',
'Lil Wayne',
'HYFR (Hell Ya Fucking Right) by Drake',
'Human by The Killers',
'Drake Radio'
]
end
end
describe '#get_stations' do
let(:xml) { read_path('fixtures/feeds/stations.xml') }
it 'returns an array of station names' do
stations = parser.get_stations(xml)
expect(stations).to eq [
'Drake Radio',
'George Strait Radio',
'Future Radio',
'Ssion Radio',
'Gucci Mane Radio',
'Frank Ocean Radio',
'Loverboy Radio',
'Lil Wayne Radio',
'Fun. Radio',
'The Killers Radio',
"pandorastats's QuickMix"
]
end
end
describe '#get_playing_station' do
let(:xml) { read_path('fixtures/feeds/station_now_playing.xml') }
it 'returns the name of the currently playing station' do
station = parser.get_playing_station(xml)
expect(station).to eq 'Drake Radio'
end
end
describe '#get_bookmarked_tracks' do
let(:xml) { read_path('fixtures/feeds/bookmarked_tracks.xml') }
it 'returns an array of hashes with the artist and track names' do
tracks = parser.get_bookmarked_tracks(xml)
expect(tracks).to eq [
{ artist: 'A Boy and His Kite', track: 'Cover Your Tracks' },
{ artist: 'Royksopp', track: 'Royksopp Forever' },
{ artist: 'The National', track: 'Lucky You' },
{ artist: 'Radical Face', track: 'Welcome Home' },
{ artist: "Margot & The Nuclear So And So's", track: 'Broadripple Is Burning (Daytrotter Sessions)' }
]
end
end
describe '#get_bookmarked_artists' do
let(:xml) { read_path('fixtures/feeds/bookmarked_artists.xml') }
it 'returns an array of artist names' do
artists = parser.get_bookmarked_artists(xml)
expect(artists).to eq [
'Trampled By Turtles',
'Adele',
'DJ Logic',
'Whitley',
'Mumford & Sons'
]
end
end
describe '#get_liked_tracks' do
it 'returns an array of hashes with the artist and track names' do
tracks = parser.get_liked_tracks(liked_tracks_html)
expect(tracks).to eq [
{ artist: "Stevie Ray Vaughan", track: "Chitlins Con Carne"},
{ artist: "Scorpions", track: "Rock You Like A Hurricane (Live)" },
{ artist: "William Clarke", track: "Evil" },
{ artist: "John Mayall", track: "Blues For Lost Days (Live)" },
{ artist: "The Mannish Boys", track: "As The Years Go Passing By (Live)" },
{ artist: "Thelonious Monk", track: "Let's Cool One (1958)" },
{ artist: "Bjorn Akesson", track: "Breathe" },
{ artist: "twoloud", track: "Greatest DJ (Radio Edit)" },
{ artist: "Lil' Ed & The Blues Imperials", track: "Nobody's Fault But My Own" },
{ artist: "Larry Garner", track: "Dog House Blues" }
]
end
end
describe '#get_liked_artists' do
it 'returns an array of artist names' do
artists = parser.get_liked_artists(liked_artists_html)
expect(artists).to eq [
'PANTyRAiD',
'Crystal Castles',
'Kito & Reija Lee',
'Portishead',
'Avicii'
]
end
end
describe '#get_liked_stations' do
it 'returns an array of station names' do
stations = parser.get_liked_stations(liked_stations_html)
expect(stations).to eq [
'Country Christmas Radio',
'Pachanga Boys Radio',
'Tycho Radio',
'Bon Iver Radio',
'Beach House Radio'
]
end
end
describe '#get_liked_albums' do
it 'returns an array of hashes with the artist and album names' do
albums = parser.get_liked_albums(liked_albums_html)
expect(albums).to eq [
{ artist: 'Kito & Reija Lee', album: 'Sweet Talk EP' },
{ artist: 'Justice', album: 'Audio, Video, Disco.' },
{ artist: 'The Mountain Goats', album: 'All Eternals Deck' },
{ artist: 'Explosions In The Sky', album: 'All Of A Sudden I Miss Everyone' },
{ artist: 'The Black Keys', album: 'Attack & Release' }
]
end
end
describe '#get_following' do
let(:html) { read_path('fixtures/ajax/no_more/following.html') }
it 'returns an array of people being followed + metadata' do
following = parser.get_following(html)
expect(following).to eq [
{ name: 'caleb', webname: 'wakcamaro', href: '/profile/wakcamaro' },
{ name: 'caleb_robert_97', webname: 'caleb_robert_97', href: '/profile/caleb_robert_97' },
{ name: 'Caleb Smith', webname: 'caleb_smith_', href: '/profile/caleb_smith_' },
{ name: 'Caleb Lalonde', webname: 'caleb_lalonde', href: '/profile/caleb_lalonde' },
{ name: 'Steve', webname: 'stortiz4', href: '/profile/stortiz4' },
{ name: 'Steve Ingals', webname: 'ingalls_steve', href: '/profile/ingalls_steve' },
{ name: 'Steve Boeckels', webname: 'steve_boeckels', href: '/profile/steve_boeckels' },
{ name: 'Steve D', webname: 'steve_diamond', href: '/profile/steve_diamond' },
{ name: 'Steve Orona', webname: 'orona_steve', href: '/profile/orona_steve' },
{ name: 'John', webname: 'john_chretien', href: '/profile/john_chretien' }
]
end
end
describe '#get_followers' do
let(:html) { read_path('fixtures/ajax/no_more/followers.html') }
it 'returns an array of followers + metadata' do
followers = parser.get_followers(html)
expect(followers).to eq [
{ name: 'pandorastats', webname: 'pandorastats', href: '/profile/pandorastats' },
{ name: 'HowZat', webname: 'stevierocksys', href: '/profile/stevierocksys' },
{ name: 'pgil28', webname: 'pgil28', href: '/profile/pgil28' },
{ name: 'sexy bella :)', webname: 'sexygirl43', href: '/profile/sexygirl43' },
{ name: 'jhendrix3188', webname: 'jhendrix3188', href: '/profile/jhendrix3188' },
{ name: 'Murtada67', webname: 'murtada67', href: '/profile/murtada67' },
{ name: 'lochead', webname: 'lochead', href: '/profile/lochead' }
]
end
end
end
| true |
d5c508b9c6f6bcdf829f22536982d9d294ddb262 | Ruby | SellaRafaeli/pickeez | /bl/phones.rb | UTF-8 | 2,399 | 3.359375 | 3 | [] | no_license | module Phones
extend self
def get_phone_country_code(international_number)
Phonelib.parse(international_number).country
end
def international_to_local(international_number)
Phonelib.parse(international_number).national.tr('-','')
end
def local_to_international(local_number,country_code)
PhonyRails.normalize_number(local_number, :country_code => country_code)
end
def is_international_phone?(phone)
Phonelib.valid?(phone)
end
def sanitize_phone(international_number)
Phonelib.parse(international_number).sanitized
end
# this method turns 'new_user_number' into an international phone.
# If it's already an international phone, return it.
# Otherwise (it's a local phone), assume it's from the same country as
# the first phone, and transform it into the international format of that country.
# Thus, if user1 (for whom we have an international phone number) invites user2 via
# an either local or international number, we can create user2's number and now we (hopefully)
# have user2's international number.
def to_international(new_number, international_number_hint)
if is_international_phone?(new_number)
sanitize_phone(new_number)
else
country_code = get_phone_country_code(international_number_hint)
international_new_number = local_to_international(new_number, country_code)
sanitize_phone(international_new_number)
end
end
end
# The default inviter is a random US number, so if user with no phones invites
# some number) we will assume it is a US number.
# (Note not using default param because passing in nil overrides a default param.)
def force_international(invited_num, inviter_num)
Phones.to_international(invited_num, inviter_num || '12125551234')
end
def test_force_international
puts force_international('0547805206', '972522934321') == '972547805206' #friend in same country, local number (IL)
puts force_international( '7348001234', '12125009999') == '17348001234' #friend in same country, local number (USA)
puts force_international('972547805206', '972522934321') == '972547805206' #friend in same country, international number.
puts force_international('17348001234', '972522934321') == '17348001234' #friend in other country, international number.
puts force_international('7348001234') == '17348001234' #no number, assume hint is USA
end
| true |
687e174ec07e292cf0c0e19e732077bb8fe919ea | Ruby | Joe-noh/nippopotamus | /lib/nippopotamus/cli.rb | UTF-8 | 748 | 2.765625 | 3 | [] | no_license | require "nippopotamus"
require "thor"
module Nippopotamus
class CLI < Thor
option :username, type: :string
desc "today", "print today's activities"
def today
config = Nippopotamus::Config.new
config.user_name = options[:username]
activities = Nippopotamus.fetch_activities(config)
puts Nippopotamus::Formatter::Plain.format(activities)
end
option :username, type: :string
desc "yesterday", "print yesterday's activities"
def yesterday
config = Nippopotamus::Config.new
config.user_name = options[:username]
config.date = Date.today - 1
activities = Nippopotamus.fetch_activities(config)
puts Nippopotamus::Formatter::Plain.format(activities)
end
end
end
| true |
a8888189d97d779ac2c77b43c2838214841ef4f4 | Ruby | bbensky/pine_ruby_exercises | /chris_pine_ex/ch6_deafgrandma.rb | UTF-8 | 257 | 3.3125 | 3 | [] | no_license | command = ''
while command != 'BYE'
command = gets.chomp
if (command == command.upcase && command != 'BYE')
puts 'NO, NOT SINCE ' + rand(1930..1950).to_s + '!'
else
if command != 'BYE'
puts 'HUH?! SPEAK UP, SONNY!'
end
end
end | true |
63b09bf24e76feef14396a01774b4bf0bf713361 | Ruby | MichaelSRomero/my-each-dumbo-web-career-012819 | /my_each.rb | UTF-8 | 308 | 3.34375 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # require 'benchmark'
def my_each(arr)
i = 0
while i < arr.length
yield(arr[i])
i += 1
end
return arr
end
# iterations = 100_000
#
# Benchmark.bm(20) do |bm|
# bm.report("My Each") do
# iterations.times do
# my_each([100, 200, 300, 400]) {|n| n - 100}
# end
# end
# end
| true |
4f91c35600588881072e3c9da86dfbb4b768696a | Ruby | androi7/sei35 | /week5/warmump/luhn.rb | UTF-8 | 1,435 | 4.0625 | 4 | [] | no_license | # class Luhn
#
# def initialize num
# @num = num.to_s
# end
#
# def valid?
# num_arr = @num.split('')
# num_arr = num_arr.reverse.each_with_index.map do |x, i|
# x = x.to_i
# if i % 2 != 0
# x = x * 2 < 10 ? x * 2 : x * 2 - 9
# else
# x = x
# end
# end.reduce(0) { |a, b| a + b } % 10 == 0
#
# end
#
# end
class Luhn
def initialize number
@number = number
end
def prepare_digits
# initialize array
all_digits = []
# e.g. 1234.digits => [4, 3, 2, 1]
@number.digits.each_with_index do |digit, index|
# check every 2nd digit
# multiply by 2
# if index % 2 != 0
# digit *= 2 # multiply by 2
# end
digit *= 2 if index % 2 != 0
# if >= 10, do -9
digit -= 9 if digit >= 10
# save digit to array
all_digits << digit
end
# return array
all_digits
end
def valid?
numbers = prepare_digits
# inject method:
# [1,2,3].inject(0, :+) => 6
# [1,2,3].inject(10, :+) => 16
# [1,2,3].inject(:*) => 6
total = numbers.inject(0, :+)
if total % 10 == 0
puts "#{@number} is a valid Luhn number."
else
puts "#{@number} is NOT a valid Luhn number."
# @number = @number + ( 10 - total % 10)
# puts "#{@number} would be a valid Luhn number."
end
end
end
l = Luhn.new(3554)
p l.valid?
l = Luhn.new(8763)
p l.valid?
| true |
2412022fb549cb9f610f9169a97e94a520b6df95 | Ruby | ZeroCBR/WeatherPredictor | /lib/prediction_regression.rb | UTF-8 | 5,085 | 3.390625 | 3 | [] | no_license | require 'matrix' # perform the matrix operation
class PredictionRegression
@@TYPE=["linear","polynomial", "exponential", "logarithmic"]
# read the arguments from the command line and jump to the specified regression
def initialize x, y, period
@x=x
@y=y
@periods=[]
periodToArray(period)
@expectY=Array.new
@coefficientP=Array.new
@coefficientE=Array.new
@coefficientL=Array.new
@varianceP=2**1000
@varianceE=2**1000
@varianceL=2**1000
end
# perform polynomial regression
def polynomialRegression(degree)
x_data = @x.map { |x_i| (0..degree).map { |pow| (x_i**pow).to_f } }
mx = Matrix[*x_data]
my = Matrix.column_vector(@y)
coefficients = ((mx.t * mx).inv * mx.t * my).transpose.to_a[0] # obtain all the coefficients from low degree to high degree
coefficients.each_with_index do |item,index|
coefficients[index]=item.round(2) # return 2 decimal places
end
calculateExpectY(coefficients,"polynomial")
end
# perform exponential regression
def exponentialRegression()
sumlny=0.0
sumXSquare=0.0
sumX=0.0
sumXlny=0.0
i=0
begin
sumlny+=Math.log(@y[i])
sumXSquare+=@x[i]**2
sumX+=@x[i]
sumXlny+=@x[i]*Math.log(@y[i])
i+=1
# catch Math::DomainError
rescue Math::DomainError
puts "Cannot perform exponential regression on this data ! "
exit(1)
end while i<@x.length
a=(sumlny*sumXSquare-sumX*sumXlny)/(@x.length*sumXSquare-sumX**2)
b=(@x.length*sumXlny-sumX*sumlny)/(@x.length*sumXSquare-sumX**2)
a=Math::E**a
a=a.round(2) # return 2 decimal places
b=b.round(2) # return 2 decimal places
@coefficientE << a
@coefficientE << b
calculateExpectY(@coefficientE,"exponential")
end
# perform logarithmic regression
def logarithmicRegression()
sumYlnx=0.0
sumY=0.0
sumlnx=0.0
sumlnxSquare=0.0
i=0
begin
sumYlnx+=@y[i]*Math.log(@x[i])
sumY+=@y[i]
sumlnx+=Math.log(@x[i])
sumlnxSquare+=Math.log(@x[i])**2
i+=1
# catch Math::DomainError
rescue Math::DomainError
puts "Cannot perform exponential regression on this data ! "
exit(1)
end while i<@x.length
b=(@x.length*sumYlnx-sumY*sumlnx)/(@x.length*sumlnxSquare-sumlnx**2)
a=(sumY-b*sumlnx)/@x.length
b=b.round(2) # return 2 decimal places
a=a.round(2) # return 2 decimal places
@coefficientL << a
@coefficientL << b
calculateExpectY(@coefficientL,"logarithmic")
end
# calculate the average variance
# - return: average variance
def calculateAverageVariance()
i=0
sumY_expectY=0.0
begin
sumY_expectY+=(@y[i]-@expectY[i])**2
i+=1
end while i<@x.length
variance=sumY_expectY/@x.length
return variance
end
# calculate the expect value through the regression equation
# - coefficient: coefficient array obtained by regression
# - type: regression type
def calculateExpectY(coefficient,type)
sum=0.0
@expectY=Array.new
case type
when @@TYPE[1]
@x.each_with_index do |x,i|
coefficient.each_with_index do |item,index|
sum+=item*@x[i]**index
end
@expectY << sum.round(4)
sum=0.0
end
tmp=calculateAverageVariance
# record the coefficient with minimum variance
if tmp<@varianceP
@varianceP=tmp
@coefficientP=coefficient
end
when @@TYPE[2]
@x.each do |x|
@expectY << @coefficientE[0]*Math::E**(@coefficientE[1]*x)
end
@varianceE=calculateAverageVariance
when @@TYPE[3]
@x.each do |x|
@expectY << @coefficientL[1]*Math.log(x)+@coefficientL[0]
end
@varianceL=calculateAverageVariance
end
end
# calculate the average for an integer array
# - array: float array
# - return: the average of float array
def calculateAverage(array)
sum=0.0
array.each do |item|
sum=sum+item.to_f
end
return sum/array.length
end
def periodToArray(period)
(1..period/10).each do |i|
@periods.push(i*10*60+Time.now.to_i)
end
end
def executeRegression
predictValue=[]
predictPro=[]
sum=0.0
(2...11).each do |degree|
polynomialRegression(degree)
end
exponentialRegression
logarithmicRegression
if @varianceP<@varianceL && @varianceP<@varianceE
@periods.each_with_index do |period,i|
@coefficientP.each_with_index do |item,index|
sum+=item*period[i]**index
end
predictValue.push(sum.round(4))
sum=0.0
end
predictValue.each do |pv|
predictPro.push(pv.abs/(pv.abs+Math.sqrt(@varianceP)))
end
elsif @varianceL<@varianceP && @varianceL<@varianceE
@periods.each do |period|
predictValue.push(@coefficientL[1]*Math.log(period)+@coefficientL[0])
end
predictValue.each do |pv|
predictPro.push(pv.abs/(pv.abs+Math.sqrt(@varianceL)))
end
elsif @varianceE<=@varianceL && @varianceE<=@varianceP
@periods.each do |period|
predictValue.push(@coefficientE[0]*Math::E**(@coefficientE[1]*period))
end
predictValue.each do |pv|
predictPro.push(pv.abs/(pv.abs+Math.sqrt(@varianceE)))
end
else
(1..@periods.size).each do |i|
predictValue.push(0)
end
predictValue.each do |pv|
predictPro.push(1)
end
end
return predictValue, predictPro
end
end | true |
53054b1771fef72a10160b3c739f8edcb9045213 | Ruby | codecell/algo | /queue.rb | UTF-8 | 1,128 | 4.0625 | 4 | [] | no_license | # Start with your code from LinkedList challenge.
class Node
attr_accessor :value, :next_node
def initialize(value, next_node = nil)
@value = value
@next_node = next_node
end
end
class Queue
def initialize(front = nil, back = nil)
@front = front
@back = back
end
def add(number)
new_node = Node.new(number)
if @front.nil?
@front = new_node
@back = @front
else
@back.next_node = new_node
@back = new_node
end
end
def remove
return -1 if @front.nil?
tracer = @front
dequeued = @front.value
tracer = tracer.next_node
@front = tracer
dequeued
end
def get_length
return 0 if @front.nil?
tracer = @front
counter = @front.nil? ? 0 : 1
until tracer.next_node.nil?
tracer = tracer.next_node
counter += 1
end
counter
end
end
queue = Queue.new
queue.add(3)
queue.add(5)
puts queue.remove
# => 3
queue.add(2)
queue.add(7)
#puts queue.remove
# => 5
p queue.get_length
#puts queue.remove
# => 2
#puts queue.remove
# => 7
#puts queue.remove
# => -1 | true |
75619b333b8ea659e543aa5c1bfdff30c75f95a0 | Ruby | Macaroni2629/Launch-School | /120_object_oriented_programming/oop_book_exercises/1_the_object_model/ex_1.rb | UTF-8 | 385 | 4.1875 | 4 | [] | no_license | # How do we create an object in Ruby?
# Give an example of the creation of an object.
class Cat
end
socks = Cat.new
=begin
We create an object by defining a class using the 'class' keyword and the reserved word 'end'.
We then instantiate the object and named it 'socks' in this case.
We create an 'instance' or also known as an object by calling the `new` class method.
=end | true |
15bf29955acd34f7f627ff5e0df3465efb3e03dc | Ruby | KatKmiotek/weekend_homework_week02 | /song.rb | UTF-8 | 118 | 2.703125 | 3 | [] | no_license | class Song
attr_reader :title, :artist
def initialize(title, artist)
@title = title
@artist = artist
end
end
| true |
4b36ae9ae8a03f569e3949b2d4d0b13b67bb9eb4 | Ruby | puppetlabs/r10k | /spec/unit/util/setopts_spec.rb | UTF-8 | 2,334 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
require 'r10k/util/setopts'
describe R10K::Util::Setopts do
let(:klass) do
Class.new do
include R10K::Util::Setopts
attr_reader :valid, :alsovalid, :truthyvalid
def initialize(opts = {})
setopts(opts, {
:valid => :self,
:duplicate => :valid,
:alsovalid => :self,
:truthyvalid => true,
:validalias => :valid,
:ignoreme => nil
})
end
end
end
it "can handle an empty hash of options" do
o = klass.new()
expect(o.valid).to be_nil
expect(o.alsovalid).to be_nil
end
it "can handle a single valid option" do
o = klass.new(:valid => 'yep')
expect(o.valid).to eq 'yep'
expect(o.alsovalid).to be_nil
end
it "can handle multiple valid options" do
o = klass.new(:valid => 'yep', :alsovalid => 'yarp')
expect(o.valid).to eq 'yep'
expect(o.alsovalid).to eq 'yarp'
end
it "can handle options marked with TrueClass" do
o = klass.new(:truthyvalid => 'so truthy')
expect(o.truthyvalid).to eq 'so truthy'
end
it "can handle aliases marked with :self" do
o = klass.new(:validalias => 'yuuup')
expect(o.valid).to eq 'yuuup'
end
it "raises an error when given an unhandled option" do
expect {
klass.new(:valid => 'yep', :notvalid => 'newp')
}.to raise_error(ArgumentError, /cannot handle option 'notvalid'/)
end
it "warns when given an unhandled option and raise_on_unhandled=false" do
test = Class.new { include R10K::Util::Setopts }.new
allow(test).to receive(:logger).and_return(spy)
test.send(:setopts, {valid: :value, invalid: :value},
{valid: :self},
raise_on_unhandled: false)
expect(test.logger).to have_received(:warn).with(%r{cannot handle option 'invalid'})
end
it "ignores values that are marked as unhandled" do
klass.new(:ignoreme => "IGNORE ME!")
end
it "warns when given conflicting options" do
test = Class.new { include R10K::Util::Setopts }.new
allow(test).to receive(:logger).and_return(spy)
test.send(:setopts, {valid: :one, duplicate: :two},
{valid: :arg, duplicate: :arg})
expect(test.logger).to have_received(:warn).with(%r{valid.*duplicate.*conflict.*not both})
end
end
| true |
2c45a538bb0388cd2e685e6915c2c427e0a7dc5a | Ruby | sergeypedan/integral-text-helpers | /lib/integral/text_helpers/phone.rb | UTF-8 | 2,264 | 2.90625 | 3 | [] | no_license | # frozen_string_literal: true
module Integral
module TextHelpers
module PhoneHelper
require "active_support/number_helper/number_converter"
require "active_support/number_helper/number_to_phone_converter"
# Uses Rails `number_to_phone` helper
# https://apidock.com/rails/v5.2.3/ActionView/Helpers/NumberHelper/number_to_phone
def humanize_telephone(number)
number = unformat_phone(number)
number_to_phone(number, { area_code: true, country_code: 7, delimiter: ' ', raise: true })
end
def number_to_phone(number, options = {})
return unless number
phone = ActiveSupport::NumberHelper::NumberToPhoneConverter.convert(number, options.symbolize_keys)
ERB::Util.html_escape(phone)
end
# Accepts standard HTML options like `class: 'my-class, id: 'my-id', like standard `link_to` does
def phone_to(phone, humanize: true, icon: nil)
options = {}
return if phone.blank?
link_text = humanize ? humanize_telephone(phone) : phone
link_text = fa_icon(icon, text: link_text) if icon.present?
if self.respond_to?(:link_to)
link_to link_text, "tel:#{unformat_phone(phone)}", options.merge({ rel: :nofollow })
else
class_list = case options[:class].class
when Array then options[:class]
when String then options[:class].split(" ")
else []
end
[
"<a ",
"href=\"tel:#{unformat_phone(phone)}\" ",
("id=\"#{options[:id]}\" " if options[:id]),
("class=\"#{class_list.join(" ")}\" " if class_list.any?),
"rel=\"nofollow\" ",
("data=\"#{options[:data]}\"" if options[:data]),
">",
link_text,
"</a>"
].join
end
end
# +7 (495) 123-45-67 --> 4951234567
# 8 (495) 123-45-67 --> 4951234567
# 7 (495) 123-45-67 --> 4951234567
# (495) 123-45-67 --> 4951234567
def unformat_phone(phone)
phone.scan(/\d/).join # leaves only digits
.sub(/^(7|8)/, '') # removes leading country code
end
end
end
end
| true |
1d257780d9368c68b61e237a61fa46f91e5bd590 | Ruby | desanlee/chifan | /app/models/gamblegame.rb | UTF-8 | 915 | 2.828125 | 3 | [] | no_license | class Gamblegame < ActiveRecord::Base
attr_accessible :description, :options, :result, :user_id
belongs_to :user
has_many :bets, foreign_key: "gamble_id"
def Gamblegame.currentgambles
cg = Array.new
Gamblegame.all.each do |g|
if g.result == nil then
cg << g
end
end
return cg
end
def Gamblegame.usersgambles user
cg = Array.new
Gamblegame.all.each
end
def optionarray
return self.options.split("#")
end
def usernotinvolved? user
notinvolved = true
self.bets.each do |b|
notinvolved = false if b.user == user
end
return notinvolved
end
def usercount selection
c = 0
self.bets.each do |b|
if b.selection == selection
c = c + 1
end
end
return c
end
def haswinner?
if self.result > 0
self.bets.each do |b|
if b.selection == self.result
return true
end
end
return false
else
return false
end
end
end
| true |
af48b8ce26509e6b9c88695d5b199b1711c973ce | Ruby | michaelherold/benchmark-memory | /lib/benchmark/memory/job.rb | UTF-8 | 3,778 | 2.921875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'forwardable'
require 'benchmark/memory/job/task'
require 'benchmark/memory/job/io_output'
require 'benchmark/memory/job/null_output'
require 'benchmark/memory/held_results'
require 'benchmark/memory/report'
require 'benchmark/memory/report/comparator'
module Benchmark
module Memory
# Encapsulate the memory measurements of reports.
class Job
extend Forwardable
# Instantiate a job for containing memory performance reports.
#
# @param output [#puts] The output to use for showing the job results.
# @param quiet [Boolean] A flag for stopping output.
#
# @return [Job]
def initialize(output: $stdout, quiet: false)
@full_report = Report.new
@held_results = HeldResults.new
@quiet = quiet
@output = quiet? ? NullOutput.new : IOOutput.new(output)
@tasks = []
end
# @return [Report] the full report of all measurements in the job.
attr_reader :full_report
# @return [Array<Task>] the measurement tasks to run.
attr_reader :tasks
def_delegator :@held_results, :holding?
# Check whether the job should do a comparison.
#
# @return [Boolean]
def compare?
!!@comparator
end
# Enable output of a comparison of the different tasks.
#
# @return [void]
def compare!(**spec)
@comparator = full_report.comparator = Report::Comparator.from_spec(spec.to_h)
end
# Enable holding results to compare between separate runs.
#
# @param held_path [String, IO] The location to save the held results.
#
# @return [void]
def hold!(held_path)
@held_results.path = held_path
end
# Add a measurement entry to the job to measure the specified block.
#
# @param label [String] The label for the measured code.
# @param block [Proc] Code the measure.
#
# @raise [ArgumentError] if no code block is specified.
def report(label = '', &block)
raise ArgumentError, 'You did not specify a block for the item' unless block_given?
tasks.push Task.new(label, block)
end
# Run the job and outputs its full report.
#
# @return [Report]
def run
@output.put_header
@held_results.load
tasks.each do |task|
held = run_task(task)
if held
@output.put_hold_notice
break
end
end
full_report
end
# Run a task.
#
# @param task [Task]
#
# @return [Boolean] A flag indicating whether to hold or not.
def run_task(task)
if @held_results.include?(task)
run_with_held_results(task)
else
run_without_held_results(task)
end
end
# Run a comparison of the entries and puts it on the output.
#
# @return [void]
def run_comparison
return unless compare? && full_report.comparable?
@output.put_comparison(full_report.comparison)
end
# Check whether the job is set to quiet.
#
# @return [Boolean]
def quiet?
@quiet
end
private
def run_with_held_results(task)
measurement = @held_results[task.label]
full_report.add_entry(task, measurement)
false
end
def run_without_held_results(task)
measurement = task.call
entry = full_report.add_entry(task, measurement)
@output.put_entry(entry)
if task == tasks.last
@held_results.cleanup
false
else
@held_results.add_result(entry)
@held_results.holding?
end
end
end
end
end
| true |
26c6e2839167ab1c8a1c3e8f0d87930ae8e87e44 | Ruby | sibprogrammer/specscan | /test/unit/mobile_operator_test.rb | UTF-8 | 1,414 | 2.5625 | 3 | [] | no_license | require 'test_helper'
class MobileOperatorTest < ActiveSupport::TestCase
test "should not save mobile operator without required attributes" do
mobile_operator = MobileOperator.new
assert !mobile_operator.save
end
test "valid mobile operator" do
mobile_operator = MobileOperator.new(:title => 'Test', :code => 'test')
assert mobile_operator.valid?
end
test "mobile operator code should be unique" do
mobile_operator = MobileOperator.new(:title => 'Test', :code => 'test')
assert mobile_operator.save
mobile_operator2 = MobileOperator.new(:title => 'Test 2', :code => 'test')
assert mobile_operator2.invalid?
end
test "mobile operator title should be unique" do
mobile_operator = MobileOperator.new(:title => 'Test', :code => 'test')
assert mobile_operator.save
mobile_operator2 = MobileOperator.new(:title => 'Test', :code => 'test2')
assert mobile_operator2.invalid?
end
test "valid mobile operator code" do
mobile_operator = MobileOperator.new(:title => 'Test')
mobile_operator.code = 'abc123'
assert mobile_operator.valid?
mobile_operator.code = 'abc 123'
assert mobile_operator.invalid?
mobile_operator.code = 'abc-123'
assert mobile_operator.invalid?
mobile_operator.code = 'abc#$%'
assert mobile_operator.invalid?
mobile_operator.code = 'ABC'
assert mobile_operator.invalid?
end
end
| true |
8917f02ff34195884d47f10d49ec47dca235371d | Ruby | SecretSurfSpot/intro_to_the_web | /app.rb | UTF-8 | 504 | 2.5625 | 3 | [] | no_license | require 'sinatra'
set :session_secret, 'super secret'
get('/') {"HELO GOODBYE"}
get('/secret') { 'Here is a secret page'}
get('/apple') { 'Here is yet another page'}
get('/pear') { 'Today is monday'}
get('/orange') { 'Tomorrow is Tuesday'}
get('/blueberry') { 'The day after tomorrow is Wednesday'}
get('/random-cat') {
@name = ["Amigo", "Oscar", "Viking"].sample
erb :index
}
post('/named-cat') {
p params
@name = params[:name]
erb :index
}
get('/cat-naming-form') {
erb :cat_naming
}
| true |
efe95e9d9c3a36e780b664f083b63a4a45c22128 | Ruby | 140ch204/14_MVC_gossip | /lib/controller.rb | UTF-8 | 514 | 2.671875 | 3 | [] | no_license | # 2_ Contrôlé par le routeur
require './lib/gossip'
require './lib/view'
class Controller
def initialize()
@view = View.new
end
def perform()
end
def create_gossip()
params = @view.create_gossip
gossip = Gossip.new(params[:content], params[:author])
puts "Gossip créé"
gossip.save()
puts "Gossip enregistré"
end
def index_gossips()
all_gossips_array = Gossip.all()
@view.index_gossips(all_gossips_array)
end
end | true |
0ed8fa3a8a31c0e6fc0ca2c07dd34d056f449231 | Ruby | tolidevs/london-web-120919 | /14-rails-associations/app/models/film.rb | UTF-8 | 312 | 2.671875 | 3 | [] | no_license | class Film < ApplicationRecord
has_many :reviews
has_many :users, through: :reviews
def average_rating
if self.reviews.size == 0
return 'N/A'
end
total = self.reviews.reduce(0){|total, review| total + review.rating }
total / self.reviews.size
end
end
| true |
799e765cc60e086c798425e4895e0819f83f1e66 | Ruby | ChristianTracy/ejercicio_26_9 | /ejercicio1/Reptiles/Reptiles.rb | UTF-8 | 539 | 2.8125 | 3 | [] | no_license | require_relative '../Animal.rb' #incluyo el archivo con la clase padre
#-------------------------
class Reptiles < Animal; end
#-------------------------
#-------------------------
class Cocodrilo < Reptiles
include Caminar
include Nadar
end
#-------------------------
#-------------------------
class Boa < Reptiles
include Desplazarse
def constriccion
puts "HAGO PRESIÓN"
end
end
#-------------------------
#-------------------------
class Cobra < Reptiles
include Desplazarse
def morder
puts "MORDER"
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.