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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
36e3c167aa2270a203d32a9a4ba2f45596a50198 | Ruby | mmatney22/ruby-objects-has-many-through-readme-online-web-sp-000 | /lib/waiter.rb | UTF-8 | 691 | 3.078125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Waiter
attr_accessor :name, :yrs_experience
@@all = []
def initialize(name, yrs_experience)
@name = name
@yrs_experience = yrs_experience
@@all << self
end
def self.all
@@all
end
def new_meal(customer, total, tip = 0)
Meal.new(self, customer, total, tip)
end
def meals
Meal.all.select {|meal| meal.waiter == self}
end
def best_tipper #create new variable to hold logic of finding highest tip num
best_tipped_meal = meals.max do |meal_a, meal_b| #compare highest nums
meal_a.tip <=> meal_b.tip #compare tip attr and rank
end
best_tipped_meal.customer #return customer attr of new variable
end
end
| true |
4291ef484a57cb5319b90d7a631d91122f7c58e9 | Ruby | blcklst-eng/kimmel | /app/models/message_media_image_variant.rb | UTF-8 | 836 | 2.65625 | 3 | [] | no_license | class MessageMediaImageVariant
def initialize(media:, height:, width:)
@height = height
@width = width
@original = media
@variant = original.variant(resize: "#{height} x #{width}")
end
def height
return original_height unless apply?
original_height * ratio
end
def width
return original_width unless apply?
original_width * ratio
end
def url
RouteHelper.rails_representation_url(variant)
end
private
attr_reader :original, :variant
def original_height
original.metadata[:height]
end
def original_width
original.metadata[:width]
end
def apply?
@height < original_height && @width < original_width
end
def ratio
if @height > @width
@height.to_f / original_height.to_f
else
@width.to_f / original_width.to_f
end
end
end
| true |
eee46205a11eef3c9b0683d31f4de03ecb07cf6b | Ruby | momchianev/test | /study/11.rb | UTF-8 | 82 | 2.90625 | 3 | [] | no_license | # with kur
n = 0
while n <= 999
n = n + 1
print n
print "\nkur"
end
| true |
ee43e30e9233817e0e23c90b64aae600eb62ded8 | Ruby | klavinslab/ProtocolsForReview | /high_throughput_culturing/protocol/dilute_collection/protocol.rb | UTF-8 | 7,748 | 2.625 | 3 | [] | no_license | # By: Eriberto Lopez
# elopez3@uw.edu
# 08/13/19
needs "Standard Libs/Debug"
needs "High Throughput Culturing/HighThroughputHelper"
class Protocol
include HighThroughputHelper
include Debug
# DEF
INPUT = "Culture Plate"
OUTPUT = "Diluted Plate"
DILUTION = "Dilution"
MEDIA = "Media"
KEEP_IN_PLT = "Keep Input Plate?"
# Constants
ALLOWABLE_DILUTANT_SAMPLETYPES = ['Yeast Strain', 'Plasmid', 'E coli strain'] # sample types that will be transferred to new plate
# Access class variables via Protocol.your_class_method
@materials_list = []
def self.materials_list; @materials_list; end
def intro
show do
title "Dilute Collection"
separator
note "This protocol will guide you on how to dilute the cultures of a culturing plate into another plate."
note "<b>1.</b> Gather materials."
note "<b>2.</b> Pre-fill new plate with media, if necessary."
note "<b>3.</b> Transfer aliquot of culture to new plate."
note "<b>4.</b> Incubate."
end
end
def main
intro
operations.retrieve.make
clean_up_arr = []
operations.make.each do |op|
dilution_factor = get_dilution_factor(op: op, fv_str: DILUTION)
op.input_array(INPUT).collections.zip(op.output_array(OUTPUT).collections) do |from_collection, to_collection|
raise "Not enough output plates have been planned please add an output field value to this operation: Plan #{op.plan.id} Operation #{op.id}." if to_collection.nil?
gather_materials(empty_containers: [to_collection], new_materials: ['P1000 Multichannel', 'Permeable Area Seals', 'Multichannel Resivior'], take_items: [from_collection] )
stamp_transfer(from_collection: from_collection, to_collection: to_collection, process_name: 'dilution')
transfer_volume = pre_fill_collection(to_collection: to_collection, dilution_factor: dilution_factor, media_item: op.input(MEDIA).item)
tech_transfer_samples(from_collection: from_collection, to_collection: to_collection, transfer_volume: transfer_volume)
from_loc = from_collection.location; to_collection.location = from_loc; to_collection.save()
(op.input(KEEP_IN_PLT).val.to_s.downcase == 'yes') ? (from_collection.mark_as_deleted; from_collection.save()) : nil
end
clean_up(item_arr: clean_up_arr)
operations.store
end
end #main
def tech_transfer_samples(from_collection:, to_collection:, transfer_volume:)
show do
title "Transferring From #{from_collection} To #{to_collection}"
separator
warning "Make sure that both plates are in the same orientation.".upcase
note "Using a Multichannel pipette, follow the table to transfer #{transfer_volume}#{MICROLITERS} of cultures:"
bullet "<b>From #{from_collection.object_type.name}</b> #{from_collection}"
bullet "<b>To #{to_collection.object_type.name}</b> #{to_collection}"
table highlight_alpha_non_empty(to_collection) {|r,c| "#{transfer_volume}#{MICROLITERS}" }
end
end
def pre_fill_collection(to_collection:, dilution_factor:, media_item:)
destination_working_volume = get_object_type_working_volume(to_collection).to_i
culture_volume = (destination_working_volume*dilution_factor.to_i).round(3)
media_volume = (destination_working_volume-culture_volume).round(3)
take [media_item], interactive: true
if dilution_factor != 'None'
total_media = ((to_collection.get_non_empty.length*media_volume*1.1)/1000).round(2) #mLs
show do
title "Pre-fill #{to_collection.object_type.name} #{to_collection} with #{media_item.sample.name}"
separator
check "Gather a <b>Multichannel Pipette<b>"
check "Gather a <b>Multichannel Resivior<b>"
check "Gather #{total_media}#{MILLILITERS}"
note "Pour the media into the resivior in 30mL aliquots"
note "You will need these materials in the next step."
end
show do
title "Pre-fill #{to_collection.object_type.name} #{to_collection} with #{media_item.sample.name}"
separator
note "Follow the table below to transfer media into #{to_collection}:"
table highlight_alpha_non_empty(to_collection){|r,c| "#{media_volume}#{MICROLITERS}"}
end
end
return culture_volume
end
def get_object_type_working_volume(container)
working_volume = JSON.parse(container.object_type.data).fetch('working_vol', nil)
raise "The #{container.id} #{container.object_type.name} ObjectType does not have a 'working_vol' association.
Please go to the container definitions page and add a JSON parsable association!".upcase if working_volume.nil?
return working_volume
end
def copy_sample_matrix(from_collection:, to_collection:)
sample_hash = Hash.new()
from_collection_sample_types = from_collection.matrix.flatten.uniq.reject{|i| i == EMPTY }.map {|sample_id| [sample_id, Sample.find(sample_id)] }
from_collection_sample_types.each {|sid, sample| (ALLOWABLE_DILUTANT_SAMPLETYPES.include? sample.sample_type.name) ? (sample_hash[sid] = sample) : (sample_hash[sid] = EMPTY) }
dilution_sample_matrix = from_collection.matrix.map {|row| row.map {|sample_id| sample_hash[sample_id] } }
to_collection.matrix = dilution_sample_matrix
to_collection.save()
end
def transfer_part_associations(from_collection:, to_collection:)
copy_sample_matrix(from_collection: from_collection, to_collection: to_collection)
from_collection_associations = AssociationMap.new(from_collection)
to_collection_associations = AssociationMap.new(to_collection)
from_associations_map = from_collection_associations.instance_variable_get(:@map)
# Remove previous source data from each part
from_associations_map.reject! {|k| k != 'part_data'} # Retain only the part_data, so that global associations do not get copied over
from_associations_map.fetch('part_data').map! {|row| row.map! {|part| part.key?("source") ? part.reject! {|k| k == "source" } : part } }
from_associations_map.fetch('part_data').map! {|row| row.map! {|part| part.key?("destination") ? part.reject! {|k| k == "destination" } : part } }
# Set edited map to the destination collection_associations
to_collection_associations.instance_variable_set(:@map, from_associations_map)
to_collection_associations.save()
return from_associations_map
end
def part_provenance_transfer(from_collection:, to_collection:, process_name:)
to_collection_part_matrix = to_collection.part_matrix
from_collection.part_matrix.each_with_index do |row, r_i|
row.each_with_index do |from_part, c_i|
if (from_part) && (ALLOWABLE_DILUTANT_SAMPLETYPES.include? from_part.sample.sample_type.name)
to_part = to_collection_part_matrix[r_i][c_i]
if !to_part.nil?
# Create source and destination objs
source_id = from_part.id; source = [{id: source_id }]
destination_id = to_part.id; destination = [{id: destination_id }]
destination.first.merge({additional_relation_data: { process: process_name }}) unless process_name.nil?
# Association source and destination
to_part.associate(key=:source, value=source)
from_part.associate(key=:destination, value=destination)
end
end
end
end
end
def stamp_transfer(from_collection:, to_collection:, process_name: nil)
from_associations_map = transfer_part_associations(from_collection: from_collection, to_collection: to_collection)
part_provenance_transfer(from_collection: from_collection, to_collection: to_collection, process_name: process_name)
return from_associations_map.fetch('part_data')
end
end #Class
| true |
859d9071571e7d151a9927ebe14f45d8b3c645cf | Ruby | lucas-duarte-webjump/POO_Ruby | /animal1.rb | UTF-8 | 289 | 2.78125 | 3 | [] | no_license | class Animal
def pular
puts 'Toing! toing! boing! poing!'
end
def dormir
puts 'ZzzzZzz!'
end
end
class Cachorro < Animal
def latir
puts 'Au au'
end
end
cachorro = Cachorro.new
cachorro.pular
cachorro.latir
cachorro.dormir
gato.pular | true |
1d3a032ecb5fc9feedf5b9112d2f372b3a6cbdd2 | Ruby | rankoliang/chess | /lib/chess_config.rb | UTF-8 | 2,357 | 2.75 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'paint'
# Contains contants used throughout the program
# :reek:TooManyConstants
module ChessConfig
SAVE_DIR = 'saves'
BOARD_WIDTH = 8
BOARD_HEIGHT = 8
TRUE_COLORS = true
Paint.mode = 256 unless TRUE_COLORS
# rubocop:disable Style/StringLiterals
BACKGROUND_DARK = Hash.new(:black).update(0xFFFFFF => "black")[Paint.mode]
BACKGROUND_LIGHT = Hash.new(:cyan).update(0xFFFFFF => "dark cyan")[Paint.mode]
PIECE_COLOR = Hash.new(:white).update(0xFFFFFF => "white")[Paint.mode]
# rubocop:enable Style/StringLiterals
PIECE_SYMBOLS = { white: { King: "\u265A",
Queen: "\u265B",
Rook: "\u265C",
Bishop: "\u265D",
Knight: "\u265E",
Pawn: "\u265F" },
black: { King: "\u2654",
Queen: "\u2655",
Rook: "\u2656",
Bishop: "\u2657",
Knight: "\u2658",
Pawn: "\u2659" },
default: '?' }.freeze
COLUMN_LABELS = ('a'..'z').to_a[0...BOARD_WIDTH]
DEFAULT_LOCATIONS = { white: { Pawn: COLUMN_LABELS.map { |letter| "#{letter}2" },
King: %w[e1],
Queen: %w[d1],
Bishop: %w[c1 f1],
Knight: %w[b1 g1],
Rook: %w[a1 h1] },
black: { Pawn: COLUMN_LABELS.map { |letter| "#{letter}7" },
King: %w[e8],
Queen: %w[d8],
Bishop: %w[c8 f8],
Knight: %w[b8 g8],
Rook: %w[a8 h8] } }.freeze
def self.opponent(color)
{ black: :white, white: :black }[color]
end
# TODO: Refactor to an easier to understand iterative method
def self.nested_hash_expand(current_level, keys = [])
return keys.product([current_level].flatten).map(&:flatten) unless current_level.is_a? Hash
result = []
current_level.each do |key, value|
result.append(*nested_hash_expand(value, [keys + [key]]))
end
result
end
end
CConf = ChessConfig
| true |
d09181b9e82005f4f0bb8d96de14424cba617d36 | Ruby | sherpanat/AR-Basics-246 | /db/seeds.rb | UTF-8 | 293 | 2.84375 | 3 | [] | no_license | # This is where you can create initial data for your app.
require 'faker'
puts 'Seed begins'
20.times do
restaurant = Restaurant.new(
name: Faker::Hipster.word,
address: Faker::Address.street_address
)
restaurant.save
end
puts 'Has successfully created 20 hypsters restaurants'
| true |
b71188be9f8a0b9fb3bbcf7943648a26101aa1f0 | Ruby | jflohre/bowling_kata | /spec/bowlingkata2_spec.rb | UTF-8 | 3,002 | 3.015625 | 3 | [] | no_license | require "spec_helper"
describe 'Bowling' do
let(:game) {game = Game.new}
it 'should return a new game' do
game.should be_an_instance_of Game
end
it 'should return 10 if the first frame has an X' do
game.line([['X'],[0,0]]).should == 10
end
it 'should return 10 if the first frame has a /' do
game.line([[5,'/'],[0,0]]).should == 10
end
it 'should return 1 if line is 1,0' do
game.line([[1,4]]).should == 5
end
it 'should return a score of 1 for a roll of 1 and 0' do
game.adding_frame([1,0]).should == 1
end
it 'should return a score of 2 for two rolls of 1' do
game.adding_frame([1,1]).should == 2
end
it 'should return 14 for a strike and two 1s' do
game.line([['X'], [1,1]]).should == 14
end
it 'should return 37 for two strikes and four 1s' do
game.line([['X'], ['X'], [1,1],[1,1]]).should ==37
end
it 'should return true if frame includes X' do
game.strike?(['X']).should == true
game.strike?([1,1]).should == false
end
it 'should return 60 for three strikes and 2 gutters' do
game.line([['X'], ['X'], ['X'],[0,0]]).should == 60
end
it 'should return 63 for 2 strikes, 5 / and 4 0' do
game.line([['X'],['X'],[5,'/'], [4,0]]).should == 63
end
it 'should return 75 for 2 strikes, 5 /, strike and two 0s' do
game.line([['X'],['X'],[5,'/'], ['X'], [0,0]]).should == 75
end
it 'should return 95 for 2 strikes, 5 /, strike, 5 /, and two 0s' do
game.line([['X'],['X'],[5,'/'], ['X'], [5,'/'], [0,0]]).should == 95
end
it 'should return 300 for 12 strikes' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X']]).should == 300
end
it 'should return 255 for 9 strikes and two 3s' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[3,3]]).should == 255
end
it 'should return 279 for 10 strikes followed by two 3s' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[3,3]]).should == 279
end
it 'should return 267 for 9 strikes, and one spare followed by a 2' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[5,'/'],[2]]).should == 267
end
it 'should return 275 for 9 strikes and one spare followed by a strike' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[5,'/'],['X']]).should == 275
end
it 'should return 260 for 9 strikes and one set of 4s' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[4,4]]).should == 260
end
it 'should return 238 for 18 strikes and two sets of 4s strikes' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[4,4],[4,4]]).should == 238
end
it 'should return 300 for 12 strikes' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[4,4],['X'],['X'],['X']]).should == 260
end
it 'should return 238 for 8 strikes and two sets of 4s' do
game.line([['X'],['X'],['X'],['X'],['X'],['X'],['X'],['X'],[4,4],[4,4]]).should == 238
end
end
| true |
93d12a99a5e2f62de9d2699a18f10e1357605bb5 | Ruby | michael-mm/launch_school_back_end | /intro_to_programming/exercises/8.rb | UTF-8 | 208 | 2.890625 | 3 | [] | no_license | #Hash using both ruby syntx styles
#old style:
epl = {:north_london => "arsenal", :merseyside => "liverpool"}
puts epl[:north_london]
#new styles:
mls = {west: "la_galaxy", east: "chicago"}
puts mls[:east]
| true |
6b47218208ff0664c4ea6d9addb3d97ce76a0c84 | Ruby | techtronics/Booting-the-Analytics-Application | /src/ruby/create_avros.rb | UTF-8 | 976 | 2.734375 | 3 | [] | no_license | require 'rubygems'
require 'avro'
require 'voldemort-rb'
require 'json'
# This is our Avro schema
SCHEMA = <<-JSON
{ "type": "record",
"name": "Email",
"fields" : [
{"name": "message_id", "type": "int"},
{"name": "topic", "type": "string"},
{"name": "user_id", "type": "int"}
]}
JSON
puts "Avro Schema: "
puts SCHEMA
puts "Writing Avros to /tmp/messages.avro..."
file = File.open('/tmp/messages.avro', 'wb')
schema = Avro::Schema.parse(SCHEMA)
writer = Avro::IO::DatumWriter.new(schema)
dw = Avro::DataFile::Writer.new(file, writer, schema)
dw << {"message_id" => 11, "topic" => "Hello World", "user_id" => 1}
dw << {"message_id" => 12, "topic" => "Jim is silly!", "user_id" => 1}
dw << {"message_id" => 13, "topic" => "I like apples.", "user_id" => 2}
dw << {"message_id" => 24, "topic" => "Round the world...", "user_id" => 2}
dw << {"message_id" => 35, "topic" => "How do I sent a message?", "user_id" => 45}
puts "Closing /tmp/messages.avro"
dw.close
| true |
c2327d74242c87537e87ab564db26db17994585f | Ruby | Moemi-Otsu/graduate_app | /spec/models/user_spec.rb | UTF-8 | 1,995 | 2.546875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
let(:user) { create(:user) }
let(:second_user) { create(:second_user) }
describe 'バリデーション確認' do
it "nameが存在しなければ、エラーを出す" do
user = User.new
expect(user.valid?).to be false
expect(user.errors[:name]).to include("を入力してください")
expect(user.errors.full_messages).to include("名前を入力してください")
end
it "nameに重複があれば、エラーを出す" do
duplicated_user = User.new(name: user.name)
expect(duplicated_user.valid?).to be false
expect(duplicated_user.errors[:name]).to include('はすでに存在します')
end
it "passwordが存在しなければ、エラーを出す" do
user = User.new(password: nil)
expect(user.valid?).to be false
expect(user.errors[:password]).to include('を入力してください')
end
it "passwordが6文字以上でなければ、エラーを出す" do
user = User.new(password: 'aaa')
expect(user.valid?).to be false
expect(user.errors[:password]).to include('は6文字以上で入力してください')
end
it "passwordが128文字以内でなければ、エラーを出す" do
user = User.new(password: 'a' * 129)
expect(user.valid?).to be false
expect(user.errors[:password]).to include('は128文字以内で入力してください')
end
it "emailに重複があれば、エラーを出す" do
duplicated_user = User.new(email: user.email)
expect(duplicated_user.valid?).to be false
expect(duplicated_user.errors[:email]).to include('はすでに存在します')
end
it "emailに@を含む前後の文字列が含まれていなければ、エラーを出す" do
user = User.new(email: 'asdfaa')
expect(user.valid?).to be false
expect(user.errors[:email]).to include('は不正な値です')
end
end
end | true |
0d0292adf88d0825e011bc45e80060022ac266e3 | Ruby | IanGeraldKing/3C_tictactoe | /board_v1.rb | UTF-8 | 885 | 3.921875 | 4 | [] | no_license | class Board
GAP = " "
def initialize
@board = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]
end
### Architecting the Board ###
def rows
rows = []
@board.each do |row|
rows <<row.join
end
return rows
end
def columns
columns = []
for i in 0..2
column = ""
@board.each do |row|
column += row[i]
end
columns << column
end
return columns
end
def diagonals
[[0,1,2], [2,1,0]].map do |columns|
columns.each_with_index.map {|column, row| @board[row][column] }.join
end
end
def [](row, column)
@board[row][column]
end
def []=(row, column, mark)
@board[row][column] = mark
end
### Drawing the Board ###
def draw_row(row)
GAP + row.join(' | ') + "\n"
end
def draw_line
"#{GAP}---------\n"
end
def draw_board
"\n" + @board.map { |row| draw_row(row) }.join(draw_line)
end
def flatten
@board.flatten
end
end
| true |
67feee5fb6f3cfdee04c7a8729dc2821e927e624 | Ruby | jajapop-m/AtCoder | /ABC_174/B.rb | UTF-8 | 132 | 2.84375 | 3 | [] | no_license | n,d = gets.split.map(&:to_i)
count = 0
n.times do
x,y = gets.split.map(&:to_i)
count += 1 if x**2 + y**2 <= d*d
end
puts count
| true |
bbe7eb49a1db58d4b8fa52f7a9e6f45270889896 | Ruby | leonardodiasb/ruby-capstone | /classes/music_album.rb | UTF-8 | 272 | 2.578125 | 3 | [] | no_license | class MusicAlbum < Item
attr_accessor :on_spotify, :title
def initialize(*args, title:, on_spotify: true)
super(*args)
@on_spotify = on_spotify
@title = title
end
private
def can_be_archived?
@publish_date > 10 && @on_spotify = true
end
end
| true |
3bca06a3483654a6b9a4dd40a4e3b03b62792891 | Ruby | ruckserve/JuniorDevs | /patterns/decorator/retry/client.rb | UTF-8 | 204 | 3.296875 | 3 | [] | no_license | class Client
def initialize(obj)
@obj = obj
end
def call_it
begin
@obj.get()
rescue => e
puts e.inspect
end
end
def print_it
@obj.print_hello_world()
end
end
| true |
c6e34d84ff718f6e2ddfdcb97206ce9feee4c89d | Ruby | josh-works/exercism | /ruby/nth-prime/nth_prime.rb | UTF-8 | 475 | 3.328125 | 3 | [] | no_license | require 'pry'
class Prime
def self.nth(number)
raise ArgumentError if number == 0
counter = 2
current_number = 2
while (counter <= number) do
current_number += 1
counter += 1 if is_prime?(current_number)
end
current_number
end
private
def self.is_prime?(number)
(2..(Math.sqrt(number).floor)).each do |n|
return false if number % n == 0
end
true
end
end
class BookKeeping
VERSION = 1
end
| true |
d044b17cb9a902fa311d278a182e5b2aebd87907 | Ruby | anoiaque/sudoku_solver_2.0 | /lib/sudoku.rb | UTF-8 | 1,784 | 3.328125 | 3 | [] | no_license | require 'sudoku_extensions.rb'
class Sudoku
@elements =[]
@blocks =[]
@lines =[]
@columns =[]
attr_accessor :elements,:blocks,:lines,:columns
def solve
change = false
#generate_doublons
# self.each_line {|l| l.solve_doublons}
(1..9).each do |number|
(1..81).each do |c|
if number.can_only_be_in?(self.element(c))
change=true
self.element(c).set_with(number)
end
end
end
self.solve if (!self.complete? && change)
end
def complete?
(1..81).each do |c|
return false if element(c).empty?
end
end
def generate_doublons
change = false
self.each_line {|l| change ||= l.generate_doublons}
self.each_column {|col| change ||= col.generate_doublons}
self.each_block {|b| change ||= b.generate_doublons}
generate_doublons if change
end
def == sudoku
(1..81).each {|k| return false if self.element(k).value!=sudoku.element(k).value}
end
def initialize sudoku_array=nil
if !sudoku_array.nil?
sudoku = sudoku_array.to_sudoku
@elements = sudoku.elements
@blocks = sudoku.blocks
@lines = sudoku.lines
@columns = sudoku.columns
end
end
def each_line
(1..9).each {|k| yield line(k)}
end
def each_column
(1..9).each {|k| yield column(k)}
end
def each_block
(1..9).each {|k| yield block(k)}
end
def each_element
(1..81).each {|k| yield element(k)}
end
def element num
@elements[num - 1]
end
def line num
@lines[num - 1]
end
def column num
@columns[num - 1]
end
def block num
@blocks[num - 1]
end
end | true |
5c544bc8b892448e72ed7255ecd92cae1df1c921 | Ruby | collinmay/bigrobot | /robot/adapter/sabertooth.rb | UTF-8 | 1,484 | 2.90625 | 3 | [] | no_license | # Author: Collin May
require_relative "../sensors.rb"
module Adapters
class Sabertooth
def initialize(connection, addr=128)
@connection = connection
@m1 = Motor.new(self, 1)
@m2 = Motor.new(self, 2)
@addr = addr
end
attr_reader :connection
attr_reader :m1
attr_reader :m2
attr_reader :addr
def name
"sabertooth"
end
def conn
@connection
end
class Motor
def initialize(sabertooth, output)
@st = sabertooth
@out_id = output
name = @st.name + " M" + output.to_s
@sensors = {
:battery => Sensors::Battery.new(name + " battery", 24),
:temperature => Sensors::Thermometer.new(name + " thermometer"),
:current => Sensors::Ammeter.new(name + " ammeter"),
:pwm => Sensors::PWM.new(name + " pwm")
}
@in_speed = 0
@out_speed = 0
end
def drive(speed)
@in_speed = speed
@st.conn.set(@st.addr, "M", @out_id, speed, 0)
@sensors[:pwm].set(speed)
end
attr_reader :in_speed
attr_reader :out_speed
attr_reader :sensors
end
module Connections
class DummyConnection
end
class TextConnection
def initialize(io)
@io = io
end
def set(addr, type, num, val, flags)
@io.puts type + num.to_s + ": " + (val*2047).floor.to_s
end
end
end
end
end
| true |
59d59dfaccd80c597436110327d3c4e23409bf4d | Ruby | chemunoz/Ironhack | /PreWork/03-Ruby/07-Shake Shack/christopher-milkshake.rb | UTF-8 | 1,736 | 3.8125 | 4 | [] | no_license | require 'pry'
#binding.pry
class ShakeShope
def initialize
@carta_milkshakes = []
end
def add_milkshakes(milkshake)
@carta_milkshakes.push(milkshake)
end
def milkshakes_list
@carta_milkshakes.each do |milkshaker|
#milkshaker
#milkshake.price_of_milkshake
#la anterior linea da como error un undefined mehod for sring (normal)
end
puts "HOLA"
end
end
class MilkShake
def initialize
@base_price = 3
@total_price = 0
@ingredients = []
end
def add_ingredient(ingredient)
@ingredients.push(ingredient)
end
def price_of_milkshake
@total_price= @base_price
@ingredients.each do |ingredient|
@total_price += ingredient.price
end
@total_price
end
end
class Ingredient
attr_reader :name, :price
def initialize(name, price)
@name = name
@price = price
end
end
banana = Ingredient.new("Banana", 2)
chocolate_chips = Ingredient.new("Chocolate Chips", 1)
mint = Ingredient.new("Mint",1)
cookies = Ingredient.new("Cookies",2)
vainilla = Ingredient.new("Vainilla",2)
crunch = Ingredient.new("Crunchs",3)
nizars_milkshake = MilkShake.new
nizars_milkshake.add_ingredient(banana)
nizars_milkshake.add_ingredient(chocolate_chips)
nizars_milkshake.add_ingredient(mint)
chris_milkshake = MilkShake.new
chris_milkshake.add_ingredient(vainilla)
chris_milkshake.add_ingredient(cookies)
chris_milkshake.add_ingredient(crunch)
#esto imprime bien los precios
#puts nizars_milkshake.price_of_milkshake
#puts chris_milkshake.price_of_milkshake
josh_shop = ShakeShope.new
josh_shop.add_milkshakes(nizars_milkshake)
josh_shop.add_milkshakes(chris_milkshake)
#La siguiente linea imprime los nombres de los batidos
puts josh_shop.milkshakes_list | true |
410b42aa43a514d866e8ff0a1aba1ccd2665a94e | Ruby | codemargaret/rock_paper_scissors_ruby | /lib/rps.rb | UTF-8 | 814 | 3.78125 | 4 | [
"MIT"
] | permissive | require('pry')
class RPS
def initialize(player1,player2)
@player1 = player1
@player2 = player2
end
def wins(player1, player2)
if (player1 === "rock") & (player2 === "scissors")
"rock beats scissors player 1 wins"
elsif (player1 === "paper") & (player2 === "rock")
"paper beats rock player 1 wins"
elsif (player1 === "scissors") & (player2 === "paper")
"scissors beats paper player 1 wins"
elsif (player1 === "rock") & (player2 === "paper")
"rock loses to paper player2 wins"
elsif (player1 === "scissors") & (player2 === "rock")
"scissors loses to rock player2 wins"
elsif (player1 === "paper") & (player2 === "scissors")
"paper loses to scissors player2 wins"
elsif (player1 === player2)
"you tied try again"
end
end
end
| true |
2aea5a366ac90f63eba178cb0a1b0c071c6e5b3f | Ruby | Slouch07/RB101 | /Small_Problems/Easy_1/how_many.rb | UTF-8 | 316 | 3.1875 | 3 | [] | no_license | vehicles = [
'car', 'car', 'truck', 'car', 'SUV', 'truck',
'motorcycle', 'motorcycle', 'car', 'truck'
]
def count_occurrences(array)
occurences = {}
array.uniq.each { |item| occurences[item] = array.count(item) }
occurences.each { |key, value| puts "#{key} => #{value}" }
end
count_occurrences(vehicles) | true |
a3128114c237332955eed361ba6e2f4700c4ca4a | Ruby | caitp222/algorithms | /word_length.rb | UTF-8 | 328 | 3.328125 | 3 | [] | no_license | def word_length(arr)
hash = {}
arr.each do |word|
hash[word] = word.length
end
hash
end
p word_length(["a", "bb", "a", "bb"]) == {"bb" => 2, "a" => 1}
p word_length(["this", "and", "that", "and"]) == {"that" => 4, "and" => 3, "this" => 4}
p word_length(["code", "code", "code", "bug"]) == {"code" => 4, "bug" => 3}
| true |
a9341216d1cff84601ee9ba3c9338c26029ed925 | Ruby | kdow/factorial | /lib/factorial.rb | UTF-8 | 334 | 4.125 | 4 | [] | no_license | # Computes factorial of the input number and returns it
# Time complexity: O(n) where n is the value of the input number
# Space complexity: O(1)
def factorial(number)
unless number
raise ArgumentError, "Non-number entered."
end
if number == 1 || number == 0
return 1
else
number * factorial(number - 1)
end
end
| true |
2fa7ace8f5f81b243181943295d255afc245c426 | Ruby | sebaquevedo/desafiolatam | /clase13/palabra_final.rb | UTF-8 | 771 | 3.796875 | 4 | [
"MIT"
] | permissive | #agrega palabra al final
#solucion iterar array
# puts "ingrese la palaba a buscar"
# palabra = gets.chomp #lee palabra desde consola
# file = File.open("hola.txt", "r"){ |file| file.read } #abre y lee archivo
# array_palabras = file.split("\n") #separa por saltos de linea
# count = 0
# array_palabras.each{|value| count+= 1 if value != palabra}
# if count > 0
# File.open('hola.txt', 'a') { |f| f.puts palabra}
# end
# #recorre el array y evalua si la palabra ingresada corresponde a alguno de
# # los elemtos separados por split, en caso de que encuentre una similitud imprime true.
#solucion file
file = File.open("hola.txt","r+")
contents = file.read.split("\n")
t= gets.chomp
if (contents.include? t) == false
file.puts t
end
file.close
| true |
bb49bc989bb9d6ad3ae7cb36b67db462b45a5437 | Ruby | rsl/stringex | /test/unit/localization/da_test.rb | UTF-8 | 3,961 | 2.921875 | 3 | [
"MIT"
] | permissive | # encoding: UTF-8
require 'test_helper'
require 'i18n'
require 'stringex'
class DanishYAMLLocalizationTest < Test::Unit::TestCase
def setup
Stringex::Localization.reset!
Stringex::Localization.backend = :i18n
Stringex::Localization.backend.load_translations :da
Stringex::Localization.locale = :da
end
{
"foo & bar" => "foo og bar",
"AT&T" => "AT og T",
"99° is normal" => "99 grader is normal",
"4 ÷ 2 is 2" => "4 divideret med 2 is 2",
"webcrawler.com" => "webcrawler punktum com",
"Well..." => "Well prik prik prik",
"x=1" => "x lig med 1",
"a #2 pencil" => "a nummer 2 pencil",
"100%" => "100 procent",
"cost+tax" => "cost plus tax",
"batman/robin fan fiction" => "batman skråstreg robin fan fiction",
"dial *69" => "dial stjerne 69",
" i leave whitespace on ends unchanged " => " i leave whitespace on ends unchanged "
}.each do |original, converted|
define_method "test_character_conversion: '#{original}'" do
assert_equal converted, original.convert_miscellaneous_characters
end
end
{
"¤20" => "20 kroner",
"$100" => "100 dollars",
"$19.99" => "19 dollars 99 cents",
"£100" => "100 pund",
"£19.99" => "19 pund 99 pence",
"€100" => "100 euro",
"€19.99" => "19 euro 99 cent",
"¥1000" => "1000 yen"
}.each do |original, converted|
define_method "test_currency_conversion: '#{original}'" do
assert_equal converted, original.convert_miscellaneous_characters
end
end
{
"Tea & Sympathy" => "Tea og Sympathy",
"10¢" => "10 cents",
"©2000" => "(c)2000",
"98° is fine" => "98 grader is fine",
"10÷5" => "10 divideret med 5",
""quoted"" => '"quoted"',
"to be continued…" => "to be continued...",
"2000–2004" => "2000-2004",
"I wish—oh, never mind" => "I wish--oh, never mind",
"½ ounce of gold" => "halv ounce of gold",
"1 and ¼ ounces of silver" => "1 and en fjerdedel ounces of silver",
"9 and ¾ ounces of platinum" => "9 and tre fjerdedele ounces of platinum",
"3>2" => "3>2",
"2<3" => "2<3",
"two words" => "two words",
"£100" => "pund 100",
"Walmart®" => "Walmart(r)",
"'single quoted'" => "'single quoted'",
"2×4" => "2x4",
"Programming™" => "Programming(tm)",
"¥20000" => "yen 20000",
" i leave whitespace on ends unchanged " => " i leave whitespace on ends unchanged "
}.each do |original, converted|
define_method "test_html_entity_conversion: '#{original}'" do
assert_equal converted, original.convert_miscellaneous_html_entities
end
end
{
"½" => "halv",
"½" => "halv",
"½" => "halv",
"⅓" => "en tredjedel",
"⅓" => "en tredjedel",
"⅔" => "to tredjedele",
"⅔" => "to tredjedele",
"¼" => "en fjerdedel",
"¼" => "en fjerdedel",
"¼" => "en fjerdedel",
"¾" => "tre fjerdedele",
"¾" => "tre fjerdedele",
"¾" => "tre fjerdedele",
"⅕" => "en femtedel",
"⅕" => "en femtedel",
"⅖" => "to femtedele",
"⅖" => "to femtedele",
"⅗" => "tre femtedele",
"⅗" => "tre femtedele",
"⅘" => "fire femtedele",
"⅘" => "fire femtedele",
"⅙" => "en sjettedel",
"⅙" => "en sjettedel",
"⅚" => "fem sjettedele",
"⅚" => "fem sjettedele",
"⅛" => "en ottendedel",
"⅛" => "en ottendedel",
"⅜" => "tre ottendedele",
"⅜" => "tre ottendedele",
"⅝" => "fem ottendedele",
"⅝" => "fem ottendedele",
"⅞" => "syv ottendedele",
"⅞" => "syv ottendedele"
}.each do |original, converted|
define_method "test_vulgar_fractions_conversion: #{original}" do
assert_equal converted, original.convert_vulgar_fractions
end
end
end
| true |
e0c6615c14e38b603cb4392e9ff988bcfe607124 | Ruby | aaj3f/alphabetize-in-esperanto-online-web-prework | /lib/alphabetize.rb | UTF-8 | 293 | 3.375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
ESPERANTO_ALPHABET = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz"
#binding.pry
def alphabetize(arr)
arr.sort_by do |phrase|
#binding.pry
new_array = phrase.split("")
#binding.pry
new_array.collect do |letter|
ESPERANTO_ALPHABET.index(letter)
end
end
end
| true |
4003e30999909f63cebc15a7785e88438a7c0671 | Ruby | narogers/sidrat | /app/validators/broadcast_validator.rb | UTF-8 | 1,365 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | class BroadcastValidator < ActiveModel::Validator
def validate(record)
end_of_range = DateTime.now + (5*365)
puts "Validating broadcast information for #{record}"
unless ['unaired', 'broadcast'].include?(record.broadcast_status)
record.errors.add(:broadcast_status, "The current status is not valid. Please select again.")
end
if !record.broadcast_starting.nil? and record.broadcast_starting <= Date.new(record.series.series_started_on, 1, 1)
record.errors.add(:broadcast_starting, "The entry must have been originally released between #(record.series.series_started_on} and #{record.series.series_ended_on}")
end
# Dates must be no more than five years in the future
if !record.broadcast_starting.nil? and record.broadcast_starting > Date.new(record.series.series_ended_on, 12, 31)
record.errors.add(:broadcast_starting, "The broadcast date must be between 1963 and #{record.series.series_ended_on}")
end
if !record.broadcast_ending.nil? and record.broadcast_ending < record.broadcast_starting
record.errors.add(:broadcast_ending, 'The broadcast dates appear to be reversed.')
end
if !record.broadcast_ending.nil? and record.broadcast_ending > end_of_range
record.errors.add(:broadcast_ending, 'The broadcast end date is too far in the future.')
end
end
end
| true |
26839a116e30dcef45b36d5187fd2b32a8562267 | Ruby | sergio-bobillier/tdd-ruby | /strings/runner.rb | UTF-8 | 724 | 3.796875 | 4 | [] | no_license | require_relative 'basic_string'
require_relative 'quoted_string'
puts '#### BasicString ####'
sentence = BasicString.new('A rose by any other name still smells sweet')
words = ['Rose', 'rose', 'smell', 'Sweet', 'violet', 'any other', 'a', 'A']
puts '#include?'
words.each do |word|
puts "\t" + [word, sentence.include?(word)].inspect
end
puts '#contains?'
words.each do |word|
puts "\t" + [word, sentence.contains?(word)].inspect
end
puts '#### QuotedString ####'
placeholder = 5 + 10
sentence = %q{The sum of 5 + 10 is: #{placeholder}}
quoted_string = QuotedString.new(sentence)
puts quoted_string
sentence = %Q{The sum of 5 + 10 is: #{placeholder}}
quoted_string = QuotedString.new(sentence)
puts quoted_string
| true |
c2ce97fd8d2a63474e17b83028191661871f37a5 | Ruby | apmiller108/anomalous | /lib/anomalous/plot/histogram.rb | UTF-8 | 1,052 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'nyaplot'
module Anomalous
module Plot
class Histogram
def initialize(features, options = {})
@ith_feature = options[:ith_feature] || :all
@dir = options[:dir] || 'histograms'
@bins = options[:bins] || 100
@features = filter_feature_set(features)
end
def call
@features.each_column.with_index do |column, index|
plot = Nyaplot::Plot.new
plot.add(:histogram, column.to_flat_array)
plot.diagrams[0].options[:bin_num] = @bins
Dir.mkdir(@dir) unless File.exists?(@dir)
plot.export_html(histogram_file_path(index))
end
true
end
private
def filter_feature_set(features)
return features if @ith_feature == :all
features[0..(features.rows - 1), @ith_feature]
end
def histogram_file_path(index)
return "#{@dir}/feature#{index}.html" if @ith_feature == :all
"#{@dir}/feature#{@ith_feature}.html"
end
end
end
end
| true |
23f042a9fa633067f1348ae04798215214c60b31 | Ruby | seanlucius/ruby-object-attributes-lab-bootcamp-prep-000 | /lib/person.rb | UTF-8 | 205 | 3.046875 | 3 | [] | no_license | class Person
def name
@name
end
def name=(new_person_name)
@name = new_person_name
end
def job
@job
end
def job=(new_person_job)
@job = new_person_job
end
end | true |
119489d2c13cc703645be3cb2618d8fd4f3ec4f1 | Ruby | alandotcom/usps_intelligent_barcode | /spec/routing_code_spec.rb | UTF-8 | 4,420 | 2.6875 | 3 | [
"MIT"
] | permissive | require File.expand_path('spec_helper', File.dirname(__FILE__))
module Imb
describe RoutingCode do
describe '::coerce' do
let(:zip) {85308}
let(:plus4) {1465}
let(:delivery_point) {12}
subject {RoutingCode.coerce(o)}
shared_examples 'coerces' do
its(:zip) {should == zip}
its(:plus4) {should == plus4}
its(:delivery_point) {should == delivery_point}
end
context 'RoutingCode' do
let(:o) {RoutingCode.new(zip, plus4, delivery_point)}
it_behaves_like 'coerces'
end
context 'nil' do
let(:o) {nil}
let(:zip) {nil}
let(:plus4) {nil}
let(:delivery_point) {nil}
it_behaves_like 'coerces'
end
context 'string' do
let(:o) {"#{zip}#{plus4}#{delivery_point}"}
context 'empty' do
let(:zip) {nil}
let(:plus4) {nil}
let(:delivery_point) {nil}
it_behaves_like 'coerces'
end
context "zip, plu4, delivery_point" do
it_behaves_like 'coerces'
end
end
context 'array' do
let(:o) {[zip, plus4, delivery_point]}
it_behaves_like 'coerces'
end
context 'unrecognized' do
let(:o) {Object.new}
specify do
expect {
RoutingCode.coerce(o)
}.to raise_error ArgumentError, 'Cannot coerce to RoutingCode'
end
end
end
describe '#string_to_array' do
subject(:array) {RoutingCode.string_to_array(s)}
context 'empty' do
let(:s) {''}
it {is_expected.to eq([nil, nil, nil])}
end
context 'zip' do
let(:s) {'85308'}
it {is_expected.to eq(['85308', nil, nil])}
end
context 'zip, plus4' do
let(:s) {'853081465'}
it {is_expected.to eq(['85308', '1465', nil])}
end
context 'zip, plu4, delivery_point' do
let(:s) {'85308146502'}
it {is_expected.to eq(['85308', '1465', '02'])}
end
context 'non-digits' do
let(:s) {'(85308 1465 02)'}
it {is_expected.to eq(['85308', '1465', '02'])}
end
context 'incorrect length' do
let(:s) {'1'}
specify do
expect {
array
}.to raise_error ArgumentError, 'Bad routing code: "1"'
end
end
end
describe '#convert' do
subject do
RoutingCode.new(zip, plus4, delivery_point)
end
context 'empty' do
let(:zip) {nil}
let(:plus4) {nil}
let(:delivery_point) {nil}
its(:convert) {should == 0}
end
context 'zip' do
let(:zip) {85308}
let(:plus4) {nil}
let(:delivery_point) {nil}
its(:convert) {should == 85309}
end
context 'zip, plus4' do
let(:zip) {85308}
let(:plus4) {1465}
let(:delivery_point) {nil}
its(:convert) {should == 853181466}
end
context 'zip, plus4, delivery_point' do
let(:zip) {85308}
let(:plus4) {1465}
let(:delivery_point) {2}
its(:convert) {should == 86308246503}
end
end
describe '#to_a' do
let(:zip) {85308}
let(:plus4) {1465}
let(:delivery_point) {2}
subject {RoutingCode.new(zip, plus4, delivery_point)}
its(:to_a) {should == [zip, plus4, delivery_point]}
end
describe '#==' do
def o1 ; RoutingCode.new(85308, 1465, 1) ; end
def o2 ; [85308, 1465, 1] ; end
def o3 ; RoutingCode.new(85308, 1465, 2) ; end
def o4 ; RoutingCode.new(85308, 1466, 1) ; end
def o5 ; RoutingCode.new(85309, 1465, 1) ; end
def o6 ; Object.new ; end
specify {expect(o1).to eq(o1)}
specify {expect(o1).to eq(o2)}
specify {expect(o1).not_to eq(o3)}
specify {expect(o1).not_to eq(o4)}
specify {expect(o1).not_to eq(o5)}
specify {expect(o1).not_to eq(o6)}
end
describe '#validate' do
let(:routing_code) {RoutingCode.new(nil, nil, nil)}
let(:long_mailer_id?) {double 'long_mailer_id?'}
specify {routing_code.validate(long_mailer_id?)}
end
describe '#shift_and_add_to' do
let(:routing_code) {RoutingCode.new(85308, 1465, 2)}
let(:long_mailer_id?) {double 'long mailer id'}
specify {expect(routing_code.shift_and_add_to(1, long_mailer_id?)).to eq(186308246503)}
end
end
end
| true |
ae8be916f4a18968a4ba8b1a4977cd7f3f648d8c | Ruby | anishshrestha007/BoggleGame | /app/controllers/v1/game_controller.rb | UTF-8 | 2,603 | 3.203125 | 3 | [
"MIT"
] | permissive | class V1::GameController < ApplicationController
def index
end
# Gets Game Data
# Url: /v1/game/getGameData
# Description: Get a new set of words based on the provided matrix size
def getGameData
length = params[:length]
status = STATUS_OK
can_proceed = true
error_msg = ""
response_data = nil
# CHECK IF THE PARAMETER IS PROVIDED
if !params.has_key?(:length) || length.nil?
error_msg = MSG_LENGTH_NOT_PROVIDED
can_proceed = false
status = STATUS_BAD_REQUEST # Bad request
end
# CHECK IF THE PARAMETER IS AN ACCEPTABLE NUMBER
if can_proceed && (!is_number?(length) || length.to_i < MIN_WORD_LENGTH || length.to_i > MAX_WORD_LENGTH)
error_msg = MSG_BOARD_LENGTH_INVALID
can_proceed = false
status = STATUS_BAD_REQUEST # Bad request
end
if can_proceed
length = length.to_i
nextChunk = BOGGLE_STRING.split("").sample(length * length).join("")
message = MSG_GAME_RETRIEVED
success = true
data = {
:game_data => nextChunk,
}
response_data = ResponseModel.new(message, success, data)
else
response_data = ResponseModel.new(error_msg, false, nil)
end
render json: response_data, status: status
end
# Checks a word
# Url: /v1/game/checkWord
# Description:
# 1. Checks if the submitted word is correct or not
# 2. Provide a score accordingly
def checkWord
word = params[:word]
status = STATUS_OK
can_proceed = true
error_msg = ""
response_data = nil
if !params.has_key?(:word) || word.nil?
error_msg = MSG_EVALUATION_WORD_EMPTY
can_proceed = false
status = STATUS_BAD_REQUEST # Bad request
end
if can_proceed and word.length < MIN_WORD_LENGTH
error_msg = MSG_LENGTH_TOO_SMALL
can_proceed = false
status = STATUS_BAD_REQUEST # Bad request
end
if can_proceed
# Checks the word with a score
response = DICTIONARY.include?(word)
score = 0
if response == true
score = word.size - 2
if score < 1
score = 1
end
if score > 6
score = 6
end
end
message = MSG_EVALUATION_SUCCESS
success = true
data = {
:is_correct => response,
:score => score,
}
response_data = ResponseModel.new(message, success, data)
else
response_data = ResponseModel.new(error_msg, false, nil)
end
render json: response_data, status: status
end
def is_number?(string)
true if Float(string) rescue false
end
end
| true |
707585e560413eb0a094e531408873356208de33 | Ruby | danwyryunq/eis | /kata3/spec/batalla_naval_spec.rb | UTF-8 | 4,711 | 3.015625 | 3 | [] | no_license | require 'rspec'
require_relative '../model/batalla_naval.rb'
describe 'BatallaNaval' do
let(:juego) { BatallaNaval.new(10,10) }
let(:jugador) { 1 }
it 'el juego se inicializa con tableros de 10 casilleros de alto y 10 de ancho' do
expect( juego.alto_tablero ).to eq 10
expect( juego.ancho_tablero ).to eq 10
end
it 'ubicar_nave(jugador, "submarino", 1, 1) ubica un submarino en la posicion (1,1) del tablero del jugador' do
juego.ubicar_nave jugador, "submarino", 1, 1
expect( juego.ocupado?(jugador, 1, 1) ).to be_truthy
expect( juego.nave_en(jugador, 1, 1) ).to be_an_instance_of Submarino
end
it 'ubicar_nave(jugador, "crucero", 1,2, "horizontal") ubica un crucero ocupando las posiciones (1,2) y (2,2) del tablero del jugador' do
juego.ubicar_nave jugador, "crucero", 1, 2, "horizontal"
expect( juego.ocupado?(jugador, 1, 2) ).to be_truthy
expect( juego.ocupado?(jugador, 2, 2) ).to be_truthy
expect( juego.nave_en(jugador, 1, 2) ).to be_an_instance_of Crucero
expect( juego.nave_en(jugador, 2, 2) ).to be_an_instance_of Crucero
end
it 'ubicar_nave(jugador, "crucero", 1,10, "vertical") ubica un crucero ocupando las posiciones (1,10) y (1,9) del tablero del jugador' do
juego.ubicar_nave jugador, "crucero", 1, 10, "vertical"
expect( juego.ocupado?(jugador, 1, 10) ).to be_truthy
expect( juego.ocupado?(jugador, 1, 9) ).to be_truthy
expect( juego.nave_en(jugador, 1, 10) ).to be_an_instance_of Crucero
expect( juego.nave_en(jugador, 1, 9) ).to be_an_instance_of Crucero
end
it 'ubicar_nave(jugador, "destructor", 1,3, "horizontal") ubica un crucero ocupando las posiciones (1,2), (2,2) y (3,2) del tablero del jugador' do
juego.ubicar_nave jugador, "destructor", 1, 3, "horizontal"
expect( juego.ocupado?(jugador, 1, 3) ).to be_truthy
expect( juego.ocupado?(jugador, 2, 3) ).to be_truthy
expect( juego.ocupado?(jugador, 3, 3) ).to be_truthy
expect( juego.nave_en(jugador, 1, 3) ).to be_an_instance_of Destructor
expect( juego.nave_en(jugador, 2, 3) ).to be_an_instance_of Destructor
expect( juego.nave_en(jugador, 3, 3) ).to be_an_instance_of Destructor
end
it 'ubicar_nave(jugador, "destructor", 2,10, "vertical") ubica un crucero ocupando las posiciones (2,10), (2,9) y (2,8) del tablero del jugador' do
juego.ubicar_nave jugador, "destructor", 2, 10, "vertical"
expect( juego.ocupado?(jugador, 2, 10) ).to be_truthy
expect( juego.ocupado?(jugador, 2, 9) ).to be_truthy
expect( juego.ocupado?(jugador, 2, 8) ).to be_truthy
expect( juego.nave_en(jugador, 2, 10) ).to be_an_instance_of Destructor
expect( juego.nave_en(jugador, 2, 9) ).to be_an_instance_of Destructor
expect( juego.nave_en(jugador, 2, 8) ).to be_an_instance_of Destructor
end
it 'ubicar_nave(jugador, "submarino", 5,5) lanza una PosicionOcupadaException si la posicion (5,5) ya estaba ocupada por otra nave' do
juego.ubicar_nave jugador, "submarino", 5, 5
expect{ juego.ubicar_nave(jugador, "submarino", 5, 5 ) }.to raise_error PosicionOcupadaException
end
it 'ubicar_nave(jugador, "crucero", 4,5, "horizontal") lanza una PosicionOcupadaException si una de las posiciones a ocupar por el crucero ya estaba ocupada por otra nave' do
juego.ubicar_nave jugador, "submarino", 5, 5
expect{ juego.ubicar_nave(jugador, "crucero", 4, 5, 'horizontal' ) }.to raise_error PosicionOcupadaException
end
it 'ubicar_nave(jugador, "destructor", 3,5, "horizontal") lanza una PosicionOcupadaException si una de las posiciones a ocupar por el destructor ya estaba ocupada por otra nave' do
juego.ubicar_nave jugador, "submarino", 5, 5
expect{ juego.ubicar_nave(jugador, "destructor", 3, 5, 'horizontal' ) }.to raise_error PosicionOcupadaException
end
it 'ubicar_nave(jugador, "submarino", 11,1, "horizontal") lanza un FueraDeTableroException' do
expect{ juego.ubicar_nave(jugador, "submarino", 11, 1, 'horizontal' ) }.to raise_error FueraDeTableroException
end
it 'ubicar_nave(jugador, crucero, 10,1, horizontal) lanza una FueraDeTableroException si no cabe la completitud del crucero en los rangos del tablero' do
expect{ juego.ubicar_nave(jugador, "crucero", 10, 1, 'horizontal' ) }.to raise_error FueraDeTableroException
end
it 'ubicar_nave(jugador, destructor , 10,1, horizontal) lanza una FueraDeTableroException si no cabe la completitud del destructor en los rangos del tablero' do
expect{ juego.ubicar_nave(jugador, "destructor", 9, 1, 'horizontal' ) }.to raise_error FueraDeTableroException
end
it 'disparar(jugador, 1,1) devuelve false' do
expect(juego.disparar(jugador,1,1) ).to be_falsey
end
end
| true |
4a81c432466c576667b57768f5546e1f8af27d35 | Ruby | ianmcknnn/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-wdc01-seng-ft-060120 | /nyc_pigeon_organizer.rb | UTF-8 | 1,445 | 3.46875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer(data)
#initializing a hash, a name array, and a data_type_list to which to add
#things as we see them in the loops
new_hash = {}
name_list = []
data_type_list = []
#loop through the hash of data-types
data.each_pair do |data_type, hash|
#loop through the hash of features
hash.each_pair do |feature, array|
#loop through the array of names
array.each do |name|
#if we have never seen a name before, add it to the name list so we
#don't overwrite it next time we want to store something for that
#name, then store the name key with the data-type, feature array
#value pair
if !name_list.include?(name)
new_hash.store(name, {data_type => [feature.to_s]})
name_list.push(name)
#if we have seen the name, but not the data_type (color, gender,
#or place), store the data type key with the feature value
elsif !new_hash[name].has_key?(data_type)
new_hash[name].store(data_type, [feature.to_s])
data_type_list.push(data_type)
#if none of the above are true, we must have seen both the name
#and data type before, so just push the feature to the feature
#array that already exists for the given name and data-type
else
new_hash[name][data_type].push(feature.to_s)
end
end
end
end
#print the new hash
new_hash
end
| true |
9f5d0109eb13b3a47c8d0fdf9441e204f31a1194 | Ruby | killy971/project-euler | /ruby/041.rb | UTF-8 | 449 | 3.09375 | 3 | [] | no_license | #!/usr/bin/ruby1.9
# vim:set ts=2 sw=2:
require 'mathn'
class Integer
def is_pandigital
str = to_s
digits = str.split("").sort
return false if digits.uniq.size < digits.size
# str[0] == ?1 && str[digits.size - 1] == digits.size + 48
digits[0].to_i == 1 && digits[digits.size - 1].to_i == digits.size
end
end
solution = 0
solution = Prime.new.each do |p|
solution = p if p.is_pandigital
break p if p > 76_543_210
end
puts solution
| true |
c88d1738366445abe807c4fb3bbbc540c81a6ab4 | Ruby | uqbar-paco/metaprogramacion-xunit-clase-20132c | /test/motor_xunit_spec.rb | UTF-8 | 1,019 | 2.78125 | 3 | [] | no_license | require_relative '../xunit/mi_test'
require_relative '../xunit/motor_xunit'
require 'rspec'
describe 'Testeo de motor xunit' do
it 'ejecutar si todos estan bien' do
motor= MotorXUnit.new
resultados = motor.correr_todos_los_tests(MiTest)
expect(resultados.all? {
|resultado| resultado.paso?
}).to eq(true)
end
it 'ejecutar no pasa si algun test falla' do
motor = MotorXUnit.new
resultados = motor.correr_todos_los_tests(OtroTest)
expect(resultados.all? { |resultado|
resultado.paso? }).to eq(false)
end
it 'Falla un test que lanza una excepcion' do
motor = MotorXUnit.new
resultados = motor.correr_todos_los_tests(TestQueTiraError)
expect(resultados.all? { |resultado|
resultado.error? }).to eq(true)
end
it 'No hay errores si no se lanzaron excepciones inesperadas' do
motor = MotorXUnit.new
resultados = motor.correr_todos_los_tests(MiTest)
expect(resultados.all? { |resultado|
resultado.error? }).to eq(false)
end
end | true |
5d5529bbb6022b4d9de8fd707531ddd85cfb5432 | Ruby | gltaborda/ruby_the_odin_project | /chess/lib/game.rb | UTF-8 | 734 | 3.34375 | 3 | [] | no_license | require_relative 'board'
require_relative 'player'
class Game
attr_reader :board, :players
attr_accessor :winner
def initialize(player1, player2)
@board = Board.new
@players = [player1, player2]
@winner = false
end
def play_match
board.load
board.display
until over?
array = players[0].move_from_to
until board.matrix[array[1]][array[0]].color == players[0].color
puts "You didn't pick a #{players[0].color} piece. Try again."
array = players[0].move_from_to
end
board.move_piece(array)
board.display
players.reverse!
end
end
def over?
self.winner || draw?
end
def winner?(row, column)
end
def draw?
false
end
end | true |
9476415eac1f7b097786b3667ec8813057dea838 | Ruby | hiddenone/Portfolio-Project-1-User-Stories | /app/helpers/application_helper.rb | UTF-8 | 666 | 2.515625 | 3 | [] | no_license | module ApplicationHelper
# Allows setting the value to show in an HTML select
# param: attribute, e.g., @story.priority
# param: default_value, what to show if no value exists for
# and instantiation
def options_default(attribute, default_value)
if attribute
return attribute
else
return default_value
end
end
# from comments to railscast
def tag_cloud(tags, classes)
max = 0
tags.each do |t|
if t.count.to_i > max
max = t.count.to_i
end
end
tags.each do |tag|
index = tag.count.to_f / max * (classes.size - 1)
yield(tag, classes[index.round])
end
end
end
| true |
791daacfb5c5b4de731873cdfc140bda8cc9cab2 | Ruby | bougui505/blog | /_plugins/jekyll.tag-cloud.rb | UTF-8 | 3,251 | 2.984375 | 3 | [
"MIT"
] | permissive | # Copyright (C) 2011 Anurag Priyam - MIT License
module Jekyll
# Jekyll plugin to generate tag clouds.
#
# The plugin defines a `tag_cloud` tag that is rendered by Liquid into a tag
# cloud:
#
# <div class='cloud'>
# {% tag_cloud %}
# </div>
#
# The tag cloud itself is a collection of anchor tags, styled dynamically
# with the `font-size` CSS property. The range of values, and unit to use for
# `font-size` can be specified with a very simple syntax:
#
# {% tag_cloud font-size: 16 - 28px %}
#
# The output is automatically formatted to use the same number of decimal
# places as used in the argument:
#
# {% tag_cloud font-size: 0.8 - 1.8em %} # => 1
# {% tag_cloud font-size: 0.80 - 1.80em %} # => 2
#
# Tags that have been used less than a certain number of times can be
# filtered out from the tag cloud with the optional `threshold` parameter:
#
# {% tag_cloud threshold: 2%}
#
# Both the parameters can be easily clubbed together:
#
# {% tag_cloud font-size: 50 - 150%, threshold: 2%}
#
# The plugin randomizes the order of tags every time the cloud is generated.
class TagCloud < Liquid::Tag
safe = true
# tag cloud variables - these are setup in `initialize`
attr_reader :size_min, :size_max, :precision, :unit, :threshold
def initialize(name, params, tokens)
# initialize default values
@size_min, @size_max, @precision, @unit = 70, 170, 0, '%'
@threshold = 1
# process parameters
@params = Hash[*params.split(/(?:: *)|(?:, *)/)]
process_font_size(@params['font-size'])
process_threshold(@params['threshold'])
super
end
def render(context)
# get an Array of [tag name, tag count] pairs
count = context.registers[:site].tags.map do |name, posts|
[name, posts.count] if posts.count >= threshold
end
# clear nils if any
count.compact!
# get the minimum, and maximum tag count
min, max = count.map(&:last).minmax
# map: [[tag name, tag count]] -> [[tag name, tag weight]]
weight = count.map do |name, count|
# logarithmic distribution
weight = (Math.log(count) - Math.log(min))/(Math.log(max) - Math.log(min))
[name, weight]
end
# sort by alhabetical order
weight.sort_by!{|name, count| name[0].downcase}
# reduce the Array of [tag name, tag weight] pairs to HTML
weight.reduce("") do |html, tag|
name, weight = tag
size = size_min + ((size_max - size_min) * weight).to_f
size = sprintf("%.#{@precision}f", size)
html << "<a style='font-size: #{size}#{unit}' href='/tags.html##{name}'>#{name}</a>\n"
end
end
private
def process_font_size(param)
/(\d*\.{0,1}(\d*)) *- *(\d*\.{0,1}(\d*)) *(%|em|px)/.match(param) do |m|
@size_min = m[1].to_f
@size_max = m[3].to_f
@precision = [m[2].size, m[4].size].max
@unit = m[5]
end
end
def process_threshold(param)
/\d*/.match(param) do |m|
@threshold = m[0].to_i
end
end
end
end
Liquid::Template.register_tag('tag_cloud', Jekyll::TagCloud)
| true |
017007f4c12935f56b94d6149b2131f2ad58681d | Ruby | nigel-lowry/means | /lib/means.rb | UTF-8 | 3,698 | 3.859375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'mathn'
require 'active_support/all'
# Allows calculation of arithmetic, geometric and harmonic means.
# Class methods allow the passing in of a data set.
# Alternatively an object can be created and elements can
# be added with #push
class Mean
# Calculate the arithmetic mean
# @param [Array<Numeric>] data the data values
# @return [Numeric, nil] the arithmetic mean or nil if there is no data
def Mean.arithmetic(data)
data.sum / data.size unless data.empty?
end
# Calculate the geometric mean
# @param (see Mean.arithmetic)
# @return [Numeric, nil] the geometric mean or nil if there is no data or any elements are zero or negative
def Mean.geometric(data)
data.reduce(:*) ** (1 / data.size) unless data.empty? or includes_zero_or_negative? data
end
# Calculate the harmonic mean
# @param (see Mean.arithmetic)
# @return [Numeric, nil] the harmonic mean or nil if there is no data or any elements are zero or negative
def Mean.harmonic(data)
data.size / data.reduce(0) {|sum, element| sum += (1 / element)} unless data.empty? or includes_zero_or_negative? data
end
# Remember the initial state.
#
# If you are passing in an initial state:
# [arithmetic mean] needs `:sum` and `:count`
# [geometric mean] needs `:product` and `:count`
# [harmonic mean] needs `:sum_of_reciprocals` and `:count`
# @param [Hash{Symbol => Numeric}]
# @raise if `:count` is negative
# @raise if `:sum_of_reciprocals` is negative
# @raise if `:product` is negative
def initialize(params={})
check_params params
assign_defaults params
end
# Add element to the data set
# @param [Numeric] element the element to add
def push(element)
@includes_zero_or_negative = true if Mean.zero_or_negative? element
unless @includes_zero_or_negative
@sum_of_reciprocals += (1 / element)
@product *= element
end
@sum += element
@count += 1
end
# Calculate the arithmetic mean
# @return [Numeric, nil] the arithmetic mean or nil if there is no data
def arithmetic_mean
@sum / @count unless @count.zero?
end
# Calculate the geometric mean
# @return [Numeric, nil] the geometric mean or nil if there is no data or any elements are zero or negative
def geometric_mean
@product ** (1 / @count) unless @count.zero? or @includes_zero_or_negative
end
# Calculate the harmonic mean
# @return [Numeric, nil] the harmonic mean or nil if there is no data or any elements are zero or negative
def harmonic_mean
@count / @sum_of_reciprocals unless @count.zero? or @includes_zero_or_negative
end
private
def check_params params
params.assert_valid_keys :count, :sum_of_reciprocals, :product, :sum
raise_error_for_negative params, :count
raise_error_for_negative params, :sum_of_reciprocals
raise_error_for_negative params, :product
end
def assign_defaults params
defaults = {
sum: 0,
sum_of_reciprocals: 0,
product: 1,
count: 0
}
options = params.reverse_merge defaults
@sum = options[:sum]
@sum_of_reciprocals = options[:sum_of_reciprocals]
@product = options[:product]
@count = options[:count]
@includes_zero_or_negative = false
end
def self.includes_zero_or_negative? data
data.any? {|element| zero_or_negative? element }
end
def self.zero_or_negative? element
element <= 0
end
def raise_error_for_negative params, key
raise %{cannot have negative "#{key.to_s}" of "#{params[key]}"} if params.has_key? key and params[key] < 0
end
end
| true |
aea92c218dde8c594a05abfdcfb424ca98150fb7 | Ruby | exceedhl/algorithm_coursra_problems | /scc/graph.rb | UTF-8 | 1,693 | 3.390625 | 3 | [] | no_license | require 'pp'
class Node
attr_reader :index
attr_accessor :incoming_edges, :outgoing_edges
def initialize(index)
@index = index
@incoming_edges = []
@outgoing_edges = []
end
def to_s
index.to_s
end
def print
puts "node: #{index.to_s}"
puts " incoming edges: #{incoming_edges.size}"
incoming_edges.each do |e|
e.print 1
end
puts " outgoing edges: #{outgoing_edges.size}"
outgoing_edges.each do |e|
e.print 1
end
end
end
class Edge
attr_accessor :head, :tail
def initialize(tail, head)
@head = head
@tail = tail
end
def to_s
tail.to_s + "," + head.to_s
end
def print(level = 0)
puts "\t"*level + "edge: {#{tail.to_s} -> #{head.to_s}}"
end
end
class Graph
attr_accessor :nodes
def initialize
@nodes = {}
end
def self.parse_graph(filepath)
g = Graph.new
i = 0
Dir.glob("data/scc-a*").each do |file|
File.new(file).readlines.each do |line|
l = line.strip.split(/\s+/)
# puts "#{i}: #{line}"
i += 1
tail_index, head_index = *l
g.nodes[tail_index] ||= Node.new(tail_index)
g.nodes[head_index] ||= Node.new(head_index)
edge = Edge.new(g.nodes[tail_index], g.nodes[head_index])
g.nodes[tail_index].outgoing_edges << edge
g.nodes[head_index].incoming_edges << edge
# if i % 100000 == 0
# GC.start
# puts "gc run on #{i}"
# end
end
GC.start
puts "processed #{file} #{i}"
end
g
end
end
g = Graph.parse_graph("SCC.txt")
# g.nodes.values.each do |n|
# n.print
# end
e1 = g.edges.values[0]
e1.print
e1.tail.print
| true |
7462d490f8f13d829ee043e98cd13089e78d41fc | Ruby | foymikek/backend_mod_1_prework | /day_1/ex7.rb | UTF-8 | 2,304 | 4.0625 | 4 | [] | no_license | # prints the text in the quotation marks and makes a new line, /n
puts "Mary had a little lamb."
# prints the string in the curly brackets within the parent string and
# makes a new line, /n
puts "Its fleece was white as #{'snow'}."
# prints the text within the quotation marks and makes a new line, /n
puts "And everywhere that Mary went."
# prints 10 full stops in a row, then makes a new line /n
puts "." * 10
# assigns the string to variable named end1
end1 = "C"
# assigns the string to variable named end2
end2 = "h"
# assigns the string to variable named end3
end3 = "e"
# assigns the string to variable named end4
end4 = "e"
# assigns the string to variable named end5
end5 = "s"
# assigns the string to variable named end6
end6 = "e"
# assigns the string to variable named end7
end7 = "B"
# assigns the string to variable named end8
end8 = "u"
# assigns the string to variable named end9
end9 = "r"
# assigns the string to vairable named end10
end10 = "g"
# assigns the string to variable named end11
end11 = "e"
# assigns the string to varible named end12
end12 = "r"
# Concatenates the variables end1, end2, end3, end4, end5 and end6 together.
# They are all strings and will combine to be one large string. Print does NOT
# make a new line, the next line will be on the same line.
print end1 + end2 + end3 + end4 + end5 + end6
# Concatenates the variables end7, end8, end9, end10, end11 and end12 then prints
# the combined strings into one large string. Puts will make a new line, /n
puts end7 + end8 + end9 + end10 + end11 + end12
# Exercise 11 - Asking for Input
print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "How much do you weigh? "
weight = gets.chomp
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."
print "Hey there, what is your name? "
name = gets.chomp
puts "Hey #{name}! I am new your new laptop Apple :D, I am friends with your other laptop Adele."
print "Welcome to Happy Cones Ice Cream, what kind of ice cream can I get for you today? "
ice_cream_chosen = gets.chomp
print "Would you like a normal cone, sugar cone or a cup? "
ice_cream_container = gets.chomp
print "Here is your #{ice_cream_chosen} ice cream in a #{ice_cream_container}. That lovely ice cream in on the house today! Enjoy the sun!!"
| true |
73e55ad51dac36d4472ee3dd2bed77af6ceaef0f | Ruby | eugmill/euler | /ruby/problem06.rb | UTF-8 | 638 | 4.09375 | 4 | [] | no_license | =begin
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first
ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first
one hundred natural numbers and the square of the sum.
=end
def sum_of_squares(n)
(1..n).to_a.map {|x| x**2}.reduce(:+)
end
def square_of_sum(n)
(1..n).reduce(:+)**2
end
puts square_of_sum(100)-sum_of_squares(100) | true |
0119c8b76cd0794907f323c3688e5bddee29c0ea | Ruby | pariyathida/my-warehouse | /test/models/parcel_test.rb | UTF-8 | 3,217 | 2.921875 | 3 | [] | no_license | require 'test_helper'
class ParcelTest < ActiveSupport::TestCase
def setup
@parcel = parcels(:supplementary_food_parcel)
end
#
# Validation
#
test "that it raises errors when fields are blank" do
parcel = Parcel.new(id: 1)
assert_equal false, parcel.valid?
assert_equal "can't be blank", parcel.errors[:import_date].first
assert_equal "can't be blank", parcel.errors[:export_date].first
assert_equal "can't be blank", parcel.errors[:weight].first
assert_equal "can't be blank", parcel.errors[:width].first
assert_equal "can't be blank", parcel.errors[:length].first
assert_equal "can't be blank", parcel.errors[:height].first
end
test "that it raises errors if weight, width, length, height is not an integer or isn't greater than or equal to 0" do
@parcel.update(weight: "a", width: -1, length: 5.5, height: ".")
assert_equal false, @parcel.valid?
assert_equal "is not a number", @parcel.errors[:weight].first
assert_equal "must be greater than or equal to 0", @parcel.errors[:width].first
assert_equal "must be an integer", @parcel.errors[:length].first
assert_equal "is not a number", @parcel.errors[:height].first
end
# for types that require weight, either weight or dimension should be provided
test "that it raises errors if weight or dimension is required but not provided" do
parcel = products(:product_clothes) # type: Cloth
parcel.update(weight: 0, width: 0, length: 0, height: 0)
assert_equal false, parcel.valid?
assert_equal "or dimension must be provided", parcel.errors[:weight].first
end
# for types that not required weight, dimension should be provided
test "that it raises errors if weight is not required but dimension is not provided" do
parcel = products(:product_others) # type: Other
parcel.update(weight: 0, width: 0, length: 0, height: 0)
assert_equal false, parcel.valid?
assert_equal "must be provided", parcel.errors[:width].first
assert_equal "must be provided", parcel.errors[:length].first
assert_equal "must be provided", parcel.errors[:height].first
end
#
# Calculation
#
test "that it returns the correct day range calculation" do
# different date, same time
@parcel.update(import_date: "09 Dec 2020 22:08:00 UTC +00:00")
@parcel.update(export_date: "10 Dec 2020 22:08:00 UTC +00:00")
assert_equal 1, @parcel.day_range
# different date, less than 24 hours fraction of the day
@parcel.update(import_date: "09 Dec 2020 22:08:00 UTC +00:00")
@parcel.update(export_date: "10 Dec 2020 20:09:00 UTC +00:00")
assert_equal 1, @parcel.day_range
# different date, more than 24 hours fraction of the day
@parcel.update(import_date: "09 Dec 2020 18:08:00 UTC +00:00")
@parcel.update(export_date: "10 Dec 2020 20:08:00 UTC +00:00")
assert_equal 2, @parcel.day_range
end
test "that it returns error if export date is not after the import date" do
@parcel.update(import_date: "11 Dec 2020 20:08:00 UTC +00:00")
@parcel.update(export_date: "10 Dec 2020 20:08:00 UTC +00:00")
assert_equal ["Export date must be after the import_date"], @parcel.errors.full_messages
end
end
| true |
f55e171619d5bd4ff2e45b3862645a99786a6ec7 | Ruby | tejasmanohar/timgur | /app.rb | UTF-8 | 1,340 | 2.625 | 3 | [
"MIT"
] | permissive | ### Gems
require 'orchestrate'
require 'sinatra'
require 'twilio-ruby'
### API Clients
app = Orchestrate::Application.new(ENV['ORCHESTRATE_API_KEY'])
subscribers = app[:subscribers]
client = Orchestrate::Client.new(ENV['ORCHESTRATE_API_KEY'])
### Configure Twilio
Twilio.configure do |config|
config.account_sid = ENV['TWILIO_ACCOUNT_SID']
config.auth_token = ENV['TWILIO_AUTH_TOKEN']
end
### Helper Methods
helpers do
def format_number(number)
digits = number.gsub(/\D/, '').split(//)
if (digits.length == 11 and digits[0] == '1')
# Strip leading 1
digits.shift
end
if (digits.length == 10)
digits = digits.join
'(%s) %s-%s' % [ digits[0,3], digits[3,3], digits[6,4] ]
end
end
end
### Routes
get '/' do
status 200
erb :home
end
post '/subscribe' do
num = format_number params[:number].to_s
if subscribers[num].nil?
status 200
subscribers.create(num, {})
end
end
get '/receive' do
@twil = Twilio::REST::Client.new
if params[:Body].eql? 'unsubscribe'
status 200
num = format_number(params[:From])
doc = client.get(:subscribers, num)
client.delete(:subscribers, num, doc.ref)
@twil.messages.create(
from: ENV['TWILIO_NUMBER'],
to: params[:From],
body: 'You are now unsubscribed.'
)
else
status 400
end
end
| true |
d2be3aba92b5e0dd1084d0ff4f3ceb00e5bbec89 | Ruby | cielavenir/procon | /codeforces/tyama_codeforces630N.rb | UTF-8 | 119 | 2.78125 | 3 | [
"0BSD"
] | permissive | #!/usr/bin/ruby
a,b,c=gets.split.map(&:to_f)
(a=-a;b=-b;c=-c)if a<0
puts [1,-1].map{|s|(-b+s*Math.sqrt(b*b-4*a*c))/2/a} | true |
f3bec9485ac1d89abdd0b914ef4cced6f70422d0 | Ruby | VictorHolanda21/cursoRuby | /exercicios/exercicio02/quest11.rb | UTF-8 | 178 | 3.59375 | 4 | [] | no_license |
puts "Digite uma nota entre 0 e 10: "
nota = gets.chomp.to_i
while (nota>10 || nota<0)
puts "Nota inválida!"
puts "Digite uma nota entre 0 e 10: "
nota = gets.chomp.to_i
end | true |
947dff9ca05634de80378f56aa8b059a25bd52bf | Ruby | TuftsUniversity/whowas | /lib/generators/whowas/templates/search_method.rb | UTF-8 | 1,984 | 2.984375 | 3 | [
"MIT"
] | permissive | module Whowas
class MySearchMethod
# All required public methods are contained in the Middleware package. It
# initializes the search method, calls search on the adapter with the
# provided input, and returns the output to the next search method or the
# caller.
#
# The Searchable modules (Validatable, Formattable, and Parsable) are
# technically optional but in practice necessary to ensure usable input and
# outputs.
include Whowas::Middleware
include Whowas::Searchable
## ADAPTER
# You MUST set this to the name of a bundled or custom adapter class.
@@adapter = ADAPTER_CLASS_HERE
private
## Validatable
# Optional but useful to prevent making unnecessary API calls when given
# invalid input.
# Defines required elements of the input hash.
# This should be an array containing the required inputs as symbols.
def required_inputs
[
# :ip,
# :timestamp
]
end
# Validates the values of required inputs.
# This should be a hash containing the required input as key, and a lambda
# taking input and returning a boolean as value.
def input_formats
{
# timestamp: lambda { |input| DateTime.parse(input) && true rescue false }
}
end
## Formattable
# Search method-wide transformations to the input. For example, if all
# mac addresses given as input to this search method should use colons as
# separators, perform that transformation here.
#
# Adapter-wide transformations to the input can be made in the adapter
# format method.
def format_input(input)
input
end
## Parsable
# Extract pieces of the results string from the adapter using regex to form
# the input hash for the next search method or the final result.
def output_formats
{
# username: /User <\K\w*/
}
end
end
end | true |
b432f6be756526c62c950667491466ea1de2522e | Ruby | heedspin/doogle | /lib/doogle/spec_version_synchronizer.rb | UTF-8 | 1,389 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'plutolib/logger_utils'
class Doogle::SpecVersionSynchronizer
include Plutolib::LoggerUtils
def initialize(spec_version_id=nil)
@spec_version_id = spec_version_id
@web_creates = 0
@web_updates = 0
@web_no_change = 0
@web_errors = 0
@web_deletes = 0
end
def run_in_background!
if @spec_version_id
self.send_later(:sync_single_display)
else
self.send_later(:sync_all_displays)
end
end
# require 'doogle/web_synchronizer' ; puts Doogle::WebSynchronizer.new.sync_all_displays
def sync_all_displays
# TODO: add time window here?
Doogle::SpecVersion.find_each do |spec_version|
sync_single_display(spec_version)
end
true
end
def sync_single_display(spec_version=nil)
spec_version ||= Doogle::SpecVersion.find(@spec_version_id)
case spec_version.sync_to_web
when :create
@web_creates += 1
when :update
@web_updates += 1
when :delete
@web_deletes += 1
when :no_change
@web_no_change += 1
when :error
@web_errors += 1
end
true
end
def results
<<-TEXT
#{@web_creates} creates
#{@web_updates} updates
#{@web_deletes} deletes
#{@web_no_change} no changes
#{@web_errors} errors
TEXT
end
def success(job)
log(results)
end
def error(job, exception)
Airbrake.notify(exception)
end
end
| true |
196a50d7a59f04b64608f7b98c129c4e8ff8aa1e | Ruby | forestturner/w2d5 | /lib/p02_hashing.rb | UTF-8 | 540 | 3.234375 | 3 | [] | no_license | class Fixnum
# Fixnum#hash already implemented for you
end
# class Array
# def hash
#
# sum = 0
# self.flatten.each_with_index { |el, index| sum += (el * index) }
# sum.hash
# end
# end
class String
def hash
int_array = self.split("").map { |el| el.ord }
int_array.hash
end
end
class Hash
# This returns 0 because rspec will break if it returns nil
# Make sure to implement an actual Hash#hash method
def hash
hash_array = self.sort.flatten.map {|el| el.to_s.hash }
hash_array.hash
end
end
| true |
9408b7bb6a1e607783099988edba3ff51b2d3710 | Ruby | sajoy/hair_salon | /spec/client_spec.rb | UTF-8 | 2,387 | 2.6875 | 3 | [] | no_license | require('spec_helper')
describe(Client) do
describe('#id') do
it("will return a client's unique id as a fixnum") do
client1 = Client.new({:name => "Kris K.", :id => nil})
client1.save()
expect(client1.id()).to(be_an_instance_of(Fixnum))
end
end
describe('#name') do
it("will return a client's name") do
client1 = Client.new({:name => "David B.", :id => nil})
expect(client1.name()).to(eq("David B."))
end
end
describe(".find") do
it("will return a Client by its given id") do
client1 = Client.new({:name => "George W.", :id => nil})
client1.save()
expect(Client.find(client1.id())).to(eq(client1))
end
end
describe("#save") do
it("will save a new Client to the hair_salon database") do
client1 = Client.new({:name => "Lily A.", :id => nil})
client1.save()
expect(Client.all()).to(eq([client1]))
end
end
describe("#update") do
it("will allow a user to update a Client's name") do
client1 = Client.new({:name => "Georgia A.", :id => nil})
client1.save()
client1.update({:name => "Georgio A."})
expect(client1.name()).to(eq("Georgio A."))
end
end
describe("#delete") do
it("will delete a Client from the database") do
client1 = Client.new({:name => "Georgia A.", :id => nil})
client1.save()
client1.delete()
expect(Client.all()).to(eq([]))
end
end
describe(".all") do
it("will start empty") do
expect(Client.all()).to(eq([]))
end
end
describe("#==") do
it("will say two Clients are equal if their names are the same") do
client1 = Client.new({:name => "Lily A.", :id => nil})
client1.save()
client2 = Client.new({:name => "Lily A.", :id => nil})
client2.save()
expect(client1).to(eq(client2))
end
end
describe("#stylist") do
it("will return a client's stylist's name") do
client1 = Client.new({:name => "Lily A.", :id => nil})
client1.save()
stylist1 = Stylist.new({:name => "Harry P.", :di => nil})
stylist1.save()
stylist1.add_client(client1)
expect(client1.stylist()).to(eq(stylist1.name()))
end
it("will return nil if a client doesn't have one") do
client1 = Client.new({:name => "Lily A.", :id => nil})
client1.save()
expect(client1.stylist()).to(eq(nil))
end
end
end
| true |
943e8e803d05b20a3c371ef29159d478c900fb69 | Ruby | samvaughn/courseproject | /ninety_nine.rb | UTF-8 | 607 | 3.125 | 3 | [] | no_license | begin_bottles = 5
now_bottles = begin_bottles
while now_bottles > 2
puts now_bottles.to_s + ' bottles of beer on the wall'
puts now_bottles.to_s + ' bottles of beer'
puts 'Take one down, pass it around'
now_bottles = now_bottles - 1
puts now_bottles.to_s + ' bottles of beer on the wall'
puts
end
puts '2 bottles of beer on the wall'
puts '2 bottles of beer'
puts 'Take one down, pass it around'
puts '1 bottle of beer on the wall'
puts
puts '1 bottle of beer on the wall'
puts '1 bottle of beer'
puts 'Take one down, pass it around'
puts 'No more bottles of beer on the wall'
puts 'Ta-da!' | true |
6959b1a7ac1a53ad38dd0fe4a6afbfd33b451231 | Ruby | ryo-s2000/practice-ruby | /ruby/somecode/erro.rb | UTF-8 | 405 | 3.125 | 3 | [] | no_license | begin
# わざと例外を起こす
5 + nil
# 例外オブジェクトを変数 error に代入
rescue => error
# 変数 error を配列で表示する。
p error.message
p error.backtrace
end
begin
# わざと例外を起こす
5 + "konnitha"
# 例外オブジェクトを変数 error に代入
rescue => error
# 変数 error を配列で表示
p error.message
p error.backtrace
end
| true |
a3832d6b03cb6237f180ff2c2a26555abe93cd97 | Ruby | rpepato/rgis | /lib/rgis/services/geometry_service.rb | UTF-8 | 9,054 | 2.703125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'rgis/lookup'
require 'rgis/request'
module RGis
module Services
module GeometryService
def project(params = {})
pre_validate_request
response = project_geometry(params)
parse_result(response)
end
def project!(params = {})
pre_validate_request
response = project_geometry(params)
parse_result_for_bang_method(response)
self
end
def simplify(params = {})
pre_validate_request
raise TypeError, "Simplify operation is not supported on envelope types" if self.is_a?(Envelope)
response = simplify_geometry(params)
parse_result(response)
end
def buffer(params = {})
pre_validate_request
raise TypeError, "Buffer operation is not supported on envelope types" if self.is_a?(Envelope)
response = buffer_geometry(params)
parse_result(response)
end
def area_and_perimeter(params = {})
pre_validate_request
raise TypeError, "Area and perimeter operation is allowed only for polygon type" unless self.is_a?(Polygon)
response = area_and_perimeter_for_geometry(params)
{:area => response[:areas], :perimeter => response[:lengths]}
end
def lengths(params = {})
pre_validate_request
raise TypeError, "Lengths operation is allowed only for polyline type" unless self.is_a?(Polyline)
response = lengths_for_geometry(params)
response[:lengths]
end
def label_points(params = {})
pre_validate_request
raise TypeError, "Label points operation is allowed only for polygon type" unless self.is_a?(Polygon)
response = label_points_for_geometry(params)
response[:labelPoints].collect { |l| {:x => l[:x], :y => l[:y]} }
end
def generalize(params = {})
pre_validate_request
raise TypeError, "Generalize opertion is allowed only for polygon or polyline types" unless self.is_a?(Polygon) || self.is_a?(Polyline)
parse_result(generalize_for_geometry(params))
end
private
def pre_validate_request
raise "The operation couldn't be performed while the geometry is in an invalid state" unless self.valid?
end
def result_type? (geometry)
return nil unless geometry.respond_to?('geometries')
return RGis::Helper::GEOMETRY_TYPES[:point] if geometry.geometries[0].respond_to?(:x)
return RGis::Helper::GEOMETRY_TYPES[:polygon] if geometry.geometries[0].respond_to?('rings')
return RGis::Helper::GEOMETRY_TYPES[:polyline] if geometry.geometries[0].respond_to?('paths')
return RGis::Helper::GEOMETRY_TYPES[:envelope] if geometry.geometries[0].respond_to?(:xmax)
return RGis::Helper::GEOMETRY_TYPES[:multipoint] if geometry.geometries[0].respond_to?(:points)
end
def parse_result(response)
if result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:point]
Point.new(response.geometries[0][:x], response.geometries[0][:y])
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:polygon]
polygon = RGis::Polygon.new()
response.geometries[0].rings.each do |ring|
r = RGis::Ring.new()
r.points = ring.collect { |point| Point.new(point[0], point[1])}
polygon.rings << r
end
polygon
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:polyline]
polyline = RGis::Polyline.new()
response.geometries[0].paths.each do |path|
p = RGis::Path.new()
p.points = path.collect { |point| Point.new(point[0], point[1])}
polyline.paths << p
end
polyline
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:envelope]
lower_left_point = Point.new(response.geometries[0][:xmin], response.geometries[0][:ymin])
upper_right_point = Point.new(response.geometries[0][:xmax], response.geometries[0][:ymax])
Envelope.new(lower_left_point, upper_right_point)
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:multipoint]
multipoint = RGis::Multipoint.new()
response.geometries[0].points.each do |point|
multipoint.points << RGis::Point.new(point[0], point[1])
end
multipoint
end
end
def parse_result_for_bang_method(response)
if result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:point]
self.x = Float(response.geometries[0][:x])
self.y = Float(response.geometries[0][:y])
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:polygon]
response.geometries[0].rings.each_with_index do |ring, ring_index|
ring.each_with_index do |point, point_index|
self.rings[ring_index].points[point_index] = RGis::Point.new(point[0], point[1])
end
end
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:polyline]
response.geometries[0].paths.each_with_index do |path, path_index|
path.each_with_index do |point, point_index|
self.paths[path_index].points[point_index] = RGis::Point.new(point[0], point[1])
end
end
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:envelope]
lower_left_point = Point.new(response.geometries[0][:xmin], response.geometries[0][:ymin])
upper_right_point = Point.new(response.geometries[0][:xmax], response.geometries[0][:ymax])
self.lower_left_point = lower_left_point
self.upper_right_point = upper_right_point
elsif result_type?(response) == RGis::Helper::GEOMETRY_TYPES[:multipoint]
response.geometries[0].points.each_with_index do |point, point_index|
self.points[point_index] = RGis::Point.new(point[0], point[1])
end
end
end
def project_geometry(params = {})
request = Request.new
request.f = 'json'
request.inSR = params[:from]
request.outSR = params[:to]
request.geometries = self.to_json
response = Lookup.post("#{RGis::Services::ServiceDirectory.geometry_service_uri}/project", request)
response
end
def simplify_geometry(params = {})
request = Request.new
request.f = 'json'
request.sr = params[:spatial_reference]
request.geometries = self.to_json
response = Lookup.post("#{RGis::Services::ServiceDirectory.geometry_service_uri}/simplify", request)
response
end
def buffer_geometry(params = {})
request = Request.new
request.f = 'json'
request.inSR = params[:input_spatial_reference]
request.outSR = params[:output_spatial_reference]
request.bufferSR = params[:buffer_spatial_reference]
request.distances = params[:distances]
request.unit = params[:distance_units]
request.unionResults = params[:union_results]
request.geometries = self.to_json
response = Lookup.post("#{RGis::Services::ServiceDirectory.geometry_service_uri}/buffer", request)
response
end
def area_and_perimeter_for_geometry(params = {})
request = Request.new
request.f = 'json'
request.sr = params[:spatial_reference]
request.lengthUnit = params[:length_unit]
request.areaUnit = JSON.unparse({:areaUnit => params[:area_unit]})
request.polygons = self.rings_to_json
response = Lookup.post("#{RGis::Services::ServiceDirectory.geometry_service_uri}/areasAndLengths", request)
response
end
def lengths_for_geometry(params = {})
request = Request.new
request.f = 'json'
request.sr = params[:spatial_reference]
request.lengthUnit = params[:length_unit]
request.geodesic = params[:geodesic]
request.polylines = self.paths_to_json
response = Lookup.post("#{RGis::Services::ServiceDirectory.geometry_service_uri}/lengths", request)
end
def label_points_for_geometry(params = {})
request = Request.new
request.f = 'json'
request.sr = params[:spatial_reference]
request.polygons = self.rings_to_json
Lookup.post("#{RGis::Services::ServiceDirectory.geometry_service_uri}/labelPoints", request)
end
def generalize_for_geometry(params = {})
request = Request.new
request.f = 'json'
request.sr = params[:spatial_reference]
request.maxDeviation = params[:max_deviation]
request.deviationUnit = params[:deviation_unit]
request.geometries = self.to_json
Lookup.post("#{RGis::Services::ServiceDirectory.geometry_service_uri}/generalize", request)
end
end
end
end
| true |
e999f513b0419d83b9d61680afbff3263aaed6a6 | Ruby | colorbox/AtCoderLog | /abc/062/d.rb | UTF-8 | 2,661 | 3.515625 | 4 | [] | no_license | class PriorityQueue
attr_accessor :data
def initialize(arr=[])
@data = arr
end
def push(e)
@data.push(e)
current_index = @data.size-1
parent_index = parent(current_index)
while current_index > 0 && @data[parent_index] > @data[current_index]
@data[current_index] = @data[parent_index]
@data[parent_index] = e
current_index = parent_index
parent_index = parent(current_index)
end
end
def pop
ret = @data.first
last = @data.last
current_index = 0
while have_child?(current_index)
li = left_child_index(current_index)
ri = right_child_index(current_index)
ni = li
ni = ri if ri < @data.size && @data[ri] < @data[li]
break if @data[ni] >= last
@data[current_index] = @data[ni]
current_index = ni
end
@data[current_index] = last
@data.pop
ret
end
def size
@data.length
end
def parent(index)
(index-1)/2
end
def left_child_index(index)
2*index+1
end
def right_child_index(index)
2*index+2
end
def have_child?(index)
left_child_index(index) < @data.size
end
end
class BigPQ < PriorityQueue
def push(e)
@data.push(e)
current_index = @data.size-1
parent_index = parent(current_index)
while current_index > 0 && @data[parent_index] < @data[current_index]
@data[current_index] = @data[parent_index]
@data[parent_index] = e
current_index = parent_index
parent_index = parent(current_index)
end
end
def pop
ret = @data.first
last = @data.last
current_index = 0
while have_child?(current_index)
li = left_child_index(current_index)
ri = right_child_index(current_index)
ni = li
ni = ri if ri < @data.size && @data[ri] > @data[li]
break if @data[ni] <= last
@data[current_index] = @data[ni]
current_index = ni
end
@data[current_index] = last
@data.pop
ret
end
end
n=gets.strip.to_i
aa = gets.strip.split.map(&:to_i)
bpq = BigPQ.new
pq = PriorityQueue.new
n.times do |i|
pq.push(aa[i])
bpq.push(aa[3*n-1-i])
end
left_score = pq.data.inject(:+)
left_scores = [left_score]
right_score = bpq.data.inject(:+)
right_scores = [right_score]
n.times do |i|
c = aa[n+i]
if c >= pq.data.first
pq.push(c)
left_score -= pq.pop
left_score += c
end
left_scores.push(left_score)
c = aa[2*n-1-i]
if c <= bpq.data.first
bpq.push(c)
right_score -= bpq.pop
right_score += c
end
right_scores.unshift(right_score)
end
result = left_scores.zip(right_scores).map {|l, r| l-r }.max
#p left_scores
#p right_scores
p result
| true |
8457af77c1e153d8c9192a14d7f6f12e3c9a54b8 | Ruby | frankzinner/RubyScripts | /tests/Haushaltskonto_test.rb | UTF-8 | 997 | 2.90625 | 3 | [] | no_license | require "Haushaltskonto"
require "test/unit"
class HaushaltskontoTest < Test::Unit::TestCase
@filename
@instance
def setup
#@filename = File.expand_path('~/Projects/RubyScripts/tests/TESTFILE.CVS')
@filename = File.expand_path('~/Projects/RubyScripts/tests/Umsatzanzeige.csv')
@instance = Haushaltskonto.new(@filename)
end
def teardown
@instance = nil
end
def test_can_create_class_Haushaltskonto
assert_not_nil(Haushaltskonto.new, "Klasse Haushaltskonto kann erzeugt werden")
end
def test_can_create_class_Haushaltskonto_with_filename
@instance = Haushaltskonto.new(@filename)
assert_equal(@filename, @instance.getFilename, "Übergebener Parameter stimmt überein")
end
def test_can_load_file
assert_match(/"Umsatzanzeige vom ";"27.01.2013 15:46"/, @instance.load)
assert_match("", Haushaltskonto.new.load)
end
def test_can_read_header
header = @instance.readDateHeader
assert_match(/Umsatzanzeige vom \d\d\.\d\d\.\d\d\d\d \d\d:\d\d/, header)
end
end
| true |
25593a27f0bcc79b26a0536c42514e31991a179d | Ruby | Yuuki-oomaru/ruby-practice | /2-8.rb | UTF-8 | 170 | 3.125 | 3 | [] | no_license | puts "計算をはじめます"
puts "2つの数字を入力してください"
a=gets.to_i
b=gets.to_i
puts "出力します"
puts "a*b=#{a*b}"
puts "終了します"
| true |
51979b9ee2c7a0138d011a3797b130da94d2227a | Ruby | gaofeiii/Dino.game-server | /app/models/god_const.rb | UTF-8 | 639 | 3.015625 | 3 | [] | no_license | module GodConst
module ClassMethods
@@hashes = {
:intelligence => 1, # 智力之神
:business => 2, # 商业之神
:war => 3, # 战争之神
:argriculture => 4 # 农业之神
}
@@gods = {
1 => {
:name => :god_of_argriculture,
},
2 => {
:name => :god_of_business,
},
3 => {
:name => :god_of_war,
},
4 => {
:name => :god_of_intelligence,
},
}
def hashes
@@hashes
end
def const
@@gods
end
end
module InstanceMethods
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
| true |
683192bbf3f6a715d1fdba2c40afb9e79c09874e | Ruby | pikajude/phl | /app/models/scheduled_attendance.rb | UTF-8 | 441 | 2.546875 | 3 | [] | no_license | class ScheduledAttendance < ActiveRecord::Base
belongs_to :player
belongs_to :game
validates_presence_of :player
validates_presence_of :game
validate :correct_team
private
def correct_team
unless self.game.away_team.players.where(id: self.player_id).exists? ||
self.game.home_team.players.where(id: self.player_id).exists?
errors.add(:player, "must belong to one of the selected teams")
end
end
end
| true |
9db03a526995234d35891f315f1c4512cc3a8e09 | Ruby | tongxm520/ruby-code | /basic/lib/verifier.rb | UTF-8 | 626 | 3.84375 | 4 | [] | no_license | class Verifier
def initialize(*words)
@words=words
@count=0
end
def verified?(string)
for e in @words
while(string[e])
@count+=1
return true
end
end
return false
end
def match_count
@count
end
end
v=Verifier.new "apple","orange"
puts v.verified?("i got an apple this morning") # => true
puts v.verified?("the oranges are delicious") #=> true
puts v.verified?("how about the banana?") #=>false
puts v.match_count #=>2
v2=Verifier.new("dog","cat")
puts v2.verified?("there is a cat")
puts v2.verified?("there are two dogs")
puts v2.match_count
| true |
1482f9b680edf169b0e68fda768b2fd9c412a493 | Ruby | nnakagaki/code-eval | /moderate/trailing_string.rb | UTF-8 | 165 | 3.109375 | 3 | [] | no_license | File.open(ARGV[0]).each_line do |line|
line.chomp!
str, substr = line.split(",")
if str[str.length - substr.length..-1] == substr
puts 1
else
puts 0
end
end | true |
549eb986f49b4cb5fd2aa48707421f6c5c25cc7b | Ruby | wwilco/wdiall | /w07/d01/sina/server.rb | UTF-8 | 5,073 | 3.09375 | 3 | [] | no_license | require 'sinatra'
get '/coin_toss' do
string = "<h1>heads or tails</h1>"
erb :index, locals:{msg: string}
end
get '/dice_roll' do
arr = [1,2,3,4,5,6].sample
string = "<h1>#{arr}</h1>"
erb :index, locals:{msg: string}
end
get '/magic8ball/will%20it%20snow%20tomorrow' do
arr = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it yes",
"Most likely",
"Outlook good",
"Yes", "Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
].sample
string = "<h1>#{arr}</h1>"
erb :index, locals:{msg: string}
end
get '/rps/:id' do
rps = ['rock', 'paper', 'scissor'].sample
# string = "<h2> computer chooses #{rps}"
path = params[:id]
if path == 'rock'
if rps == 'paper'
string2 = "<p>computer chooses paper. you lose</p>"
erb :index, locals:{msg: string2}
elsif rps == 'scissor'
string2 = "<p>computer chooses scissor. you win!</p>"
erb :index, locals:{msg: string2}
else
string2 = "<p>computer also picked rock. you tie</p>"
erb :index, locals:{msg: string2}
end
end
if path == 'paper'
if rps == 'scissor'
string2 = "<p>computer chooses scissor. you lose</p>"
erb :index, locals:{msg: string2}
elsif rps == 'rock'
string2 = "<p>computer chooses rock. you win!</p>"
erb :index, locals:{msg: string2}
else
string2 = "<p>computer also picked paper. you tie</p>"
erb :index, locals:{msg: string2}
end
end
if path == 'scissor'
if rps == 'paper'
string2 = "<p>computer chooses paper. you lose</p>"
erb :index, locals:{msg: string2}
elsif rps == 'rock'
string2 = "<p>computer chooses rock. you win!</p>"
erb :index, locals:{msg: string2}
else
string2 = "<p>computer also picked scissor. you tie</p>"
erb :index, locals:{msg: string2}
end
end
else
string2 = "<p>must choose rock, paper or scissor</p>"
erb :index, locals:{msg: string2}
end
end
# if path == 'rock' && rps == 'scissor'
# string2 = "<p>you win!</p>"
# erb :index, locals:{msg: string2}
# end
#
# if path == 'rock' && rps == 'rock'
# string2 = "<p>you tie</p>"
# erb :index, locals:{msg: string2}
# end
# end
# #sams method
# get '/tortilla/rice' do
# string = "<h1>mmmmmmmmm</h1>"
# erb :index, locals:{msg: string}
# end
# get '/tortilla/guac' do
# string = "<h2>ahhh</h2>"
# erb :index, locals:{msg: string}
# end
# get '/tortilla/:id' do
# string = "<p> Well, #{params[:id]} is good on a tortilla too</p>"
# erb :index, locals:{msg: string}
# end
# get '*' do
# string = "<h3>sorry we only serve burritos</h3>"
# erb :index, locals:{msg: string}
# end
# require 'sinatra' #just like js, but no var!
#
# get '/tortilla/rice' do
# erb(:index, locals:{name: "MMMMM"})
# end
#
# get '/tortilla/guac' do
# erb(:index, locals:{name: "AHHHHH"})
# end
# #sinatra uses port 4567
# require 'sinatra'
#
# get '/:id' do
#
# erb(:index, locals:{text: "Sorry, we only serve burritos here!"})
#
# end
#
# get '/tortilla/:id' do
#
# path = params[:id]
#
# if path == "rice"
# erb(:index, locals:{text: "MMMMM"})
# elsif path == "guac"
# erb(:index, locals:{text: "AHHH!"})
# else
# erb(:index, locals:{text: "Tortilla", p: "Well, #{path} is good on a tortilla, too."})
# end
#
# end
# # davids method
# require 'sinatra'
#
# get '/tortilla/:id' do
# path = (params[:id])
#
# if path == "rice"
# message = "<h1> MMMMMM </h1>"
# erb(:index, locals:{text: message})
# elsif path == "guac"
# message = "<h2> yessss </h2>"
# erb(:index, locals:{text: message})
# end
# end
# require 'sinatra'
#
# get '/' do # http://localhost:4567/
# erb(:index, locals:{text:"Willyum"}) #takes 2 arguments. index: gets the file, locals: a variable within the erb file
# end
#
# my_name = "Willyum" #using a variable
# get '/' do #
# erb(:index, locals: {name:my_name}) #takes 2 arguments. index: gets the file, locals: a variable within the erb file
# end
#
# get '/goodbye' do # http://localhost:4567/goodbye
# not_a_name = "goodbye"
# erb(:index, locals:{name:not_a_name})
# end
#
# # get ':id' do #http://localhost:4567/whateva, this prints 'whateva' on the screen
# # path = (params[:id])
# # erb(:index, locals:{name:path})
# # end
#
# get '/google' do
# str = "<a target=_blank href='http://google.com'>google</a>"
# erb(:index, locals:{name:str})
# end
#
# get '/:id' do #can perform operations within the path
# path = (params[:id]) #params is used when somethign happens sinatra is not prepared for
# pathnum = path.length
# counter = 0
# repeated = ''
# while counter < pathnum do
# repeated += path
# counter += 1
# end
# puts params
# erb(:index, locals:{name:repeated})
# end
| true |
21e2e43f14ac944154fb60b4c5cc6ea0460c1437 | Ruby | lborner/calculators | /laby.rb | UTF-8 | 242 | 3.4375 | 3 | [] | no_license |
puts "What is the length of the base of your triangle"
number = gets.chomp.to_f
puts "What is the height of the triangle?"
service = gets.chomp.to_f
totalarea = number*service/2
puts "The area of the triangle is " + totalarea.to_s
| true |
241cd5898102a921aa439064565a645a8b3f2f5b | Ruby | autogrow/RedisAlerting | /lib/redis_alerting/config.rb | UTF-8 | 1,199 | 2.671875 | 3 | [
"MIT"
] | permissive | module RedisAlerting
class Config
def initialize(opts)
@config = opts
parse_config
end
def to_hash
@config
end
private
def parse_config
raise ArgumentError, "No config file specified" if @config[:config].nil?
# automatically use a relative config path
if @config[:config][0] != "/"
@config[:config] = File.expand_path(@config[:config], @config[:pwd])
end
@config[:faye_url] = @config[:"faye-url"] || @config[:faye_url]
raise ArgumentError, "Invalid config file: #{@config[:config]}" unless File.exists? @config[:config]
yaml = YAML.load_file(@config[:config])
@config.merge!(yaml)
@config[:log_level] = parse_log_level
raise ArgumentError, "Incomplete configuration" unless valid_config?
end
def parse_log_level
return Logger::UNKNOWN if @config[:log].nil? or @config[:log] == false
case @config[:log]
when "error"
Logger::ERROR
when "debug"
Logger::DEBUG
else
Logger::INFO
end
end
# TODO: check we have all the needed options
def valid_config?
true
end
end
end | true |
44977518c83a4d422688c0ce78d77379a6859df7 | Ruby | jthoenes/code_slide_generator | /lib/power_point/text_range.rb | UTF-8 | 1,002 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | module PowerPoint
class TextRange
def initialize shape, text_range
@shape, @text_range = shape, text_range
end
def text
begin
return @text_range.Text
rescue
return ""
end
end
def add_text text
start_position = @text_range.Length+1
@text_range.InsertAfter text
TextRange.new(@shape, @text_range.Characters(start_position, text.length))
end
def clear!
@text_range.Text = ""
end
def reset_format!
unbold!
black!
end
def font_family=(font_family)
@text_range.Font.Name = font_family
end
def font_size=(font_size)
@text_range.Font.Size = font_size
end
def bold!
@text_range.Font.Bold = 1
end
def unbold!
@text_range.Font.Bold = 0
end
def black!
@text_range.Font.Color.RGB = "000000".hex
end
def white!
@text_range.Font.Color.RGB = @shape.background_color
end
def red!
@text_range.Font.Color.RGB = "0000D2".hex
end
end
end | true |
f22a166dcefefad488cb117872ebd2285e600790 | Ruby | gstewart88/Hotels | /methods.rb | UTF-8 | 1,369 | 4.1875 | 4 | [] | no_license | def menu
puts `clear`
puts "*** Poor Hotels - Our hotels are just the worst ***"
puts
puts
puts "1. Check In"
puts "2. Check Out"
puts "3. Lists all Rooms"
puts "4. List all Guests"
puts "5. Create Room"
puts "6. Create Guest"
puts "7. Occupancy Report"
# puts "8. List Hotels"
puts
puts "0. Quit"
puts
print "--> "
gets.to_i
end
def list_moved_in(hotel)
puts hotel.list_moved_in
end
def list_guests(hotel)
puts hotel.list_guests
end
def list_rooms(hotel)
puts hotel.list_rooms
end
# def list_hotels(chain)
# puts chain.list_hotels
# end
def create_room(hotel)
print "Type: "
title = gets.chomp
print "Room Type: "
room_type = gets.chomp
room = Room.new(title: title)
hotel.add_room(room)
end
def create_guest(hotel)
print "Name: "
name = gets.chomp
guest = guest.new(name: name)
chain.add_guest(guest)
end
def check_in(hotel)
print "Which guest is going to check in (by name): "
guest_name = gets.chomp
puts
puts hotel.list_rooms
puts
print "Choose from available room types (by name): "
room_title = gets.chomp
hotel.check_in(guest_name, room_title)
end
def check_out(hotel)
print "Which guest is going to check out (by name): "
guest_name = gets.chomp
guest = hotel.guests[guest_name]
room_title = guest.list_rooms
hotel.move_out(guest_name, room_title)
end | true |
e56123ebf08fa587eaa8787f82fe7d3d06f382f1 | Ruby | HarrisonMc555/euler | /euler51.rb | UTF-8 | 3,867 | 3.59375 | 4 | [] | no_license | #!/usr/bin/env ruby
require 'prime'
module Enumerable
def this_many? n, &block
count = 0
self.each { |x|
if block.call x
count += 1
return false if count > n
end
}
return count == n
end
def this_many_range? range, &block
count = 0
e = self.each
been_in_range = false
loop do
if block.call e.next
count += 1
if range.include? count
been_in_range = true
elsif been_in_range
return false
end
end
end
return range.include? count
end
end
# testing this_many? and this_many_range?
if false
puts [1,2,3].this_many?(1) { |x| x < 3 }
puts [1,2,3].this_many?(2) { |x| x < 3 }
puts [1,2,3].this_many?(3) { |x| x < 3 }
puts '[1,2,3](1..2) { |x| x < 3 }'
p [1,2,3].this_many_range?(1..2) { |x| x < 3 }
p '[1,2,3](1...2) { |x| x < 3 }'
p [1,2,3].this_many_range?(1...2) { |x| x < 3 }
p '[1,2,3](1..3) { |x| x < 3 }'
p [1,2,3].this_many_range?(1..3) { |x| x < 3 }
p '[1,2,3](3..4) { |x| x < 3 }'
p [1,2,3].this_many_range?(3..4) { |x| x < 3 }
p '[1,2,3](3..4) { |x| x < 3 }'
p [1,2,3].this_many_range?(2..2) { |x| x < 3 }
p '[1,2,3](3..4) { |x| x < 3 }'
p [1,2,3].this_many_range?(2...2) { |x| x < 3 }
end
def valid_prime_digits(first, last)
if last
['1','3','5','7','9']
elsif first
('1'..'9')
else
('0'..'9')
end
end
def prime_digit_families(num_digits, num_same, first=false)
# offset = "\t"*(2-num_digits)
# puts "#{offset}prime_digit_families(#{num_digits}, #{num_same}, #{first})"
Enumerator.new do |enum|
# base case, 0 digits left
if num_digits == 0
enum.yield ""
else
# only add a non-same digit if we have extra digits to use (if num_digits
# == num_same then the rest of the digits need to be the same).
if num_same < num_digits
# if first
# my_digits = ('1'..'9')
# else
# my_digits = ('0'..'9')
# end
digits = valid_prime_digits(first, num_digits == 1)
# puts "#{offset}using digits #{my_digits}"
digits.each do |digit|
prime_digit_families(num_digits - 1, num_same).each { |family_str|
# puts "#{offset} digit: '#{digit}' + family_str = '#{family_str}'"
enum.yield(digit+family_str)
}
end
end
# if we have any of the 'same' digits to add, add them
if num_same > 0
# puts "#{offset}using same digit (*)"
prime_digit_families(num_digits - 1, num_same - 1).each { |family_str|
# puts "#{offset} digit: '*' + family_str = '#{family_str}'"
enum.yield('*'+family_str)
}
end
end
end
end
def nums_from_family(family_str)
digits = valid_prime_digits(family_str[0] == '*', family_str[-1] == '*')
digits.map { |digit| family_str.tr('*',digit) }
end
def family_has_n_primes?(n, family_str)
nums_from_family(family_str).this_many?(n) { |s| Prime.prime? s.to_i }
end
def first_prime_from_family(family_str)
nums_from_family(family_str).find { |s| Prime.prime? s.to_i }
end
# testing functions
if false
p prime_digit_families(3,2,true).to_a
p nums_from_family("56**3")
p family_has_n_primes?(7, "56**3")
p first_prime_from_family("56**3")
puts first_prime_from_family(
prime_digit_families(5,2,true).find { |family_str|
family_has_n_primes? 7, family_str
}
)
end
nprimes = 8
mindigits = 5
minsame = 3
(mindigits..Float::INFINITY).lazy.each do |ndigits|
# puts "#{ndigits} digits"
(minsame..ndigits).reverse_each do |nsame|
# puts "\t#{nsame} same"
family_str = prime_digit_families(ndigits,nsame,true).find { |family_str|
family_has_n_primes? nprimes, family_str
}
if family_str
puts first_prime_from_family family_str
exit
end
end
end
| true |
04fc8ce559a5e963583c34751e1a501180346891 | Ruby | stoic-coder/hetzner-k3s | /lib/hetzner/infra/ssh_key.rb | UTF-8 | 1,799 | 2.953125 | 3 | [
"MIT"
] | permissive | module Hetzner
class SSHKey
def initialize(hetzner_client:, cluster_name:)
@hetzner_client = hetzner_client
@cluster_name = cluster_name
end
def create(ssh_key_path:)
@ssh_key_path = ssh_key_path
puts
if ssh_key = find_ssh_key
puts "SSH key already exists, skipping."
puts
return ssh_key["id"]
end
puts "Creating SSH key..."
response = hetzner_client.post("/ssh_keys", ssh_key_config).body
puts "...SSH key created."
puts
JSON.parse(response)["ssh_key"]["id"]
end
def delete(ssh_key_path:)
@ssh_key_path = ssh_key_path
if ssh_key = find_ssh_key
if ssh_key["name"] == cluster_name
puts "Deleting ssh_key..."
hetzner_client.delete("/ssh_keys", ssh_key["id"])
puts "...ssh_key deleted."
else
puts "The SSH key existed before creating the cluster, so I won't delete it."
end
else
puts "SSH key no longer exists, skipping."
end
puts
end
private
attr_reader :hetzner_client, :cluster_name, :ssh_key_path
def public_key
@public_key ||= File.read(ssh_key_path).chop
end
def ssh_key_config
{
name: cluster_name,
public_key: public_key
}
end
def fingerprint
@fingerprint ||= ::SSHKey.fingerprint(public_key)
end
def find_ssh_key
key = hetzner_client.get("/ssh_keys")["ssh_keys"].detect do |ssh_key|
ssh_key["fingerprint"] == fingerprint
end
unless key
key = hetzner_client.get("/ssh_keys")["ssh_keys"].detect do |ssh_key|
ssh_key["name"] == cluster_name
end
end
key
end
end
end
| true |
96bac2c6ebec42b17acb0841abe4f823135da00b | Ruby | VIP-eDemocracy/elmo | /app/models/form_versioning_policy.rb | UTF-8 | 2,975 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | # Implements the policy about when a form's version should be upgraded.
# Any form component objects (Option, OptionSet, OptionNode, Question, Questioning) should call this class after updating.
# It will tell the appropriate Forms to upgrade their versions.
class FormVersioningPolicy
# Sets the upgrade_neccessary flag on forms where necessary.
def notify(obj, action)
forms_needing_upgrade(obj, action).each do |f|
f.reload
raise "standard forms should not be subject to version policy" if f.standardizable? && f.is_standard?
f.flag_for_upgrade!
end
end
private
# Returns a list of forms needing upgrade based on the given object and action.
# If the list is empty, it means that no form's version will have to be updated.
def forms_needing_upgrade(obj, action)
case obj.class.name
when "Option"
case action
when :destroy
# changing an option is fine, but destroying an option is a trigger
return obj.forms
end
when "OptionSet"
case action
when :update
# changing the option order is a trigger if the form is smsable
return obj.forms.select(&:smsable?) if obj.ranks_changed?
end
when "OptionNode"
# If option_set is nil, it means the option set is just getting created, so no need to go any further.
return [] if obj.option_set.nil?
case action
when :create
# adding an option to an option set is a trigger for smsable forms
return obj.option_set.forms.select(&:smsable?)
when :destroy
# Removing an option from an option set is always trigger.
return obj.option_set.forms
end
when "Questioning"
case action
when :create
# creating a new required question is a trigger
return [obj.form] if obj.required?
when :update
# if required is changed, it's a trigger
# changing question rank is a trigger if form is smsable
# changing question visibility is a trigger if changed to visible (not hidden)
return [obj.form] if obj.required_changed? || obj.rank_changed? && obj.form.smsable? || obj.hidden_changed? && !obj.hidden?
end
when "Condition"
case action
when :create
# creating a condition is a trigger if question is required
return [obj.form] if obj.questioning.required?
when :update
# changing condition is a trigger if question is required
return [obj.form] if obj.changed? && obj.questioning.required?
when :destroy
# destroying a condition is a trigger if question is required
return [obj.form] if obj.questioning.required?
end
when "Question"
case action
when :update
# changing question type, option set, or constraints is a trigger
return obj.forms if obj.qtype_name_changed? || obj.option_set_id_changed? || obj.constraint_changed?
end
end
return []
end
end | true |
7b8e76a132c3fa8443502f3ea8a92911f26260c7 | Ruby | sunny-b/backend_practice | /Programming_Foundations/Lesson_2_SmProg/calculator.rb | UTF-8 | 2,126 | 4.3125 | 4 | [] | no_license | # Build a calculator that takes two numbers and an operation,
# and then displays the results.
require 'yaml'
MESSAGES = YAML.load_file('calculator_messages.yml')
def prompt(message)
Kernel.puts("=> #{message}")
end
def valid_number?(num)
num =~ /[[:digit:]]/
end
def valid_operation?(num)
(1..4).cover? num.to_i
end
def operation_to_message(op)
ans = case op
when '1'
'Adding'
when '2'
'Subtracting'
when '3'
'Multiplying'
when '4'
'Dividing'
end
return ans
end
def calculator(num1, num2, op)
result = case op
when '1'
result = num1.to_f() + num2.to_f()
when '2'
result = num1.to_f() - num2.to_f()
when '3'
result = num1.to_f() * num2.to_f()
when '4'
result = num1.to_f() / num2.to_f()
end
prompt("Your result is #{result}")
end
num1 = nil
num2 = nil
operation = nil
prompt(MESSAGES['welcome'])
name = ""
loop do
name = Kernel.gets().chomp()
if name.empty?()
prompt(MESSAGES['valid_name'])
else
break
end
end
prompt("Hi #{name}")
loop do
loop do
prompt(MESSAGES['give_num'])
num1 = Kernel.gets().chomp()
if valid_number?(num1)
break
else
prompt(MESSAGES['error_num'])
end
end
loop do
prompt(MESSAGES['another_num'])
num2 = Kernel.gets().chomp()
if valid_number?(num2)
break
else
prompt(MESSAGES['error_num'])
end
end
operator_prompt = <<-MSG
What operation would you like to perform?
1.) add
2.) subtract
3.) multiply
4.) divide
MSG
prompt(operator_prompt)
loop do
operation = Kernel.gets().chomp()
if valid_operation?(operation)
break
else
prompt(MESSAGES['error_op'])
end
end
prompt("#{operation_to_message(operation)} #{num1} and #{num2}...")
calculator(num1, num2, operation)
Kernel.puts()
prompt(MESSAGES['again'])
answer = Kernel.gets().chomp()
break unless answer.downcase.start_with?('y')
Kernel.puts()
end
prompt(MESSAGES['thanks'])
| true |
bafc4ed2023251d5bd03d7427de9d2e3684f14f3 | Ruby | edmondtam1/ruby-small-problems | /advanced_ruby/challenges/medium_1/protein_translation/protein_translation.rb | UTF-8 | 880 | 3.203125 | 3 | [] | no_license | class InvalidCodonError < StandardError
end
class Translation
CODON_MAPPING = {
['AUG'] => 'Methionine',
['UUU', 'UUC'] => 'Phenylalanine',
['UUA', 'UUG'] => 'Leucine',
['UCU', 'UCC', 'UCA', 'UCG'] => 'Serine',
['UAU', 'UAC'] => 'Tyrosine',
['UGU', 'UGC'] => 'Cysteine',
['UGG'] => 'Tryptophan',
['UAA', 'UAG', 'UGA'] => 'STOP'
}
def self.of_codon(codon)
CODON_MAPPING.each do |type, acid|
return acid if type.include?(codon)
end
false
end
def self.of_rna(rna)
result = []
rna.scan(/.{3}/).each do |codon|
translation = of_codon(codon)
raise InvalidCodonError if translation == false
return result if translation == 'STOP'
result << translation
end
result
end
end
# puts Translation.of_codon('UUU')
# puts Translation.of_rna('AUGUUUUAA')
# puts Translation.of_rna('CARROT')
| true |
17bd2bdbed501b0fbb3c4ac5552940d4908ecf48 | Ruby | jan-czekawski/introduction-to-programming-exercises | /more/mongo/mongoid/module_3/41_pluck_scope.rb | UTF-8 | 2,114 | 3.1875 | 3 | [] | no_license | # pluck => will get all the non nil values for the provided field
Movie.all.pluck(:title)
# entire doc is not returned; selected fields at the db level
# using a projection is retrieved
# entire doc is returned, grab 2 fields, rest is discarded
Movie.where(rated: "PG").map { |movie| [movie.title, movie.release_date]}
# projection => only 2 fields are returned
Movie.where(rated: "PG").pluck(:title, :release_date)
# using lt with a string
Movie.where(:title.lt => "A").pluck(:title)
# scope => provides good way to reuse common criteria with more business
# domain style syntax
# named scopes => are simply criteria defined at class load that are referenced
# by a provided name
class Movie
# (...)
field :year, type: Integer
scope :current, ->{ where(:year.gt => Date.current.year - 5) }
end
Movie.current.where(rated: "R").pluck(:title, :year)
# can use multiple scopes
# instead of providing criteria in the query => can do it
# in the code on the db layer
# default scope => can be useful when applying same criteria
# to most queries and you want something to be there by default
class Movie
field :active, type: Boolean, default: true
end
# same criteria to most queries and something to be there by default
class Airline
include Mongoid::Document
field :name, type: String
field :active, type: Boolean, default: true
default_scope ->{ where(active: true) }
end
airlineUA = Airline.create(name: "UNITED")
airlineLH = Airline.create(name: "LUFTHANSA")
airlinePA = Airline.create(name: "PANAM", active: false)
Airline.each do |airline|
# all airlines here are active
end
Airline.all.count # => 2
# SELECT * from airlines where active = true
Airline.unscoped.all.count # => 3
# SELECT * from airlines
# OR and IN
# union with IN => second condition (AND)
Movie.where(:year.gt => 2014).in(title: ["The Martian"]).pluck(:plot)
# union with OR => or ID or title
Movie.or({id: "tt3659388"}, {title: "The Martian"}).pluck(:plot)
# works even if we make a mistake with id => title stil works => id or title
Movie.or({id: "tt3659388xxx"}, {title: "The Martian"}).pluck(:plot) | true |
2cfe9088aef27e49f3e0f16f795cc26f5be87cc4 | Ruby | Dan2552/gathering-of-scripts | /ruby/simple-rspec | UTF-8 | 5,135 | 3.1875 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'open3'
require 'pry'
require 'io/console'
class String
def black; "\e[30m#{self}\e[0m" end
def red; "\e[31m#{self}\e[0m" end
def green; "\e[32m#{self}\e[0m" end
def brown; "\e[33m#{self}\e[0m" end
def yellow; "\e[33m#{self}\e[0m" end
def blue; "\e[34m#{self}\e[0m" end
def magenta; "\e[35m#{self}\e[0m" end
def cyan; "\e[36m#{self}\e[0m" end
def gray; "\e[37m#{self}\e[0m" end
def bg_black; "\e[40m#{self}\e[0m" end
def bg_red; "\e[41m#{self}\e[0m" end
def bg_green; "\e[42m#{self}\e[0m" end
def bg_brown; "\e[43m#{self}\e[0m" end
def bg_blue; "\e[44m#{self}\e[0m" end
def bg_magenta; "\e[45m#{self}\e[0m" end
def bg_cyan; "\e[46m#{self}\e[0m" end
def bg_gray; "\e[47m#{self}\e[0m" end
def bold; "\e[1m#{self}\e[22m" end
def italic; "\e[3m#{self}\e[23m" end
def underline; "\e[4m#{self}\e[24m" end
def blink; "\e[5m#{self}\e[25m" end
def reverse_color; "\e[7m#{self}\e[27m" end
end
class Ask
def self.list(title, options)
Ask.new(title, options).list
end
def initialize(title, options)
@title = title
@options = options
@selected = 0
@last_length = 0
end
def list
print_choices
@waiting_for_input = true
while(waiting_for_input) do
handle_key_input
end
selected
end
private
attr_reader :title,
:options,
:selected,
:waiting_for_input
def handle_key_input
c = read_char
case c
when "\r"
handle_choice
when "\e[A"
handle_up
when "\e[B"
handle_down
when "\u0003" # ctrl + c
exit 0
when "A"
handle_up
when "B"
handle_down
end
end
def handle_choice
@waiting_for_input = false
end
def handle_up
@selected = selected - 1
@selected = options.count - 1 if selected < 0
print_choices
end
def handle_down
@selected = selected + 1
@selected = 0 if selected > options.count - 1
print_choices
end
def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << $stdin.read_nonblock(3) rescue nil
input << $stdin.read_nonblock(2) rescue nil
end
STDIN.echo = true
STDIN.cooked!
input
end
def print_choices
choices = options.map.with_index do |option, index|
if index == selected
"‣ #{option}".blue
else
" #{option}"
end
end
print_to_fit("#{title}\n#{choices.join("\n")}")
end
def get_line_width
`tput cols`.chomp.to_i
end
def print_to_fit(str)
print("\b" * @last_length)
width = get_line_width
lines = str.split("\n")
one_big_line = ""
lines.each do |line|
line_for_measure = line.gsub("‣", ">").gsub(/\e\[(\d+)(;\d+)*m/, "").gsub("\e[m", "")
one_big_line = one_big_line + line + (" " * (width - line_for_measure.length))
end
@last_length = one_big_line.length
print "\r" + one_big_line
end
end
class RunResult
attr_reader :stdout,
:stderr,
:exit_status
def initialize(stdout, stderr, exit_status)
@stdout = stdout
@stderr = stderr
@exit_status = exit_status
end
end
def run_command(command, args = [])
command_with_args = "#{command} #{args.join(' ')}"
stdout, stderr, status = Open3.capture3(*([command.split(" "), args].flatten))
RunResult.new(stdout || "", stderr || "", status.exitstatus)
end
def find_debugger
file_paths = Dir.glob('**/*').select { |path| File.file?(path) && path.end_with?('.rb') }
file_paths.each do |path|
text = File.read(path)
return true if text.include?("binding.pry") || text.include?("debugger") || text.include?("byebug")
end
false
end
@running = nil
if find_debugger
puts "debugger found"
begin
@running = Process.spawn("bundle exec rspec --fail-fast --color --format documentation")
Process.wait
rescue SignalException
system("kill -9 #{@running}")
exit
end
puts ""
response = Ask.list("Options", ["Do nothing", "Remove pry"])
if response == 1
system("remove-pry")
exit 0
end
exit 2
end
printf("rspec... ")
run = run_command("bundle exec rspec --fail-fast")
focused = run.stdout.include?("include {:focus=>true}")
if run.exit_status == 0
focused_output = focused ? "(focused)".yellow : ""
puts "\e[32mPass\e[0m #{focused_output}"
else
run.stdout.lines do |line|
line = line.gsub("\e[32m.", "")
# line = line.gsub("\e[31mF", "")
line = line.gsub(/^Failed examples.*/, "")
line = line.gsub(/^Finished in.*/, "")
line = line.gsub(/^Failures:.*/, "")
line = line.gsub(/^.* examples, 1 failure/, "")
# binding.pry if line.include?("rspec")
line = line.gsub(/\e\[31mrspec /, "\n\e[31msimple-rspec ")
puts line if line.gsub(/\e\[(\d+)(;\d+)*m/, "").strip.length > 0
end
end
if focused
puts ""
response = Ask.list("Options", ["Do nothing", "Remove focus"])
if response == 1
system("remove-focus")
exit 0
end
exit 2
end
| true |
a9ca5fd9c25ad008fea7d2f73bb4b0337b4653df | Ruby | MrOdnan/Ruby | /RockPaperScissors-practice | UTF-8 | 1,641 | 4.25 | 4 | [] | no_license | #!/usr/bin/env ruby
class Rps
def intro
puts "Welcome to Rock, Paper, Scissors!"
sleep(0.5)
puts "Please enter your name"
@player_name = gets.chomp
sleep(0.5)
puts "Welcome #{@player_name}!"
end
def weapon_player
sleep(0.5)
@weapon_player = gets.chomp.downcase
if !(@weapon_player == "rock" || @weapon_player == "paper" || @weapon_player == "scissors")
puts "That's not rock, paper or scissors! Try again..."
weapon_player
else
puts "You have chosen #{@weapon_player}"
end
end
def weapon_computer
sleep(1)
@weapon_computer = ["rock", "paper", "scissors"].sample(1).join(", ")
puts "Computer has chosen #{@weapon_computer}"
end
def run_game
sleep(1)
if @weapon_player == @weapon_computer
puts "It's a tie!"
elsif @weapon_player == "rock" && @weapon_computer == "scissors"
puts "Rock beats scissors - you won #{@player_name}!"
elsif @weapon_player == "scissors" && @weapon_computer == "paper"
puts "Scissors beats paper - you won #{@player_name}!"
elsif @weapon_player == "paper" && @weapon_computer == "rock"
puts "Paper beats rock - you won #{@player_name}!"
else
puts "Unlucky #{@player_name}! You lost!"
end
end
def play_again?
sleep(1)
puts "Would you like to play again?"
answer = gets.chomp.downcase
if answer == "yes"
start
elsif answer == "no"
puts "Thanks for playing #{@player_name}!"
else
puts "YES or NO?"
play_again?
end
end
end
def start
game = Rps.new
game.intro
puts "Choose your weapon! Rock, paper or scissors?"
game.weapon_player
game.weapon_computer
game.run_game
game.play_again?
end
start
| true |
a4fd2534815a763ba7ef62083752cc1022dad298 | Ruby | hanqingchen15/Algorithms | /Binary Search/findPeakElement.rb | UTF-8 | 308 | 3.375 | 3 | [] | no_license | def find_peak_element(nums)
left = 0
right = nums.length - 1
while left <= right
return left if left == right
mid = left + (right - left) / 2
if nums[mid] < nums[mid + 1]
left = mid + 1
else
right = mid
end
end
return -1
end | true |
c42e1ab8ac15e93312d130fabad5d671b87d72db | Ruby | ketan37dm/marvelor | /lib/marvelor/api/character_info.rb | UTF-8 | 822 | 2.53125 | 3 | [
"MIT"
] | permissive | module Marvelor
module API
class CharacterInfo < BaseInfo
attr_accessor :options
PER_PAGE = 30
BASE_URL = '/v1/public/characters'
def initialize(options = {})
@options = options
end
def fetch_response
self.class.get(url, params)
rescue => e
{
error_class: e.class.name,
message: e.message
}
end
private
def params
options.merge!(pagination_params)
{ query: options }
end
def pagination_params
params = { limit: options[:limit] || PER_PAGE }
params.merge!({ offset: options[:offset] }) if options[:offset]
params
end
def url
[
BASE_URL,
options[:id]
].compact.join('/')
end
end
end
end
| true |
ae720a6e76959d95125d2f68b39ee41330a9b60f | Ruby | VladimirGarciaM/POO_TF_V01 | /TF/model/servicio.rb | UTF-8 | 250 | 2.796875 | 3 | [] | no_license | class Servicio
attr_accessor :codigo, :nombre, :residente, :estado, :mes
def initialize(codigo, nombre, residente, estado, mes)
@codigo, @nombre, @residente, @estado, @mes = codigo, nombre, residente, estado, mes
end
def pago
end
end | true |
ccbafeac76543ac24a27803e92c36f671bcd76af | Ruby | DamirSvrtan/noodles | /lib/noodles/environment.rb | UTF-8 | 738 | 2.640625 | 3 | [
"MIT"
] | permissive | module Noodles
module Environment
class << self
def development?
environment.to_s == 'development'
end
def production?
environment.to_s == 'production'
end
def test?
environment.to_s == 'test'
end
def environment?
environment
end
def to_s
environment
end
def to_sym
environment.to_sym
end
def ==(other)
case other
when String
environment.to_s == other
when Symbol
environment.to_sym == other
else
super
end
end
private
def environment
ENV['RACK_ENV'] || 'development'
end
end
end
end | true |
05b3de644fbe73e8c5617308ff91014ef86cd036 | Ruby | LiliFelsen/ttt-10-current-player-bootcamp-prep-000 | /lib/current_player.rb | UTF-8 | 183 | 3.109375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def turn_count(board)
count = 0
board.each do |move|
if move == "X" || move == "O"
count += 1
end
end
count
end
def current_player(board)
turn_count(board).even? ? "X" : "O"
end
| true |
711a9ea32acbe5d79034be2aa357cffda54c420c | Ruby | saifulAbu/ProgrammingRuby | /24/dynamic-class.rb | UTF-8 | 223 | 3.515625 | 4 | [] | no_license | Person = Struct.new(:name, :address, :likes)
class Person
def to_s
"#{self.name} lives in #{self.address} and likes #{self.likes}"
end
end
dave = Person.new("dave", "tx")
dave.likes = "programming languages"
puts dave
| true |
9055fcdd1c5dd1d5770a28f5533c1226b5823088 | Ruby | SajjadAhmad14/Enumerables | /enum.rb | UTF-8 | 4,305 | 2.828125 | 3 | [] | no_license | # rubocop:disable Metrics/ModuleLength
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/PerceivedComplexity
module Enumerable
def my_each
return to_enum(:my_each) unless block_given?
size.times do |x|
yield to_a[x]
end
self
end
def my_each_with_index
return to_enum(:my_each_with_index) unless block_given?
j = 0
size.times do |x|
yield to_a[x], j
j += 1
end
self
end
def my_select
return to_enum(:my_select) unless block_given?
if self.class == Hash
size.times do |x|
to_a[x] if yield to_a[x]
end
self
else
n = []
size.times do |x|
n.push(to_a[x]) if yield to_a[x]
end
n
end
end
def my_all?(pattern = nil)
if block_given? == false && pattern.nil? == true
to_a.size.times do |x|
return false if to_a[x] == false || to_a[x].nil?
end
return true
end
if pattern.nil?
size.times do |x|
return false unless yield to_a[x]
end
elsif pattern.class == Regexp
to_a.size.times do |x|
return false if to_a[x].is_a?(String) && !pattern.match(to_a[x])
end
elsif pattern.class == Class
to_a.size.times do |x|
return false unless to_a[x].is_a?(pattern)
end
else
to_a.size.times do |x|
return false if to_a[x] != pattern
end
end
true
end
def my_any?(pattern = nil)
if block_given? == false && pattern.nil? == true
to_a.size.times do |x|
return true unless to_a[x] == false || to_a[x].nil?
end
return false
end
if pattern.nil?
to_a.size.times do |x|
return true if yield to_a[x]
end
elsif pattern.class == Regexp
to_a.size.times do |x|
return true if to_a[x].is_a?(String) && pattern.match(to_a[x])
end
elsif pattern.class == Class
to_a.size.times do |x|
return true if to_a[x].is_a?(pattern)
end
else
to_a.size.times do |x|
return true if to_a[x] == pattern
end
end
false
end
def my_none?(pattern = nil)
if block_given? == false && pattern.nil? == true
to_a.size.times do |x|
return false unless to_a[x] == false || to_a[x].nil?
end
return true
end
if pattern.nil?
to_a.size.times do |x|
return false if yield to_a[x]
end
elsif pattern.class == Regexp
to_a.size.times do |x|
return false if to_a[x].is_a?(String) && pattern.match(to_a[x])
end
elsif pattern.class == Class
to_a.size.times do |x|
return false if to_a[x].is_a?(pattern)
end
else
to_a.size.times do |x|
return false if to_a[x] == pattern
end
end
true
end
def my_count(*key)
if key.length.positive?
counter = 0
size.times do |x|
counter += 1 if self[x] == key[0]
end
return counter
elsif block_given?
counter = 0
size.times do |x|
counter += 1 if yield to_a[x]
end
return counter
end
size
end
def my_map(proc = nil)
return to_enum(:my_map) unless block_given?
new_array = []
if proc.nil?
size.times do |x|
new_array.push(yield to_a[x])
end
else
size.times do |x|
new_array.push(proc.call(to_a[x]))
end
end
new_array
end
def my_inject(arg1 = nil, arg2 = nil)
if !arg1.nil? && !arg2.nil?
memo = arg1
to_a.size.times do |x|
memo = memo.send(arg2.to_s, to_a[x])
end
elsif arg1.is_a?(Numeric) && block_given?
memo = arg1
to_a.size.times do |x|
memo = yield(memo, to_a[x])
end
elsif arg1.is_a?(Symbol)
memo = to_a[0]
to_a.size.times do |x|
next if x.zero?
memo = memo.send(arg1.to_s, to_a[x])
end
else
memo = to_a[0]
to_a.size.times do |x|
next if x.zero?
memo = yield(memo, to_a[x])
end
end
memo
end
end
# rubocop:enable Metrics/ModuleLength
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/PerceivedComplexity
def multiply_els(arg)
arg.inject(:*)
end
| true |
2b42ff6b75d74aac9e6926ffc4c27deee3a2a1aa | Ruby | rvadalamudi/ruby_programing | /Ruby/string_sort.rb | UTF-8 | 215 | 3.75 | 4 | [] | no_license | def string_sort(string)
result = []
words = string.split(" ").to_a
result = words.sort_by { |x| x.length }
result.join(" ")
end
puts "enter a string : "
string = gets.chomp
op = string_sort(string)
puts "#{op}" | true |
f2709fe5007a584ab7a801cea5d2ce059851f092 | Ruby | pombredanne/ruby-deb822 | /lib/deb822/scanner.rb | UTF-8 | 1,801 | 2.9375 | 3 | [
"MIT"
] | permissive | require 'deb822'
require 'stringio'
module Deb822
# Low-level parser for deb822 documents
class Scanner
def initialize(input)
@input = input.is_a?(String) ? StringIO.new(input) : input
@in_paragraph = false
end
WS = /[ \t]/
def next_line
loop do
begin
line = @input.readline
rescue EOFError
break
end
case line
when /\A#{WS}*\Z/o
# > The paragraphs are separated by empty lines.
# > Parsers may accept lines consisting solely of U+0020 SPACE and U+0009 TAB as paragraph separators
if @in_paragraph
@in_paragraph = false
break [:paragraph_separator]
else
next
end
when /\A#/
# > Lines starting with U+0023 ‘#’, without any preceding whitespace are comments lines
break [:comment, $']
when /\A(#{FieldName::PATTERN}):#{WS}*/o
name = $1
value = $'.chomp
@in_paragraph = true
break [:field, name, value]
when /\A#{WS}\.?/o
# > The lines after the first are called continuation lines and must start with a U+0020 SPACE or a U+0009 TAB.
# > Empty lines in field values are usually escaped by representing them by a U+0020 SPACE followed
# > by a dot (U+002E ‘.’).
raise FormatError, "Unexpected continuation line: #{line.inspect}" unless @in_paragraph
break [:continuation, $']
else
raise FormatError, "Ill-formed line: #{line.inspect}"
end
return nil
end
end
def each_line
return to_enum(:each_line) unless block_given?
while l = next_line
yield l
end
end
alias :lines :each_line
end
end
| true |
bc532a19dbdf5f937acedd34d4cbb3f65bcd8fd7 | Ruby | LBHackney-IT/report-a-defect | /app/presenters/report_presenter.rb | UTF-8 | 2,469 | 2.71875 | 3 | [
"MIT"
] | permissive | module ReportPresenter
attr_accessor :schemes, :report_form
def date_range
"From #{report_form.from_date} to #{report_form.to_date}"
end
def defects_by_status(text:)
defects.where(status: text)
end
def defects_by_category(category:)
trade_names = Defect::CATEGORIES[category]
defects.for_trades(trade_names)
end
def category_percentage(category:)
percentage_for(
number: Float(defects_by_category(category: category).count),
total: Float(defects.count)
)
end
def priority_percentage(priority:)
percentage_for(
number: Float(defects_completed_on_time(priority: priority).count),
total: Float(defects_by_priority(priority: priority).count)
)
end
def due_defects_by_priority(priority:)
defects = defects_by_priority(priority: priority)
defects.open.where('target_completion_date >= ?', Date.current)
end
def overdue_defects_by_priority(priority:)
(
defects_closed_late(priority: priority) +
defects_still_open_and_overdue(priority: priority) +
closed_defects_with_no_completion_date(priority: priority)
).uniq
end
def defects_completed_on_time(priority:)
closed_defects(priority: priority).select do |closed_defect|
next if closed_defect.actual_completion_date.nil?
closed_defect.actual_completion_date <= closed_defect.target_completion_date
end
end
private
def percentage_for(number:, total:)
return '0.0%' if number.zero? || total.zero?
percentage = (number / total) * 100
"#{percentage.round(2)}%"
end
def closed_defects(priority:)
defects_by_priority(priority: priority).closed
end
def defects_closed_late(priority:)
defects = defects_by_priority(priority: priority)
defects.closed.where('target_completion_date < actual_completion_date')
end
# This is a catch-all, as some defects may not have a completion date due to
# the hacky way in which they are marked as closed - we have no way of telling whether
# they were completed on time, so this should make any data inconsistencies obvious
# for the team to fix
def closed_defects_with_no_completion_date(priority:)
defects = defects_by_priority(priority: priority)
defects.closed.where(actual_completion_date: nil)
end
def defects_still_open_and_overdue(priority:)
defects = defects_by_priority(priority: priority)
defects.open.where('target_completion_date < ?', Date.current)
end
end
| true |
c8d7b7322ebb1d754edd6bd04db3329cb9149596 | Ruby | bjoernalbers/faxomat | /spec/validators/fax_validator_spec.rb | UTF-8 | 1,096 | 2.8125 | 3 | [
"MIT"
] | permissive | describe FaxValidator do
let(:subject) do
class SampleModel
include ActiveModel::Model
attr_accessor :fax_number
validates :fax_number,
fax: true # This enables the FaxValidator.
end
SampleModel.new
end
it 'validates minimum length' do
subject.fax_number = '0123456'
expect(subject).to be_invalid
expect(subject.errors[:fax_number]).to be_present
subject.fax_number = '01234567'
expect(subject).to be_valid
end
it 'validates excactly one leading zero' do
%w(123456789 00123456789).each do |fax_number|
subject.fax_number = fax_number
expect(subject).to be_invalid
expect(subject.errors[:fax_number]).to be_present
end
end
it 'adds a nice error message' do
subject.fax_number = '0123456'
expect(subject).to be_invalid
expect(subject.errors[:fax_number]).
to include('ist keine gültige nationale Faxnummer mit Vorwahl')
end
it 'does not validate presence' do
[nil, ''].each do |attr|
subject.fax_number = attr
expect(subject).to be_valid
end
end
end
| true |
66ff5a94bee4a43f140f7a0fd90771c740b34e1e | Ruby | floatbox/eap-ota | /lib/layered_exchange.rb | UTF-8 | 3,447 | 3 | 3 | [] | no_license | # example
# date = Date.today
# ExchangeWithFallback.new(
# SynchronizedRates.new(
# DoubleConvertThrough.new('RUB',
# InverseRatesFor.new( {from: 'RUB'},
# RatesUpdatedWithFallback.new(
# ActiveRecordRates.new(CurrencyRate.where(date: date, bank: 'cbr')),
# LazyRates.new { CentralBankOfRussia.new.update_rates(date) } )))))
module LayeredExchange
# наследуем ради exchange_with и прочего.
class ExchangeWithFallback < Money::Bank::VariableExchange
def initialize(fallback_rates, &block)
@fallback_rates = fallback_rates
super &block
end
attr_reader :fallback_rates
def get_rate(from, to)
unless rate = super
if rate = fallback_rates.get_rate(Money::Currency.wrap(from), Money::Currency.wrap(to))
add_rate(from, to, rate)
end
end
rate
end
end
class RatesUpdatedWithFallback
def initialize(main_rates, fallback_rates)
@main_rates = main_rates
@fallback_rates = fallback_rates
end
def get_rate(from, to)
unless rate = @main_rates.get_rate(from, to)
if rate = @fallback_rates.get_rate(from, to)
@main_rates.add_rate(from, to, rate)
end
end
rate
end
# нужен ли?
def add_rate(from, to, rate)
@main_rates.add_rate(from, to, rate)
end
end
class LazyRates
def initialize(&expensive_setup)
@expensive_setup = expensive_setup
end
def get_rate(from, to)
rates.get_rate(from, to)
end
def add_rate(from, to)
rates.add_rate(from, to)
end
def rates
@rates ||= @expensive_setup.call
end
private :rates
end
class ActiveRecordRates
def initialize(scope_or_class)
@scope = scope_or_class
end
def get_rate(from, to)
if rec = @scope.where(from: from.to_s, to: to.to_s).first
rec.rate
end
end
def add_rate(from, to, rate)
rec = @scope.where(from: from.to_s, to: to.to_s).first_or_initialize
rec.update_attributes rate: rate
rate
end
end
# read only
class InverseRatesFor
def initialize(to_or_from, rates)
if to_or_from[:from]
@reverse_from = Money::Currency.wrap(to_or_from[:from])
elsif to_or_from[:to]
@reverse_to = Money::Currency.wrap(to_or_from[:to])
end
@rates = rates
end
def get_rate(from, to)
if @reverse_from == from || @reverse_to == to
if rate = @rates.get_rate(to, from)
1 / rate
end
else
@rates.get_rate(from, to)
end
end
end
# read only
class DoubleConversionThrough
def initialize(base, rates)
@base = Money::Currency.wrap(base)
@rates = rates
end
def get_rate(from, to)
if from != @base && to != @base
rate1 = @rates.get_rate(from, @base) or return
rate2 = @rates.get_rate(@base, to) or return
rate1 * rate2
else
@rates.get_rate(from, to)
end
end
end
# каргокульт. для многозадачности!
class SynchronizedRates
def initialize(rates)
@mutex = Mutex.new
@rates = rates
end
def get_rate(from, to)
@mutex.synchronize { @rates.get_rate(from, to) }
end
def add_rate(from, to, rate)
@mutex.synchronize { @rates.add_rate(from, to, rate) }
end
end
end
| true |
64bb4f7a1fe63b96cd7d6971a49b98ac503ab9b6 | Ruby | gchelms/rumi-ruby | /lib/dictionary.rb | UTF-8 | 433 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'marky_markov'
markov = MarkyMarkov::Dictionary.new('dictionary')
markov.parse_file "there_is_a_way.txt"
markov.parse_file "the_breeze_at_dawn.txt"
markov.parse_file "not_intrigued_with_evening.txt"
markov.parse_file "moving_water.txt"
markov.parse_file "out_beyond_ideas.txt"
markov.parse_file "there_is_a_community_of_spirit.txt"
puts markov.generate_n_words 100
puts markov.generate_n_sentences 5
markov.save_dictionary!
| true |
7c675fadcc45062604902ebd42c43ab642f9c134 | Ruby | thechanmoon/ramda-ruby | /spec/ramda/relation_spec.rb | UTF-8 | 6,158 | 2.875 | 3 | [
"MIT",
"Ruby"
] | permissive | require 'spec_helper'
describe Ramda::Relation do
let(:r) { Ramda }
context '#equals' do
it 'from docs' do
expect(r.equals(1, 1)).to be_truthy
expect(r.equals(1, '1')).to be_falsey
expect(r.equals([1, 2, 3], [1, 2, 3])).to be_truthy
expect(r.equals({}, {})).to be_truthy
end
it 'is curried' do
expect(r.equals(1).call(1)).to be_truthy
end
end
context '#count_by' do
it 'from docs' do
letters = ['a', 'b', 'A', 'a', 'B', 'c']
expect(r.count_by(R.to_lower).call(letters)).to eq('a' => 3, 'b' => 2, 'c' => 1)
end
end
context '#difference' do
it 'from docs' do
expect(r.difference([1, 2, 3, 4], [7, 6, 5, 4, 3])).to eq([1, 2])
expect(r.difference([7, 6, 5, 4, 3], [1, 2, 3, 4])).to eq([7, 6, 5])
expect(r.difference([{ a: 1 }, { b: 2 }], [{ a: 1 }, { c: 3 }])).to eq([{ b: 2 }])
end
end
context '#difference_with' do
it 'from docs' do
cmp = ->(x, y) { x.fetch(:a) == y.fetch(:a) }
l1 = [{ a: 1, b: 1 }, { a: 2, b: 1 }, { a: 3, b: 1 }]
l2 = [{ a: 3, b: 2 }, { a: 4, b: 2 }, { a: 5, b: 2 }]
expect(r.difference_with(cmp, l1, l2)).to eq([{ a: 1, b: 1 }, { a: 2, b: 1 }])
end
end
context '#eq_by' do
it 'from docs' do
size_fn = ->(x) { x.size }
expect(r.eq_by(size_fn, ['abc'], [100])).to be_truthy
expect(r.eq_by(size_fn, [1, 2], [1])).to be_falsey
end
end
context '#gt' do
it 'from docs' do
expect(r.gt(2, 1)).to be_truthy
expect(r.gt(2, 2)).to be_falsey
expect(r.gt(2, 3)).to be_falsey
expect(r.gt('a', 'z')).to be_falsey
expect(r.gt('z', 'a')).to be_truthy
end
it 'is curried' do
expect(r.gt(2).call(1)).to be_truthy
end
end
context '#gte' do
it 'from docs' do
expect(r.gte(2, 1)).to be_truthy
expect(r.gte(2, 2)).to be_truthy
expect(r.gte(2, 3)).to be_falsey
expect(r.gte('a', 'z')).to be_falsey
expect(r.gte('z', 'a')).to be_truthy
end
it 'is curried' do
expect(r.gte(2).call(1)).to be_truthy
end
end
context '#identical' do
it 'from docs' do
o = {}
expect(R.identical(o, o)).to be_truthy
expect(R.identical(1, 1)).to be_truthy
expect(R.identical(1, '1')).to be_falsey
expect(R.identical([], [])).to be_falsey
expect(R.identical(nil, nil)).to be_truthy
end
end
context '#intersection' do
it 'from docs' do
expect(r.intersection([1, 2, 3, 4], [7, 6, 5, 4, 3])).to eq([3, 4])
end
it 'is curried' do
expect(r.intersection([1, 2, 3, 4]).call([7, 6, 5, 4, 3])).to match_array([3, 4])
end
end
context '#lt' do
it 'from docs' do
expect(r.lt(2, 1)).to be_falsey
expect(r.lt(2, 2)).to be_falsey
expect(r.lt(2, 3)).to be_truthy
expect(r.lt('a', 'z')).to be_truthy
expect(r.lt('z', 'a')).to be_falsey
end
it 'is curried' do
expect(r.lt(2).call(1)).to be_falsey
end
end
context '#lte' do
it 'from docs' do
expect(r.lte(2, 1)).to be_falsey
expect(r.lte(2, 2)).to be_truthy
expect(r.lte(2, 3)).to be_truthy
expect(r.lte('a', 'z')).to be_truthy
expect(r.lte('z', 'a')).to be_falsey
end
it 'is curried' do
expect(r.lt(2).call(1)).to be_falsey
end
end
context '#max' do
it 'from docs' do
expect(r.max(789, 123)).to be(789)
expect(r.max('a', 'b')).to eq('b')
end
end
context '#max_by' do
it 'from docs' do
square = ->(n) { n * n; }
expect(r.max_by(square, -3, 2)).to eq(-3)
expect(R.reduce(r.max_by(square), 0, [3, -5, 4, 1, -2])).to eq(-5)
expect(R.reduce(r.max_by(square), 0, [])).to eq(0)
end
end
context '#min' do
it 'from docs' do
expect(r.min(789, 123)).to be(123)
expect(r.min('a', 'b')).to eq('a')
end
end
context '#min_by' do
it 'from docs' do
square = ->(n) { n * n; }
expect(r.min_by(square, -3, 2)).to eq(2)
expect(R.reduce(r.min_by(square), 100, [3, -5, 4, 1, -2])).to eq(1)
expect(R.reduce(r.min_by(square), 0, [])).to eq(0)
end
end
context '#prop_eq' do
it 'from docs' do
abby = { name: 'Abby', age: 7, hair: 'blond' }
fred = { name: 'Fred', age: 12, hair: 'brown' }
rusty = { name: 'Rusty', age: 10, hair: 'brown' }
alois = { name: 'Alois', age: 15, disposition: 'surly' }
kids = [abby, fred, rusty, alois]
has_brown_hair = r.prop_eq(:hair, 'brown')
expect(R.filter(has_brown_hair, kids)).to eq([fred, rusty])
end
end
context '#path_eq' do
it 'with hash' do
user1 = { address: { zipCode: 90_210 } }
user2 = { address: { zipCode: 55_555 } }
user3 = { name: 'Bob' }
users = [user1, user2, user3]
is_famous = R.path_eq([:address, :zipCode], 90_210)
expect(R.filter(is_famous, users)).to eq([user1])
end
it 'with array' do
col1 = [[11_111], [22_222], [33_333]]
col2 = [[44_444], [55_555], [66_666]]
col3 = [[77_777], [88_888], [99_999]]
cols = [col1, col2, col3]
predicate = R.path_eq([1, 0], 55_555)
expect(R.filter(predicate, cols)).to eq([col2])
end
end
context '#sort_by' do
it 'from docs 1' do
sort_by_first_item = r.sort_by(R.prop(0))
pairs = [[-1, 1], [-2, 2], [-3, 3]]
expect(sort_by_first_item.call(pairs)).to eq([[-3, 3], [-2, 2], [-1, 1]])
end
it 'from docs 2' do
alice = { name: 'ALICE', age: 101 }
bob = { name: 'Bob', age: -10 }
clara = { name: 'clara', age: 314.159 }
people = [clara, bob, alice]
sort_by_name_case_insensitive = r.sort_by(R.compose(R.to_lower, R.prop(:name)))
expect(sort_by_name_case_insensitive.call(people)).to eq([alice, bob, clara])
end
end
context '#union' do
it 'from docs' do
expect(r.union([1, 2, 3], [2, 3, 4])).to eq([1, 2, 3, 4])
end
end
context '#union_with' do
it 'from docs' do
l1 = [{ a: 1 }, { a: 2 }]
l2 = [{ a: 1 }, { a: 4 }]
expect(r.union_with(R.prop(:a), l1, l2)).to eq([{ a: 1 }, { a: 2 }, { a: 4 }])
end
end
end
| true |
b2d3074dd17f71e1d7ebe299621275a5fc97d6e4 | Ruby | osahyoun/boutros | /lib/boutros.rb | UTF-8 | 593 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require "boutros/version"
require 'boutros/client'
require 'boutros/config'
module Boutros
extend Config
class << self
# Alias for Boutros::Client.new
#
# @return [Boutros::Client]
def new(options={})
Boutros::Client.new(options)
end
# Delegate to Boutros::Client
def method_missing(method, *args, &block)
return super unless new.respond_to?(method)
new.send(method, *args, &block)
end
def respond_to?(method, include_private=false)
new.respond_to?(method, include_private) || super(method, include_private)
end
end
end | true |
df5db57884fa528e7332928c803298b6c3aac991 | Ruby | GapIntelligence/gapintelligence-gem | /lib/gap_intelligence/client/requestable.rb | UTF-8 | 1,929 | 2.515625 | 3 | [
"MIT"
] | permissive | module GapIntelligence
module Requestable
# Makes a request to a specified endpoint
#
# @param [Symbol] method one of :get, :post, :put, :delete
# @param [String] path URL path of request
# @param [Hash] options the options to make the request with
# @yield [req] The Faraday request
# @raise [RequestError] If raise_errors set true and request fails for any reason
def perform_request(method, path, options = {}, &block)
record_class = options.delete(:record_class)
raise_error = options.fetch(:raise_errors, raise_errors)
options[:headers] = headers
options[:raise_errors] = false
options[:init_with_response_body] = options.fetch(:init_with_response_body, false)
response = connection.request(method, path, options, &block)
if response.error
error = RequestError.new(parse_error_message(response))
raise(error) if raise_error
return nil
end
return instantiate_record(record_class, response_body: response.body) if options[:init_with_response_body]
hash = response.parsed
data = hash['data']
case data
when Array
objects = record_class.nil? ? data : data.collect{ |object| record_class.new(object) }
RecordSet.new(objects, meta: hash.fetch('meta', {}))
when Hash
instantiate_record(record_class, data, meta: hash.fetch('meta', {}))
end
end
private
def instantiate_record(record_class, data, options = {})
record_class.nil? ? data : record_class.new(data, options)
end
def default_option(opts, key, value)
opts[key] = opts.fetch(key, value)
end
def build_resource_path(*path)
URI.parse(path.join('/')).path
end
def parse_error_message(response)
if response.parsed && response.parsed['error']
response.parsed['error']
else
response.error
end
end
end
end
| true |
486d291eac842be418c8f9670b7e2d657a941d79 | Ruby | plawtr/mortgage | /mortgage.rb | UTF-8 | 466 | 3.140625 | 3 | [] | no_license | def provide_mortgage?(salary, deposit, property_value, bankrupt)
return false if bankrupt
loan_amount = property_value - deposit
property_value <= 650000 ? min_deposit = 0.05 : min_deposit = 0.20 # 20%
max_multiplier = 5 # how many annual incomes can be borrowed
return true if deposit/property_value >= 0.75
deposit >= property_value * min_deposit &&
salary * max_multiplier >= loan_amount
end
puts provide_mortgage?(25000, 30000, 150000, true)
| true |
f33f8ec048b53c877c4c52c7d832da3b1548ff7d | Ruby | Joshuaatt/dictionary | /spec/word_spec.rb | UTF-8 | 673 | 2.953125 | 3 | [] | no_license | require("rspec")
require("word")
describe(Word) do
describe("#initialize") do
it("creates a new Word object, and instantiates it with the two " \
"provided arguments") do
expect(test_def = Word.new("carrot", "english")).to(eq(test_def))
end
end
describe("#word") do
it("returns the Word for a newly created Word object") do
test_def = Word.new("carrot", "english")
expect(test_def.word()).to(eq("carrot"))
end
end
describe("#language") do
it("returns the language for a newly created Word object") do
test_def = Word.new("carrot", "english")
expect(test_def.language()).to(eq("english"))
end
end
end
| true |
6caa70d650fdabc20443e131eb39d1a8b7966310 | Ruby | pierrewebdev/programming-univbasics-4-simple-looping-lab-nyc04-seng-ft-071220 | /lib/simple_loops.rb | UTF-8 | 471 | 3.875 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Write your methods here
def loop_message_five_times(message)
count = 0
until count == 5 do
puts message
count += 1
end
end
def loop_message_n_times(message,n)
count = 0
until count == n do
puts message
count += 1
end
end
def output_array(message)
message.each do |element|
puts element
end
end
def return_string_array(array)
string_array = []
array.each do |element|
string_array.push(element.to_s)
end
string_array
end | true |
4857df00b05e1fa4e2c2147f88e1b7459f06803b | Ruby | abbyarmada/LamaZone | /app/models/order_item.rb | UTF-8 | 1,253 | 2.765625 | 3 | [] | no_license | class OrderItem < ActiveRecord::Base
before_validation :update_price
validates :price, :quantity, presence: true
validates :price, numericality: { greater_than: 0 }
validates :quantity, numericality: { only_integer: true,
greater_than_or_equal_to: 0 }
belongs_to :book
belongs_to :order
rails_admin do
object_label_method do
:custom_label_method
end
end
class << self
def compact_order_items(order_items)
order_items = order_items.group_by{|h| h.book_id}.values.map do |a|
OrderItem.new(book_id: a.first.book_id,
quantity: a.inject(0){|sum,h| sum + h.quantity})
end
order_items.each do |item|
item.price = item.book.price
end
order_items
end
def compact_if_not_compacted(order_items)
if order_items != self.compact_order_items(order_items)
temp_items = order_items
order_items.each { |item| item.destroy }
order_items << self.compact_order_items(temp_items)
end
end
end
private
def update_price
self.price = self.book.price * self.quantity
end
def custom_label_method
"#{Book.find(self.book_id).title}"
end
end
| true |
0919a4ac9bc25498473e7d4a02eef5c3514a8d4d | Ruby | andrew1barron/Project | /app/models/user.rb | UTF-8 | 713 | 2.65625 | 3 | [] | no_license | class User < ActiveRecord::Base
# shows the user has a secure, encrypted password
has_secure_password
# can own many posts and replies, both of which are dependent on the user existing
has_many :posts, dependent: :destroy
has_many :replies, dependent: :destroy
# User must have a first and last name
# also must have a unique email address
validates :first_name,
presence: true
validates :last_name,
presence: true
validates :email,
presence: true,
uniqueness: true,
format: {
with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
}
# ensures first name and last name are entered
def to_s
"#{first_name} #{last_name}"
end
end
| true |
8d11f9bdb71e242147b6c3542e0a924698f40787 | Ruby | weima-sage/rspec-rails | /gatherer/app/helpers/tasks_helper.rb | UTF-8 | 439 | 2.59375 | 3 | [] | no_license | module TasksHelper
include ProjectManagement
def self.recent_time?(time)
time >= VELOCITY_COUNTING_WEEKS.weeks.ago
end
def self.size_sum(tasks_to_sum)
tasks_to_sum.to_a.inject(0) { |current, task| current + task.size }
end
def self.velocity_sum(tasks_to_sum)
tasks_to_sum.to_a.inject(0) { |current, task| current + task.points_toward_velocity }
end
def total_size
TasksHelper.size_sum(tasks)
end
end
| true |
bb926db23561c6d290ba637be8176f582154a158 | Ruby | palhamel/Ruby_exercises | /times_test.rb | UTF-8 | 48 | 3.0625 | 3 | [] | no_license | 30.times do
print "What's your name? "
end
| true |
c4c702a0c6b437631b05f9ddea6d5ab24aaf4334 | Ruby | scmgalaxy/chef_environment | /chef-repo/ruby_code/staticmethod.rb | UTF-8 | 522 | 3.640625 | 4 | [] | no_license | module AwesomeModule
class Awesomeclass
attr_accessor :awesome_level
def initialize(awesome_level)
@awesome_level=awesome_level
end
def self.mystatic_method
puts " i am static method"
end
def mynonstatic_method
puts "i am in non static method"
end
end
end
foo=AwesomeModule::Awesomeclass.new(10)
bar=AwesomeModule::Awesomeclass.new(20)
foo.awesome_level=40
puts foo.awesome_level
puts bar.awesome_level
AwesomeModule::Awesomeclass.mystatic_method
AwesomeModule::Awesomeclass.mynonstatic_method
| true |
3f6bbf9b35d1d652ede4ebc0e87bb2adc6bc228b | Ruby | funapy-sandbox/ruby_sample | /7/24/main.rb | UTF-8 | 63 | 2.828125 | 3 | [] | no_license | def hoge()
yield ?a
yield ?b
end
hoge() do |ch|
p ch
end | true |
4ec42359061e62b27113f55cc9cb62710b41b910 | Ruby | mjjor/mems | /app/controllers/coil_length_controller.rb | UTF-8 | 2,144 | 2.59375 | 3 | [] | no_license | class CoilLengthController < ApplicationController
layout "mems_landing"
def lengthNew
end
def lengthCalc
@outerDiam = params[:outerDiamIn].split.map {|r| Rational(r) }.inject(:+).to_f
@innerDiam = params[:innerDiamIn].split.map {|r| Rational(r) }.inject(:+).to_f
@width = params[:widthIn].split.map {|r| Rational(r) }.inject(:+).to_f
# calc the area of the coil in square inches
@area = Math::PI * ((@outerDiam.to_f**2) - (@innerDiam.to_f**2)) / 4
# calc the length of the coil in inches using the area calc'd above
@length = @area / params[:thickness].to_f
# convert the length to feet
@feet = (@length.to_f / 12)
# calc the squarae footage from the length
@sqfootage = (@feet.to_f) * (@width.to_f / 12)
#(divided input by 12 to get feet
# calc the weight of a sqft
@weight = (40.8 * params[:thickness].to_f)
# calc thex total weight
@totalWeight = @weight.to_f * @sqfootage.to_f
case params[:thickness].to_f
# when 0.0994..0.1174
when 0.097..0.1174
then @coilGauge = "12"
@coilMils = "97"
# when 0.0705..0.0865
when 0.068..0.0865
then @coilGauge = "14"
@coilMils = "68"
# when 0.0575..0.00695
when 0.054..0.0695
then @coilGauge = "16"
@coilMils = "54"
# when 0.0466..0.0566
when 0.0430..0.0566
then @coilGauge = "18"
@coilMils = "43"
# when 0.0356..0.0436
when 0.0330..0.0436
then @coilGauge = "20"
@coilMils = "33"
# when 0.0326..0.0172
when 00172..0.0326
then @coilGauge = "25"
@coilMils = "18"
else @coilGauge = "N/A"
@coilMils = "N/A"
end
redirect_to(:action => 'showResult', :results => [params[:thickness], @width , @innerDiam, @outerDiam,
@feet, @weight, @totalWeight, @sqfootage, @coilGauge, @coilMils])
end
def showResult
render('coil_length/lengthResult')
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.