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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6b11fc452b7391ceee681664711c526cfadfe3bc
|
Ruby
|
rmulhol/mastermind_the_first
|
/second_attempt/spec/command_line_display_spec.rb
|
UTF-8
| 3,179
| 3.5625
| 4
|
[] |
no_license
|
require 'command_line_display'
describe CommandLineDisplay do
let(:test) { described_class.new }
describe "#welcome_user" do
it "welcomes the user" do
expect { test.welcome_user }.to output("Welcome to Mastermind\n").to_stdout
end
end
describe "#explain_rules" do
it "explains the game rules" do
expect { test.explain_rules }.to output("In this game, you will think up a secret code, and I will try to figure it out within ten turns. Your code should be four colors long, with repeats allowed, and the colors you can choose from are: red, blue, green, yellow, purple, and orange.\n").to_stdout
end
end
describe "#offer_to_begin_game" do
it "tells the user to begin the game by hitting enter" do
expect { test.offer_to_begin_game }.to output("Hit enter when you've come up with a secret code and are ready to begin!\n").to_stdout
end
end
describe "#get_input" do
before do
$stdin = StringIO.new("Hello")
end
after do
$stdin = STDIN
end
it "takes input" do
expect(test.get_input).to eq("Hello")
end
end
describe "#display_first_guess" do
it "offers first guess" do
expect { test.display_first_guess(["red", "red", "red", "red"]) }.to output("My first guess is [\"red\", \"red\", \"red\", \"red\"]\n").to_stdout
end
end
describe "#display_next_guess" do
it "offers another guess" do
expect { test.display_next_guess(["red", "red", "red", "red"]) }.to output("My next guess is [\"red\", \"red\", \"red\", \"red\"]\n").to_stdout
end
end
describe "#solicit_feedback_on_black_pegs" do
it "asks the user for the number of black pegs" do
expect { test.solicit_feedback_on_black_pegs }.to output("How many of my picks are the correct color and in the correct position?\n").to_stdout
end
end
describe "#solicit_feedback_on_white_pegs" do
it "asks the user for the number of white pegs" do
expect { test.solicit_feedback_on_white_pegs }.to output("How many of my picks are the correct color but not in the correct position?\n").to_stdout
end
end
describe "#convert_numbers_to_colors" do
it "converts an array of [1, 1, 1, 1] to [\"red\", \"red\", \"red\", \"red\"]" do
expect(test.convert_numbers_to_colors([1, 1, 1, 1])).to eq(["red", "red", "red", "red"])
end
it "converts an array of [2, 2, 2, 2] to [\"blue\", \"blue\", \"blue\", \"blue\"]" do
expect(test.convert_numbers_to_colors([2, 2, 2, 2])).to eq(["blue", "blue", "blue", "blue"])
end
end
it "converts an array of [1, 2, 3, 4] to [\"red\", \"blue\", \"green\", \"yellow\"]" do
expect(test.convert_numbers_to_colors([1, 2, 3, 4])).to eq(["red", "blue", "green", "yellow"])
end
describe "#error_message" do
it "notifies the user of invalid input and solicits another try" do
expect { test.error_message }.to output("Invalid response. Please try again.\n").to_stdout
end
end
describe "#codebreaker win" do
it "announces the codebreaker has won with turns" do
expect { test.codebreaker_win(5) }.to output("I figured out your code in 5 turns!\n").to_stdout
end
end
end
| true
|
ca7a00576b216c63a4a7d18ddc1dd68b6c6ed891
|
Ruby
|
bethqiang/psychic-potato
|
/app/controllers/contacts_controller.rb
|
UTF-8
| 1,738
| 2.703125
| 3
|
[] |
no_license
|
class ContactsController < ApplicationController
def new
# GET reqeust to /contact-us
# Show new contact form
# Every time someone pulls up our comments form, Rails will create a new
# blank contact object
# Store it in the contact variable
# @ indicates instance variable
@contact = Contact.new
end
# POST request /contacts
# Whenever you want to save to db, use create
def create
# Contact object is re-assigning to the fields
# Mass assigment of form fields into Contact object
@contact = Contact.new(contact_params)
# Save the Contact object to the database
if @contact.save
# If the save is successful
# Grab the name, email, and comments from the parameters
# and store them in these variables
name = params[:contact][:name]
email = params[:contact][:email]
body = params[:contact][:comments]
# Plug variables into Contact Mailer email method and send email
ContactMailer.contact_email(name, email, body).deliver
# Store success message in flash hash and redirect to new action
flash[:success] = "Message sent."
redirect_to new_contact_path
else
# If Contact object doesnt save, store errors in flash hash
# and redirect to new action
# Errors will be in an array format
flash[:danger] = @contact.errors.full_messages.join(", ")
redirect_to new_contact_path
end
end
# "Strong parameters"
# Whitelist these 3 fields as being able to be mass-assigned
# THIS IS REQUIRED
# Private methods are designed to only to be used inside your file
private # or protected
def contact_params
params.require(:contact).permit(:name, :email, :comments)
end
end
| true
|
28ff2e0bff18399dec1d9392a4185ef3031e23fa
|
Ruby
|
vkurennov/tceh_ruby
|
/01_ruby_intro/hello.rb
|
UTF-8
| 241
| 3.640625
| 4
|
[] |
no_license
|
puts "Привет, как тебя зовут?"
name = gets.chomp
puts "Какой твой год рождения?"
year = gets.to_i
puts "Привет, #{name}!"
puts "Твой примерный возраст #{2015 - year} лет"
| true
|
3159a75b538589e4e86c6c2eae62151617157b93
|
Ruby
|
lusketeer/aa-works
|
/w1/w1d5/TicTacToeAI/skeleton/lib/tic_tac_toe_node.rb
|
UTF-8
| 1,904
| 3.6875
| 4
|
[] |
no_license
|
require_relative 'tic_tac_toe'
class TicTacToeNode
attr_accessor :board, :next_mover_mark, :prev_move_pos
def initialize(board, next_mover_mark, prev_move_pos = nil)
@board, @next_mover_mark, @prev_move_pos =
board, next_mover_mark, prev_move_pos
end
def losing_node?(evaluator)
if board.over?
if board.winner == other_mark(evaluator)
return true
else #nil or evaluator
return false
end
end
if evaluator == next_mover_mark &&
children.all? { |ch| ch.losing_node? evaluator }
return true
end
if evaluator != next_mover_mark &&
children.any? { |ch| ch.losing_node? evaluator }
return true
end
false
end
def winning_node?(evaluator)
if board.over?
if board.winner == evaluator
return true
else #nil or evaluator
return false
end
end
if evaluator == next_mover_mark &&
children.any? { |ch| ch.winning_node? evaluator }
return true
end
if evaluator != next_mover_mark &&
children.all? { |ch| ch.winning_node? evaluator }
return true
end
false
end
# This method generates an array of all moves that can be made after
# the current move.
def children
board_nodes = []
(0...3).each do |r|
(0...3).each do |c|
if board.empty? [r, c]
temp_board = board.dup
temp_board[[r, c]] = next_mover_mark
mark = (next_mover_mark == :o) ? :x : :o
board_nodes << TicTacToeNode.new(temp_board, mark, [r, c])
end
end
end
board_nodes
end
def other_mark(mark)
(mark == :o) ? :x : :o
end
end
empty_board_node = TicTacToeNode.new(Board.new, :x)
empty_board_node.board[[0,0]] = :o
empty_board_node.board[[0,1]] = :o
empty_board_node.board[[0,2]] = :o
empty_board_node.losing_node?(:o)
empty_board_node.losing_node?(:x)
| true
|
23e4cf374a1a125503c986c054606e5fd2f4d9bd
|
Ruby
|
Eli1771/tic-tac-toe-rb-online-web-sp-000
|
/lib/tic_tac_toe.rb
|
UTF-8
| 2,362
| 4.125
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def input_to_index(user_input)
user_input.to_i - 1
end
def move(board, index, current_player)
board[index] = current_player
end
def position_taken?(board, location)
board[location] != " " && board[location] != ""
end
def valid_move?(board, index)
index.between?(0,8) && !position_taken?(board, index)
end
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index)
token = current_player(board)
move(board, index, token)
display_board(board)
else
turn(board)
end
end
def turn_count(board)
turn = 0
board.each do |space|
if space == "X" || space == "O"
turn += 1
end
end
return turn
end
def current_player(board)
turns_taken = turn_count(board)
if turns_taken % 2 == 0
return "X"
else
return "O"
end
end
def won?(board)
won = false
WIN_COMBINATIONS.each do |win_combination|
win_space_1 = win_combination[0]
win_space_2 = win_combination[1]
win_space_3 = win_combination[2]
board_1 = board[win_space_1]
board_2 = board[win_space_2]
board_3 = board[win_space_3]
if board_1 == "X" && board_2 == "X" && board_3 == "X"
won = true
return win_combination
break
elsif board_1 == "O" && board_2 == "O" && board_3 == "O"
won = true
return win_combination
break
end
end
if won == false
return false
end
end
def full?(board)
board.all? do |space|
space == "X" || space == "O"
end
end
def draw?(board)
!won?(board) && full?(board)
end
def over?(board)
won?(board) || draw?(board) || full?(board)
end
def winner(board)
if won?(board) != false
winning_positions = won?(board)
first_spot = winning_positions[0]
token = board[first_spot]
return token
else
return nil
end
end
def play(board)
until over?(board)
turn(board)
end
if won?(board)
puts "Congratulations #{winner(board)}!"
elsif draw?(board)
puts "Cat's Game!"
end
end
| true
|
e9fec3749119ef91135d4786fdfc8d80f22de10d
|
Ruby
|
landlessness/playing-with-fibers
|
/event_machine_intro/echo.rb
|
UTF-8
| 202
| 2.59375
| 3
|
[] |
no_license
|
# to use:
# telnet localhost 10000
require 'eventmachine'
class Echo < EM::Connection
def receive_data(data)
send_data(data)
end
end
EM.run do
EM.start_server("0.0.0.0", 10000, Echo)
end
| true
|
80015dc5de01c4c6c04331c2e46204bbc99b4aa5
|
Ruby
|
palderson/tutorli
|
/app/models/enrolment.rb
|
UTF-8
| 1,674
| 2.515625
| 3
|
[] |
no_license
|
class Enrolment < ActiveRecord::Base
belongs_to :user
belongs_to :course
attr_accessor :stripe_card_token
OUR_COMMISSION = 0.2
TRANSACTION_FEE = Money.new(30)
STRIPE_COMMISSION = 0.029
def save_with_payment(is_test = false)
Rails.logger.debug "save_with_payment(#{is_test})"
price = course.price.cents
Rails.logger.debug "Course price is $#{price}"
Rails.logger.debug "stripe_card_token = '#{stripe_card_token}'"
if valid?
unless is_test
begin
charge = Stripe::Charge.create(
:amount => price,
:currency => "usd",
:card => stripe_card_token,
:description => "#{user.email} enrolled in course #{course.course_name}"
)
self.stripe_charge_id = charge.id
rescue Stripe::InvalidRequestError => e
Rails.logger.debug "Stripe error while creating charge: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
else
self.stripe_charge_id = "ABCD123"
end
payment_from_user(Money.new(price))
self.save!
end
end
def payment_from_user(price)
Rails.logger.debug "payment_from_user(#{price})"
payment = Payment.new(:price => price, :publisher_price => less_commision(price))
payment.enrolment = self
payment.publisher = course.publisher
payment.user = self.user
payment.purchased_at = Time.now
payment.save!
end
def less_commision(price)
stripe_commission = price * STRIPE_COMMISSION + TRANSACTION_FEE
our_commission = price * OUR_COMMISSION
price - our_commission - stripe_commission
end
end
| true
|
9acb3d82371a40727eb3bae38ae132099b340dc3
|
Ruby
|
AndyDangerous/mastermind
|
/test/guess_builder_test.rb
|
UTF-8
| 844
| 2.765625
| 3
|
[] |
no_license
|
gem 'minitest', '~> 5.2'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/guess_builder'
class GuessBuilderTest < Minitest::Test
attr_reader :gb
def setup
@gb = GuessBuilder.new
Game.new(4, %w(r g b y))
end
def test_it_builds_a_valid_guess
assert gb.build('rrrr', 4)
end
def test_it_downcases_an_uppercase_input
expected = %w(r r r r)
assert_equal expected, gb.build('RRRR', 4).code
end
def test_it_does_not_build_an_invalid_input
refute gb.build('XXXXX', 4)
end
def test_it_builds_with_an_input_with_medium_difficulty
assert gb.build('rgbycm', 6)
end
def test_it_builds_with_an_input_with_hard_difficulty
assert gb.build('rgbycmwk', 8)
end
def test_it_does_not_build_an_easy_guess_with_letters_from_hard
refute gb.build('cmwk', 4)
end
end
| true
|
736675779ad1bf44d366a9ebf38e7ba9c9c06e05
|
Ruby
|
jrabeck/weekend_work
|
/weekend_one/attr_readers.rb
|
UTF-8
| 608
| 4.28125
| 4
|
[] |
no_license
|
class Car
# Our car will have 2 properties:
# - color
# - make
attr_reader :color, :mileage
def initialize(color, make)
@color = color
@make = make
@mileage = calculate_mileage(50, 50)
end
def calculate_mileage(number1, number2)
"Mileage blah" + @color
end
# # attr_reader creates this method
# # this is the GETTER
# def color
# @color
# end
# attr_writer creates this method
# this is the SETTER
def color=(new_color)
@color = new_color
end
end
car = Car.new("Black", "Toyota")
puts car.color
puts car.mileage
car.color = "Red"
puts "New color is: " + car.color
| true
|
9040dc72fb613eec9ecd286159fd2deaa7be73e9
|
Ruby
|
dbpatnode/favfest
|
/app/models/artist_festival.rb
|
UTF-8
| 770
| 2.640625
| 3
|
[] |
no_license
|
class ArtistFestival < ApplicationRecord
belongs_to :artist
belongs_to :festival
def self.search (search)
search = search.titleize
if search.empty?
@artist_fesitval = nil
else
find_festival(search)
end
end
def self.find_festival(search)
key = "%#{search}%"
@festival = Festival.where('location LIKE :search OR name LIKE :search', search: key).order(:name)
find_artist(search, @festival)
end
def self.find_artist(search, festival)
key = "%#{search}%"
@artist = Artist.where('name LIKE :search OR genre LIKE :search', search: key).order(:name)
search_results(festival, @artist)
end
def self.search_results(festival, artist)
@artist_festival = festival + artist
end
end
| true
|
6772f4316cf729d8b0a338262dd1be264f3dfcb7
|
Ruby
|
ctdupuis/array-methods-lab-online-web-pt-090819
|
/lib/array_methods.rb
|
UTF-8
| 309
| 3.5
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def using_include(array, element)
array.include?(element)
end
def using_sort(array)
arr = array.sort
arr
end
def using_reverse(array)
arr = array.reverse
arr
end
def using_first(array)
first = array.first
first
end
def using_last(array)
last = array.last
last
end
def using_size(array)
array.size
end
| true
|
50b980127d479c886d94e40656d41cf8a9bb61e4
|
Ruby
|
snlkumar/weightloss
|
/db/migrate/20110401005701_create_exercises.rb
|
UTF-8
| 773
| 2.6875
| 3
|
[] |
no_license
|
require 'csv'
class CreateExercises < ActiveRecord::Migration
def self.up
create_table :exercises do |t|
t.string :description, :category
t.decimal :mets, :precision => 5, :scale => 2
t.timestamps
end
csv = CSV.read(File.join(::Rails.root.to_s, 'utils', "exercise_mets.csv"))
headers = csv[0].collect{|col| puts col; col.downcase }
csv.shift
csv.each do |row|
exercise = Exercise.new
row.each_with_index do |val, index|
if headers[index].eql?('heading')
attr = 'category='
else
attr = "#{headers[index]}="
end
exercise.send(attr, val.try(:titleize))
end
exercise.save
end
end
def self.down
drop_table :exercises
end
end
| true
|
6e94293facbe618901625197b386615fd019c9b5
|
Ruby
|
jaintarun/appfigures
|
/lib/appfigures.rb
|
UTF-8
| 7,496
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
require 'appfigures/version'
require 'appfigures/connection'
require 'utils/hash_extensions'
require 'date'
require 'json'
class Appfigures
attr_reader :connection
def initialize(options = {})
@connection = Appfigures::Connection.new options[:username], options[:password], options[:client_key]
end
#https://api.appfigures.com/v2/reports/sales/?group_by=product&client_key=c0725e4c875b412fbca6b12b5db44a4e
def product_sales(product_id = nil)
url = 'reports/sales'
options = {group_by: 'product'}
unless product_id.nil?
options = options.merge({products: product_id})
end
response = self.connection.get(url, options)
response.body.map do |id, hash|
if response.status == 200
Hashie::Mash.new({
'product_id' => hash['product']['id'],
'store_id' => hash['product']['store_id'],
'store_name' => hash['product']['store'],
'name' => hash['product']['name'],
'sku' => hash['product']['sku'],
'ref_no' => hash['product']['ref_no'],
'added_timestamp' => Date.parse(hash['product']['source']['added_timestamp']),
'icon' => hash['product']['icon'],
'downloads' => hash['downloads'].to_i,
'returns' => hash['returns'].to_i,
'updates' => hash['updates'].to_i,
'net_downloads' => hash['net_downloads'].to_i,
'promos' => hash['promos'].to_i,
'gift_redemptions'=> hash['gift_redemptions'].to_i,
'revenue' => hash['revenue'].to_f,
'active' => hash['product']['source']['active']
})
else
puts "Appfigures service error for #{url} #{options}:"
puts hash.to_json
Hashie::Mash.new
end
end
end
# GET /reports/sales/dates+products?start=2017-03-01&end=2017-03-31&products=6403600
# See http://docs.appfigures.com/api/reference/v2/sales
def date_sales(start_date, end_date, options = {})
url = "reports/sales/dates+products"
options = {start: start_date.strftime('%Y-%m-%d'),
end: end_date.strftime('%Y-%m-%d')}.merge(options)
response = self.connection.get(url, options)
if response.status == 200
response.body.map do |date, product|
product.map do |product_id, hash|
Hashie::Mash.new({
'date' => Date.parse(date),
'product_id' => hash['product_id'].to_i,
'downloads' => hash['downloads'].to_i,
'returns' => hash['returns'].to_i,
'updates' => hash['updates'].to_i,
'net_downloads' => hash['net_downloads'].to_i,
'promos' => hash['promos'].to_i,
'gift_redemptions'=> hash['gift_redemptions'].to_i,
'revenue' => hash['revenue'].to_f
})
end.first
end
else
response.body.map do |id, hash|
puts "Appfigures service error for #{url} #{options}: "
puts hash.to_json
Hashie::Mash.new
end
end
end
# GET /reports/sales?group_by=country&start=start_date&end=end_date
# See http://docs.appfigures.com/api/reference/v2/sales
def country_sales(start_date, end_date, options = {})
url = "reports/sales"
options = {group_by: 'country',
start: start_date.strftime('%Y-%m-%d'),
end: end_date.strftime('%Y-%m-%d')}.merge(options)
#"/?group_by=country&start=#{start_date.strftime('%Y-%m-%d')}/#{end_date.strftime('%Y-%m-%d')}#{options.to_query_string(true)}"
response = self.connection.get(url, options)
response.body.map do |country, hash|
if response.status == 200
Hashie::Mash.new({
'iso' => hash['iso'],
'country' => hash['country'],
'downloads' => hash['downloads'],
'updates' => hash['updates'],
'returns' => hash['returns'],
'net_downloads' => hash['net_downloads'],
'promos' => hash['promos'],
'revenue' => hash['revenue'],
'gift_redemptions' => hash['gift_redemptions'],
})
else
puts "Appfigures service error for #{url} #{options}: "
puts hash.to_json
Hashie::Mash.new
end
end
end
# GET /reviews?products={productId}&lang=en
# See http://docs.appfigures.com/api/reference/v2/reviews
def product_reviews(product_id, options = {})
url = "reviews"
options = {products: product_id,
lang: 'en'
}.merge(options)
response = self.connection.get(url, options)
if response.status == 200
body = response.body
reviews = Hashie::Mash.new({
'total' => body['total'].to_i,
'pages' => body['pages'].to_i,
'this_page' => body['this_page'].to_i,
'reviews' => body['reviews'].map do |review|
Hashie::Mash.new({
'author' => review['author'],
'title' => review['title'],
'review' => review['review'],
'stars' => review['stars'],
'iso' => review['iso'],
'version' => review['version'],
'date' => review['date'],
'product' => review['product'],
'id' => review['id']
})
end
})
else
puts "Appfigures service error for #{url} #{options}: "
puts response.body.to_json
return Hashie::Mash.new
end
end
# GET /ratings?group_by=product&start_date={today}&end_date={today}products={productId}
def product_ratings(product_id, options = {})
url = "ratings"
now = Time.now
today = Date.new(now.year, now.month, now.day).strftime('%Y-%m-%d')
options = {group_by: 'product',
products: product_id,
start_date: today,
end_date: today}.merge(options)
response = self.connection.get(url, options)
response.body.map do |product, hash|
if response.status == 200
Hashie::Mash.new({
'stars' => product['stars'],
'product' => product['product']
})
else
puts "Appfigures service error for #{url} #{options}: "
puts hash.to_json
return Hashie::Mash.new
end
end.first
end
#https://api.appfigures.com/v2/products/(apple | google_play)/{STORE_ID}&client_key=c0725e4c875b412fbca6b12b5db44a4e
def product(store_id, options = {})
url = "products/#{if store_id.start_with?('com') then 'google_play' else 'apple' end}/#{store_id}"
response = self.connection.get(url, options)
if response.status == 200
body = response.body
self.product_sales(body['id']).first
else
puts "Appfigures service error for #{url} #{options}: "
puts hash.to_json
Hashie::Mash.new
end
end
end
| true
|
5e58fb71af417b53d40964e9f905f90f2b262546
|
Ruby
|
JonahMoses/sales_engine
|
/test/items/transaction_test.rb
|
UTF-8
| 1,211
| 2.71875
| 3
|
[] |
no_license
|
require 'minitest'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/items/transaction'
require './lib/items/invoice'
require './lib/repos/invoice_repo'
require "./lib/sales_engine"
class TransactionTest < MiniTest::Test
attr_reader :transaction_repo,
:engine
def setup
@engine = SalesEngine.new
@transaction_repo = engine.transaction_repository
end
def transaction
@transaction ||= @transaction_repo.transactions.first
end
def test_transaction_id
assert_equal 1, transaction.id
end
def test_invoice_id
assert_equal "1", transaction.invoice_id
end
def test_credit_card_number
assert_equal 4654405418249632, transaction.credit_card_number
end
def test_credit_card_expiration_date
assert_equal "", transaction.credit_card_expiration_date
end
def test_result
assert_equal "success", transaction.result
end
def test_created_at
assert_equal "2012-03-27 14:54:09 UTC", transaction.created_at
end
def test_updated_at
assert_equal "2012-03-27 14:54:09 UTC", transaction.updated_at
end
def test_each_transaction_returns_an_invoice
assert_kind_of Invoice, transaction.invoice
end
end
| true
|
12f7ed2d13c41539c0bf7129f1792d4796a8ab62
|
Ruby
|
swetakumari95/Programming-Ruby
|
/Chapter 6/example7.rb
|
UTF-8
| 211
| 3.828125
| 4
|
[] |
no_license
|
#Chapter 6, More about Methods
#expanding arrays in method calls
def five(a,b,c,d,e)
"I was passed #{a}, #{b}, #{c}, #{d}, #{e}"
end
puts five(1,2,3,4,5)
puts five(1,2,3,*['a', 'b'])
puts five(*(10..14).to_a)
| true
|
f901d2ae37a173a595f6dd0aaca423c16c695c3d
|
Ruby
|
cjfuller/imageanalysistools
|
/src/main/resources/edu/stanford/cfuller/imageanalysistools/resources/common_methods.rb
|
UTF-8
| 4,218
| 2.75
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
#--
# /* ***** BEGIN LICENSE BLOCK *****
# *
# * Copyright (c) 2012 Colin J. Fuller
# *
# * Permission is hereby granted, free of charge, to any person obtaining a copy
# * of this software and associated documentation files (the Software), to deal
# * in the Software without restriction, including without limitation the rights
# * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# * copies of the Software, and to permit persons to whom the Software is
# * furnished to do so, subject to the following conditions:
# *
# * The above copyright notice and this permission notice shall be included in
# * all copies or substantial portions of the Software.
# *
# * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# * SOFTWARE.
# *
# * ***** END LICENSE BLOCK ***** */
#++
##
# A collection of methods to enhance the ruby scripting interface
#
# @author Colin J. Fuller
#
module IATScripting
Filter_package_name = "edu.stanford.cfuller.imageanalysistools.filter."
##
# Gets an instance of a Filter by its class name.
# @param filter_name a symbol that supplies the name of the filter (relative to the ...filter java package;
# for morphological filters, supply, e.g. :morph.OpeningFilter)
# @return an instance of the requested Filter object
#
def get_filter(filter_name)
java_import (Filter_package_name + filter_name.to_s)
Module.const_get(filter_name).new
end
##
# Creates a read-only (deep) copy of an Image object.
# @param another_image an object that implements the Image interface.
# @return an object that implements the Image interface and is a deep copy of the supplied Image.
#
def image_copy(another_image)
java_import Java::edu.stanford.cfuller.imageanalysistools.image.ImageFactory
ImageFactory.create(another_image)
end
##
# Creates a shallow read-only copy of an Image object.
# @param another_image an object that implements the Image interface.
# @return an object that implements the Image interface and shares the same
# pixeldata and metadata as the supplied Image but can be boxed and
# iterated separately.
#
def image_shallow_copy(another_image)
java_import Java::edu.stanford.cfuller.imageanalysistools.image.ImageFactory
ImageFactory.createShallow(another_image)
end
##
# Creates a writable (deep) copy of an Image object.
# @param another_image an object that implements the Image interface that wil be copied
# @return an object that implements the WritableImage interface and is a
# deep copy of the supplied Image.
#
def writable_image_copy(another_image)
java_import Java::edu.stanford.cfuller.imageanalysistools.image.ImageFactory
ImageFactory.createWritable(another_image)
end
##
# Defines a parameter in the parameter dictionary used for the analysis.
# Any existing value will be overwritten.
#
# @param [Symbol] key a symbol that is the name of the parameter
# @param value the value to be associated with the key
# @return the value of the parameter; nil if it could not be set
#
def set_parameter(key, value)
return nil unless @__parameter_dictionary
@__parameter_dictionary.setValueForKey(key.to_s, value.to_s)
end
##
# Gets a parameter from the parameter dictionary used for the analysis.
# Any existing value will be overwritten.
#
# @param [Symbol] key a symbol that is the name of the parameter
# @return [String] the value of that parameter or nil if it does not exist
#
def parameter(key)
unless @__parameter_dictionary and @__parameter_dictionary.hasKey(key.to_s) then
return nil
end
@__parameter_dictionary.getValueForKey(key.to_s)
end
end
| true
|
836f81e91134accd6db71a382f6bc6c61af3fe3e
|
Ruby
|
skovachev/Ruby-on-Rails-1
|
/week2/1-micro-blog/app/app.rb
|
UTF-8
| 708
| 2.78125
| 3
|
[] |
no_license
|
require_relative 'post'
require_relative 'tag'
require_relative 'support'
require_relative 'setupdb'
class App
def all_tags
Tag.find_all.map(&:name)
end
def all_posts
Post.find_all
end
def extract_tags(content)
content.scan(/#(\w+)/).flatten
end
def posts_for_tag(tag)
Post.find_by_tag tag
end
def add_post(title, content)
post = Post.new title, content
valid = post.valid?
if valid
# get post tags
tags = extract_tags content
# save post and tags
post.tags = tags
Post.insert post
end
valid ? post : nil
end
def get_post(id)
Post.find_by_id id
end
def delete_post(id)
Post.delete_by_id id
end
end
| true
|
5ea6f73f4c06e50d3c264b381623cac5ebfb4ecf
|
Ruby
|
pmichaeljones/learn-to-program
|
/roman_numeral.rb
|
UTF-8
| 3,533
| 3.609375
| 4
|
[] |
no_license
|
def roman_numeral(year)
roman = ""
roman << "M" * (year / 1000)
year -= (year / 1000) * 1000
if year / 100 == 0
if year / 50 == 1
roman << "L"
year -= 50
if year / 9 == 1
roman << "IX"
year -= 9
elsif year / 5 == 1
roman << "V"
year -= 5
if (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 10 == 1) || (year / 10 == 2) || (year / 10 == 3)
roman << "X" * (year / 10)
year -= (year / 10) * 10
if year / 9 == 1
roman << "IX"
year -= 9
elsif year / 5 == 1
roman << "V"
year -= 5
if (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 10 == 4)
roman << "XL"
year -= 40
if year / 9 == 1
roman << "IX"
year -= 9
elsif year / 5 == 1
roman << "V"
year -= 5
if (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
end
elsif year / 100 == 1
roman << "C"
year -= 100
if year / 50 == 1
roman << "L"
year -= 50
if year / 9 == 1
roman << "IX"
year -= 9
elsif year / 5 == 1
roman << "V"
year -= 5
if (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 10 == 1) || (year / 10 == 2) || (year / 10 == 3)
roman << "X" * (year / 10)
year -= (year / 10) * 10
if year / 9 == 1
roman << "IX"
year -= 9
elsif year / 5 == 1
roman << "V"
year -= 5
if (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 10 == 4)
roman << "XL"
year -= 40
if year / 9 == 1
roman << "IX"
year -= 9
elsif year / 5 == 1
roman << "V"
year -= 5
if (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
elsif (year / 1 == 1) || (year / 1 == 2) || (year / 1 == 3)
roman << "I" * (year / 10)
elsif year / 1 == 4
roman << "IV"
end
end
elsif year / 100 == 2
roman << "CC"
year -= 200
elsif year / 100 == 3
roman << "CCC"
year -= 300
elsif year / 100 == 4
roman << "CD"
year -= 400
elsif year / 500 == 1
roman << "D"
year -= 500
end
puts roman
puts year
end
| true
|
577980b4d6c491ca77ca453eeb500ff0c0ae1db7
|
Ruby
|
apexskier/code4cash
|
/ClockAngles/ClockAngles.rb
|
UTF-8
| 1,151
| 3.15625
| 3
|
[] |
no_license
|
DEG_PER_HOUR = (360.to_f / 12)
# puts DEG_PER_SEC
DEG_PER_MIN = (360.to_f / 60)
DEG_PER_SEC = DEG_PER_MIN
file = File.new("SampleInput.txt", "r")
lines = file.readlines
file.close
# puts lines.inspect
count = lines.shift
lines.map! do |line|
hour = line[0..1]
minute = line[3..4]
second = line[6..7]
# puts "#{hour}:#{minute}:#{second}"
hour_angle = (hour.to_f * DEG_PER_HOUR) + (DEG_PER_HOUR/60)*minute.to_f + (DEG_PER_HOUR/60/60)*second.to_f
minute_angle = (minute.to_f * DEG_PER_MIN) + (DEG_PER_MIN/60)*second.to_f
second_angle = second.to_f * DEG_PER_SEC
# puts "#{hour_angle}, #{minute_angle}"
hour_min = (hour_angle - minute_angle).abs
# puts hour_min
if hour_min.abs > 180
hour_min = (360 - hour_min.abs).abs
end
hour_sec = (hour_angle - second_angle).abs
if hour_sec.abs > 180
hour_sec = (360 - hour_sec.abs).abs
end
min_sec = (minute_angle - second_angle).abs
if min_sec.abs > 180
min_sec = (360 - min_sec.abs).abs
end
"#{hour_min.round(2)}, #{hour_sec.round(2)}, #{min_sec.round(2)}"
end
file = File.new("Output.txt", "w")
lines.each do |line|
file.puts line
end
file.close
| true
|
bbd70dab83f68c1f2b9f54f5cbc25d7047aaac23
|
Ruby
|
vowyy/BiliBuddy
|
/app/models/meal.rb
|
UTF-8
| 2,059
| 2.59375
| 3
|
[] |
no_license
|
class Meal < ApplicationRecord
belongs_to :foreigner
belongs_to :location
has_many :matches, dependent: :destroy
has_many :favors, dependent: :destroy
has_many :japanese, through: :favors
has_one :room, dependent: :destroy
NOBODY_IS_CHOSEN = 0
EXCESSIVE_ARE_CHOSEN = 3
MEAL_SAIZ_LIMITATION = 5
validates :date, presence: true
validates :time, presence: true
validates :skype, inclusion: { in: [true, false] }
validates :male, numericality: { less_than: 4 }
validates :female, numericality: { less_than: 4 }
validates :foreigner_id, presence: true
validates :location_id, presence: true
validate :date_time_cannot_be_in_the_past
validate :nobody_is_chosen
validate :excessive_is_chosen
def self.size_over?(foreigner)
where(foreigner_id: foreigner).size < MEAL_SAIZ_LIMITATION
end
def already_offered?
matches.exists?
end
def count_offer
matches.where(meal_id: self, ok: 0).size
end
def already_matched?
room
end
private
def date_time_cannot_be_in_the_past
errors.add(:date, "is past.") if date.present? && date < Date.current
end
def nobody_is_chosen
errors[:base] << "Please select more than one person." if male + female == NOBODY_IS_CHOSEN
end
def excessive_is_chosen
errors[:base] << "Please select less than three people." if male + female > EXCESSIVE_ARE_CHOSEN
end
end
# 同一人物による同じ日の同じ時間帯のmealを作れない要する。
# == Schema Information
#
# Table name: meals
#
# id :bigint(8) not null, primary key
# date :date
# female :integer not null
# male :integer not null
# note :text(65535)
# skype :boolean
# time :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# foreigner_id :bigint(8)
# location_id :bigint(8)
#
# Indexes
#
# index_meals_on_foreigner_id (foreigner_id)
# index_meals_on_location_id (location_id)
#
| true
|
23454666805ca3297d59b2beb3e42b2df2eda65b
|
Ruby
|
jwworth/exercism
|
/ruby/affine-cipher/affine_cipher.rb
|
UTF-8
| 1,156
| 3.484375
| 3
|
[] |
no_license
|
require 'openssl'
class Affine
ALPHA = ('a'..'z').to_a
attr_reader :key_first, :key_last
def initialize(key_first, key_last)
raise ArgumentError if coprime?(key_first, alpha_length)
@key_first = key_first
@key_last = key_last
end
def encode(plaintext)
prepare_text(plaintext).map do |letter|
if index = ALPHA.index(letter)
replace_index = (key_first * index + key_last) % alpha_length
ALPHA[replace_index]
else
letter
end
end.each_slice(5).map(&:join).join(' ')
end
def decode(cipher)
mmi = mmi(key_first, alpha_length)
prepare_text(cipher).map do |letter|
if index = ALPHA.index(letter)
replace_index = mmi * (index - key_last) % alpha_length
ALPHA[replace_index]
else
letter
end
end.join
end
private
def coprime?(key_first, length)
OpenSSL::BN.new(key_first).gcd(length) != 1
end
def mmi(key_first, length)
OpenSSL::BN.new(key_first).mod_inverse(length)
end
def prepare_text(text)
text.downcase.gsub(/\W/, '').chars
end
def alpha_length
@alpha_length ||= ALPHA.length
end
end
| true
|
26a4de29251acb46daa27fcf85de58c14ee2fc40
|
Ruby
|
krumfola/FERR
|
/hw3/HW_03.rb
|
UTF-8
| 3,055
| 4.53125
| 5
|
[] |
no_license
|
###############################################################################
#
# Introduction to Ruby on Rails
#
# Homework 03
#
# Purpose:
#
# Read the links below and complete the exercises in this file. This Lab
# is to help you better understand Arrays, Hashes and Loops that we
# learned in Lesson 03.
#
###############################################################################
#
# 1. Review your solution to Lab 02. Copy and Paste your solution to
# this file.
#
# 2. Create a new Array variable called `set_of_numbers`, this will be
# a range between 1 - 10 that our Player will guess from. Each value
# in the Array should be an integer.
#
# 3. Change the variable `secret_number` (HW_02) so that instead of a hard-coded
# Integer, it randomly chooses one of the options from `set_of_numbers`
# ('secret_number' is the integer our Player will try to guess).
#
# Hint: Look up Array#sample in the Ruby documentation.
#
# 4. Create a new Hash variable called `messages`. In this Hash will be
# four Keys Value pairs:
#
# 1. :win - A String telling the Player that they have won.
#
# 2. :lose - A String telling the Player that they have lost and what
# the correct number was.
#
# 3. :too_low - A String telling the Player that their guess was too
# low.
#
# 4. :too_high - A String telling the Player that their guess was too
# high.
#
# 5. Change the behavior of your program, so instead of hard coding, use the principles of DRY(don't repeat yourself).
# This means using a Loop to iterate over your code either until the Player has guessed the
# correct number, or they have tried to guess 3 times.
#
# 6. Make sure to comment your code so that you have appropriate
# documentation for you and for the TAs grading your homework. :-)
#
###############################################################################
#
#Put your solution below this line.
#
###############################################################################
puts prompt = "What's your first name?"
first_name = gets.chomp
puts prompt = "What's your last name?"
last_name = gets.chomp
player_name = first_name + " " + last_name
puts "Welcome" + " " + player_name + "!" + "You have 3 guesses to guess the Secret Number between 1 and 10."
guesses_left = 3
set_of_numbers = (1..10).to_a
secret_number = set_of_numbers.sample #this will give a random #
messages = Hash.new
messages[:win] = "You Won!"
messages[:lose] = "You lost."
messages[:too_low] = "Your guess is too low"
messages[:too_high] = "Your guess is too high"
3.times do |count|
puts "you have #{guesses_left} guesses left"
puts "Please make your guess:"
players_guess = $stdin.gets.chomp.to_i
guesses_left -= 1
if secret_number == players_guess
puts messages[:win]
puts "you guessed in #{count + 1} turns!"
exit
elsif secret_number < players_guess
puts messages[:too_high]
elsif secret_number > players_guess
puts messages[:too_low]
end
end
puts messages[:lose]
puts "The secret number is #{secret_number}"
| true
|
5fb85c2565e53d19f0696692944954b9f8ddaf7c
|
Ruby
|
obale/semantic_crawler
|
/meta_extract.rb
|
UTF-8
| 2,625
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
require 'nokogiri'
require 'open-uri'
require 'awesome_print'
require 'microdata'
module Extractor
class Extractor::HTMLParser
def extract_microdata(items)
hash = Hash.new
if items.kind_of? Array and items.first and items.first.kind_of? String
hash = items
elsif items.kind_of? Array and items.first
items.each do |item|
props = item.properties
properties = Hash.new
props.each do |key, value|
hash[item.type.first] ||= Array.new
values = extract_microdata(value)
properties.merge!(key.to_s => values)
end
hash[item.type.first] << properties
end
else
raise "Not implemented!"
end
hash
end
def get_microdata_json(url)
doc = Nokogiri::HTML(open(url))
microdata = Microdata::Document.new(doc.to_s)
items = microdata.extract_items
extract_microdata(items)
end
def extractLink(url)
doc = Nokogiri::HTML(open(url))
doc.css('link').each do |node|
if !node['type'].nil?
puts node['type'] + " => " + node['href']
if node['type'].downcase.eql?("application/rdf+xml")
rdf = Nokogiri::XML(open(node['href']))
ap "-------------"
ap "Name: #{rdf.xpath("/rdf:RDF/foaf:Person/foaf:name", rdf.namespaces).text}"
ap "Homepage: #{rdf.xpath("/rdf:RDF/foaf:Person/foaf:homepage/@rdf:resource", rdf.namespaces).text}"
pubs = rdf.xpath("/rdf:RDF/foaf:Person/foaf:publications/@rdf:resource", rdf.namespaces)
if pubs
pubs.each do |pub|
publication = rdf.xpath("//rdf:RDF/*[@rdf:ID='#{pub.text.gsub('#', '')}']")
if publication
ap "Publications: #{publication.xpath("./bibtex:hasTitle").text}"
end
end
end
ap "-------------"
end
end
end
end
def extractMeta(url)
doc = Nokogiri::HTML(open(url))
doc.css('meta').each do |node|
if !node['name'].nil?
puts node['name'] + " => " + node['content']
end
if !node['property'].nil?
puts node['property'] + " => " + node['content']
end
end
end
end
end
url = "https://www.alex-oberhauser.com"
html = Extractor::HTMLParser.new
#html.extractLink url
json = html.get_microdata_json(url)
ap json
ap json["http://schema.org/Organization"].size == 3
ap json["http://schema.org/EducationalOrganization"].size == 2
#puts "-------------"
#html.extractMeta url
| true
|
15304acf7ee24c0b09b4075826f9066c2bf91ebe
|
Ruby
|
bluespheal/etapa0
|
/sem_1/martes/say_hi.rb
|
UTF-8
| 171
| 3.53125
| 4
|
[] |
no_license
|
def say_hi(name)
if name == "Daniel"
"Welcome back"
else
"Hi, #{name}"
end
end
# Pruebas
p say_hi('Daniel') == "Welcome back"
p say_hi('Juan') == "Hi, Juan"
| true
|
1b9e0a506f5d3993aac7febd433c4279611e80c9
|
Ruby
|
RenCarothers/array-equals
|
/lib/array_equals.rb
|
UTF-8
| 596
| 3.6875
| 4
|
[] |
no_license
|
def find_length(array)
x = 0
return nil if array == nil
array.each do |element|
x += 1
end
return x
end
def compare_elements(array1, array2)
x = 0
while array1[x] && array2[x]
if array1[x] != array2[x]
return false
end
x += 1
end
return true
end
def array_equals(array1, array2)
length1 = find_length(array1)
length2 = find_length(array2)
if length1 != length2
return false
elsif length1 == nil && length2 == nil
return true
elsif length1 == nil || length2 == nil
return false
else
compare_elements(array1, array2)
end
end
| true
|
8405868bfc48d47056330e33f6d78feb8828d1e5
|
Ruby
|
zms/ironyard_v2
|
/lecture_code_notes/cosmicomics_lecture_010615.rb
|
UTF-8
| 1,625
| 4.46875
| 4
|
[] |
no_license
|
#require 'pry'
def has_joiner?(word1, word2)
word1[-1] == word2[0]
end
def is_anagram?(word1, word2)
word1.chars.sort == word2.chars.sort
end
def is_funny_word?(word1, word2)
is_anagram?(word1, word2) && has_joiner?(word1, word2)
end
def build_dictionary
result = Hash.new([])
File.open('english-dict.txt', 'r') do |f|
f.each_line do |l|
word = l.chomp
result[word.length] += [word] if word.length > 1
end
end
result
end
def cosmicomics
dict = build_dictionary
dict.each do |length, words|
words.combination(2) do |word1, word2|
puts word1[0, length-1] + word2 if is_funny_word?(word1, word2)
end
end
end
cosmicomics
#thoughts
#result[word.length] += [word] if word.length > 1
# before I reviewed the code this year, I was contemplating the most efficient
# data structure to solve this puzzle. I know that I should use a hash table
# where either the key or value represented the length of the word.
# This ensures that when we check for is_funny_word, we are only testing words
# with the same character length. However, I didn't think to make the key, the
# character length and the value an array of all the words that have that same
# character length. Using the assignment operator, += makes it easier to code
# since all the words with the same char length is associated to one key.
# def is_funny_word?(word1, word2)
# is_anagram?(word1, word2) && has_joiner?(word1, word2)
# end
#
# If you validate for has_joiner?() before is_anagram?(), the code runs faster since
# the code does not have to sort every time to validate, which takes up more time.
| true
|
b4a79aad30b2b0ab50b2cfea2ea9bd2e6f5aa8c7
|
Ruby
|
shota27182/id-shukatsu
|
/app/models/concerns/active_model/enum.rb
|
UTF-8
| 2,086
| 2.625
| 3
|
[] |
no_license
|
module ActiveModel
module Enum
extend ActiveSupport::Concern
module ClassMethods
def enum(definitions)
raise ArgumentError, 'enum attribute: { key: value, key, value, ...} の形式で指定してください' unless valid?(definitions)
attribute = definitions.keys.first
values = definitions.values.first
# getterを上書き
define_method(attribute.to_s) do
values.invert[attributes[attribute.to_s]]
end
# 既存のsetterを別名に退避
alias_method "#{attribute}_value=", "#{attribute}="
# setterを上書き
define_method("#{attribute}=") do |argument|
checked_argument = case argument
when Integer
values.values.include?(argument) ? argument : nil
when String
values[argument.to_sym]
when Symbol
values[argument]
else
raise ArgumentError, 'string, symbol, integerのいずれかを指定してください'
end
raise ArgumentError, "'#{argument}' is not a valid #{attribute}" if checked_argument.nil?
send("#{attribute}_value=", checked_argument)
end
# enum_helpの_i18n的なメソッド追加
define_method("#{attribute}_i18n") do
enumed_value = send(attribute)
I18n.t("enums.#{self.class.name.underscore}.#{attribute}.#{enumed_value}", default: enumed_value.to_s)
end
end
private
def valid?(definitions)
return false unless definitions.is_a?(Hash)
return false if definitions.keys.size != 1
values = definitions.values.first
return false unless values.is_a?(Hash)
return false unless values.keys.all? { |key| key.is_a?(Symbol) }
return false unless values.values.all? { |value| value.is_a?(Integer) }
true
end
end
end
end
| true
|
d8fd565433a928f7c669de3276bda289049840f5
|
Ruby
|
mtvillwock/RailsCodingChallenge
|
/lib/cuboid.rb
|
UTF-8
| 2,313
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
class Point
attr_accessor :x, :y, :z
def initialize(coordinates)
@x = coordinates[:x]
@y = coordinates[:y]
@z = coordinates[:z]
end
end
class Cuboid
attr_reader :origin, :vertices, :length, :width, :height
def initialize(dimensions)
@origin = dimensions[:origin] #bottom, left, front vertex
@vertices = []
@length = dimensions[:length]
@width = dimensions[:width]
@height = dimensions[:height]
set_vertices
end
#BEGIN public methods that should be your starting point
def move_to!(x, y, z)
@origin = Point.new({x: x, y: y, z: z})
set_vertices
@origin
end
def set_vertices
anti_origin = Point.new({ x: @origin.x + @width, y: @origin.y + @height, z: @origin.z + @length }) # top, right, back
b = Point.new({ x: @origin.x + @width, y: @origin.y, z: @origin.z }) # bottom, right, front
c = Point.new({ x: @origin.x, y: @origin.y, z: @origin.z + @length }) # bottom, left, back
d = Point.new({ x: @origin.x, y: @origin.y + @height, z: @origin.z }) # top, left, front
e = Point.new({ x: @origin.x, y: @origin.y + @height, z: @origin.z + @length }) # top, left, back
f = Point.new({ x: @origin.x + @width, y: @origin.y + @height, z: @origin.z }) #top, right, front
g = Point.new({ x: @origin.x + @width, y: @origin.y, z: @origin.z + @length }) # bottom, right, back
@vertices = [@origin, b, c, d, e, f, g, anti_origin]
end
def contains?(point)
anti_origin = self.vertices[-1]
return false if point.x < @origin.x || point.x > anti_origin.x
return false if point.y < @origin.y || point.y > anti_origin.y
return false if point.z < @origin.z || point.z > anti_origin.z
return true
end
def touches?(point)
anti_origin = self.vertices[-1]
return true if point.x == @origin.x || point.x == anti_origin.x
return true if point.y == @origin.y || point.y == anti_origin.y
return true if point.z == @origin.z || point.z == anti_origin.z
return false
end
#returns true if the two cuboids intersect each other. False otherwise.
def intersects?(cuboid)
cuboid.vertices.each do |vertex|
if self.contains?(vertex) || self.touches?(vertex)
return true
end
end
return false
end
#END public methods that should be your starting point
end
| true
|
6351550bd59b6bdf81acc684164a297972fb3879
|
Ruby
|
bettymakes/data_visualization_pokemon
|
/get_poketype.rb
|
UTF-8
| 4,414
| 3.046875
| 3
|
[] |
no_license
|
require 'nokogiri'
# gem that allows you to download the web page so we can parse it
# require 'open-uri' ... removed open uri because we are no longer scraping off of a website
# url variable set to web page we are parsing/scraping
# url = "http://pokemondb.net/pokedex/national"
file = 'pokemon-list.html' #downloaded site to file, scraping downloaded file instead
# Nokogiri object, parse HTML document (nokogiri can parse diff types of docs), open this 'url' (line 6)
data = Nokogiri::HTML(open( file ))
data_hash = { :fire => ['fire', 'fire', 'fire' ]}
data_hash{ :fire => ['fire', 'fire', 'fire' ] }
data_hash[ :fire ] = ['fire', 'fire', 'fire' ]
poke_types = %w(fire grass rock water bug normal poison electic ground fighting psychic ghost ice dragon steel dark flying)
data_hash[categories[0].to_sym]
categories.each do |cat|
data_hash[ cat.to_sym ] = []
end
pokemon = data.css(".item")
poketype_array = Array.new
cat_values_array = Array.new
#new set of category arrays
# fire_poketype_array = Array.new
# grass_poketype_array = Array.new
# rock_poketype_array = Array.new
# water_poketype_array = Array.new
# bug_poketype_array = Array.new
# normal_poketype_array = Array.new
# poison_poketype_array = Array.new
# electric_poketype_array = Array.new
# ground_poketype_array = Array.new
# fighting_poketype_array = Array.new
# psychic_poketype_array = Array.new
# ghost_poketype_array = Array.new
# ice_poketype_array = Array.new
# dragon_poketype_array = Array.new
# steel_poketype_array = Array.new
# dark_poketype_array = Array.new
# flying_poketype_array = Array.new
pokemon.each do |info|
poke_info = info.at_css(".note").text.strip.gsub(/(\W.+)/, "")
poketype_array << poke_type_info
end
poketype_array.each do |type|
# data_hash[:fire] << type if type == "Fire"
data_hash[ type.downcase.to_sym ] << type
# fire_poketype_array << type if type == "Fire"
# grass_poketype_array << type if type == "Grass"
# rock_poketype_array << type if type == "Rock"
# water_poketype_array << type if type == "Water"
# bug_poketype_array << type if type == "Bug"
# normal_poketype_array << type if type == "Normal"
# poison_poketype_array << type if type == "Poison"
# electric_poketype_array << type if type == "Electric"
# ground_poketype_array << type if type == "Ground"
# fighting_poketype_array << type if type == "Fighting"
# psychic_poketype_array << type if type == "Psychic"
# ghost_poketype_array << type if type == "Ghost"
# ice_poketype_array << type if type == "Ice"
# dragon_poketype_array << type if type == "Dragon"
# steel_poketype_array << type if type == "Steel"
# dark_poketype_array << type if type == "Dark"
# flying_poketype_array << type if type == "Flying"
end
count_total = poketype_array.length
cat_values_array << count_fire = fire_poketype_array.length
cat_values_array << count_grass = grass_poketype_array.length
cat_values_array << count_rock = rock_poketype_array.length
cat_values_array << count_water = water_poketype_array.length
cat_values_array << count_bug = bug_poketype_array.length
cat_values_array << count_normal = normal_poketype_array.length
cat_values_array << count_poison = poison_poketype_array.length
cat_values_array << count_electric = electric_poketype_array.length
cat_values_array << count_ground = ground_poketype_array.length
cat_values_array << count_fighting = fighting_poketype_array.length
cat_values_array << count_pychic = psychic_poketype_array.length
cat_values_array << count_ghost = ghost_poketype_array.length
cat_values_array << count_ice = ice_poketype_array.length
cat_values_array << count_dragon = dragon_poketype_array.length
cat_values_array << count_steel = steel_poketype_array.length
cat_values_array << count_dark = dark_poketype_array.length
cat_values_array << count_flying = flying_poketype_array.length
data_hash =
File.open('poke_page.html', 'w') do |html|
for i in 0..16 do
div_width = (count_type_array / count_total)*100
html.write("<div class="bar-default">")
html.write(" <div class='bar-filled highlight' style='width:' + div_width + '%;' >\n")
#<div class="bar-filled highlight" style="width: 100%"></div>
html.write("<div class="bar-title">___variable____</div>")
html.write("</div>")
html.write("</div>")
end
| true
|
78183a4adddc8113fa06094c2fb7f53a968e43b4
|
Ruby
|
reduviidae/module-one-holiday-project-dumbo-web-121018
|
/seeding/sentiment/google_sentiment.rb
|
UTF-8
| 1,127
| 3.21875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require_relative '../../config/environment'
# Imports the Google Cloud client library
require "google/cloud/language"
def analyze_assign_sentiment
Quote.all.each do |quote|
# Instantiates a client
language = Google::Cloud::Language.new
# Detects the sentiment of the text
response = language.analyze_sentiment content: quote.content, type: :PLAIN_TEXT
# Get document sentiment from response
sentiment = response.document_sentiment
# displays results to me as it works so I can be sure legit values are going in
puts "#{quote.content}"
puts "Score: #{sentiment.score}, #{sentiment.magnitude}"
# saves the score and magnitude to the analyzed quote
quote.score = sentiment.score
quote.magnitude = sentiment.magnitude
# rudimentary analysis saves a string evaluation to quote.sentiment
if quote.score > 0.1 && quote.magnitude > 0.2
quote.sentiment = "positive"
elsif quote.score < 0 && quote.magnitude > 0.2
quote.sentiment = "negative"
elsif (0..0.19).include?(quote.magnitude)
quote.sentiment = "neutral"
end
quote.save
end
end
analyze_assign_sentiment
| true
|
bb8d406edce58096fe53e57796138d85dd7f43ff
|
Ruby
|
shu0115/receibo
|
/vendor/bundler/ruby/1.9.1/gems/heroku-2.15.1/lib/heroku/command/ps.rb
|
UTF-8
| 3,425
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require "heroku/command/base"
# manage processes (dynos, workers)
#
class Heroku::Command::Ps < Heroku::Command::Base
# ps:dynos [QTY]
#
# scale to QTY web processes
#
# if QTY is not specified, display the number of web processes currently running
#
def dynos
app = extract_app
if dynos = args.shift
current = heroku.set_dynos(app, dynos)
display "#{app} now running #{quantify("dyno", current)}"
else
dynos = heroku.dynos(app)
display "#{app} is running #{quantify("dyno", dynos)}"
end
end
alias_command "dynos", "ps:dynos"
# ps:workers [QTY]
#
# scale to QTY background processes
#
# if QTY is not specified, display the number of background processes currently running
#
def workers
app = extract_app
if workers = args.shift
current = heroku.set_workers(app, workers)
display "#{app} now running #{quantify("worker", current)}"
else
workers = heroku.workers(app)
display "#{app} is running #{quantify("worker", workers)}"
end
end
alias_command "workers", "ps:workers"
# ps
#
# list processes for an app
#
def index
app = extract_app
ps = heroku.ps(app)
objects = ps.sort_by do |p|
t,n = p['process'].split('.')
[t, n.to_i]
end.each do |p|
p['state'] << ' for ' << time_ago(p['elapsed']).gsub(/ ago/, '')
p['command'] = truncate(p['command'], 36)
end
display_table(
objects,
['process', 'state', 'command'],
['Process', 'State', 'Command']
)
end
# ps:restart [PROCESS]
#
# restart an app process
#
# if PROCESS is not specified, restarts all processes on the app
#
def restart
app = extract_app
opts = case args.first
when NilClass then
display "Restarting processes... ", false
{}
when /.+\..+/
ps = args.first
display "Restarting #{ps} process... ", false
{ :ps => ps }
else
type = args.first
display "Restarting #{type} processes... ", false
{ :type => type }
end
heroku.ps_restart(app, opts)
display "done"
end
alias_command "restart", "ps:restart"
# ps:scale PROCESS1=AMOUNT1 ...
#
# scale processes by the given amount
#
# Example: heroku scale web=3 worker+1
#
def scale
app = extract_app
current_process = nil
changes = args.inject({}) do |hash, process_amount|
if process_amount =~ /^([a-zA-Z0-9_]+)([=+-]\d+)$/
hash[$1] = $2
end
hash
end
error "Usage: heroku ps:scale web=2 worker+1" if changes.empty?
changes.each do |process, amount|
display "Scaling #{process} processes... ", false
amount.gsub!("=", "")
new_qty = heroku.ps_scale(app, :type => process, :qty => amount)
display "done, now running #{new_qty}"
end
end
alias_command "scale", "ps:scale"
# ps:stop PROCESS
#
# stop an app process
#
# Example: heroku stop run.3
#
def stop
app = extract_app
opt =
if (args.first =~ /.+\..+/)
ps = args.first
display "Stopping #{ps} process... ", false
{:ps => ps}
elsif args.first
type = args.first
display "Stopping #{type} processes... ", false
{:type => type}
else
error "Usage: heroku ps:stop PROCESS"
end
heroku.ps_stop(app, opt)
display "done"
end
alias_command "stop", "ps:stop"
end
| true
|
77f9efe4bb9a3aea811bff458bde98a82fcec2db
|
Ruby
|
octonion/tennis
|
/ita/scrapers/ita_league_menus.rb
|
UTF-8
| 1,519
| 2.625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'csv'
require 'mechanize'
agent = Mechanize.new{ |agent| agent.history.max_size=0 }
agent.user_agent = 'Mozilla/5.0'
menus = Array.new
conferences = CSV.open("csv/ita_conference.csv", "w")
conferences << ["league_id", "conference_id", "conference_name"]
teams = CSV.open("csv/ita_team.csv", "w")
teams << ["league_id", "team_id", "team_name"]
seasons = CSV.open("csv/ita_season.csv", "w")
seasons << ["league_id", "season_id", "season_name"]
menus << ["conference", '//*[@id="ctl00_ContentPlaceHolder1_drpConference"]/option', conferences]
menus << ["team", '//*[@id="ctl00_ContentPlaceHolder1_drpTeam"]/option', teams]
menus << ["season", '//*[@id="ctl00_ContentPlaceHolder1_drpSeason"]/option', seasons]
leagues = CSV.open("csv/ita_league.csv", "r", {:headers => TRUE})
url = "http://itarankings.itatennis.com/TeamSchedule.aspx"
page = agent.get(url)
form = page.forms[0]
leagues.each do |league|
league_id = league["league_id"]
league_name = league["league_name"]
form["ctl00$ContentPlaceHolder1$drpLeague"] = league_id
page = form.submit
menus.each do |menu|
category = menu[0]
search = menu[1]
file = menu[2]
found = 0
row = [league_id]
page.parser.xpath(search).each do |option|
id = option.attributes["value"]
name = option.inner_text.scrub.strip
file << row+[id, name]
found += 1
end
print "#{league_name}/#{category} found #{found}\n"
end
end
conferences.close
teams.close
seasons.close
| true
|
22388a7eadefc00ab709109f47530b5b5b719527
|
Ruby
|
nigel-lowry/the_ray_tracer_challenge
|
/lib/intersection.rb
|
UTF-8
| 285
| 3.046875
| 3
|
[] |
no_license
|
class Intersection
include Comparable
attr_reader :t, :object
def initialize t, object
@t, @object = t, object
freeze
end
def <=>(other)
@t <=> other.t
end
def ==(other)
self.class == other.class and @t == other.t and @object == other.object
end
end
| true
|
c46c8fd8d53b96ca64ab78694e844b2d003a54ea
|
Ruby
|
seosgithub/threadsafe-hiredis-rb
|
/test/threadsafe-test.rb
|
UTF-8
| 903
| 2.8125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
require '../lib/hiredis.rb'
require 'hiredis'
require 'redis'
@conn = Hiredis::ThreadSafeConnection.new
@conn.connect("127.0.0.1", 6379)
@conn2 = Redis.new
$stderr.puts "Could not connect" unless @conn
def push_data
Thread.new do
begin
key = rand(100000000000)
1000.times do |i|
@conn.write ["SET", "temp://#{key.to_s}#{key}#{i}", i]
@conn.write ["EXPIRE", "temp://#{key.to_s}#{key}#{i}", 5]
@conn.read
@conn2.set("lol", "lol")
end
1000.times do
@conn.read
end
1000.times do |i|
@conn.write ["GET", "temp://#{key.to_s}#{key}#{i}"]
end
1000.times do |i|
res = @conn.read.to_i
if res != i
raise "not equal"
end
end
p "Test passed! #{key}"
rescue => e
$stderr.puts e
end
end
end
100.times do
push_data
end
loop do
sleep 1
end
| true
|
31b4e61262161b153947bb813b04c7c59e029235
|
Ruby
|
tbierwirth/little_shop
|
/app/models/cart.rb
|
UTF-8
| 487
| 3.25
| 3
|
[] |
no_license
|
class Cart
attr_reader :contents
def initialize(contents)
if contents
@contents = contents
@contents.default = 0
else
@contents = Hash.new(0)
end
end
def total
@contents.values.sum
end
def add_item(item_id)
@contents[item_id.to_s] += 1
end
def remove_item(item_id)
@contents[item_id.to_s] -= 1
end
def count_of(id)
@contents[id.to_s].to_i
end
def subtotal(price, quantity)
price * quantity.to_f
end
end
| true
|
6d871621907e4bf35347570610b3fd9aee1b069b
|
Ruby
|
Pensive1881/Learn_Ruby
|
/15_in_words.rb
|
UTF-8
| 1,689
| 3.90625
| 4
|
[] |
no_license
|
class Fixnum
def in_words
num = self
answer = ""
return "zero" if num == 0
if num > 999999
million = num / 1000000
num -= million * 1000000
answer << converter(million) << "million "
end
if num > 999
thousand = num / 1000
num -= thousand * 1000
answer << converter(thousand) << "thousand "
end
answer << converter(num)
answer = answer.chomp!(' ')
end
def converter(n)
string = ""
ones_teens = {1 => "one ", 2 => "two ", 3 => "three ", 4 => "four ",
5 => "five ", 6 => "six ", 7 => "seven ", 8 => "eight ", 9 => "nine ",
10 => "ten ", 11 => "eleven ", 12 => "twelve ", 13 => "thirteen ",
14 => "fourteen ", 15 => "fifteen ", 16 => "sixteen ",
17 => "seventeen ", 18 => "eighteen ", 19 => "nineteen "}
tens = {20 => "twenty ", 30 => "thirty ", 40 => "forty ", 50 => "fifty ",
60 => "sixty ", 70 => "seventy ", 80 => "eighty ", 90 => "ninety "}
if n > 99
hundred = n / 100
n -= hundred * 100
string << ones_teens[hundred] << "hundred "
end
if n > 19
x = (n/10)*10
n -= x
string << tens[x]
end
if ones_teens.include?(n) == true
string << ones_teens[n]
end
string
end
end
class Bignum
def in_words
num = self
answer = ""
if num > 999999999999
trillion = num/10**12
num -= trillion*10**12
answer << trillion.in_words << " trillion "
end
if num > 999999999
billion = num/10**9
num -= billion*10**9
answer << billion.in_words << " billion "
end
answer << num.in_words if num < 10**9 && num > 0
answer = answer.chomp(' ')
end
end
| true
|
a381c42497bc8fe5520c78e81003f3daa01d2a6d
|
Ruby
|
awslabs/cloud-templates-ruby
|
/lib/aws/templates/utils/guarded.rb
|
UTF-8
| 811
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'aws/templates/utils'
module Aws
module Templates
module Utils
##
# Remember Alan Turing's halting problem and don't believe in miracles. The method will
# only work with parameters because they are supposed to be pure unmodifying functions.
# Hence we can terminate if a parameter method was invoked twice in the stack with the same
# context.
module Guarded
Call = Struct.new(:instance, :entity)
def guarded_for(instance, entity)
current_call = Call.new(instance, entity)
return unless trace.add?(current_call)
ret = yield
trace.delete(current_call)
ret
end
private
def trace
Thread.current[Guarded.name] ||= ::Set.new
end
end
end
end
end
| true
|
e28f38dc017a11fa561c9f8c57d28e9afa90efb6
|
Ruby
|
jalbersh/Sept14CodeChallange
|
/acceptance/spec/helpers/LOWER_UNDERSCORE_NAME_server.rb
|
UTF-8
| 1,770
| 2.53125
| 3
|
[] |
no_license
|
require_relative './retry_for'
class APPLICATION_NAMEServer
attr_reader :app_port
def initialize(port, simulator_port)
@app_port = port
@simulator_port = simulator_port
end
def start
return if app_is_running?
unless artifact_exists?
puts ''
puts '<'*80
puts ''
puts "No artifact found, create with 'cd ~/workspace/SERVICE_GIT_PROJECT_NAME/ && ./gradlew clean assemble'"
puts ''
puts '>'*80
exit!
end
java_opts = ENV['ACCEPTANCE_JAVA_OPTS']
@service_offering_groups_app_pid = Process.spawn(
"SERVER_PORT=#{app_port} SIMULATOR_PORT=#{simulator_port} java #{java_opts} -jar build/libs/SERVICE_GIT_PROJECT_NAME.jar",
chdir: '../',
pgroup: true,
out: 'application.std.log',
err: 'application.err.log'
)
puts "Attempting to start the application at http://localhost:#{app_port}"
retry_for(240) {
resp = health_check
raise 'Application never came up. Does `gradle dev` work?' unless resp.code == 200
}
resp = health_check
puts resp.body
end
def stop
return unless service_offering_groups_app_pid
puts 'Shutting down the application'
puts "Killing pid #{service_offering_groups_app_pid}"
Process.kill('TERM', service_offering_groups_app_pid)
end
private
attr_reader :service_offering_groups_app_pid, :simulator_port
def health_check
HTTParty.get("http://localhost:#{app_port}/health")
end
def app_is_running?
begin
health_check.code == 200
rescue
false
end
end
def artifact_exists?
artifact_found = `[ -e ../build/libs/SERVICE_GIT_PROJECT_NAME.jar ] && echo true || echo false`
return true if artifact_found == "true\n"
false
end
end
| true
|
e557d006d79108d2f9b0a9be2917402c87df991c
|
Ruby
|
maye-gallardo/QUADRITOS
|
/spec/line_spec.rb
|
UTF-8
| 974
| 3.015625
| 3
|
[] |
no_license
|
require './lib/line'
describe "Pruebas de la clase Line" do
before :each do |single|
@line = Line.new(10, 10, 20, 20)
end
it "deberia crearse una linea con su posicion x1 igual '10'" do
expect(@line.getPosX1()).to eq 10
end
it "deberia crearse una linea con su posicion x2 igual '10'" do
expect(@line.getPosX2()).to eq 10
end
it "deberia crearse una linea con su posicion y1 igual '20'" do
expect(@line.getPosY1()).to eq 20
end
it "deberia crearse una linea con su posicion y2 igual '20'" do
expect(@line.getPosY2()).to eq 20
end
it "deberia crearse una linea que no este visible" do
expect(@line.isItVisible()).to eq false
end
it "deberia hacerse visible" do
@line.toVisible
expect(@line.isItVisible()).to eq true
end
it "deberia retornar las posiciones de la linea" do
expect(@line.getPositions()).to eq "10_10_20_20"
end
end
| true
|
7fa37698b681a1f98a674a98f969f8e0a1cee9dc
|
Ruby
|
surfer8137/KataBankOCR
|
/lib/entryparser.rb
|
UTF-8
| 1,297
| 3.734375
| 4
|
[] |
no_license
|
require 'digit'
class EntryParser
LINES = 4
CHARS_PER_DIGIT = 9
CHARS_PER_DIGIT_PER_LINE = 3
NUMBER_OF_DIGITS = 9
class << self
def parse(input)
result = ''
NUMBER_OF_DIGITS.times do |digit_position|
digit_chars = parse_digit(input, digit_position)
result << Digit.parse(digit_chars)
end
result
end
private
def parse_digit(input, position)
digit_initial_position = calculate_initial_position(position)
[
chars_from(input, digit_initial_position, first_line),
chars_from(input, digit_initial_position, second_line),
chars_from(input, digit_initial_position, third_line),
chars_from(input, digit_initial_position, fourth_line)
].join('')
end
def calculate_initial_position(position)
CHARS_PER_DIGIT_PER_LINE * position
end
def chars_from(string, from, position)
string[from + position, CHARS_PER_DIGIT_PER_LINE]
end
def number_of_chars_in_a_line
NUMBER_OF_DIGITS * CHARS_PER_DIGIT_PER_LINE
end
def first_line
0
end
def second_line
number_of_chars_in_a_line
end
def third_line
number_of_chars_in_a_line * 2
end
def fourth_line
number_of_chars_in_a_line * 3
end
end
end
| true
|
cbaaca9a2252992d282ab65f99e8d841aa582eef
|
Ruby
|
luciaprietosantamaria/Bioinformatic-programming-challenges
|
/Assignment2/Protein.rb
|
UTF-8
| 4,918
| 3.109375
| 3
|
[] |
no_license
|
#-----------------------------------------------------
# Bioinformatic programming challenges
# Assignment2: PROTEIN Object
# author: Lucía Prieto Santamaría
#-----------------------------------------------------
require 'net/http'
require 'json'
require './PPI.rb'
class Protein
attr_accessor :prot_id # UniProt ID
attr_accessor :intact_id # IntAct ID, if the protein interacts with another protein
attr_accessor :network # Network ID, if the protein is member of one
@@total_protein_objects = Hash.new # Class variable that will save in a hash all the instances of Protein created (key: prot_id)
@@total_protwithintact_objects = Hash.new # Class variable that will save in a hash all the instances of Protein created (key: intact_id)
#-----------------------------------------------------
def initialize (params = {})
@prot_id = params.fetch(:prot_id, "XXXXXX")
@intact_id = params.fetch(:intact_id, nil)
@network = params.fetch(:network, nil)
@@total_protein_objects[prot_id] = self
if intact_id
@@total_protwithintact_objects[intact_id] = self
end
end
#-----------------------------------------------------
#-----------------------------------------------------
def self.all_prots
# Class method to get the hash with all the instances of Protein object
return @@total_protein_objects
end
#-----------------------------------------------------
#-----------------------------------------------------
def self.all_prots_withintact
# Class method to get the hash with all the instances of Protein object with key the IntAct ID
return @@total_protwithintact_objects
end
#-----------------------------------------------------
#-----------------------------------------------------
def self.create_prot (prot_id, level, gene_id = nil, intact = nil)
# Class method that creates a Protein object, given its protein ID and the current level of interaction depth
# The gene ID (when we are at level 0) and the IntAct ID (when we are creating Protein object from a PPI) can be given
if not intact # If the IntAct ID is not provided, we look if the protein has it
intact = self.get_prot_intactcode(gene_id) # Retrieve whether the protein is present in IntAct Database, and which is its accession code
end
if intact && (level < $MAX_LEVEL)
# Once we know the protein has an IntAct ID, and if we are in a lower level than the maximum, we look for the interacting proteins
PPI.create_ppis(intact, level)
end
Protein.new(
:prot_id => prot_id,
:intact_id => intact,
:network => nil # We first set all networks relationships to empty
)
level += 1 # We deep one level
end
#-----------------------------------------------------
#-----------------------------------------------------
def self.exists(intact_id)
# Class method that given an IntAct ID returns TRUE if a Protein instance has already been created with it,
# FALSE if not
if @@total_protwithintact_objects.has_key?(intact_id)
return true
else
return false
end
end
#-----------------------------------------------------
#-----------------------------------------------------
def self.get_prot_intactcode(gene_id)
# Class method that searchs whether a given protein is present in IntAct database or not
# If it is, the function will return th IntAct ID
address = URI("http://togows.org/entry/ebi-uniprot/#{gene_id}/dr.json")
response = Net::HTTP.get_response(address)
data = JSON.parse(response.body)
if data[0]['IntAct']
return data[0]['IntAct'][0][0] # If the protein is present, the result returned will be the protein accession code. If it not, the result will be empty
else
return nil
end
end
#-----------------------------------------------------
#-----------------------------------------------------
def self.intactcode2protid(intact_accession_code)
# Class method to obtain the UniProt ID given a protein IntAct accession code
intact_accession_code.delete!("\n")
if intact_accession_code =~ /[OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2}/
# We check the accession UniProt code is correct.
# Regular expression obtained from "https://www.uniprot.org/help/accession_numbers"
begin
address = URI("http://togows.org/entry/ebi-uniprot/#{intact_accession_code}/entry_id.json")
response = Net::HTTP.get_response(address)
data = JSON.parse(response.body)
return data[0]
rescue
return "UniProt ID not found"
end
else
return "UniProt ID not found"
end
end
#-----------------------------------------------------
end
| true
|
d2f5f90f8c9958e23deea9302d0ab766f4a45d2f
|
Ruby
|
itgsod-simon-lundgren/bildgen
|
/filer/funktiontest.rb
|
UTF-8
| 562
| 2.703125
| 3
|
[] |
no_license
|
require 'devil'
# class Pictures
hej = []
files = Dir.glob('storabilder/*')
files = files.map { |file| [file.count("/"), file] }
files = files.sort.map { |file| file[1] }
files.each do |base|
hej << File.basename(base)
end
puts hej
hej.each do |file|
Dir.chdir('./storabilder')
puts Dir.getwd
Devil.with_image(file) do |img|
img.thumbnail2(150)
img.save("../thumbnails/Thumbnail_#{file}")
end
Dir.chdir("..")
puts Dir.getwd
end
# Dir.foreach ("storabilder.") do |filer|
# puts filer
# end
# Dir.glob("*.{jpg,png}") do |filer|
# puts filer
# end
| true
|
ca212c0830aedd68452a348a5e5be1b121e7be39
|
Ruby
|
Enocruz/SWArchitectureClass
|
/decorator/src/coffee_test.rb
|
UTF-8
| 1,382
| 3.171875
| 3
|
[] |
no_license
|
# The source code contained in this file is used to
# test the coffee.rb program.
# Adapter Pattern
# Date: 08-March-2018
# Authors:
# A01374648 Mario Lagunes Nava
# A01375640 Brandon Alain Cruz Ruiz
# File: coffee_test.rb
# Adding the namespaces require to run the file
require 'minitest/autorun'
require './coffee'
# Class declaration
class CoffeeTest < Minitest::Test
# Testing the Espresso class with no condiments
def test_espresso
beverage = Espresso.new
assert_equal("Espresso", beverage.description)
assert_equal(1.99, beverage.cost)
end
# Testing the DarkRoast class with condiments
def test_dark_roast
beverage = DarkRoast.new
beverage = Milk.new(beverage)
beverage = Mocha.new(beverage)
beverage = Mocha.new(beverage)
beverage = Whip.new(beverage)
assert_equal("Dark Roast Coffee, Milk, Mocha, Mocha, Whip",
beverage.description)
assert_equal(1.59, beverage.cost)
end
# Testing the HouseBlend class with condiments
def test_house_blend
beverage = HouseBlend.new
beverage = Soy.new(beverage)
beverage = Mocha.new(beverage)
beverage = Whip.new(beverage)
assert_equal("House Blend Coffee, Soy, Mocha, Whip",
beverage.description)
assert_equal(1.34, beverage.cost)
end
end
| true
|
11e35fd117ca9a3e339414d1f4f9e33628ab8e70
|
Ruby
|
maxximus87/Game
|
/console_human.rb
|
UTF-8
| 278
| 3.671875
| 4
|
[] |
no_license
|
class Human
attr_reader :marker
def initialize(marker)
@marker = marker
end
def get_move(board)
puts "Make a move"
move = gets.chomp.to_i - 1
if board[move] == ""
move
else
puts "Spot already taken."
get_move(board)
end
end
end
| true
|
be335536201fcea10e74085994d5e68959efdf48
|
Ruby
|
kokoko313/codewars
|
/fizzbuzz.rb
|
UTF-8
| 295
| 3.609375
| 4
|
[] |
no_license
|
puts (1..20).map {|i|
f = i % 3 == 0 ? 'Fizz' : nil
b = i % 5 == 0 ? 'Buzz' : nil
f || b ? "#{ f }#{ b }" : i
}
(1..100).each do |num|
message = ""
message << "fizz" if num%3 == 0
message << "buzz" if num%5 == 0
message << num.to_s if message.length == 0
puts message
end
| true
|
06a30e3b023704e5005796d3bd512a629224b5f0
|
Ruby
|
dmn88mia/ls_exercises
|
/101_109_small_problems/easy_5/aplabet_nums.rb
|
UTF-8
| 2,346
| 4.5
| 4
|
[] |
no_license
|
# Understand the problem :
# Write a method that takes an Array of Integers between 0 and 19, and returns an Array
# of those Integers sorted based on the English words for each number:
# Set up your test cases
# alphabetic_number_sort((0..19).to_a) == [
# 8, 18, 11, 15, 5, 4, 14, 9, 19, 1, 7, 17,
# 6, 16, 10, 13, 3, 12, 2, 0
# ]
# Describe your inputs, outputs, and data structures
# input will be an array
# output: an array that is in alpabetical order determined on the string word of the integer
# Describe your algorithm
# pair the integer with the string represnting word. Push that into an array. Then sort that array with the string comparison, since they are paired
# it will return the pairs in aplabetical order, Then I flatten the array which leaves integers and strings, the integers at this point are still in order by aplabetical order
# Last I used select to choose the integers only.
# Alphabetical Numbers
# Write a method that takes an Array of Integers between 0 and 19, and returns an Array of those Integers sorted based on the English words for each number:
# zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen
# Examples:
# alphabetic_number_sort((0..19).to_a) == [
# 8, 18, 11, 15, 5, 4, 14, 9, 19, 1, 7, 17,
# 6, 16, 10, 13, 3, 12, 2, 0
# ]
# -------------------------------------------------------------------------------------
# Begin coding:
WORD_NUM = %w(zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen)
def alphabetic_number_sort(array)
pairs = array.each_with_object([]) { |idx, arr| arr << [idx, WORD_NUM[idx]] }
order = pairs.sort { | a, b | a[1] <=> b[1] }.flatten.select { |n| n.to_s.to_i == n }
end
def alphabetic_number_sort(array)
array.each_with_object([]) { |idx, arr| arr << [idx, WORD_NUM[idx]] }.sort { | a, b | a[1] <=> b[1] }.to_h.keys
end
# NUMBER_WORDS = %w(zero one two three four
# five six seven eight nine
# ten eleven twelve thirteen fourteen
# fifteen sixteen seventeen eighteen nineteen)
# def alphabetic_number_sort(numbers)
# numbers.sort_by { |number| NUMBER_WORDS[number] }
# end
p alphabetic_number_sort((0..19).to_a)
| true
|
826e5599e3ff56cb39e6715ebfeca8bd34b2ac6a
|
Ruby
|
syntacticsugar/Lovespell
|
/alt_animal_bird.rb
|
UTF-8
| 742
| 3.609375
| 4
|
[] |
no_license
|
class Brood
NAMES = %w( feathers quill falcon aerie nest eggs smokey skittles cereal merlin).map &:capitalize
def initialize(n)
@names = NAMES.sort {rand - 0.5}.take n
end
def hatch
if @names.empty?
raise EmptyNestException
else
n = @names.shift
f = rand 10
Bird.new n, f
end
end
class EmptyNestException < StandardError; end
end
class Animal
def initialize(name, fuzziness)
if name.is_a?(String) && fuzziness >= 0 && fuzziness <= 10
@name = name
@fuzziness = fuzziness
else
raise InanimateObjectException
end
end
class InanimateObjectException < StandardError; end
attr_reader :name, :fuzziness
end
class Bird < Animal
def eggs(n)
Brood.new n
end
end
| true
|
dafded257f52c2f53d871243cad01560391e3d5f
|
Ruby
|
andynu/rfk
|
/impression_log_to_scikitlearn_tsvs.rb
|
UTF-8
| 2,447
| 3.03125
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#!/usr/bin/env ruby
require 'chronic'
require 'set'
# Convert impression log into linear set of tag impressions
#
# outputs env_details.tsv:
# song label value impression
#
env = {}
File.open('env_detail.tsv','w') do |f|
File.open('data/impression.log').each_with_index do |line,i|
time,tag,*rest = line.strip.split("\t")
time = Chronic.parse(time)
case tag
when 'env'
key, value = rest
env[key] = value
when 'tag'
song, value, impression = rest
f.puts [song, 'tag', value, impression].join("\t")
when 'karma'
song, impression = rest
tags = {
hour: time.hour,
wday: time.wday,
mday: time.mday,
}
tags.each_pair do |label,val|
f.puts [song, label, val, impression].join("\t")
end
env.each_pair do |label,val|
f.puts [song, label, val, impression].join("\t")
end
else
warn [time,tag,rest].inspect
end
end
end
# aggregate details
hash = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
File.open('env_detail.tsv').each_with_index do |line,i|
song,label,value,impression = line.strip.split("\t")
hash[song][label][value] = 0 if hash[song][label][value].kind_of? Hash
hash[song][label][value] += 1
end
# output env_aggregate.tsv
# song label value sum_impression
File.open("env_aggregate.tsv",'w') do |f|
hash.each_pair do |song,label_value_counts|
label_value_counts.each_pair do |label,value_counts|
value_counts.each_pair do |value,count|
f.puts [song,label,value,count].join("\t")
end
end
end
end
# Collect labels
labels = Set.new
song_label_impressions = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
File.open('env_aggregate.tsv').each_with_index do |line,i|
song,label,value,impression = line.strip.split("\t")
key = [label,value].join(":")
labels << key
song_label_impressions[song][key] = impression
end
# Output group labels
labels = labels.to_a.sort
File.open("song_group_labels.tsv",'w') do |f|
labels.each do |label|
f.puts label
end
end
# Output song impressions by label:
# song group1_impression group2_impression group3_impression ...
File.open("song_group_matrix.tsv",'w') do |f|
song_label_impressions.each_pair do |song, label_impressions|
f.puts [song, labels.map{|key|
(label_impressions[key] == {}) \
? 0 \
: label_impressions[key]
}].flatten.join("\t")
end
end
| true
|
262f49dae146e4f3f5932e7e80e74d97fd9b497b
|
Ruby
|
loantranuet/BTVN_Ruby-Intro
|
/hw-ruby-intro-master/hw-ruby-intro-master/lib/ruby_intro.rb
|
UTF-8
| 2,239
| 4.28125
| 4
|
[] |
no_license
|
# Part 1
# Define a method sum(array) that takes an array of integers as an argument and returns the sum of its elements.
def sum (arr)
s=0
arr.each{|a| s+=a}
return s
end
# Define a method max_2_sum(array) which takes an array of integers as an argument and returns the sum of its two largest elements.
def max_2_sum (arr)
s=0
if (arr.length == 1)
return arr[0]
end
if (arr.length == 0)
return 0
end
if (!arr.empty?)
arr=arr.sort{ |x,y| y <=> x }
end
s= arr[0] + arr[1]
return s
end
# Define a method sum_to_n?(array, n) that takes an array of integers and an additional integer, n,
def sum_to_n? (arr, n)
count=false
if !(arr.empty? || arr.length == 1)
count=!! arr.uniq.combination(2).detect{|a,b| a + b == n}
end
return count
end
# # Part 2
# Define a method hello(name) that takes a string representing a name and returns the string "Hello, " concatenated with the name.
def hello(name)
str = "Hello, #{name}"
return str
end
# Define a method starts_with_consonant?(s) that takes a string and returns true if it starts with a consonant and false otherwise.
def starts_with_consonant? (s)
start = false
if ((s =~ /\A(?=[^aeiou])(?=[a-z])/i) == 0)
start = true
end
return start
end
# Define a method binary_multiple_of_4?(s) that takes a string and returns true if the string represents a binary number that is a multiple of 4.
def binary_multiple_of_4? (s)
isIt = false
if((s.to_i(2).is_a? Integer) && (s[0] == '0' || s[0] == '1'))
if(s.to_i(2) % 4 == 0)
isIt = true
end
end
return isIt
end
# # Part 3
# Define a class BookInStock which represents a book with an ISBN number, isbn, and price of the book as a floating-point number, price, as attributes.
class BookInStock
def initialize (isbn, price)
raise ArgumentError, "Argument not valid!" unless
!(!(price > 0) or !(isbn != ""))
@isbn = isbn
@price = price
end
attr_accessor :isbn
attr_accessor :price
def price_as_string ()
return "$#{'%.2f' % @price}"
end
end
| true
|
3c3b92a7ab5c0c531496a4ad8ed80ff837a7eb82
|
Ruby
|
dancernerd32/my-first-repository
|
/hours_in_a_year.rb
|
UTF-8
| 212
| 3.734375
| 4
|
[] |
no_license
|
puts "What year is it?"
year=gets.to_i
if year%4==0 && year%100!=0 || year%400==0
hours=366*24
puts "366 days times 24 hours per day"
else
hours=365*24
end
puts "There are " + hours.to_s + " hours in this year."
| true
|
eefa3f2eb2679ef1b2c8ea0369ba130de590b166
|
Ruby
|
prichard191/ruby-enumerables-introduction-to-map-and-reduce-lab-dumbo-web-120919
|
/lib/my_code.rb
|
UTF-8
| 1,200
| 3.421875
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def map_to_negativize(source_array)
new_arry = []
i = 0
while i < source_array.length do
new_arry.push( source_array[i] * -1 )
i += 1
end
return new_arry
end
def map_to_no_change(source_array)
some_arry = []
i = 0
while i < source_array.length do
some_arry.push( source_array[i] )
i += 1
end
return some_arry
end
def map_to_double(source_array)
this_arry = []
i = 0
while i < source_array.length do
this_arry.push( source_array[i] * 2 )
i += 1
end
return this_arry
end
def map_to_square(source_array)
brand_new = []
i = 0
while i < source_array.length do
brand_new.push( source_array[i] * source_array[i] )
i += 1
end
return brand_new
end
def reduce_to_total(source_array, starting_point=0)
new = starting_point
i = 0
while i < source_array.length do
new += source_array[i]
i += 1
end
return new
end
def reduce_to_all_true(source_array)
i = 0
while i < source_array.length do
return false if !source_array[i]
i += 1
end
return true
end
def reduce_to_any_true(source_array)
i = 0
while i < source_array.length do
return true if source_array[i]
i += 1
end
return false
end
| true
|
1f6c60a7699297465b2c899358463da89ab79676
|
Ruby
|
senseizp92/notepad
|
/task.rb
|
UTF-8
| 871
| 2.859375
| 3
|
[] |
no_license
|
# Подключим встроенный в руби класс Date для работы с датами
require 'date'
# Класс Задача, разновидность базового класса "Запись"
class Task < Post
def initialize
super # вызываем конструктор родителя
# потом инициализируем специфичное для Задачи поле - дедлайн
@due_date = Time.now
end
# Этот метод пока пустой, он будет спрашивать 2 строки - описание задачи и дату дедлайна
def read_from_console
end
# Массив из трех строк: дедлайн задачи, описание и дата создания
# Будет реализован в след. уроке
def to_strings
end
end
| true
|
1f564f26364af08552570a887be0bb5aff12021e
|
Ruby
|
repl-electric/dl-_-lb
|
/rescue/support/midi.rb
|
UTF-8
| 7,738
| 2.546875
| 3
|
[] |
no_license
|
def state()
$daw_state ||= {}
end
def warm
alive pad: 1 , apeg: 1, bass: 1, piano: 1, vocal: 1, kick: 1
[:c3, :cs3, :d3, :ds3, :e3, :f3, :fs3, :g3, :gs3, :a3, :as3, :b3,
:c4, :cs4, :d4, :ds4, :e4, :f4, :fs4, :g4, :gs4, :a4, :as4, :b4,
:c5, :cs5, :d5, :ds5, :e5, :f5, :fs5, :g5, :gs5, :a5, :as5, :b5,
].each{|n|
midi n,1, sus: 0.125, port: '*', channel: '*'
sleep 0.25
}
end
def alive(args)
_, opts = split_params_and_merge_opts_array(args)
opts.each{|s|
state[s[0]] = ((s[1] == 0) || (s[1] == 0.0)) ? false : true
v = (s[1] == 0.0) ? 127 : 0
case s[0]
when :pad
midi_cc 20, v, port: :iac_bus_1, channel: 1
when :harp
midi_cc 20, v, port: :iac_bus_1, channel: 2
when :perc
midi_cc 20, v, port: :iac_bus_1, channel: 3
when :crystal
midi_cc 21, v, port: :iac_bus_1, channel: 3
when :vastness
midi_cc 20, v, port: :iac_bus_1, channel: 4
when :pedal
midi_cc 22, v, port: :iac_bus_1, channel: 4
when :waves
midi_cc 21, v, port: :iac_bus_1, channel: 4
when :piano
midi_cc 20, v, port: :iac_bus_1, channel: 5
when :kalim #Kalims are mutually exclusive
midi_cc 21, v, port: :iac_bus_1, channel: 5
midi_cc 22, 0.0, port: :iac_bus_1, channel: 9
when :kalim2
midi_cc 22, v, port: :iac_bus_1, channel: 9
when :vocal
midi_cc 20, v, port: :iac_bus_1, channel: 6
when :kick
midi_cc 20, v, port: :iac_bus_1, channel: 7
end
}
end
def pad(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi_note_on n,vel, *(args << {channel: 1})
end
end
def pad_cc(cc)
cc.keys.each do |k|
n = case k
when :tone; 50
when :pitch; 51
when :motion; 52
when :fx; 53
else
nil
end
if n
midi_cc n, cc[k]*127.0, channel: 1
end
end
end
def octave(n, oct)
if n
note = SonicPi::Note.new(n)
note("#{note.pitch_class}#{oct}")
else
n
end
end
#scale C, D, E♭, F, G, A♭, and B♭.
def kick(v=100)
midi :C3 ,v, channel:7
end
def vastness(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n.is_a?(Array)
if state[:vastness]
synth = "Vastness"
elsif state[:waves]
synth = "waves"
end
puts synth
puts "!!!: Note array %s %s" %[n.to_s.ljust(4, " "), "[#{synth}]"]
return
end
if n
midi n, vel, *(args << {channel: 4, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
if state[:vastness]
synth = "Vastness"
elsif state[:waves]
synth = "waves"
end
puts "%s%s" %[nname.ljust(4, " "), "[#{synth}]"] if synth
vastness_cc opts
end
end
def vastness_on(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi_note_on n, vel, *(args << {channel: 4, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
if state[:vastness]
synth = "Vastness"
elsif state[:waves]
synth = "waves"
end
puts "%s%s" %[nname.ljust(4, " "), "[#{synth}]"] if synth
vastness_cc opts
end
end
def vastness_x(*args)
midi_all_notes_off port: :iac_bus_1, channel: 4
end
def vastness_cc(cc)
cc.keys.each do |k|
n = case k
when :detune; 49
when :pulse; 50
when :filter; 51
when :tone; 52
when :shape; 53
else
nil
end
if n == 49
midi_pitch_bend cc[k], channel: 4
elsif n
midi_cc n, cc[k]*127.0, port: :iac_bus_1, channel: 4
end
end
end
def perc(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi n, vel, *(args << {channel: 6, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
puts "%s%s" %[nname.ljust(4, " "), "[Perc]"] #if state[:vastness]
end
end
def crystal(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
if true#note(n) != note(:ds3)
midi n, vel, *(args << {channel: 11, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
puts "%s%s" %[nname.ljust(4, " "), " <Crystal>"] if state[:crystal]
end
end
end
def bright(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi n, vel, *(args << {channel: 5, port: :iac_bus_1})
if !opts[:piano] || opts[:piano] != 0
midi n, vel, *(args << {channel: 6, port: :iac_bus_1})
end
midi n, vel, *(args << {channel: 8, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
puts "%s%s" %[nname.ljust(4, " "), "[*Bright*]"] if state[:piano]
bright_cc opts
end
end
def kalim2(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi n, vel, *(args << {channel: 11, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
puts "%s%s" %[nname.ljust(4, " "), "[*Kalim*]"] if state[:piano]
end
end
def zero_delay(phases)
delays = phases
zero_cc rdelay: delays[0], ldelay: delays[1], cdelay: delays[2]
end
def zero_cc(cc)
channel = 5
cc.keys.each do |k|
n = case k
when :wash; 60
when :cdelay
m={1=> 0, 2 => 0.2, 3=>0.25, 4=> 0.4, 5=> 0.5, 6 => 0.65, 8 => 0.8, 16=> 1.0}
v = m[cc[k]]
if v
midi_cc 61, 127*v, port: :iac_bus_1, channel: channel
end
nil
when :ldelay
m={1=> 0, 2 => 0.2, 3=>0.25, 4=> 0.4, 5=> 0.5, 6 => 0.65, 8 => 0.8, 16=> 1.0}
v = m[cc[k]]
if v
midi_cc 62, 127*v, port: :iac_bus_1, channel: channel
end
nil
when :rdelay
m={1=> 0, 2 => 0.2, 3=>0.25, 4=> 0.4, 5=> 0.5, 6 => 0.65, 8 => 0.8, 16=> 1.0}
v = m[cc[k]]
if v
midi_cc 63, 127*v, port: :iac_bus_1, channel: channel
end
nil
else
nil
end
if n == 49
#midi_pitch_bend cc[k], channel: 4
elsif n
midi_cc n, cc[k]*127.0, port: :iac_bus_1, channel: channel
end
end
end
def bright_cc(cc)
cc.keys.each do |k|
n = case k
when :detune; 49
when :cutoff; 50
else
nil
end
if n == 49
#midi_pitch_bend cc[k], channel: 4
elsif n
midi_cc n, cc[k]*127.0, port: :iac_bus_1, channel: 5
end
end
end
def operator(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi n, vel, *(args << {channel: 6, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
puts "%s%s" %[nname.ljust(4, " "), "[Operator]"] if state[:piano]
end
end
def harp(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi n, vel, *(args << {channel: 2, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
puts "%s%s" %[nname.ljust(4, " "), "[Harp]"] if state[:harp]
end
end
def voices(*args)
params, opts = split_params_and_merge_opts_array(args)
opts = current_midi_defaults.merge(opts)
n, vel = *params
if n
midi n, vel, *(args << {channel: 8, port: :iac_bus_1})
nname = SonicPi::Note.new(n).midi_string
puts "%s%s" %[nname.ljust(4, " "), "[Harp]"] if state[:voice]
end
end
| true
|
5f91a29b32a9330ba81161519008afbdb2ca8860
|
Ruby
|
codegorilla/lang2
|
/CharacterLiteral.rb
|
UTF-8
| 287
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
require 'erb'
class CharacterLiteral
attr_reader :value
def initialize (value)
@value = value
end
def render ()
file = File.read("view/character_literal.c.erb")
template = ERB.new(file, nil, trim_mode=">", eoutvar='_sub01')
template.result(binding)
end
end
| true
|
8f58b322360b2e980140325fafd6d3472a378a2c
|
Ruby
|
Alex-ray/craigslist_jr
|
/db/seeds.rb
|
UTF-8
| 636
| 2.734375
| 3
|
[] |
no_license
|
require 'faker'
def seed_categories
categories = ["Hover Cars", "Spaceship",
"Flying Carpets", "Jet Packs",
"Google Glasses", "Doo Hickeys"]
categories.each do |category|
Category.create(name: category)
end
end
def seed_posts
categories = Category.all
100.times do
category = categories.sample
category.posts.create(title: Faker::Lorem.words(2).join(" "),
description: Faker::Lorem.paragraphs(3).join("\n"),
price: rand(59..999),
email: Faker::Internet.email)
end
end
seed_categories
seed_posts
| true
|
96fd404d0e46be13c0214bdb721727f0a0296cca
|
Ruby
|
oozywaters/thinknetika-lessons
|
/Lesson-02/05_date.rb
|
UTF-8
| 780
| 3.953125
| 4
|
[] |
no_license
|
puts "Введите число (день):"
day = gets.chomp.to_i
puts "Введите порядковый номер месяца:"
month = gets.chomp.to_i - 1
puts "Введите год:"
year = gets.chomp.to_i
def leap_year?(year)
(year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)
end
days_count = 0
months_days = [31, (leap_year?(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
is_correct_date = months_days[month] && day > 0 && day <= months_days[month]
if is_correct_date
months_days.first(month).each { |n| days_count += n}
days_count += day
month_str = (month + 1).to_s.rjust(2, '0')
puts "#{day}.#{month_str}.#{year} - это #{days_count}-й день в году"
else
puts "Вы ввели неправильную дату!"
end
| true
|
b6a732a49885f0b0ecf8cfd60c82b5a0b059f4a6
|
Ruby
|
mathewdbutton/exercism-exercises
|
/ruby/difference-of-squares/difference_of_squares.rb
|
UTF-8
| 352
| 2.953125
| 3
|
[] |
no_license
|
class Squares
POWER = 2
def initialize(natural_number)
@natural_number = natural_number
end
def square_of_sum
(1..@natural_number).sum ** POWER
end
def sum_of_squares
(1..@natural_number).map { |n| n ** POWER }.sum
end
def difference
square_of_sum - sum_of_squares
end
end
module BookKeeping
VERSION = 4
end
| true
|
a230a6741998d802fca145fd9770dcb7cdd0c5a6
|
Ruby
|
sis-berkeley-edu/calcentral
|
/app/models/hub_edos/student_api/v2/student/student_attribute.rb
|
UTF-8
| 2,050
| 2.828125
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"ECL-2.0"
] |
permissive
|
module HubEdos
module StudentApi
module V2
module Student
# A Student Attribute is a free form characteristic assigned to the student via various processes.
class StudentAttribute
def initialize(data)
@data = data || {}
end
# a short descriptor representing the kind of attribute assigned to the student, such as American Cultures, Incentive Awards Program, etc.
def type
::HubEdos::Common::Reference::Descriptor.new(@data['type']) if @data['type']
end
# returns type descriptor code
def type_code
type.try(:code)
end
# a short descriptor representing the origination of this attribute
def reason
::HubEdos::Common::Reference::Descriptor.new(@data['reason']) if @data['reason']
end
# a component that describes the term on which this attribute became associated with the student
def from_term
::HubEdos::StudentApi::V2::Term::Term.new(@data['fromTerm']) if @data['fromTerm']
end
# a component that describes the term on which this attribute is no longer to be associated with the student
def to_term
::HubEdos::StudentApi::V2::Term::Term.new(@data['toTerm']) if @data['toTerm']
end
# the date on which this attribute became associated with the student date
def from_date
@from_date ||= begin
Date.parse(@data['fromDate']) if @data['fromDate']
end
end
# the date on which this attribute is no longer to be associated with the student date
def to_date
@to_date ||= begin
Date.parse(@data['toDate']) if @data['toDate']
end
end
# free form text giving additional information about this attribute or its assignment string
def comments
@data['comments']
end
end
end
end
end
end
| true
|
f9622b1f0cd4f723e669df099797efec2b19a092
|
Ruby
|
csuhta/environment
|
/bin/random
|
UTF-8
| 2,876
| 3.28125
| 3
|
[
"Unlicense"
] |
permissive
|
#!/usr/bin/env ruby
# encoding: utf-8
# Generates random values
# Usage: random [-uxah] [--uuid] [--hexadecimal] [--alphanumeric] [--help] [length]
# -x, --hexadecimal Return a hexadecimal number
# -a, --alphanumeric Return alphanumeric characters (default)
# -u, --uuid Return a purely random UUID instead (length ignored)
# -v, --version Print the version and exit
# -h, --help Show this message
# Unseat OpenSSL so that we only use /dev/urandom when calling SecureRandom
if Object.constants.include?(:OpenSSL)
Object.send(:remove_const, :OpenSSL)
end
require "securerandom"
require "optparse"
# ----------------------------------------------------------------------------
# OPTIONS
# ----------------------------------------------------------------------------
@options = {
alphanumeric: true
}
@limit = 32
@parser = OptionParser.new do |opts|
opts.banner = "Usage: \e[1mrandom\e[0m [\e[1m-uxah\e[0m] "
opts.banner << "[\e[1m--uuid\e[0m] "
opts.banner << "[\e[1m--hexadecimal\e[0m] "
opts.banner << "[\e[1m--alphanumeric\e[0m] "
opts.banner << "[\e[1m--help\e[0m] "
opts.banner << "[\e[4mlength\e[0m]"
opts.on("-x", "--hexadecimal", "Return a hexadecimal number") do |option|
@options[:hexadecimal] = option
end
opts.on("-a", "--alphanumeric", "Return alphanumeric characters (default)") do |option|
# This is the default
end
opts.on("-u", "--uuid", "Return a purely random UUID instead (length ignored)") do |option|
@options[:uuid] = option
end
opts.on("-v", "--version", "Print the version and exit") do |option|
puts "random 1.0.5"
exit 0
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit 0
end
end
begin @parser.parse! ARGV
rescue OptionParser::InvalidOption => error
puts error
puts @parser
exit 1
end
def invalid_length
puts "Invalid length given, must be 1 or greater"
puts @parser
exit 1
end
# ----------------------------------------------------------------------------
# UUID
# ----------------------------------------------------------------------------
if @options[:uuid]
puts SecureRandom.uuid
exit 0
end
# ----------------------------------------------------------------------------
# RANDOM CHARACTERS
# ----------------------------------------------------------------------------
# If a limit was given, don't use the default. Exit if invalid
if ARGV.first
@limit = ARGV.first.to_i
invalid_length unless @limit > 0
@limit = @limit
end
# Hexadecimals requested?
if @options[:hexadecimal]
puts SecureRandom.hex(@limit * 3)[0..(@limit - 1)]
exit 0
end
# Alphanumeric characters requested?
if @options[:alphanumeric]
puts SecureRandom.urlsafe_base64(@limit * 3).gsub(/[-_]/,"")[0..(@limit - 1)]
exit 0
end
| true
|
0e8f953af2da53169cd3314b7aa511b7dbfdf541
|
Ruby
|
emmiehayes/credit_check
|
/test/credit_check_test.rb
|
UTF-8
| 2,108
| 3.15625
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require "minitest/pride"
require './lib/credit_check'
class CreditCheckTest < Minitest::Test
def test_it_can_convert_integer_to_reversed_array
cc = CreditCheck.new
expected = [3, 4, 5, 0, 5, 2, 7, 7, 4, 5, 3, 7, 9, 2, 9, 4]
assert_equal expected, cc.card_number_to_reversed_array('4929735477250543')
end
def test_it_can_double_every_other_number
cc = CreditCheck.new
numbers = [3, 4, 5, 0, 5, 2, 7, 7, 4, 5, 3, 7, 9, 2, 9, 4]
expected = [3, 8, 5, 0, 5, 4, 7, 14, 4, 10, 3, 14, 9, 4, 9, 8]
assert_equal expected, cc.double_every_other_number(numbers)
end
def test_it_can_sum_numbers_over_nine
cc = CreditCheck.new
numbers = [3, 8, 5, 0, 5, 4, 7, 14, 4, 10, 3, 14, 9, 4, 9, 8]
expected = [3, 8, 5, 0, 5, 4, 7, 5, 4, 1, 3, 5, 9, 4, 9, 8]
assert_equal expected, cc.sum_numbers_over_nine(numbers)
end
def test_it_can_sum_the_final_array
cc = CreditCheck.new
numbers = [3, 8, 5, 0, 5, 4, 7, 5, 4, 1, 3, 5, 9, 4, 9, 8]
assert_equal 80, cc.sum_final_array(numbers)
end
def test_can_can_recognize_valid_card_numbers
cc = CreditCheck.new
assert_equal "Card is valid.", cc.validate_card("4929735477250543")
assert_equal "Card is valid.", cc.validate_card("4024007136512380")
assert_equal "Card is valid.", cc.validate_card("6011797668867828")
end
def test_can_recognize_invalid_card_numbers
cc = CreditCheck.new
assert_equal "Card is invalid.", cc.validate_card('5541801923795240')
assert_equal "Card is invalid.", cc.validate_card('4024007106512380')
assert_equal "Card is invalid.", cc.validate_card('6011797668868728')
end
def test_can_recognize_valid_American_Express_number
cc = CreditCheck.new
assert_equal "Card is valid.", cc.validate_card('342804633855673')
end
def test_can_recognize_invalid_American_Express_number
cc = CreditCheck.new
assert_equal "Card is invalid.", cc.validate_card('342801633855673')
end
def test_can_handle_empty_case
cc = CreditCheck.new
assert_equal "Card is invalid.", cc.validate_card('')
end
end
| true
|
a482437b2027e84c41fad3138c8fc916cf507445
|
Ruby
|
michaelrizzo2/Ruby-Development
|
/array_iterator.rb
|
UTF-8
| 344
| 3.921875
| 4
|
[] |
no_license
|
#!/usr/bin/ruby
#This will iterate through an array using an until loop and while loop
array=[1,2,3,4,5]
#This will set the iterator index for the array
index=0
#while index<array.length
# puts "array entry #{index} is #{array[index]}"
# index+=1
#end
until index==array.length
puts "array entry #{index} is #{array[index]}"
index+=1
end
| true
|
255a4eb237e173e2ba4cea9e6fef9034f2f8caaa
|
Ruby
|
esmith2078/launch_school
|
/ruby_basics/user_input/print_something2.rb
|
UTF-8
| 514
| 4.125
| 4
|
[] |
no_license
|
# print_something2.rb
loop do
puts '>> Do you want me to print something? (y/n)'
choice = gets.chomp
if choice.upcase.eql? "Y"
puts 'something'
elsif choice.upcase.eql? "N"
else
puts 'Incorrect selection, try again'
end
break
end
# Solution version
=begin
choice = nil
loop do
puts '>> Do you want me to print something? (y/n)'
choice = gets.chomp.downcase
break if %w(y n).include?(choice)
puts '>> Invalid input! Please enter y or n'
end
puts 'something' if choice == 'y'
=end
| true
|
aa91c2f9c28388ab7edb5986947e4573a482f531
|
Ruby
|
mrrusof/algorithms
|
/paint-house/ruby/main.rb
|
UTF-8
| 1,040
| 4.0625
| 4
|
[] |
no_license
|
#!/usr/bin/env ruby
=begin
There are a row of n houses, each house can be painted with one of the
three colors: red, blue or green. The cost of painting each house with
a certain color is different. You have to paint all the houses such
that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by
a n x 3 cost matrix. For example, costs[0][0] is the cost of painting
house 0 with color red; costs[1][2] is the cost of painting house 1
with color green, and so on... Find the minimum cost to paint all
houses.
=end
def mc_ph cm
ac = [0,0,0]
cm.each do |cv|
ac = cv.each_with_index.map do |c, i|
c + ac.each_with_index.select{ |_, j| j != i }.map{ |c, _| c }.min
end
end
return ac.min
end
[ [ 4, [ [1,2,3], [3,2,1], [2,1,3], [3,2,1] ] ],
[ 3, [ [1,2,3], [1,3,3] ] ],
[ 2, [ [1,2,3], [1,1,3] ] ]
].each do |exp, cm|
act = mc_ph(cm)
if exp == act
puts "PASS mc_ph #{cm} = #{exp}"
else
puts "FAIL mc_ph #{cm} = #{act} (#{exp})"
end
end
| true
|
c8550fa8791ba71ea87368b784d47024b92f9d50
|
Ruby
|
marcbobson2/supplement
|
/quiz1int/problem4.rb
|
UTF-8
| 368
| 4.25
| 4
|
[] |
no_license
|
numbers = [1, 2, 3, 4]
numbers.each do |number|
p number
numbers.shift(1)
end
#first will print out 1
#next will reduce array to [2,3,4]
#question: how does each work
# since each calls the block for each element, it should print out 2, then 3, then 4
numbers = [1, 2, 3, 4]
numbers.each do |number|
p number
numbers.pop(1)
end
# should print 1 and 2
| true
|
e97a7f508902691c69a2f3beeb2648d7d7b6e73a
|
Ruby
|
mbj/formitas
|
/lib/formitas/binding.rb
|
UTF-8
| 2,446
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
module Formitas
# Abstract base class for field with value
class Binding
include Adamantium::Flat, AbstractType
abstract_method :html_value
abstract_method :domain_value
# Return field
#
# @return [Field]
#
# @api private
#
attr_reader :field
private
# Initialize object
#
# @param [Field] field
#
# @api private
#
def initialize(field)
@field = field
end
end
class Binding
# Binding for empty field
class Empty < self
include Equalizer.new(:field)
EMPTY_STRING = ''.freeze
# Return html value
#
# @return [String]
#
# @api private
#
def html_value
EMPTY_STRING
end
# Return domain value
#
# @return [:Undefined]
#
# @api private
#
def domain_value
Undefined
end
end
# Binding for field with html value
class HTML < self
include Equalizer.new(:field, :html_value)
# Return domain value loaded from html
#
# @return [Object]
# if successful
#
# @return [Undefined]
# otherwise
#
# @api private
#
def domain_value
field.domain_value(html_value)
end
memoize :domain_value
private
# Initialize object
#
# @param [Field] field
# @param [String] html_value
#
# @api private
#
def initialize(field, html_value)
super(field)
@html_value = html_value
end
end
# Class for field with domain value
class Domain < self
include Equalizer.new(:field, :domain_value)
# Return html value dumped from domain value
#
# @return [String]
# if successful
#
# @return [Undefined]
# otherwise
#
# @api private
#
def html_value
field.html_value(domain_value)
end
memoize :html_value
# Return bound domain value
#
# @return [Object]
#
# @api private
#
attr_reader :domain_value
private
# Initialize object
#
# @param [Field] field
#
# @param [Object] domain_value
#
# @return [undefined]
#
# @api private
#
def initialize(field, domain_value)
super(field)
@domain_value = domain_value
end
end
end
end
| true
|
16ba790ae6f5006798aa0c3dd80ee1ea1d50dc54
|
Ruby
|
vzasade/myscrpts
|
/explode.rb
|
UTF-8
| 2,048
| 2.890625
| 3
|
[] |
no_license
|
if __FILE__ == $0
# TODO Generated stub
end
def suppress_warnings
original_verbosity = $VERBOSE
$VERBOSE = nil
result = yield
$VERBOSE = original_verbosity
return result
end
require 'rubygems'
require 'zip/zip'
suppress_warnings{require 'FileUtils'}
require 'find'
def unzip_file (file, destination)
puts "Unzip " + file + " to " + destination
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
#puts "Extract " + f.to_s + " to " + f_path
zip_file.extract(f, f_path) unless File.exist?(f_path)
}
}
end
def iterateThroughFiles( dirname )
Find.find( dirname ) do | thisfile |
thisfile.gsub!( /\// , '\\' )
yield(thisfile)
end
end
def isAllowedJar(fname)
if fname == 'schemas.jar' or fname == 'adf-loc.jar'
return true
else
puts "Skipping " + fname
end
end
def isArchive(fname)
ext = File.extname(fname).downcase
if (ext == '.ear') or (ext == '.war') or (ext == '.mar')
return true
end
if ext == '.jar'
return isAllowedJar(File.basename(fname.downcase))
end
return false
end
def getDestDir(file)
return File.join(File.dirname(file), "_" + File.basename(file))
end
def explodeArchive(file, dest_dir)
unzip_file(file, dest_dir)
file_list = Array.new
iterateThroughFiles(dest_dir) do |path|
if !FileTest.directory?(path)
if isArchive(path)
file_list.push(path)
end
end
end
file_list.each do |file|
explodeArchive(file, getDestDir(file))
end
end
######################################################
# Body
######################################################
if ARGV.length != 2
puts 'Incorrect number of arguments!'
puts 'USAGE: explode.rb <archive> <dest_dir>'
exit -1
end
archive = ARGV[0]
dest_dir = ARGV[1]
if !isArchive(archive)
raise "This is not an archive"
end
puts "Removing " + dest_dir
FileUtils.rm_rf(dest_dir)
explodeArchive(archive, dest_dir)
| true
|
3a475e5590d9deb0a380cc4137a2b7d4e537493b
|
Ruby
|
li-thy-um/leetcode
|
/4-median-of-two-sorted-arrays.rb
|
UTF-8
| 3,208
| 3.34375
| 3
|
[] |
no_license
|
# @param {Integer[]} nums1 (Array A)
# @param {Integer[]} nums2 (Array B)
# @return {Float}
def find_median_sorted_arrays(nums1, nums2)
raise "Empty inputs" if nums1.size + nums2.size == 0
return nums2.sorted_median if nums1.size == 0
return nums1.sorted_median if nums2.size == 0
solve(nums1, nums2, 0, nums1.size-1, 0, nums2.size-1)
end
def solve(n1, n2, i1, j1, i2, j2)
l1 = j1 - i1 + 1
l2 = j2 - i2 + 1
mi1 = n1.index_of_sorted_median(i1, j1)
mi2 = n2.index_of_sorted_median(i2, j2)
m1 = n1.sorted_median(i1, j1)
m2 = n2.sorted_median(i2, j2)
case
when l1 == 1 && l2 == 1
(n1[i1] + n2[i2]) / 2.0
when l1 == 1
n2.median_single i2, j2, n1[i1]
when l2 == 1
n1.median_single i1, j1, n2[i2]
when l1 == 2
n2.median_double i2, j2, n1[i1], n1[j1]
when l2 == 2
n1.median_double i1, j1, n2[i2], n2[j2]
when m1 == m2
m1
when m1 > m2
x = j1 - mi1[1]
y = mi2[0] - i2
z = x < y ? x : y
solve(n1, n2, i1, j1 - z, i2 + z, j2)
when m1 < m2
solve(n2, n1, i2, j2, i1, j1)
end
end
class Array
def prev(i)
i - 1 < 0 ? nil : self[i - 1]
end
def next(i)
self[i + 1]
end
# precondition => n1 <= n2
def median_double(i = 0, j = self.size - 1, n1, n2)
mi1, mi2 = self.index_of_sorted_median(i, j)
m1, m2 = self[mi1], self[mi2]
l = j - i + 1
if l.even?
m1_prev = self.prev(mi1)
m2_next = self.next(mi2)
case
when n2 <= m1
[[n2, m1_prev].compact.max, m1]
when m1 <= n1 && n2 <= m2
[n1, n2]
when n1 <= m1 && m1 <= n2 && n2 <= m2
[m1, n2]
when m1 <= n1 && n1 <= m2 && m2 <= n2
[n1, m2]
when n1 <= m1 && m2 <= n2
[m1, m2]
when m2 <= n1
[m2, [n1, m2_next].compact.min]
end
else
m, mi = m1, mi1
m_prev = self.prev(mi)
m_next = self.next(mi)
case
when n1 <= m && m <= n2
[m, m]
when n2 <= m
[[m_prev, n2].compact.max] * 2
when m <= n1
[[m_next, n1].compact.min] * 2
end
end.reduce(0, &:+) / 2.0
end
def median_single(i = 0, j = self.size - 1, n)
mi1, mi2 = self.index_of_sorted_median(i, j)
m1, m2 = self[mi1], self[mi2]
l = j - i + 1
if l.even?
case
when n <= m1
[m1, m1]
when n >= m2
[m2, m2]
else
[n, n]
end
else
m, mi = m1, mi1
case
when n < (m_prev = self.prev(mi))
[m, m_prev]
when n > (m_next = self.next(mi))
[m, m_next]
else
[n, m]
end
end.reduce(0, &:+) / 2.0
end
def index_of_sorted_median(i = 0, j = self.size - 1)
raise "Empty Array Error" if self.size == 0
# Special cases.
i, j = j, i if i > j
return [i, i] if i == j
i = 0 if i < 0
j = self.size - 1 if j >= self.size
# Compute index of median
n = j - i + 1
if n.even?
[i+n/2-1, i+n/2]
else
m = (n+1)/2-1
[i+m, i+m]
end
end
def sorted_median(i = 0, j = self.size - 1)
i1, i2 = index_of_sorted_median(i, j)
(self[i1] + self[i2]) / 2.0
end
end
puts find_median_sorted_arrays([1,2,6,7], [3,4,5,8])
| true
|
1fb4702da3f67c4762704860ddd17df2fa82362a
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/leap/ba18aff13a8645178373b3ce10a9344b.rb
|
UTF-8
| 410
| 3.59375
| 4
|
[] |
no_license
|
module Year
extend self
def leap?(year)
return fourth_year?(year) if div_by?(year, 400)
return fourth_year_of_a_non_century?(year)
end
private
def fourth_year_of_a_non_century?(year)
fourth_year?(year) && !century?(year)
end
def century?(year)
div_by?(year, 100)
end
def fourth_year?(year)
div_by?(year, 4)
end
def div_by?(year, n)
(year % n).zero?
end
end
| true
|
7085bb5ed17ad3214678faa0ed0bf16986dea173
|
Ruby
|
tdooner/advent-code
|
/2020/14/process.rb
|
UTF-8
| 1,545
| 3.5
| 4
|
[] |
no_license
|
require 'pry'
input = $<.map(&:strip)
def solve(input)
bitmask = nil
mem = {}
input.map do |line|
cmd, value = line.split(' = ')
if cmd == 'mask'
bitmask = value.reverse
else
mem_id = cmd[4..-2]
binary = value.to_i.to_s(2).each_char.map(&:to_i).reverse
masked_value = bitmask.each_char.each_with_index.map do |mask, i|
bit = binary[i] || 0
if mask == 'X'
bit
else
mask
end
end.reverse.join.to_i(2)
puts [mem_id, masked_value].inspect
mem[mem_id] = masked_value
end
end
mem.values.sum
end
def each_x(str)
num_x = str.count('X')
(0...2**num_x).each do |i|
binary = i.to_s(2).reverse.each_char.to_a
new_str = str.dup
loop do
break unless new_str['X']
new_str['X'] = binary.shift || '0'
end
yield new_str.to_i(2)
end
end
def solve2(input)
bitmask = nil
mem = {}
input.map do |line|
cmd, value = line.split(' = ')
if cmd == 'mask'
bitmask = value.reverse
else
mem_id = cmd[4..-2]
binary = mem_id.to_i.to_s(2).each_char.map(&:to_i).reverse
masked_value = bitmask.each_char.each_with_index.map do |mask, i|
bit = binary[i] || 0
if mask == '0'
bit
else
mask
end
end.reverse.join
each_x(masked_value) do |address|
mem[address] = value.to_i
end
end
end
mem.values.sum
end
puts 'Part 1:'
puts solve(input).inspect
puts 'Part 2:'
puts solve2(input).inspect
| true
|
5b1266434fc0e2fa4947f7d19a85c9cad9be8dd0
|
Ruby
|
Lodi2244/THP-semaine-0
|
/exo_19.rb
|
UTF-8
| 251
| 2.953125
| 3
|
[] |
no_license
|
my_array = []
0.upto(50) do |i|
i += 1
if i < 10
my_array << "Tite.Lodi.0#{i}@email.com"
else
my_array << "Tite.Lodi.#{i}@email.com"
end
end
for i in 0..my_array.size
if i % 2 != 0
break if i == 50
puts my_array[i]
end
end
| true
|
8093c87b6d66c6a10b6aaa32d6227290d7e18279
|
Ruby
|
Capncavedan/Powerball-numbers
|
/lib/powerball_html_grabber.rb
|
UTF-8
| 364
| 2.65625
| 3
|
[] |
no_license
|
require 'open-uri'
class PowerballHtmlGrabber
def html
URI.parse(url).read
end
private
def end_date
Date.parse("1 November 1997").strftime("%m/%d/%Y")
end
def start_date
Date.today.strftime("%m/%d/%Y")
end
def url
"http://www.powerball.com/powerball/pb_nbr_history.asp?startDate=#{start_date}&endDate=#{end_date}"
end
end
| true
|
24172346c81fc7e7e985bbdc41885ee155c366e9
|
Ruby
|
ElvinGarcia/my_find_code_along-v-000
|
/lib/my_find.rb
|
UTF-8
| 240
| 3.453125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
def my_find(collection)
i=0
while i < collection.length
return collection[i] if yield(collection[i])
i+=1
end
end
collection = (1..100).to_a
my_find(collection) do |obj|
obj % 3 == 0 && obj % 5 == 0
end
| true
|
133d6bee677a2297acd944d34ae81e53ce1a76f4
|
Ruby
|
alvarezleonardo/kleer_generala
|
/app.rb
|
UTF-8
| 1,012
| 2.546875
| 3
|
[] |
no_license
|
require 'sinatra'
require './lib/Generala.rb'
get '/' do
@@generala = Generala.new
@images = []
erb :home
end
post '/tirardados' do
@@generala.tirarDados
@images = ["","","","",""]
@index = 0
@@generala.getDados.each do |dado|
@images[@index] = "<img src='./images/dado"+dado.to_s+".png'/>"
@index=@index+1
end
@index = 0
@selecciones = @@generala.getSeleccionDado
@@generala.getSeleccionDado.each do |seleccion|
if seleccion != 0
@selecciones[@index] = "<li>"+ (@index+1).to_s + " - " + seleccion.to_s + "<input type='radio' name='dado' value='"+ (@index+1).to_s + "'/></li>"
else
@selecciones[@index] = "-"
end
@index=@index+1
end
erb :home
end
post '/seleccionardados' do
@@generala.setDadoSelecionado params["dado"].to_i
@images = ["","","","",""]
@index = 0
@@generala.tirarDados
@@generala.getDados.each do |dado|
@images[@index] = "<img src='./images/dado"+dado.to_s+".png'/>"
@index=@index+1
end
@selecciones = []
erb :home
end
| true
|
9897bf95e6eb1e5076aca5e9d010ac12f046d170
|
Ruby
|
cmezouar/thpw1_ruby_loops
|
/lib/03_stairway.rb
|
UTF-8
| 1,576
| 4.1875
| 4
|
[] |
no_license
|
def game_setup
stairway=[]
count=0
11.times do
stairway.push(count)
count=count+1
end
return stairway
end
def roll_dice
n= 1+rand(6)
puts n
return n
end
def climb_stairs(position,stairway)
new_position=position+1
position=stairway[new_position]
if position != 10
puts "You climbed one step! Current position: #{position}th step."
end
return position
end
def down_stairs(position, stairway)
new_position=position-1
position=stairway[new_position]
puts "You went one step down! Current position: #{position}th step."
return position
end
def play_game
stairway=game_setup
position=0
number_of_turns=0
while position != 10
n=roll_dice
if n==5 || n==6
position=climb_stairs(position,stairway)
end
if n==1 && position!=0
position=down_stairs(position,stairway)
end
if n==1 && position==0
puts "Nothing happened. Current position: #{position}"
end
if n==2 || n==3 || n==4
puts "Nothing happened. Current position: #{position}"
end
number_of_turns = number_of_turns+1
end
puts "Congratulations! You reached the 10th step !"
return number_of_turns
end
def average_finish_time(n)
values=[]
n.times do
number_of_turns=play_game
values.push(number_of_turns)
end
size=values.size
sum=values.sum
average_finish_time=sum/size
puts average_finish_time
end
average_finish_time(100)
| true
|
345131734abf11160e996011ef4622d2c566ad5c
|
Ruby
|
vasipetrova/blog
|
/app/models/user.rb
|
UTF-8
| 1,760
| 2.859375
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
has_many :posts
has_many :comments
attr_accessor :password
#before you save the password encrypt it BCrypt
before_save :encrypt_password
#validate that the password isn't blank
validates_confirmation_of :password
# The username, password and email cannot be blank when the user is being created
validates_presence_of :password, :on => :create
validates_presence_of :email, :on => :create
validates_presence_of :username, :on => :create
# Validate that the username and email for each user are unique
validates_uniqueness_of :email
validates_uniqueness_of :username
# Authenticate a user with teh email and password using BCrypt
def self.authenticate_by_email(email, password)
# Get the user record from the database using the email as a key
user = User.find_by_email(email)
# If the password is valid return the user object otherwise return an empty object
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
# Authenticate a user with teh username and password using BCrypt
def self.authenticate_by_username(username, password)
# Get the user record from the database using the username as a key
user = find_by_username(username)
# if the user is valid and the hashed passwords math return the user object
# otherwise return an empty object
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
# Hasing the password with salt using BCrypt
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
| true
|
05cb58ecc915adc70e2ede35490b892850b94a57
|
Ruby
|
layornos/7lan7wks
|
/Ruby/regex_file.rb
|
UTF-8
| 351
| 2.671875
| 3
|
[] |
no_license
|
if RUBY_VERSION =~ /2.3/ # assuming you're running Ruby ~1.9
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
end
filename = "example.txt"
text = File.open(filename).read
linenumber = 1
text.each_line do |line|
if line =~ /ü(.*)ö(.*)(ä.*)/
puts linenumber.to_s + ": " + line
end
linenumber += 1
end
| true
|
205e75a76eb42a1b07db255907d18aa74ea52681
|
Ruby
|
dflourusso/curso-programacao
|
/algoritmos/ruby/sintaxe/palavras_reservadas.rb
|
UTF-8
| 6,078
| 3.5625
| 4
|
[] |
no_license
|
=begin ordem alfabética
BEGIN Code, enclosed in {}, to run before the program runs.
END Code, enclosed in {}, to run when the program ends.
alias Cria um apelido para um método, operador ou variável global
and Operador lógico, mesmo que &&, mas com precedência menor
begin Begins a code block or group of statements; closes with end.
break Terminates a while or until loop, or a method inside a block.
case Compares an expression with a matching when clause; closes with end. See when.
class Defines a class; closes with end.
def Defines a method; closes with end.
defined? A special operator that determines whether a variable, method, super method, or block exists.
do Begins a block, and executes code in that block; closes with end.
else Executes following code if previous conditional is not true, set with if, elsif, unless, or case. See if, elsif.
elsif Executes following code if previous conditional is not true, set with if or elsif.
end Ends a code block (group of statements) started with begin, class, def, do, if, etc.
ensure Always executes at block termination; use after last rescue.
false Logical or Boolean false; instance of FalseClass; a pseudovariable. See true.
for Begins a for loop; used with in.
if Executes code block if conditional statement is true. Closes with end. Compare unless, until.
in Used with for loop. See for.
module Defines a module; closes with end.
next Jumps to the point immediately before the evaluation of the loop’s conditional. Compare redo.
nil Empty, uninitialized, or invalid; always false, but not the same as zero; object of NilClass; a pseudovariable.
not Logical operator; same as !.
or Logical operator; same as || except or has lower precedence.
redo Jumps after a loop’s conditional. Compare next.
rescue Evaluates an expression after an exception is raised; used before ensure.
retry When called outside of rescue, repeats a method call; inside rescue, jumps to top of block (begin).
return Returns a value from a method or block.
self Current object (receiver invoked by a method); a pseudovariable.
super Calls method of the same name in the superclass. The superclass is the parent of this class.
then Separator used with if, unless, when, case, and rescue. May be omitted, unless conditional is all on one line.
true Logical or Boolean true; instance of TrueClass; a pseudovariable. See false.
undef Makes a method undefined in the current class.
unless Executes code block if conditional statement is false. Compare if, until.
until Executes code block while conditional statement is false. Compare if, unless.
when Starts a clause (one or more) under case.
while Executes code while the conditional statement is true.
yield Executes the block passed to a method.
__FILE__ Name of current source file; a pseudovariable.
__LINE__ Number of current line in the current source file; apseudovariable.
=end
=begin agrupados
BEGIN Code, enclosed in {}, to run before the program runs.
END Code, enclosed in {}, to run when the program ends.
alias Cria um apelido para um método, operador ou variável global
defined? A special operator that determines whether a variable, method, super method, or block exists.
undef Makes a method undefined in the current class.
module Defines a module; closes with end.
def Defines a method; closes with end.
class Defines a class; closes with end.
self Current object (receiver invoked by a method); a pseudovariable.
super Calls method of the same name in the superclass. The superclass is the parent of this class.
not Logical operator; same as !.
and Operador lógico, mesmo que &&, mas com precedência menor
or Logical operator; same as || except or has lower precedence.
true Logical or Boolean true; instance of TrueClass; a pseudovariable. See false.
false Logical or Boolean false; instance of FalseClass; a pseudovariable. See true.
nil Empty, uninitialized, or invalid; always false, but not the same as zero; object of NilClass; a pseudovariable.
begin Begins a code block or group of statements; closes with end.
end Ends a code block (group of statements) started with begin, class, def, do, if, etc.
yield Executes the block passed to a method.
return Returns a value from a method or block.
do Begins a block, and executes code in that block; closes with end.
else Executes following code if previous conditional is not true, set with if, elsif, unless, or case. See if, elsif.
elsif Executes following code if previous conditional is not true, set with if or elsif.
rescue Evaluates an expression after an exception is raised; used before ensure.
ensure Always executes at block termination; use after last rescue.
for Begins a for loop; used with in.
in Used with for loop. See for.
next Jumps to the point immediately before the evaluation of the loop’s conditional. Compare redo.
redo Jumps after a loop’s conditional. Compare next.
break Terminates a while or until loop, or a method inside a block.
retry When called outside of rescue, repeats a method call; inside rescue, jumps to top of block (begin).
while Executes code while the conditional statement is true.
until Executes code block while conditional statement is false. Compare if, unless.
if Executes code block if conditional statement is true. Closes with end. Compare unless, until.
then Separator used with if, unless, when, case, and rescue. May be omitted, unless conditional is all on one line.
unless Executes code block if conditional statement is false. Compare if, until.
when Starts a clause (one or more) under case.
case Compares an expression with a matching when clause; closes with end. See when.
__FILE__ Name of current source file; a pseudovariable.
__LINE__ Number of current line in the current source file; apseudovariable.
=end
| true
|
37fcd4b25f20683f6d06678ab232ab91638856ed
|
Ruby
|
guidance-guarantee-programme/reporting
|
/app/view_models/costs/items.rb
|
UTF-8
| 803
| 2.78125
| 3
|
[] |
no_license
|
module Costs
class Items
attr_reader :year_months
def initialize(year_months:)
@year_months = year_months
end
def all
@all ||= begin
items = CostItem.current | CostItem.during_months(@year_months)
items = items.sort_by { |cost_item| [cost_item.cost_group, cost_item.name] }
items.map do |cost_item|
Costs::Item.new(cost_item: cost_item, year_months: @year_months)
end
end
end
def by_cost_group
@by_cost_group ||= all.group_by(&:cost_group)
end
def for(id, month)
all.detect { |item| item.id == id }.for(month)
end
def sum_for(month, cost_group = nil)
scope = cost_group ? by_cost_group.fetch(cost_group) : all
scope.sum { |item| item.for(month).value }
end
end
end
| true
|
e41bebe637d7670306d73c326ae33dbc58664ea3
|
Ruby
|
menyhertfatyol/learning_rspec
|
/customer.rb
|
UTF-8
| 245
| 2.859375
| 3
|
[] |
no_license
|
class Customer
def initialize(opts)
@discounts = opts[:discounts]
end
def has_discount_for?(product_code)
@discounts.has_key? product_code
end
def discount_amount_for(product_code)
@discounts[product_code] || 0
end
end
| true
|
ad1af6595c29326bdf060b52202327c840206db5
|
Ruby
|
cconstantine/lemming
|
/lib/lemming.rb
|
UTF-8
| 1,681
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'benchmark'
require 'timeout'
require 'thread'
require 'pty'
require 'open3'
require 'json'
require File.join(File.dirname(__FILE__), 'result_set.rb')
require File.join(File.dirname(__FILE__), 'client')
module Lemming
class Lemming
attr_accessor :delay, :tick, :total_time, :results
def initialize(opts=Hash.new)
@incoming = Queue.new
self.delay = opts[:delay] || 0.1
self.tick = opts[:delay] || 10
self.total_time = opts[:delay] || 5 * 60
@command = opts[:command]
raise "You must specify a command to run" unless @command
self.results = ResultSet.new
Thread.new do
while true
begin
r = @incoming.pop
results.add(r)
rescue
p $!
end
end
end
end
def run
puts "RUNNING #{@command}"
start = Time.now
tick_start = Time.now
while Time.now - start < total_time
if Time.now - tick_start > tick
puts "****************************************************"
results.report
results = ResultSet.new
tick_start = Time.now
end
Thread.new do
Open3.popen3(*@command) do |stdin, stdout, stderr, wait_thr|
stdout.each_line do |line|
begin
@incoming << JSON.parse(line.strip)
rescue
puts $!.inspect
end
end
stdin.close
end
end
sleep( delay )
end
while !@incoming.empty?;
p 'not empty'
sleep 0.1
end
results.report
end
end
end
| true
|
a7a22d7b1276e6a0f4f8ad2d09ccc475dfb17adc
|
Ruby
|
rohit-mathew/ruby-ds-algo
|
/Algorithms/sort.rb
|
UTF-8
| 939
| 4.21875
| 4
|
[] |
no_license
|
# Merge Sort requires O n * log n time and O (n) space
# Merges two already sorted arrays
def merge(array1, array2)
ptr1 = 0
ptr2 = 0
high1 = array1.length - 1
high2 = array2.length - 1
array_final = []
while (ptr1 <= high1) && (ptr2 <= high2) do
if (array1[ptr1] < array2[ptr2])
array_final << array1[ptr1]
ptr1 += 1
else
array_final << array2[ptr2]
ptr2 += 1
end
end
if ptr1 <= high1
while (ptr1 <= high1) do
array_final << array1[ptr1]
ptr1 += 1
end
elsif ptr2 <= high2
while (ptr2 <= high2) do
array_final << array2[ptr2]
ptr2 += 1
end
end
return array_final
end
# Helper function for recursion
def mergesort(array)
if array.count <= 1
return array
end
middle = array.count/2
return merge(mergesort(array[0, middle]), mergesort(array[middle, array.count]))
end
puts mergesort([9,8,7,6,5,4,3,2,1])
# 1 2 3 4 5 6 7 8 9
| true
|
3ddb31870ec6da4906ae7b328b407472b1fe6a0f
|
Ruby
|
fentontaylor/sweater-weather
|
/app/facades/forecast_facade.rb
|
UTF-8
| 1,041
| 2.859375
| 3
|
[] |
no_license
|
class ForecastFacade
attr_reader :id, :type
def initialize(location)
@location = location
@id = nil
@type = 'forecast'
end
def location_info
geolocation_decorator.location_info
end
def summary
forecast_decorator.summary
end
def current_forecast
forecast_decorator.current_forecast
end
def hourly_forecast
forecast_decorator.hourly_forecast
end
def daily_forecast
forecast_decorator.daily_forecast
end
private
def geocode_service
@geocode_service ||= GeocodeService.new(@location)
end
def forecast_service
@forecast_service ||= ForecastService.new(geolocation.lat_long_string)
end
def geolocation
@geolocation ||= Geolocation.new(geocode_service.get_location)
end
def geolocation_decorator
@geolocation_decorator ||= GeolocationDecorator.new(geolocation)
end
def forecast
@forecast ||= Forecast.new(forecast_service.get_forecast)
end
def forecast_decorator
@forecast_decorator ||= ForecastDecorator.new(forecast)
end
end
| true
|
1e7bace2b8de1fa24629e0612594d838876c2624
|
Ruby
|
kaspernj/wref
|
/lib/wref/implementations/id_class_unique.rb
|
UTF-8
| 1,137
| 2.609375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
class Wref::Implementations::IdClassUnique
def initialize(object)
@id = object.__id__
@class_name = object.class.name.to_sym
ObjectSpace.define_finalizer(object, method(:destroy))
@unique_id = object.__wref_unique_id__ if object.respond_to?(:__wref_unique_id__)
end
def get!
object = get
raise ::Wref::Recycled unless object
return object
end
def get
return nil if !@class_name || !@id
begin
object = ObjectSpace._id2ref(@id)
rescue RangeError
destroy
return nil
end
#Some times this class-name will be nil for some reason - knj
object_class_name = object.class.name
if !object_class_name || @class_name != object_class_name.to_sym || @id != object.__id__
destroy
return nil
end
if @unique_id
destroy
return nil if !object.respond_to?(:__wref_unique_id__) || object.__wref_unique_id__ != @unique_id
end
return object
end
def alive?
if get
return true
else
return false
end
end
private
def destroy(*args)
@id = nil
@class_name = nil
@unique_id = nil
end
end
| true
|
e5f0fcae321629acfd227b21c73fe22bbfd8ec70
|
Ruby
|
Cyan101/code-examples
|
/daily-programmer/#317/collatz_tag_system.rb
|
UTF-8
| 554
| 3.984375
| 4
|
[
"MIT"
] |
permissive
|
#[2017-05-29] Challenge #317 [Easy] Collatz Tag System
#https://www.reddit.com/r/dailyprogrammer/comments/6e08v6/20170529_challenge_317_easy_collatz_tag_system/
def collatz(tag)
tag_keys = %w(a b c)
tag_system = %w(bc a aaa)
while tag.length > 1
case tag.chr
when tag_keys[0]
tag = tag[2..-1] + tag_system[0]
when tag_keys[1]
tag = tag[2..-1] + tag_system[1]
when tag_keys[2]
tag = tag[2..-1] + tag_system[2]
end
puts tag
end
puts '~Done~'
end
collatz('aaa')
| true
|
f90c114df3345270a78a9f89df0432184d41fdae
|
Ruby
|
ash106/rwc
|
/app/services/kml_parser.rb
|
UTF-8
| 996
| 2.859375
| 3
|
[] |
no_license
|
require 'open-uri'
class KmlParser
def initialize(id, model_name)
@id = id
@model_name = model_name.constantize
end
def parse_polygon
model = get_model
doc = open_doc(model)
coordinates_array = parse_coordinates(doc.at_css("polygon coordinates").text)
polygon =
{
type: "Polygon",
coordinates: [
coordinates_array
]
}
model.update_column(:polygon, polygon)
end
def parse_point
model = get_model
doc = open_doc(model)
coordinates_set = parse_coordinates(doc.at_css("point coordinates").text)
point =
{
type: "Point",
coordinates: coordinates_set[0]
}
model.update_column(:point, point)
end
private
def get_model
@model_name.find(@id)
end
def open_doc(model)
Nokogiri::HTML(open(model.kml.url))
end
def parse_coordinates(coordinates)
coordinates.scan(/(-?\d+.\d+),(-?\d+.\d+)/).collect { |lon, lat| [lon.to_f, lat.to_f]}
end
end
| true
|
56ca62a3ec920ef11b30284a7dffaf51593fd6b6
|
Ruby
|
govfollower/repfinder
|
/app/services/rep_finders/by_state_district.rb
|
UTF-8
| 729
| 2.546875
| 3
|
[] |
no_license
|
require 'json'
module RepFinders
class ByStateDistrict
def initialize (abbr, district_no)
@state = State.find_by(abbr: abbr)
@district = District.find_by(state_id: @state.id, number: district_no.to_i) if @state.present?
end
def perform
return false unless @district
house_rep = HouseRep.find_by(district_id: @district.id, in_office: true).as_representative
senate_reps = SenateRep.where(state_id: @state.id).map { |rep| rep.as_representative }
reps = {
district: {
name: @state.name,
abbr: @state.abbr,
number: @district.number
},
house: house_rep,
senate: senate_reps
}
return reps
end
end
end
| true
|
33e5a08c53088975e8ddb9c8514da3a603ac6c80
|
Ruby
|
VSuhas/Ruby-exercise-Suhas-V
|
/eleven.rb
|
UTF-8
| 806
| 3.953125
| 4
|
[] |
no_license
|
puts " 1 : adddition, 2 : Subtraction , 3: Multiplication, 4 : Division "
puts "Enter the choice number"
ch=gets.chomp
case ch
when "1"
puts "enter two numbers"
puts "enter first number"
a=gets.chomp
a1=a.to_f
puts "enter Second number"
b=gets.chomp
b1=b.to_f
c = a1 + b1
puts c
when "2"
puts "enter two numbers"
puts "enter first number"
a=gets.chomp
a1=a.to_f
puts "enter Second number"
b=gets.chomp
b1=b.to_f
c = a1 - b1
puts c
when "3"
puts "enter two numbers"
puts "enter first number"
a=gets.chomp
a1=a.to_f
puts "enter Second number"
b=gets.chomp
b1=b.to_f
c = a1 * b1
puts c
when "4"
puts "enter two numbers"
puts "enter first number"
a=gets.chomp
a1=a.to_f
puts "enter Second number"
b=gets.chomp
b1=b.to_f
c = a1 / b1
puts c
else
puts "invalid entry"
end
| true
|
aef72c5c2ad7b28cc9877e754b40e034be64a85e
|
Ruby
|
sendgrid/geo_location
|
/lib/geo_location/countries.rb
|
UTF-8
| 807
| 2.859375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module GeoLocation
class << self
def country(country_code)
return nil if GeoLocation::countries.empty?
GeoLocation::countries[country_code.to_sym]
end
def build_countries
if GeoLocation::countries.empty?
data = {}
file = File.join(File.dirname(__FILE__), 'countries.txt')
File.open(file, "r") do |infile|
while (line = infile.gets)
countries = line.split("\n")
countries.each do |c|
c = c.split(" ")
code = c[0].to_sym
country = c[1]
data[code] = country
end # end countries.each
end # end while
end # end file.open
GeoLocation::countries = data
end # end if
end
end
end
| true
|
ae3b916c98d9c37fa61b5ccfdcbe1e2329f4fe87
|
Ruby
|
ilya-burinskiy/Ruby
|
/Railway/console_interface.rb
|
UTF-8
| 1,266
| 3.40625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
class ConsoleInterface
def show_instructions(instructions)
instructions.each do |instruction|
puts instruction
end
end
def read_command
print '>>> '
gets.to_i
end
def read_station_name
print 'Enter station name: '
station_name = gets.chomp
end
def read_train_number
print 'Enter train number: '
train_number = gets.chomp
end
def read_train_type
print 'Enter train type: '
train_type = gets.chomp.downcase
end
def read_route_name
print 'Enter route name: '
route_name = gets.chomp
end
def read_carriage_capacity
print 'Enter carriage capacity: '
carriage_capacity = gets.chomp.to_f
end
def read_free_seats_num
print 'Enter carriage free seats number: '
free_seats_num = gets.chomp.to_i
end
def show_trains_on_station(station)
station.trains.each { |train| puts train.number }
end
def show_train_carriages(train)
train.carriages.each { |carriage| puts carriage.type }
end
def read_carriage_idx
print 'Enter carriage index in train: '
carriage_idx = gets.to_i
end
def read_carg_volume
print 'Enter carg volume: '
carg_volume = gets.to_f
end
def show_msg(msg)
puts msg
end
end
| true
|
2538dcb3342eb45650e9c94604f3afea484fcaca
|
Ruby
|
patrickdavey/AoC
|
/2015/day19/molecule_calibrator.rb
|
UTF-8
| 545
| 2.65625
| 3
|
[] |
no_license
|
require 'set'
class MoleculeCalibrator
def initialize(initial_molecule:, replacements:)
@initial_molecule = initial_molecule.freeze
@replacements = replacements
@combinations = Set.new
end
def distinct_molecules
replacements.each do |replacement|
initial_molecule.clone.gsub(/#{replacement.starting_molecule}/) do |match|
combinations << ($` << replacement.inserted_molecule << $')
end
end
combinations.count
end
private
attr_reader :initial_molecule, :replacements, :combinations
end
| true
|
72f587a809e7b58b9de22a3a4c7e5ef83c316025
|
Ruby
|
mindpin/short-comment-service
|
/app/models/post.rb
|
UTF-8
| 712
| 2.515625
| 3
|
[] |
no_license
|
class Post
include Mongoid::Document
include Mongoid::Timestamps
field :url, type: String
has_many :comments, :order => :votes_count.desc
has_many :votes
def self.get(url)
url = url.split(/#|\?/).first
Post.find_or_create_by(url: url)
end
def has_comment?(user_id)
self.comments.where(:user_id => user_id).exists?
end
def comment_content_of(user_id)
return "" if !has_comment?(user_id)
self.comments.where(:user_id => user_id).first.content
end
def has_vote?(user_id)
self.votes.where(:user_id => user_id).exists?
end
def vote_comment_of(user_id)
return nil if !has_vote?(user_id)
self.votes.where(:user_id => user_id).first.comment
end
end
| true
|
550f657ea585e4215031d86581831b9011b834f6
|
Ruby
|
JordanStafford/Ruby
|
/Ruby Practice Continued/Arrays/acessing_array-elements.rb
|
UTF-8
| 638
| 4.4375
| 4
|
[] |
no_license
|
sharks = ["Hammerhead", "Great White", "Tiger"]
sharks.length #will find how many elemnents there are
print sharks.index("Tiger") #will find out what index the value is in the array
print sharks.index[-1] # will get the last element of the array
puts sharks.first #will get the first element
puts sharks.last #will get the last element
arr = [1, 2, 3, 4, 5, 6]
arr.at(0) #will find the element at that index
arr.take(3) # this will return the first n elements of the array
#Accessing elements
a[index] #return the element at index n of array n
a.first # return the first element of aray n
a.last #return the last element of array n
| true
|
d48c47a8635a1465c29d05982d5716554c329759
|
Ruby
|
hussyvel/ruby
|
/programas_diversos/lacos.rb
|
UTF-8
| 307
| 3.046875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
x = 1
until x == 10
puts x
x += 1
end
# valor = 1
# loop do
# puts valor
# valor += 1
# break if valor <= 10
# end
# valor = 1
# for a in 4..25 do
# puts a
# a += 1
# end
# a = 2
# while a <= 10
# puts a
# a += 1
# end
| true
|
32582d3b69b3a9f7bbda713f40c37637acd330dc
|
Ruby
|
AELSchauer/turing-headcount
|
/test/csv_extractor_test.rb
|
UTF-8
| 11,661
| 2.71875
| 3
|
[] |
no_license
|
require './test/test_helper'
require './lib/csv_extractor'
class CSVExtractorTest < Minitest::Test
def test_create
extractor = setup
expected_data = {
:enrollment=>{},
:statewide_test=>{},
:economic_profile=>{}
}
assert_equal expected_data, extractor.districts_hashes
end
def test_extract_csv
extractor = setup
csv = extractor.extract_csv(CSVFiles.generic_csv_file(1))
expected_headers = [:location, :timeframe, :dataformat, :data]
assert_equal CSV::Table, csv.class
assert_equal expected_headers, csv.headers
assert_equal "gregville", csv[0][:location]
end
def test_determine_headers
extractor = setup
csv_1 = extractor.extract_csv(CSVFiles.generic_csv_file(1))
csv_2 = extractor.extract_csv(CSVFiles.generic_csv_file(2))
csv_3 = extractor.extract_csv(CSVFiles.generic_csv_file(3))
csv_4 = extractor.extract_csv(CSVFiles.generic_csv_file(4))
csv_5 = extractor.extract_csv(CSVFiles.generic_csv_file(5))
headers_1 = extractor.determine_headers(csv_1)
headers_2 = extractor.determine_headers(csv_2)
headers_3 = extractor.determine_headers(csv_3)
headers_4 = extractor.determine_headers(csv_4)
headers_5 = extractor.determine_headers(csv_5)
expected_headers_1 = [:location, :timeframe, :data]
expected_headers_2 = [:location, :score, :timeframe, :data]
expected_headers_3 = [:location, :timeframe, :dataformat, :data]
expected_headers_4 = [:location, :category, :timeframe, :data]
expected_headers_5 = [:location, :race_ethnicity, :timeframe, :data]
assert_equal expected_headers_1, headers_1
assert_equal expected_headers_2, headers_2
assert_equal expected_headers_3, headers_3
assert_equal expected_headers_4, headers_4
assert_equal expected_headers_5, headers_5
end
def test_create_districts_hashes
extractor, csv = setup_with_generic_csv_file(1)
extractor.create_districts_hashes(:enrollment, csv)
expected_data = {
"GREGVILLE"=>{:name=>"GREGVILLE"},
"ASHLEYVILLE"=>{:name=>"ASHLEYVILLE"}
}
assert_equal expected_data, extractor.districts_hashes[:enrollment]
end
def test_extract_data_from_csv
extractor, csv = setup_with_generic_csv_file(2)
extractor.create_districts_hashes(:enrollment, csv)
extractor.merge_csv_data_into_districts_hashes(:enrollment, :generic_csv_data_2, csv)
expected_data = {
"GREGVILLE"=>{
:name=>"GREGVILLE",
:generic_csv_data_2=>{
:math=>{2010=>0.11, 2011=>0.21, 2012=>0.31},
:reading=>{2010=>0.115, 2011=>0.215, 2012=>0.315}
}
},
"ASHLEYVILLE"=>{
:name=>"ASHLEYVILLE",
:generic_csv_data_2=>{
:math=>{2010=>0.41, 2011=>0.51, 2012=>0.61},
:reading=>{2010=>0.415, 2011=>0.515, 2012=>0.615}
}
}
}
assert_equal expected_data, extractor.districts_hashes[:enrollment]
end
def test_extract_data_from_multiple_csvs
extractor = setup
csv_1 = extractor.extract_csv(CSVFiles.generic_csv_file(2))
csv_2 = extractor.extract_csv(CSVFiles.generic_csv_file(4))
csv_3 = extractor.extract_csv(CSVFiles.generic_csv_file(5))
extractor.create_districts_hashes(:enrollment, csv_1)
extractor.create_districts_hashes(:enrollment, csv_2)
extractor.create_districts_hashes(:enrollment, csv_3)
extractor.merge_csv_data_into_districts_hashes(:enrollment, :generic_csv_data_1, csv_1)
extractor.merge_csv_data_into_districts_hashes(:enrollment, :generic_csv_data_2, csv_2)
extractor.merge_csv_data_into_districts_hashes(:enrollment, :generic_csv_data_3, csv_3)
expected_data = expected_hash_for_generic_csv_files_2_4_5
assert_equal expected_data, extractor.districts_hashes[:enrollment]
end
def test_load_data
extractor = setup
extractor.load_data(CSVFiles.small_data_set)
expected_data = expected_hash_for_small_data_set
assert_equal expected_data, extractor.districts_hashes
end
def test_get_district_list
extractor = setup_big_data_set
district_list = extractor.get_district_list
expected_list = [{:name=>"ASHLEYVILLE"}, {:name=>"COLORADO"}, {:name=>"GREGVILLE"}, {:name=>"TURINGTOWN"}]
assert_equal expected_list, district_list
end
def test_third_grade_load_data
extractor = setup_all_csv_files
binding.pry
end
def setup
CSVExtractor.new
end
def setup_with_generic_csv_file(n)
extractor = setup
[extractor, extractor.extract_csv(CSVFiles.generic_csv_file(n))]
end
def setup_big_data_set
extractor = setup
extractor.load_data(CSVFiles.big_data_set)
extractor
end
def setup_all_csv_files
extractor = setup
extractor.load_data(CSVFiles.all_csv_files)
extractor
end
def expected_hash_for_generic_csv_files_2_4_5
{
"GREGVILLE"=>{
:name=>"GREGVILLE",
:generic_csv_data_1=>{
:math=>{2010=>0.11, 2011=>0.21, 2012=>0.31},
:reading=>{2010=>0.115, 2011=>0.215, 2012=>0.315}
},
:generic_csv_data_2=>{
:all_students=>{2011=>0.002, 2012=>0.004},
:asian=>{2011=>0.0, 2012=>0.007},
:black=>{2011=>0.0, 2012=>0.002},
:female_students=>{2011=>0.002, 2012=>0.004},
:hispanic=>{2011=>0.004, 2012=>0.006},
:male_students=>{2011=>0.002, 2012=>0.004},
:native_american=>{2011=>0.0, 2012=>0.036},
:pacific_islander=>{2011=>0.0, 2012=>0.0},
:two_or_more=>{2011=>0.0, 2012=>0.0},
:white=>{2011=>0.002, 2012=>0.004}
}
},
"ASHLEYVILLE"=>{
:name=>"ASHLEYVILLE",
:generic_csv_data_1=>{
:math=>{2010=>0.41, 2011=>0.51, 2012=>0.61},
:reading=>{2010=>0.415, 2011=>0.515, 2012=>0.615}
},
:generic_csv_data_2=>{
:all_students=>{2011=>0.072, 2012=>0.063},
:asian=>{2011=>0.083, 2012=>0.0},
:black=>{2011=>0.08, 2012=>0.037},
:female_students=>{2011=>0.062, 2012=>0.051},
:hispanic=>{2011=>0.073, 2012=>0.066},
:male_students=>{2011=>0.081, 2012=>0.075},
:native_american=>{2011=>0.206, 2012=>0.065},
:pacific_islander=>{2011=>0.0, 2012=>0.0},
:two_or_more=>{2011=>0.0, 2012=>0.0},
:white=>{2011=>0.058, 2012=>0.058}
},
:generic_csv_data_3=>{
:all_students=>{2011=>0.317, 2012=>0.28, 2013=>0.303, 2014=>0.298},
:asian=>{2011=>0.0, 2012=>0.0, 2013=>0.0, 2014=>0.0},
:black=>{2011=>0.226, 2012=>0.216, 2013=>0.259, 2014=>0.218},
:hispanic=>{2011=>0.312, 2012=>0.279, 2013=>0.299, 2014=>0.293},
:native_american=>{2011=>0.364, 2012=>0.346, 2013=>0.32, 2014=>0.321},
:pacific_islander=>{2011=>0.0, 2012=>0.0, 2013=>0.0, 2014=>0.0},
:two_or_more=>{2011=>0.5, 2012=>0.435, 2013=>0.25, 2014=>0.382},
:white=>{2011=>0.346, 2012=>0.276, 2013=>0.339, 2014=>0.34}
}
},
"COLORADO"=>{
:name=>"COLORADO",
:generic_csv_data_2=>{
:all_students=>{2011=>0.03, 2012=>0.029},
:asian=>{2011=>0.017, 2012=>0.016},
:black=>{2011=>0.044, 2012=>0.044},
:female_students=>{2011=>0.028, 2012=>0.027},
:hispanic=>{2011=>0.049, 2012=>0.047},
:male_students=>{2011=>0.032, 2012=>0.032},
:native_american=>{2011=>0.065, 2012=>0.054},
:pacific_islander=>{2011=>0.029, 2012=>0.038},
:two_or_more=>{2011=>0.017, 2012=>0.017},
:white=>{2011=>0.02, 2012=>0.019}
},
:generic_csv_data_3=>{
:all_students=>{2011=>0.553, 2012=>0.54, 2013=>0.55, 2014=>0.544},
:asian=>{2011=>0.657, 2012=>0.659, 2013=>0.682, 2014=>0.685},
:black=>{2011=>0.37, 2012=>0.367, 2013=>0.378, 2014=>0.375},
:hispanic=>{2011=>0.368, 2012=>0.366, 2013=>0.377, 2014=>0.376},
:native_american=>{2011=>0.379, 2012=>0.366, 2013=>0.366, 2014=>0.339},
:pacific_islander=>{2011=>0.558, 2012=>0.512, 2013=>0.519, 2014=>0.531},
:two_or_more=>{2011=>0.617, 2012=>0.607, 2013=>0.612, 2014=>0.603},
:white=>{2011=>0.663, 2012=>0.645, 2013=>0.656, 2014=>0.647}
}
},
"TURINGTOWN"=>{
:name=>"TURINGTOWN",
:generic_csv_data_3=>{
:all_students=>{2011=>0.719, 2012=>0.706, 2013=>0.72, 2014=>0.716},
:asian=>{2011=>0.827, 2012=>0.808, 2013=>0.811, 2014=>0.789},
:black=>{2011=>0.515, 2012=>0.504, 2013=>0.482, 2014=>0.519},
:hispanic=>{2011=>0.607, 2012=>0.598, 2013=>0.623, 2014=>0.624},
:native_american=>{2011=>0.6, 2012=>0.589, 2013=>0.61, 2014=>0.621},
:pacific_islander=>{2011=>0.726, 2012=>0.683, 2013=>0.717, 2014=>0.727},
:two_or_more=>{2011=>0.727, 2012=>0.719, 2013=>0.747, 2014=>0.732},
:white=>{2011=>0.74, 2012=>0.726, 2013=>0.741, 2014=>0.735}
}
}
}
end
def expected_hash_for_small_data_set
{
:enrollment=>{
"COLORADO"=>{
:name=>"COLORADO",
:kindergarten=>{2007=>0.395, 2006=>0.337, 2005=>0.278, 2004=>0.24, 2008=>0.536, 2009=>0.598, 2010=>0.64, 2011=>0.672, 2012=>0.695, 2013=>0.703, 2014=>0.741}
},
"GREGVILLE"=>{
:name=>"GREGVILLE",
:kindergarten=>{2007=>0.392, 2006=>0.354, 2005=>0.267, 2004=>0.302, 2008=>0.385, 2009=>0.39, 2010=>0.436, 2011=>0.489, 2012=>0.479, 2013=>0.488, 2014=>0.49}
},
"TURINGTOWN"=>{
:name=>"TURINGTOWN",
:kindergarten=>{2007=>0.306, 2006=>0.293, 2005=>0.3, 2004=>0.228, 2008=>0.673, 2009=>1.0, 2010=>1.0, 2011=>1.0, 2012=>1.0, 2013=>0.998, 2014=>1.0}
}
},
:statewide_test=>{
"COLORADO"=>{
:name=>"COLORADO",
:third_grade=>{
:math=>{2008=>0.697, 2009=>0.691, 2010=>0.706, 2011=>0.696, 2012=>0.71, 2013=>0.723, 2014=>0.716},
:reading=>{2008=>0.703, 2009=>0.726, 2010=>0.698, 2011=>0.728, 2012=>0.739, 2013=>0.733, 2014=>0.716},
:writing=>{2008=>0.501, 2009=>0.536, 2010=>0.504, 2011=>0.513, 2012=>0.525, 2014=>0.511, 2013=>0.509}
}
},
"ASHLEYVILLE"=>{
:name=>"ASHLEYVILLE",
:third_grade=>{
:math=>{2008=>0.857, 2009=>0.824, 2010=>0.849, 2011=>0.819, 2012=>0.83, 2013=>0.855, 2014=>0.835},
:reading=>{2008=>0.866, 2009=>0.862, 2010=>0.864, 2011=>0.867, 2012=>0.87, 2013=>0.859, 2014=>0.831},
:writing=>{2008=>0.671, 2009=>0.706, 2010=>0.662, 2011=>0.678, 2012=>0.655, 2014=>0.639, 2013=>0.669}
}
},
"GREGVILLE"=>{
:name=>"GREGVILLE",
:third_grade=>{
:math=>{2008=>0.56, 2009=>0.54, 2010=>0.469, 2011=>0.476, 2012=>0.39, 2013=>0.437, 2014=>0.512},
:reading=>{2008=>0.523, 2009=>0.562, 2010=>0.457, 2011=>0.571, 2012=>0.54, 2013=>0.548, 2014=>0.477},
:writing=>{2008=>0.426, 2009=>0.479, 2010=>0.312, 2011=>0.31, 2012=>0.288, 2014=>0.275, 2013=>0.284}
}
}
},
:economic_profile=>{
"COLORADO"=>{
:name=>"COLORADO",
:median_household_income=>{2005=>56222, 2006=>56456, 2008=>58244, 2007=>57685, 2009=>58433}
},
"ASHLEYVILLE"=>{
:name=>"ASHLEYVILLE",
:median_household_income=>{2005=>85060, 2006=>85450, 2008=>89615, 2007=>88099, 2009=>89953}
},
"GREGVILLE"=>{
:name=>"GREGVILLE",
:median_household_income=>{2005=>41382, 2006=>40740, 2008=>41886, 2007=>41430, 2009=>41088}
}
}
}
end
end
| true
|
f563bdfda6f39aea0f4eea2e0083d523f8b69fce
|
Ruby
|
tarasdemyanets/LinkUp-practice
|
/02_calculator/calculator.rb
|
UTF-8
| 272
| 3.171875
| 3
|
[] |
no_license
|
def add(a,b)
a+b
end
def subtract(a,b)
a-b
end
def sum(a)
a.sum
end
def multiply(a,b)
a*b
end
def power(a,b)
a**b
end
def factorial(n)
if n<0
return nil
end
if n ==0
1
end
res=1
while n>0
res=res*n
n-=1
end
return res
end
| true
|
e3b9a98003eb40d1366700d27d9256e71a70c7ed
|
Ruby
|
gnfisher/sudoku_puzzle_validator
|
/spec/sudoku_puzzle_spec.rb
|
UTF-8
| 1,366
| 3.109375
| 3
|
[] |
no_license
|
require_relative "../lib/sudoku_puzzle"
describe SudokuPuzzle do
describe "#rows" do
it "returns an array of rows from puzzle" do
puzzle_string = <<~TEXT
8 5 0 |0 0 2 |4 0 0
7 2 0 |0 0 0 |0 0 9
0 0 4 |0 0 0 |0 0 0
------+------+------
TEXT
result = SudokuPuzzle.new(puzzle_string).rows
expect(result.size).to eq 3
expect(result.first).to eq([8,5,0,0,0,2,4,0,0])
expect(result.last).to eq([0,0,4,0,0,0,0,0,0])
end
end
describe "#cols" do
it "returns an array of cols from puzzle" do
puzzle_string = <<~TEXT
8 5 0 |0 0 2 |4 0 0
7 2 0 |0 0 0 |0 0 9
0 0 4 |0 0 0 |0 0 0
------+------+------
TEXT
result = SudokuPuzzle.new(puzzle_string).cols
expect(result.size).to eq 9
expect(result.first).to eq([8,7,0])
expect(result.last).to eq([0,9,0])
end
end
describe "#subgroups" do
it "returns an array of subgroups from puzzle" do
puzzle_string = <<~TEXT
8 5 0 |0 0 2 |4 0 0
7 2 0 |0 0 0 |0 0 9
0 0 4 |0 0 0 |0 0 0
------+------+------
TEXT
result = SudokuPuzzle.new(puzzle_string).subgroups
expect(result.size).to eq 3
expect(result.first).to eq([8,5,0,7,2,0,0,0,4])
expect(result.last).to eq([4,0,0,0,0,9,0,0,0])
end
end
end
| true
|
dade17ba3be69f9ae9fbae1c8eea8162290195e7
|
Ruby
|
jmils/RubytheHardWay
|
/ex39.rb
|
UTF-8
| 2,101
| 4.5625
| 5
|
[] |
no_license
|
#create a mapping of state to abbreviation.
#State is the key, abbreviation is the value
states = {
'Oregon' => 'OR',
'Florida' => 'FL',
'California' => 'CA',
'New York' => 'NY',
'Michigan' => 'MI'
}
#create a basic set of states and some cities in them
#City abbrev is the key, city name is the value
cities = {
'CA' => 'San Fransico',
'MI' => 'Detroit',
'FL' => 'Jacksonville'
}
#add some more cities into the cities hash
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
#puts out some cities
puts '-' * 10
puts "NY State has: #{cities['NY']}"
puts "OR State has: #{cities['OR']}"
#puts some states
puts '-' * 10
puts "Michigan's abbreviation is: #{states['Michigan']}"
puts "Florida's abbreviation is: #{states['Florida']}"
#do it by using the state then cities dict
puts '-' * 10
puts "Michigan has: #{cities[states['Michigan']]}"
puts "Florida has: #{cities[states['Florida']]}"
#puts every state abbreviation
puts '-' * 10
#Loop on the states hash that names 2 variables.
#Says for every value in this hash, put the string with the state variable and abbrev variable.
states.each do |state, abbrev|
puts "#{state} is abbreviated #{abbrev}"
end
#puts every city in state
puts '-' * 10
#Loop on the citites hash that names 2 variables.
#Says for each value in this hash, put the string with the abbrev variable and city variable
cities.each do |abbrev, city|
puts "#{abbrev} has the city #{city}"
end
#now do both at the same time
puts "-" * 10
#Loop on the states hash that names 2 variables.
#For each value in state
states.each do |state, abbrev|
#Introduces a new variable city that calls the cities hash uses the variable abbrev from state loop.
city = cities[abbrev]
puts "#{state} is abbreviated #{abbrev} and has city #{city}"
end
puts '-' * 10
#by default ruby says "nil" when something isn't in there
state = states['Texas']
#If the state is false (which it is), print the string
if !state
puts "Sorry, no Texas."
end
#default values using //= with the nil result
city = cities['TX']
city ||= "Does Not Exist"
puts "The city for the state 'TX' is: #{city}"
| true
|
9e7ddbfc77d871ea639fe2e21e0cf487832a3992
|
Ruby
|
podshara/rk
|
/lib/rk.rb
|
UTF-8
| 2,407
| 3.453125
| 3
|
[
"MIT"
] |
permissive
|
# Module for including +rk+ to global namespace (class Object).
module Rk
# Build Redis keys of several elements.
# rk("user", 10) => "user:10"
class Rk
attr_accessor :separator, :prefix, :suffix, :keys
# Set defaults
# * <tt>separator</tt> - :
# * <tt>prefix</tt> - empty
# * <tt>suffix</tt> - empty
# * <tt>keys</tt> - empty
def initialize
@separator = ":"
@prefix = ""
@suffix = ""
@keys = {}
end
# Build a string including prefix/suffix, joining all elements with the separator.
def rk(*elements)
([@prefix] + elements + [@suffix]).reject { |element| element.to_s.empty? }.join(@separator)
end
# Add methods dynamically to define/access elements.
# rk.user = "user"
# rk(rk.user, 10) => "user:10"
def method_missing(method, *arg)
# Raise an error if a method gets accessed which was not defined before
raise RuntimeError, "'rk.#{method.to_s}' is undefined" unless method.to_s.include?("=")
# Define a method to return a value as set, for example rk.settings = 'set' defines
# a method called "settings" which returns the string "set"
key = method.to_s.sub(/=/, "")
val = (arg || []).first.to_s
instance_eval(%Q[
def #{key}
"#{val}"
end
])
# Store user-defined key
@keys[key] = val
end
# Define key elements by key/value pairs of a hash, symbols and strings allowed for
# keys/values.
#
# rk.keys = { user: "user", "statistics" => "stats", "session" => :sess }
def keys=(h)
# Allow hash only
raise TypeError, "invalid type" unless h.is_a?(Hash)
# Call rk.<key> = <val> for each pair of hash
h.each_pair do |key, val|
self.send("#{key}=", val)
end
end
end # class Rk
# Create and call a global instance of Rk to either build a key or set/get attributes.
def rk(*elements)
$_rk = Rk.new unless $_rk
# Differ between calling "rk" without/with params
if elements.empty?
# Return instance of Rk for calling methods like "rk.separator"
$_rk
else
# Return key build by Rk.rk
$_rk.rk(elements)
end
end
end # module Rk
# We could use +extend Rk+ to extend only +main+, but we would have to +include Rk+ in
# any class, hence we include Rk to the global object.
class Object
include Rk
end
| true
|
75fb22e86c722c13c88e3a2fbb661061ff1c232e
|
Ruby
|
albertbahia/wdi_june_2014
|
/w02/d02/sean_jennings/cars/lib/deloream.rb
|
UTF-8
| 326
| 3.421875
| 3
|
[] |
no_license
|
class Delorean < Car
def initialize(horsepower,fuel,current_time)
@horsepower = horsepower
if fuel > 5
@fuel = 5
elsif fuel < 0
@fuel = 0
else
@fuel = fuel
end
@current_time = current_time
end
def time_travel(year)
if year > 0
@current_time = year
end
end
end
| true
|
e7fdf59b5199ceefddb1f1f4a93614fff7fcb749
|
Ruby
|
CarlosUvaSilva/pikachu
|
/randomizer.rb
|
UTF-8
| 171
| 2.546875
| 3
|
[] |
no_license
|
class Randomizer
def initiliaze
@pokemons = ["media/bulbasaur.png","media/pikachu.png","media/raichu.png"]
end
def random_poke
pokemons.sample
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.