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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bdddcd10e8a2035e5c1c03be2b8f02d8e5b0d0eb | Ruby | tomdalling/advent_of_code_2016 | /vec3_spec.rb | UTF-8 | 643 | 2.984375 | 3 | [] | no_license | require_relative 'vec3'
RSpec.describe Vec3 do
it 'does vector operations' do
v1 = Vec3[1,2,3]
v2 = Vec3[4,5,6]
expect(v1.to_a).to eq([1,2,3])
expect(v1 + v2).to eq(Vec3[5,7,9])
expect(v1 - v2).to eq(Vec3[-3, -3, -3])
expect(3 * v1).to eq(Vec3[3, 6, 9])
expect(-v1).to eq(Vec3[-1, -2, -3])
expect(v1).to eq(Vec3[1,2,3])
expect(v1.hash).to eq(Vec3[1,2,3].hash)
expect(v1).not_to eq(v2)
expect(v1.hash).not_to eq(v2.hash)
end
it 'interoperates with arrays a bit' do
v1 = Vec3[1,2,3]
expect(v1 + [10, 11]).to eq(Vec3[11,13,3])
expect(v1 - [10, 11]).to eq(Vec3[-9,-9,3])
end
end
| true |
5d0a387a9bf7e31b7d86fc350dca8c37affd70f9 | Ruby | Cmajewski/ruby-music-library-cli-online-web-pt-071519 | /lib/song.rb | UTF-8 | 913 | 3.15625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require "pry"
class Song
attr_accessor :name
attr_reader :artist, :genre
@@all=[]
extend Concerns::Findable
def initialize (name,artist=nil,genre=nil)
@name=name
self.artist=artist
self.genre=genre
save
end
def self.all
@@all
end
def self.destroy_all
@@all.clear
end
def self.new_from_filename (path)
new_song=path.split(" - ")
name=new_song[1]
artist=new_song[0]
genre=new_song[2].gsub(".mp3","")
x=Artist.find_or_create_by_name(artist)
y=Genre.find_or_create_by_name(genre)
self.new(name,x,y)
end
def self.create_from_filename (path)
self.new_from_filename(path)
end
def self.create (song)
self.new(song)
end
def save
@@all<<self
end
def artist= (artist)
@artist=artist
artist && artist.add_song(self)
end
def genre= (genre)
@genre=genre
genre && genre.add_song(self)
end
end
| true |
14878cd9585017cfb1392e04b0149860604944dc | Ruby | ivx/serverless-workshop | /part-9/handler.rb | UTF-8 | 1,038 | 2.6875 | 3 | [] | no_license | #!/bin/ruby
require 'json'
require 'httparty'
require 'aws-sdk-dynamodb'
DYNAMO_DB = Aws::DynamoDB::Client.new(region: 'eu-central-1')
def temperature(event:, context:)
db_query = {
table_name: 'weather',
expression_attribute_values: {
':id' => 1
},
key_condition_expression: 'locationId = :id',
projection_expression: 'temperature',
}
resp = DYNAMO_DB.query(db_query)
temp = resp['items'].first['temperature'].to_f.round(1)
{
statusCode: 200,
body: JSON.generate({temperature: temp}),
headers: {
'Access-Control-Allow-Origin': '*',
}
}
end
def updateTemperature(event:, context:)
url = 'https://www.metaweather.com/api/location/646099/'
resp = HTTParty.get(url).parsed_response
temp = resp['consolidated_weather'].first['the_temp'].round(1)
resp = DYNAMO_DB.update_item({
table_name: 'weather',
key: {
locationId: 1
},
update_expression: 'set temperature = :t',
expression_attribute_values: {':t' => temp }
})
puts resp.inspect
end
| true |
998eafb8118aaf692e789f1e010a7c9622e7dc84 | Ruby | proyectoFilas/simulacionFilas | /InputManager.rb | UTF-8 | 550 | 3.03125 | 3 | [] | no_license | load 'UI.rb'
class InputManager
def initialize
@userInterface = UI.new()
end
def inputs
input = Array.new()
@userInterface.show("Digite:\n 1 Para sistema de única fila\n 2 Para sistema de múltiples filas")
input << gets.chomp.to_i
@userInterface.show("Ingrese el número de cajas activas")
input << gets.chomp.to_i
@userInterface.show("Ingrese el tiempo de la simulación en minutos")
input << gets.chomp.to_i
@userInterface.show("Ingrese el delta de tiempo")
input << gets.chomp.to_i
end
end
| true |
2f7133532e75eef53825b9ad4bcb4cb1de7327b1 | Ruby | david-meza/algorithms | /warmup/4_staircase.rb | UTF-8 | 333 | 3.34375 | 3 | [] | no_license | # https://www.hackerrank.com/challenges/staircase/submissions/code/12571457
# Enter your code here. Read input from STDIN. Print output to STDOUT
height = gets.chomp.to_i
going_up = 1
going_down = height - 1
while going_up <= height
print " " * going_down
print "#" * going_up
print "\n"
going_up += 1
going_down -= 1
end | true |
1741a2857e11a905f61417e0d10f4ffdf60c899d | Ruby | lukesherwood/tic-tac-toe-rb-online-web-sp-000 | /lib/tic_tac_toe.rb | UTF-8 | 2,273 | 4.15625 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
[0,1,2], #top row
[3,4,5], #middle row
[6,7,8], #bottow row
[0,3,6], #left column
[1,4,7], #middle column
[2,5,8], #right column
[0,4,8], #diagonal1
[2,4,6] #diagonal2
]
board = [" "," "," "," "," "," "," "," "," "]
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(input)
converted_input = input.to_i-1
end
def move(board, index, character)
board[index] = character
puts display_board(board)
end
def position_taken?(board, index)
if board[index] == "X" || board[index] == "O"
true
else
false
end
end
def valid_move?(board, index)
if !position_taken?(board, index) && index.between?(0,8)
true
else
false
end
end
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index) == true
move(board, index, (current_player(board)))
else
puts "Please enter a valid number"
turn(board)
end
end
def turn_count(board)
count = 0
board.each do |turn|
if turn == "X"|| turn == "O"
count +=1
end
end
return count
end
def current_player(board)
if turn_count(board).even?
return "X"
else
return "O"
end
end
def won?(board)
WIN_COMBINATIONS.detect do |win_combination|
win_combination.all? { |win_index| board[win_index] == "X" } ||
win_combination.all? { |win_index| board[win_index] == "O" }
end
end
def full?(board)
board.each {|a| return false if a == " "}
end
def draw?(board)
if !won?(board) && full?(board)
return true
end
end
def over?(board)
if won?(board) || full?(board) || draw?(board)
return true
end
end
def winner(board)
win = won?(board)
if win
return board[win[0]]
end
end
def play(board)
while over?(board) != true
turn(board)
end
if draw?(board) == true
puts "Cat's Game!"
else
puts "Congratulations #{winner(board)}!"
end
end
| true |
12ab73fc8af4ea5d7c0ba1db652a8d0cddd8ae01 | Ruby | dcuddhy/crm-data-challenge | /bin/run_02.rb | UTF-8 | 602 | 2.65625 | 3 | [] | no_license | require_relative('../data/crm.rb')
require 'pp'
result = []
CRM[:companies].each do |company|
CRM[:people].each do |person|
person[:employments].each do |employment|
unless person[:employments].empty?
employments_hash = {
:company_id => company[:id],
:commpany_name => company[:name],
:person_id => person[:id],
:person_first_name => person[:first_name],
:person_last_name => person[:last_name],
:title => employment[:title]
}
result << employments_hash
end
end
end
end
pp result
| true |
21e83d7fc3b8f45538b621d454b892f0ca23dada | Ruby | gustavoescocard/isbn13_generator | /lib/isbn_calculator.rb | UTF-8 | 371 | 3.4375 | 3 | [
"MIT"
] | permissive | class IsbnCalculator
attr_accessor :number
def calculate_last_digit(number)
array_number = number.to_s.chars.map(&:to_i)
array_number.each_with_index do |n, index|
array_number[index] = index.even? ? n * 1 : n * 3
end
mod_isbn = array_number.sum.modulo(10)
last_digit = mod_isbn > 0 ? 10 - mod_isbn : 0
return last_digit
end
end
| true |
adf563d31c980e5ffd4e1e4d21612e0caab625bc | Ruby | JacopoCortellazzi/rubyassignment | /one/src/my_test.rb | UTF-8 | 946 | 3.40625 | 3 | [] | no_license | require 'test/unit'
class Array
def dd(other)
return false unless other.kind_of? Array
return false unless other.size == self.size
return self.all? { |e| other.include?( e ) }
end
end
class TestPerson
attr_accessor :name, :age
def initialize(name, age)
@name, @age = name, age
end
def <=>(other); @age <=> other.age; end
def inspect
"#{@name}(#{@age})"
end
end
class ArrayTest < Test::Unit::TestCase
def setup
load 'array_extension.rb'
@johan = TestPerson.new('Johan', 26)
@tobias = TestPerson.new('Tobias', 29)
@beatrice = TestPerson.new('Beatrice', 32)
@tobias_again = TestPerson.new('Tobias', -29)
@array = [@johan, @tobias, @beatrice, @tobias_again]
end
def test_select_all_where_name_is
assert_equal(@array.select_all(:name => 'Tobias' ), [@tobias, @tobias_again] )
assert_equal(@array.select_all_where_name_is( 'Tobias' ), [@tobias, @tobias_again] )
end
end
| true |
22683c20f907181aebfc19cde4af977446505852 | Ruby | randallreedjr/getto24-sinatra | /app/controllers/get_to_24_controller.rb | UTF-8 | 1,905 | 2.625 | 3 | [
"MIT"
] | permissive | class GetTo24Controller < ApplicationController
get '/' do
erb :'get_to_24/index'
end
get '/about' do
erb :'get_to_24/about'
end
get '/problem' do
problem = Math24.generate_problem.join(" ")
erb :'get_to_24/problem', :locals => {:problem => problem}
end
get '/solve' do
erb :'get_to_24/solve', :locals => {:invalid => false}
end
post '/solution' do
problem = "#{params[:problem] || ""}"
if problem.include?(",")
numbers = problem.delete(" ").split(",")
else
numbers = problem.squeeze(" ").split
end
valid = numbers.all? do |number|
number.to_i > 0 && number.to_i < 10
end
if valid
solution = Math24.solve(numbers)
message = solution ? "#{solution} = 24" : "No solution found"
erb :'get_to_24/solution', :locals => {:problem => numbers.join(" "),
:message => message,
:last_answer => 24}
else
erb :'get_to_24/solve', :locals => {:invalid => true}
end
end
post '/check' do
problem = "#{params[:problem] || ""}"
solution = "#{params[:solution] || ""}"
numbers = problem.split
begin
valid_solution = Math24.check(numbers, solution)
rescue ArgumentError
error = true
valid_solution = false
end
if valid_solution
erb :'get_to_24/correct',
:locals => {
:problem => problem,
:solution => solution
}
elsif error
erb :'get_to_24/incorrect', :locals => {:problem => problem,
:solution => solution,
:last_answer => '???'}
else
erb :'get_to_24/incorrect', :locals => {:problem => problem,
:solution => solution,
:last_answer => instance_eval(solution)}
end
end
end
| true |
05c6bf63a7e4b91938a51888f6c61ad6f6047faa | Ruby | sgdoolin/ruby_spring_pt | /color.rb | UTF-8 | 397 | 4.1875 | 4 | [] | no_license | # Ask the user for their favorite color
# If they answer
# -Blue
# -Green
# say good choice"
# Otherwise say
# Say the color and say it stinks
puts "What's your favorite color?"
favorite_color = gets.chomp
if favorite_color.downcase == "blue" || favorite_color.downcase == "green"
puts "Good choice. That's a great color!"
else
puts "Really? #{favorite_color} is not really my favorite..."
end | true |
84f7f1cf81eb80a656f3fb44555347ed3facd8b7 | Ruby | josephecombs/Chess | /pieces/knight.rb | UTF-8 | 1,401 | 3.125 | 3 | [] | no_license | # require './stepping_piece.rb'
class Knight < SteppingPiece
attr_accessor :string_representation
attr_reader :color
def initialize(board, color, coordinates)
@string_representation = "n"
@color = color
@coordinates = coordinates
@board = board
end
def offsets
[[ 2, 1],
[ 2,-1],
[-2, 1],
[-2,-1],
[ 1, 2],
[ 1,-2],
[-1, 2],
[-1,-2]]
end
# def view
# legal_moves_array = []
#
# legal_moves_array << [(@coordinates[0] + 2), (@coordinates[1] + 1)]
# legal_moves_array << [(@coordinates[0] + 2), (@coordinates[1] - 1)]
# legal_moves_array << [(@coordinates[0] - 2), (@coordinates[1] + 1)]
# legal_moves_array << [(@coordinates[0] - 2), (@coordinates[1] - 1)]
# legal_moves_array << [(@coordinates[0] + 1), (@coordinates[1] + 2)]
# legal_moves_array << [(@coordinates[0] + 1), (@coordinates[1] - 2)]
# legal_moves_array << [(@coordinates[0] - 1), (@coordinates[1] + 2)]
# legal_moves_array << [(@coordinates[0] - 1), (@coordinates[1] - 2)]
#
# legal_moves_array = legal_moves_array.delete_if { |coord| !inside_bounds?(coord) }
#
# same_color = legal_moves_array.reject do |coord|
# @board.tiles[coord[0]][coord[1]].nil?
# end.select do |coord|
# @board.tiles[coord[0]][coord[1]].color == self.color
# end
#
# (legal_moves_array - same_color)
# end
end | true |
2708231d7a1fdc84c3bed723af1d9bdf496dc327 | Ruby | Rasit1/Exercices-Ruby | /exo_15.rb | UTF-8 | 164 | 3.390625 | 3 | [] | no_license | puts "Votre année de naissance? "
print ">"
anneeUser = gets.chomp
age =0
for i in (anneeUser.to_i..2017)
puts "En #{i}, vous avez #{age} an(s) "
age += 1
end
| true |
74d5276841bd4615322f6880dfa46a069b76252b | Ruby | geka0396/Ruby | /Leeson_1/hello3.rb | UTF-8 | 179 | 2.921875 | 3 | [] | no_license | puts "Как тебя зовут?"
name = gets.chop
puts "В каком году родился?"
year = gets.chop
puts "#{name}, privet! Tebe primerno #{2019 - year.to_i} let." | true |
1ce716cc0237666683be469e3b7b9244216b7aca | Ruby | matt-morris/project-euler | /5.rb | UTF-8 | 882 | 3.796875 | 4 | [] | no_license | # Smallest multiple
# Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# (1..Float::INFINITY).each do |n|
# if (1..20).select { |i| n % i == 0 }.compact.length == 20
# p n
# break
# end
# end
start = Time.now
#
# first approach:
# brute force works, but it's _way_ too slow
#
# (1..Float::INFINITY).each do |n|
# divisions = (1..20).select do |i|
# x = n % i
# break if x != 0
# x
# end || []
# if divisions.compact.length == 20
# p n
# break
# end
# end
#
# second approach:
# discovered the greatest common divisor method
# http://en.wikipedia.org/wiki/Least_common_multiple
#
p (1..20).reduce { |x, y| x.lcm(y) }
p "finished in #{Time.now - start} seconds."
| true |
fbb022d9dcf96b09d6751a628f788751ce548f0d | Ruby | Cooky90/LaunchSchool | /ProgrammingFoundations-101/Small-Exercises/Easy-7/Exercise10.rb | UTF-8 | 310 | 3.71875 | 4 | [] | no_license | def penultimate(string)
string.split[-2]
end
penultimate('last word') == 'last'
penultimate('Launch School is great!') == 'is'
# Further Exploration #
def middle_word(string)
middle = ((string.split.size).to_f/2).round
string.split[middle - 1]
end
middle_word('hello this is a test')
middle_word('')
| true |
e25950eee3e24c45919550eb4be3b1f1964ad774 | Ruby | visitvinoth/tw | /app/libraries.rb | UTF-8 | 468 | 3.34375 | 3 | [] | no_license | class Fixnum
@@roman_literal_map = [["M",1000],["CM",900],["D",500],["CD",400],["C",100],["XC",90],["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]
def self.from(roman_string)
sum = 0
for key, value in @@roman_literal_map
while roman_string.index(key)==0
sum += value
roman_string.slice!(key)
end
end
sum
end
end
class String
def is_a_valid_intergalactic_string?
InterGalacticNotation.notation_strings.include? self
end
end
| true |
4d115fd469d9ff9e2c8d770eb5162cef6132424f | Ruby | dominikgrygiel/appetite-0.1.0 | /test/test__router.rb | UTF-8 | 4,801 | 2.84375 | 3 | [
"MIT"
] | permissive | module AppetiteTest__Appetite
class App < Appetite
format :html, :xml
def index
action
end
def exact arg
arg
end
def post_exact arg
arg
end
def one_or_two arg1, arg2 = nil
[arg1, arg2]
end
def one_or_more arg1, *a
[arg1, *a]
end
def any *a
a
end
end
Spec.new App do
Testing 'zero args' do
r = get
is?(r.status) == 200
is?(r.body) == 'index'
r = post
is?(r.status) == 200
is?(r.body) == 'index'
Should 'return 404 cause it does not accept any args' do
r = get :a1
is?(r.status) == 404
r = get :a1, :a2
is?(r.status) == 404
end
end
Testing 'one arg' do
r = get :exact, :arg
is?(r.status) == 200
is?(r.body) == 'arg'
r = post :exact, :arg
is?(r.status) == 200
is?(r.body) == 'arg'
Should 'return 404 cause called without args' do
r = get :exact
is?(r.status) == 404
r = post :exact
is?(r.status) == 404
end
Should 'return 404 cause redundant args provided' do
r = post :exact, :arg, :redundant_arg
is?(r.status) == 404
end
Should 'return 404 cause :head_exact action does not exists' do
r = head :exact
expect(r.status) == 404
end
end
Testing 'one or two args' do
r = get :one_or_two, :a1
is?(r.status) == 200
is?(r.body) == ['a1', nil].to_s
r = get :one_or_two, :a1, :a2
if ::AppetiteUtils::RESPOND_TO__PARAMETERS
is?(r.status) == 200
is?(r.body) == ['a1', 'a2'].to_s
else
is?(r.status) == 404
is?(r.body) == 'max params accepted: 1; params given: 2'
end
Should 'return 404 cause no args provided' do
r = get :one_or_two
expect(r.status) == 404
end
Should 'return 404 cause redundant args provided' do
r = get :one_or_two, 1, 2, 3, 4, 5, 6
expect(r.status) == 404
end
Should 'return 404 cause :post_one_or_two action does not exists' do
r = post :one_or_two
expect(r.status) == 404
end
end
Testing 'one or more' do
r = get :one_or_more, :a1
is?(r.status) == 200
is?(r.body) == ['a1'].to_s
r = get :one_or_more, :a1, :a2, :a3, :etc
if ::AppetiteUtils::RESPOND_TO__PARAMETERS
is?(r.status) == 200
is?(r.body) == ['a1', 'a2', 'a3', 'etc'].to_s
else
Should 'return 404 cause trailing default params does not work on Appetite running on ruby1.8' do
is?(r.status) == 404
is?(r.body) == 'max params accepted: 1; params given: 4'
end
end
end
Testing 'any number of args' do
r = get :any
is?(r.status) == 200
is?(r.body) == [].to_s
r = get :any, :number, :of, :args
if ::AppetiteUtils::RESPOND_TO__PARAMETERS
is?(r.status) == 200
is?(r.body) == ['number', 'of', 'args'].to_s
else
Should 'return 404 cause splat params does not work on Appetite running on ruby1.8' do
is?(r.status) == 404
is?(r.body) == 'max params accepted: 0; params given: 3'
end
end
end
Ensure '`[]` and `route` works properly' do
map = {
:index => '/index',
:exact => '/exact',
:post_exact => '/exact',
}
When 'called at class level' do
map.each_pair do |action, url|
url = map() + url
expect(App[action]) == url
expect(App.route action) == url
expect(App.route action, :arg1) == url + '/arg1'
expect(App.route action, :arg1, :arg2) == url + '/arg1/arg2'
expect(App.route action, :arg1, :var => 'val') == url + '/arg1?var=val'
expect(App.route action, :arg1, :var => 'val', :nil => nil) == url + '/arg1?var=val'
App.format?(action).each do |format|
expect(App.route action.to_s + format) == url + format
is(App.route action.to_s + '.blah') == map() + '/' + action.to_s + '.blah'
end
end
is(App.route :blah) == map() + '/blah'
end
And 'when called at instance level' do
ctrl = App.new
map.each_pair do |action, url|
url = map() + url
expect(ctrl[action]) == url
expect(ctrl.route action) == url
expect(ctrl.route action, :nil => nil) == url
App.format?(action).each do |format|
expect(ctrl.route action.to_s + format) == url + format
is(ctrl.route action.to_s + '.blah') == map() + '/' + action.to_s + '.blah'
end
end
is(ctrl.route :blah) == map() + '/blah'
end
end
end
end
| true |
9f6b488ea1c511067801e52b74091576aa344ee0 | Ruby | barruda/invoice-revolution-pro | /app/actions/invoice_pay.rb | UTF-8 | 913 | 2.578125 | 3 | [] | no_license | # frozen_string_literal: true
class InvoicePay
def process(params)
@invoice = Invoice.find_by_invoice_id(params[:invoice_id])
if !@invoice || @invoice.status == (InvoiceStatus::CHARGEBACKED || InvoiceStatus::PAID)
raise Business::InvalidTransactionException
end
payment = Payment.new(params)
check_payments_total params[:amount]&.to_i
save_invoice_payment payment
payment
end
private
def check_payments_total(transaction_value)
payments = @invoice.payments
payment_amount = transaction_value
payments&.each do |payment|
payment_amount += payment.amount
end
if payment_amount == @invoice.amount
@invoice.status = InvoiceStatus::PAID
elsif payment_amount > @invoice.amount
raise Business::AmountExceedsException
end
end
def save_invoice_payment(payment)
@invoice.payments << payment
@invoice.save!
end
end
| true |
73da3394477d909b8e812bb5c20f4499875c03bc | Ruby | sealink/app_launcher | /app/models/service.rb | UTF-8 | 956 | 2.59375 | 3 | [] | no_license | class Service
attr_reader :id
ALLOWED_TYPES = %w(solr resque-pool schedule unicorn)
def initialize(app_id, id, service_type)
if !ALLOWED_TYPES.include?(service_type)
raise ArgumentError, "Unknown service type: [#{service_type}]"
end
@app_id = app_id
@id = id
@service_type = service_type
end
def start
return if status.running?
perform('start')
end
def stop
return if !status.running?
perform('stop')
end
def status
ServiceStatus.for cmd_string('status')
end
def running?
status.running?
end
def to_s
@id
end
private
def cmd_string(action)
%{ service #{@service_type} "#{action} #{@app_id}" }
end
def perform(action)
if !%w(start stop).include?(action.to_s)
raise ArgumentError, "Cannot perform action: [#{action}]"
end
spawned_process = Process.spawn cmd_string(action)
Process.detach(spawned_process)
end
end
| true |
71891de8ea90613f4e2c320fa50061aad122a4b3 | Ruby | puppetlabs/puppetlabs-amazon_aws | /tasks/cloudfront_aws_create_streaming_distribution2018_06_18.rb | UTF-8 | 1,995 | 2.734375 | 3 | [] | no_license | #!/opt/puppetlabs/puppet/bin/ruby
require 'puppet'
require 'aws-sdk'
def CreateStreamingDistribution2018_06_18(*args)
puts "Calling task operation CreateStreamingDistribution2018_06_18"
argstring=args[0]
argstring=argstring.delete('\\')
arg_hash=JSON.parse(argstring)
#Remove task name from arguments
arg_hash.delete("_task")
client = Aws::CloudFront::Client.new(region: get_region)
if arg_hash.empty?
response = client.create_streaming_distribution2018_06_18()
else
call_hash={}
arg_hash.each do |k,v|
key=k.to_sym
if k.to_s.end_with?"s"
call_hash[key]=v.split(",")
else
#Parameter formatting for hash like structures - example: parameter_name="{:item=>[i1,i2];:item2=>stringElement}"
if v.include? "{"
requestHash=Hash.new
msg=v.gsub("{","").gsub("}","")
arr = msg.split(";")
arr.each do |item|
vals=item.split("=>")
if vals[1].include? "["
valarr=[]
elements = vals[1].gsub("[","").gsub("]","").split(",")
elements.each do |e|
valarr << e
end
requestHash[vals[0].gsub(":","").strip.to_sym]=valarr
else
requestHash[vals[0].gsub(":","").strip.to_sym]=vals[1].gsub("'","").strip
end
end
call_hash[key]=requestHash
else
call_hash[key]=v
end
end
end
response = client.create_streaming_distribution2018_06_18(call_hash)
end
hash_response = response_to_hash(response)
return hash_response
end
def response_to_hash(response)
hashed = {}
hashed = hashed.merge!(response)
hashed
end
def get_region
ENV['AWS_REGION'] || 'us-west-2'
end
#Get operation parameters from an input JSON
params = STDIN.read
begin
result = CreateStreamingDistribution2018_06_18(params)
puts JSON.pretty_generate(result)
exit 0
rescue Aws::CloudFront::Errors::ServiceError => e
puts({ status: 'failure', error: e.message }.to_json)
exit 1
end | true |
4440b81f060b900b54a1001bce75687a7a623547 | Ruby | dota2arena/dota2arena_courier | /lib/dota2_arena_courier/team.rb | UTF-8 | 1,645 | 2.953125 | 3 | [
"MIT"
] | permissive | class Dota2ArenaCourier::Team
attr_reader :win, :players, :kills, :deaths, :assists, :xpm, :gpm, :net_worth, :last_hits, :denies, :lvl_ups, :level
def initialize(players, radiant_win)
@players = players
@win = check_if_win(radiant_win)
end
def set_attributes
kills = 0; deaths = 0; assists = 0
xpm = 0; gpm = 0; net_worth = 0
last_hits = 0; denies = 0; level = 0
lvl_ups = []
@players.each do |p|
kills += p.kills; deaths += p.deaths; assists += p.assists
xpm += p.xpm; gpm += p.gpm; net_worth += p.net_worth
last_hits += p.last_hits; denies += p.denies
level += p.level
add_levels(lvl_ups, player_convert_levels(p.lvl_ups))
end
@kills = kills; @deaths = deaths; @assists = assists
@xpm = xpm; @gpm = gpm; @net_worth = net_worth; @last_hits = last_hits
@denies = denies; @lvl_ups = lvl_ups; @level = level
@json = nil
self
end
def player_convert_levels(levels)
new_levels = []
target_level = 3
len = levels.size
levels[target_level - 1 .. len - 1].each_with_index { |time, i| new_levels << time if i % target_level == 0 }
new_levels
end
def add_levels(current_levels, new_levels)
new_levels.each_with_index do |l, index|
if current_levels[index].nil?
current_levels[index] = {players: 1, sum: l}
else
current_levels[index][:players] += 1
current_levels[index][:sum] += l
end
end
end
def check_if_win(radiant_win)
if radiant_win && @players[0].player_slot < 128 || !radiant_win && @players[0].player_slot >= 128
true
else
false
end
end
end | true |
660f0148499be09ade8cd3c7ea5f1e7108268dab | Ruby | GeeVeldek/rails-longest-word-game | /app/controllers/games_controller.rb | UTF-8 | 1,055 | 3.375 | 3 | [] | no_license | require 'json'
require 'open-uri'
class GamesController < ApplicationController
def new
@letters =[]
10.times{ @letters << ("a".."z").to_a.sample.capitalize }
end
def score
letters = params[:letters]
letters_a = letters.split(' ')
word = params[:word].upcase
url = "https://wagon-dictionary.herokuapp.com/#{word}"
user_serialized = open(url).read
user = JSON.parse(user_serialized)
if user["found"]
if (word.chars.all? { |letter| word.count(letter) <= letters_a.count(letter) })
@results = "good job"
else
@results = "nice try bro, those letters are not in the picks"
end
else
@results = "nope doesnt exist"
end
# if
# else
# end
end
end
# word.each_char do |w|
# if letters_a.include? w
# if user["found"]
# @score = "Good Word"
# else
# @score = "Wrong english word"
# end
# else
# @score = "You picked letters that aren't in the grid!"
# raise
| true |
64978f040d123c1b6b9b7bbfa6e23a8da6348644 | Ruby | d12/leetcode-solutions | /0392-is_subsequence.rb | UTF-8 | 250 | 3.5 | 4 | [] | no_license |
# O(n) time, O(1) space
def is_subsequence(s, t)
if s.length == 0
return true
end
s_index = 0
t.chars.each do |c|
if c == s[s_index]
s_index += 1
end
if s_index == s.length
return true
end
end
false
end | true |
72d85cbc8f508c000c73b4a983e6e0374facdaa4 | Ruby | apricots/learntoprogram-exercises | /Exercises/6.rb | UTF-8 | 425 | 3.703125 | 4 | [] | no_license | # puts 'What is your first name?'
# name1 = gets.chomp
# puts "What is your middle name?"
# name2 = gets.chomp
# puts "What is your last night?"
# name3 = gets.chomp
# nametotal = name1 + name2 + name3
# puts 'Did you know there are ' + nametotal.length.to_s + ' characters in your name?'
# angry boss
# puts "WHAT DO YOU WANT"
# request = gets.chomp
# puts "WHAT DO YOU MEAN " + request.upcase + "?????!!?! YOU ARE FIRED!" | true |
07e12722da2b17e0602b4ddddafe91e8367ebbdf | Ruby | andela/ruby-reduce-exercise | /reducer_answers.rb | UTF-8 | 1,069 | 3.453125 | 3 | [] | no_license | # attr_reader :object
#
# def initialize(object)
# @object = object
# end
#
# def reduce
# object.reduce(Hash.new(0)) do |memo, number|
# memo[number] = memo[number] + 1
# memo
# end
# end
#
# def initialize(object)
# @object = object
# end
#
# def reduce
# object.reduce(Hash.new(0)) do |memo, number|
# memo[number] += 1
# memo
# end
# end
#
# def sent_reverse
# array = object.chars
# # require 'pry' ; binding.pry
# # array.reduce("") do |memo, letter|
# # memo.insert(0,letter)
# # end
# # or
# object.chars.reduce("") do |memo, letter|
# memo = letter + memo
# end
# end
#
# def word_reverse
# array = object.split(" ")
# (1..array.length).inject([]) do |result, index|
# result << array[-1 * index]
# end.join(" ")
# end
# def word_reverse1
# building_word = ""
# (1..object.size).each do |number|
# building_word += object[-1 * number]
# end
# return building_word
# end
| true |
a51ea5da53e7369aaea4eb5d03cbbe3f43bfa8a6 | Ruby | echobind/cat | /lib/custom_utilities.rb | UTF-8 | 123 | 2.671875 | 3 | [
"MIT"
] | permissive | module CustomUtilities
def convert_string_array_to_integer_array(strings_array)
strings_array.map!(&:to_i)
end
end
| true |
ced95ff5692e127907c43ce6d998ac4b93f60005 | Ruby | akavinash1994/ruby_training | /code/item.rb | UTF-8 | 456 | 3.34375 | 3 | [] | no_license | require_relative 'tax_calculator'
class Item
include TaxCalculator
attr_accessor :name, :cost, :quantity, :detail
def initialize(item)
@detail = item
assign
end
def assign
@cost = detail[-1].to_f
@quantity = detail[0].to_f
@name = detail[1..detail.length - 3].join(' ')
end
def display_name
(imported? ? ' imported ' : ' ') + name.gsub('imported ', '')
end
def imported?
name.include?('imported')
end
end
| true |
cde07430a8f3e8557b174ae66b86416c63330d4a | Ruby | mariusz-kowalski/char_canvas | /lib/char_canvas.rb | UTF-8 | 373 | 3.421875 | 3 | [
"BSD-2-Clause"
] | permissive | # documentation in README file
class CharCanvas
def initialize
@canvas = []
end
def insert(string, line, column = 0)
@canvas[line] ||= []
string.each_char do |char|
@canvas[line][column] = char
column += 1
end
end
def paint
@canvas.each do |line|
line.each { |char| print char || ' ' } if line
puts
end
end
end
| true |
c4fc216c935bfa9a8428544fc0b81e9b19b02c72 | Ruby | ldgarber/sinatra-workout-planner | /app/controllers/application_controller.rb | UTF-8 | 4,580 | 2.578125 | 3 | [] | no_license | require './config/environment'
require 'rack-flash'
class ApplicationController < Sinatra::Base
ADJECTIVES = ["sexy", "strong", "powerful", "courageous", "hardworking", "beautiful", "intimidating", "classy", "foxy", "studly", "tenacious"]
NOUNS = ["beast", "devil", "human", "athlete", "specimen", "fighter", "stud", "tamale"]
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "secret"
use Rack::Flash
end
get '/' do
@home = true
if !session[:id]
redirect to '/login'
end
@user = User.find(session[:id])
@adjective = ADJECTIVES.sample
@noun = NOUNS.sample
@workouts = Workout.all
erb :index
end
get '/signup' do
if session[:id]
redirect to '/'
else
erb :signup
end
end
post '/signup' do
@user = User.new(username: params[:username], email: params[:email], password: params[:password])
if @user.save
session[:id] = @user.id
redirect to '/'
else
flash[:message] = "Name, email and password are required"
redirect to '/signup'
end
end
get '/login' do
if session[:id]
redirect to '/'
end
erb :login
end
post '/login' do
if @user = User.find_by(username: params[:username]).try(:authenticate, params[:password])
session[:id] = @user.id
redirect to '/'
else
flash[:message] = "Invalid username or password"
redirect to '/login'
end
end
get '/users/:slug' do
redirect to '/login' if !session[:id]
@user = User.find_by_slug(params[:slug])
erb :'/users/show'
end
get '/workouts' do
@workout = true
redirect to '/login' if !session[:id]
@workouts = Workout.all
@exercises = Exercise.all
erb :'/workouts/index'
end
post '/workouts' do
redirect to '/login' if !session[:id]
flash[:message] = nil
@user = User.find(session[:id])
@user.workouts << Workout.create(params[:workout])
redirect to '/workouts'
end
get '/workouts/find' do
@items = Item.all
erb :'/workouts/find'
end
post '/workouts/find' do
@workouts = Workout.all
@items = []
if params[:item_ids]
params[:item_ids].each do |item|
@items << Item.find(item)
end
end
@results = []
@workouts.each do |workout|
if (workout.items - @items).empty?
@results << workout
end
end
@exercises = Exercise.all
if @results.empty?
flash[:message] = "No workouts found, try adding equipment or create your own workout below"
end
@workouts = @results
erb :'/workouts/index'
end
get '/workouts/:id' do
redirect to '/login' if !session[:id]
@workout = Workout.find(params[:id])
@workouts = Workout.all
erb :'/workouts/show'
end
get '/workouts/:id/edit' do
@workout = Workout.find(params[:id])
@exercises = Exercise.all
@items = Item.all
if session[:id] != @workout.user_id
redirect to "/workouts/#{params[:id]}"
end
erb :'/workouts/edit'
end
patch '/workouts/:id' do
@workout = Workout.find(params[:id])
@workout.update(params[:workout])
redirect to "/workouts/#{params[:id]}"
end
get '/exercises' do
@exercise = true
redirect to '/login' if !session[:id]
@exercises = Exercise.all
@items = Item.all
erb :'/exercises/index'
end
post '/exercises' do
redirect to '/login' if !session[:id]
@user = User.find(session[:id])
@exercise = Exercise.create(params[:exercise])
if params[:item_name] != ""
@items = params[:item_name].split(",").collect {|x| x.strip || x }
@items.each do |item|
@exercise.items << Item.create(name: item)
end
end
@user.exercises << @exercise
redirect to '/exercises'
end
get '/exercises/:id' do
@exercises = true
redirect to '/login' if !session[:id]
@exercise = Exercise.find(params[:id])
erb :'/exercises/show'
end
get '/exercises/:id/edit' do
@exercises = true
@exercise = Exercise.find(params[:id])
@items = Item.all
if session[:id] != @exercise.user_id
redirect to "/exercises/#{params[:id]}"
end
erb :'/exercises/edit'
end
patch '/exercises/:id' do
@exercise = Exercise.find(params[:id])
@exercise.update(params[:exercise])
redirect to "/exercises/#{params[:id]}"
end
get '/logout' do
if session[:id]
session.clear
redirect to '/login'
else
redirect to '/'
end
end
end
| true |
81bd01e33eef35c6913d2c52b5e8842b0ac7036d | Ruby | yicheng-w/competitive_programming | /contests/codejam/codejam2017/quals/tidynumbers.rb | UTF-8 | 1,411 | 3.734375 | 4 | [] | no_license | # Input
# T
# for q in T
# N
def main()
_T = gets.chomp.to_i
_N = nil
# puts "TEST T is #{_T}"
(1.._T).each do |q|
_N = gets.chomp.to_i
w = get_last_tidy(_N)
print "Case ##{q}: "
# test(_N)
print "#{w}"
puts
end
# [129, 999, 7, 123, 321, 2220, 12342372 ].each do |n|
# # test(n)
# end
# 100.times do
# n = rand(2**10)
# # test(n)
# end
end
def tidy?(n)
# Convert to integer values
digits = n.to_s.split('').map { |ch| ch.to_i }
# Check ascending order
return digits.each_cons(2).all? { |i,j| i <= j }
end
def get_unbalanced_idx(n)
if tidy?(n)
return -1
else
# Convert to integer values
digits = n.to_s.split('').map { |ch| ch.to_i }
# Iterate through digits to check ascending order
(1..(digits.length-1)).each do |idx|
# Return index if untidy
i = digits[idx-1]
j = digits[idx]
return (idx-1) if i >= j
end
end
end
def get_last_tidy(n)
if tidy?(n)
return n
else
# Brute force
# n.downto(1) do |i|
# return i if tidy?(i)
# end
digits = n.to_s.split('').map { |ch| ch.to_i }
idx = get_unbalanced_idx(n)
digits[idx] = digits[idx] - 1
((idx+1)..(digits.length-1)).each do |idx|
digits[idx] = 9
end
return digits.join('').to_i
end
end
def test(n)
puts "TEST n = #{n}"
puts "is tidy? #{tidy?(n)}"
puts "last tidy: #{get_last_tidy(n)}"
puts "unbalanced_idx: #{get_unbalanced_idx(n)}"
puts
end
main()
| true |
1f611cdc645d840d158cbb39d679ded99bf5e546 | Ruby | JFVF/cucumber_022015 | /Vanessa/Session 6/array.rb | UTF-8 | 706 | 4.46875 | 4 | [] | no_license | =begin
Array examples
=end
nums = [1, 3.0, 'something', 'something else']
puts 'Third element:'
puts nums[2]
puts 'Last element:'
puts nums[-1]
puts 'Last element:'
puts nums.last
puts 'First element:'
puts nums.first
puts "\n"
mystuff = ['samsung', 'nokia', 'iphone']
puts 'Length of mystuff'
puts mystuff.length
otherstuff = %w{samsung nokia iphone}
puts 'Length of otherstuff'
puts otherstuff.length
puts "\n"
my_array = [1,2,5,7,11]
puts 'puts my_array'
puts my_array
puts 'puts my_array.inspect'
puts my_array.inspect
puts 'p my_array'
p my_array
puts "\n"
puts 'intersection'
puts [1,2,3] & [3,4,5]
puts 'addition'
puts [1,2,3] + [3,4,5]
puts 'substraction'
puts [1,2,3] - [3,4,5]
puts "\n"
| true |
75043d69726465a33d94e647c2e337699d4782bc | Ruby | phyzical/advent-of-code | /2020/17.1.rb | UTF-8 | 2,624 | 3.234375 | 3 | [] | no_license | require_relative "helpers"
module DaySeventeenPartOne
module_function
def solve(file)
grid = { "0": prepare_inputs(file) }
6.times { grid = do_cycle(grid) }
byebug
grid.reduce(0) do |acc, slice|
acc +
slice.reduce(0) do |acc2, val|
acc2 += 1 if val == "#"
acc2
end
end
end
def do_cycle(grid)
new_front_slice_index = (grid.first.first.to_s.to_i - 1).to_s.to_sym
new_back_slice_index = (grid.to_a.last.first.to_s.to_i + 1).to_s.to_sym
y_len = grid[grid.first.first].count
x_len = grid[grid.first.first].first.count
grid[new_front_slice_index] = Array.new(y_len, Array.new(x_len, "."))
grid[new_back_slice_index] = Array.new(y_len, Array.new(x_len, "."))
grid = grid.sort_by { |k, _v| k.to_s.to_i }.to_h
## make new grid with same keys to be filled with extra heights
new_grid = grid.keys.product([Array.new(y_len + 2, [])]).to_h
grid.each do |current_index, slice|
forward_slice = grid[(current_index.to_s.to_i - 1).to_s.to_sym]
behind_slice = grid[(current_index.to_s.to_i + 1).to_s.to_sym]
slice.each_with_index do |y_slice, y|
y_slice.prepend(".").append(".")
y_slice.each_with_index do |value, x|
new_value = value
actives = 0
actives += count_slice_actives(forward_slice, x, y) if forward_slice
actives += count_slice_actives(slice, x, y, false)
actives += count_slice_actives(behind_slice, x, y) if behind_slice
if value == "#" && ![2, 3].include?(actives)
new_value = "."
elsif value == "." && actives == 3
new_value = "#"
end
new_grid[current_index][y][x] = new_value
end
end
end
new_grid
end
def count_slice_actives(slice, x, y, disable_middle = true)
matches = []
y_max = slice.count - 1
matches << slice[y - 1][x + 1] if (y - 1) >= 0
matches << slice[y][x + 1]
matches << slice[y + 1][x + 1] if (y + 1) <= y_max
matches << slice[y - 1][x] if (y - 1) >= 0
matches << slice[y][x] if disable_middle
matches << slice[y + 1][x] if (y + 1) <= y_max
matches << slice[y - 1][x - 1] if (y - 1) >= 0
matches << slice[y][x - 1]
matches << slice[y + 1][x - 1] if (y + 1) <= y_max
matches.reduce(0) do |acc, val|
acc += 1 if val == "#"
acc
end
end
def prepare_inputs(file)
Helpers.split_inputs_by_line(Helpers.read_file(file)).map(&:chars)
end
end
ap DaySeventeenPartOne.solve("#{__dir__}/17test.txt")
# ap DaySeventeenPartOne.solve(__dir__ + '/17.txt')
| true |
11b0144cb8f45d1073e00c7b7f49da3dc7a10372 | Ruby | deependersingla/ruby_script | /athinkkingapecircle.rb | UTF-8 | 419 | 3.078125 | 3 | [] | no_license | def array(a)
@array=a
#print @array
for i in 0...@array.length-1
if (i==1 or i.odd?)
#print i
@array[i]=@array[i+1]
end
i=i+1
end
m=@array.uniq
return m
end
print " enter n "
d=gets.chomp
d=d.to_i
j=0
#d.chomp
#print d
#print " ia m here"
#print d.type
c=(1..d).to_a
k=c
for l in 0..d
print "i am here"
k=array(k)
k=k.to_a
print k
if (k[1].nil?)
break
end
end
print k
| true |
191f6f7c690f64d6976993fd04960a990329981b | Ruby | IlyaMur/ruby_learning | /Simdyanov_exercises/Chapter 10/1.rb | UTF-8 | 83 | 2.921875 | 3 | [] | no_license | num1 = gets.to_i
begin
num2 = gets.to_i
end while num2 == 0
puts num1 / num2
| true |
2e0e16296e5f6b3afe2d3e62f4ca9f4d2f15a6b0 | Ruby | qermyt/miniputer | /lib/miniputer/physics/simulator.rb | UTF-8 | 877 | 2.84375 | 3 | [
"MIT"
] | permissive | module Physics
class Simulator
def initialize
@clocks = []
@electric_flow = ElectricFlow.new
end
def flow_size
@electric_flow.wireflow.size
end
def hook_up_clock(clock)
@clocks << clock
end
def hook_up_electric_flow(flow)
@electric_flow = flow
end
def tick
@clocks.each(&:tick)
@electric_flow.flow_all
end
def run_until_stable
tick until @electric_flow.stable?
end
def run_one_clock_tick
(CLOCK_HIGH_PULSE + CLOCK_LOW_PULSE).times { tick }
end
def run_until_clock_stable
loop do
(CLOCK_HIGH_PULSE + CLOCK_LOW_PULSE).times { tick }
break if @electric_flow.stable?
end
end
def mark_as_flowing(wire)
@electric_flow.mark_as_flowing(wire)
end
def equilibrium?
@electric_flow.stable?
end
end
end
| true |
bc124022bb7000c255475a345f0d67a5742ae783 | Ruby | tarcieri/celluloid-io | /lib/celluloid/io/tcp_socket.rb | UTF-8 | 2,667 | 2.78125 | 3 | [
"MIT"
] | permissive | require 'socket'
require 'resolv'
module Celluloid
module IO
# TCPSocket with combined blocking and evented support
class TCPSocket
include CommonMethods
extend Forwardable
def_delegators :@socket, :read_nonblock, :write_nonblock, :close, :closed?
def_delegators :@socket, :addr, :peeraddr, :setsockopt
# Convert a Ruby TCPSocket into a Celluloid::IO::TCPSocket
def self.from_ruby_socket(ruby_socket)
# Some hax here, but whatever ;)
socket = allocate
socket.instance_variable_set(:@socket, ruby_socket)
socket
end
# Opens a TCP connection to remote_host on remote_port. If local_host
# and local_port are specified, then those parameters are used on the
# local end to establish the connection.
def initialize(remote_host, remote_port, local_host = nil, local_port = nil)
# Is it an IPv4 address?
begin
@addr = Resolv::IPv4.create(remote_host)
rescue ArgumentError
end
# Guess it's not IPv4! Is it IPv6?
unless @addr
begin
@addr = Resolv::IPv6.create(remote_host)
rescue ArgumentError
end
end
# Guess it's not an IP address, so let's try DNS
unless @addr
addrs = Array(DNSResolver.new.resolve(remote_host))
raise Resolv::ResolvError, "DNS result has no information for #{remote_host}" if addrs.empty?
# Pseudorandom round-robin DNS support :/
@addr = addrs[rand(addrs.size)]
end
case @addr
when Resolv::IPv4
family = Socket::AF_INET
when Resolv::IPv6
family = Socket::AF_INET6
else raise ArgumentError, "unsupported address class: #{@addr.class}"
end
@socket = Socket.new(family, Socket::SOCK_STREAM, 0)
@socket.bind Addrinfo.tcp(local_host, local_port) if local_host
begin
@socket.connect_nonblock Socket.sockaddr_in(remote_port, @addr.to_s)
rescue Errno::EINPROGRESS
wait_writable
# HAX: for some reason we need to finish_connect ourselves on JRuby
# This logic is unnecessary but JRuby still throws Errno::EINPROGRESS
# if we retry the non-blocking connect instead of just finishing it
retry unless defined?(JRUBY_VERSION) && @socket.to_channel.finish_connect
rescue Errno::EISCONN
# We're now connected! Yay exceptions for flow control
# NOTE: This is the approach the Ruby stdlib docs suggest ;_;
end
end
def to_io
@socket
end
end
end
end
| true |
5763e4098352a3dc299b0893ea5d10847c3c76bc | Ruby | evangoad/squidbuilds | /util/splat_scraper/lib/splat_scraper/wikia/article_table.rb | UTF-8 | 359 | 2.59375 | 3 | [
"MIT"
] | permissive | module SplatScraper::Wikia::ArticleTable
def extract_table(table_node)
rows = table_node.xpath("tr[td]")
header = table_node.xpath("tr[th]").xpath("//th/text()").map {|n| n.to_s.strip}
rows.map do |row|
obj = {}
header.each_with_index do |h, i|
obj[h] = row.xpath("td")[i].text.strip
end
obj
end
end
end
| true |
843322e145118aaf9fb95e39b9b67b6ebdfaaf73 | Ruby | haydenwalls/fibonacci | /lib/fibonacci.rb | UTF-8 | 690 | 4.0625 | 4 | [] | no_license | # Computes the nth fibonacci number in the series starting with 0.
# fibonacci series: 0 1 1 2 3 5 8 13 21 ...
# e.g. 0th fibonacci number is 0
# e.g. 1st fibonacci number is 1
# ....
# e.g. 6th fibonacci number is 8
def fibonacci(n)
if n == 0
return 0
elsif n == 1
return 1
elsif n.class != Integer || n < 0
raise ArgumentError.new
end
x = 0
y = 1
z = nil
(n - 1).times do
z = x + y
x = y
y = z
end
return z
end
# the time complexity is O(n) because the solution must iterate through the loop (n - 1) times
# the space complexity is O(1) because only 3 additional variables are opened in memory which are then reassigned as the loop iterates
| true |
e55db81adaa05057be3bca472ff48920fee5da4c | Ruby | jhelman22/challenges | /project_euler/012.rb | UTF-8 | 1,264 | 4.71875 | 5 | [] | no_license | # Problem 12
#
# The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# Let us list the factors of the first seven triangle numbers:
#
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
# 10: 1,2,5,10
# 15: 1,3,5,15
# 21: 1,3,7,21
# 28: 1,2,4,7,14,28
#
# We can see that 28 is the first triangle number to have over five divisors.
#
# What is the value of the first triangle number to have over five hundred divisors?
#
# Understand the algorithm? http://code.jasonbhill.com/sage/project-euler-problem-12/
def num_divisors(n)
n /= 2 if n.even?
divisors = 1
count = 0
while n.even?
count += 1
n /= 2
end
divisors *= (count + 1)
m = 3
while n != 1
count = 0
while n % m == 0
count += 1
n /= m
end
divisors *= (count + 1)
m += 2
end
divisors
end
def triangle_index(factors)
n = 1
left = num_divisors(n)
right = num_divisors(n+1)
while left * right < factors
n += 1
left = right
right = num_divisors(n+1)
end
n
end
n = triangle_index(500)
triangle = (n * (n +1)) / 2
puts triangle
# Answer: 76576500
| true |
aedaa13889b4a2496cf75bdcab8205e3e06df6f3 | Ruby | wchu248/MailerTest | /app/models/user.rb | UTF-8 | 3,632 | 2.609375 | 3 | [] | no_license | class User < ApplicationRecord
# Daily Wellness Survey @ 10 AM everyday
def self.email_all
User.all.each do |u|
UserMailer.pre_practice_email(u).deliver_now
end
end
# Men's Basketball 5 @ 7PM
def self.email_mbb
User.all.each do |u|
if u.team_id == 5
UserMailer.post_practice_email(u).deliver_now
end
end
end
# Women's Basketball 6 @ 7PM
def self.email_wbb
User.all.each do |u|
if u.team_id == 6
UserMailer.post_practice_email(u).deliver_now
end
end
end
# Women's Tennis 9
def self.email_wtennis
# array of 30 minutes past practice end times for women's tennis
# parameters for DateTime object are year, month, day, hour, minute
# .change sets the DateTime object in our time zone (US Eastern)
practice_times = [
DateTime.new(2018, 2, 12, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 13, 18, 30).change(:offset => "-0500"),
DateTime.new(2018, 2, 14, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 15, 8, 30).change(:offset => "-0500"),
DateTime.new(2018, 2, 19, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 20, 18, 30).change(:offset => "-0500"),
DateTime.new(2018, 2, 21, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 22, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 24, 9, 30).change(:offset => "-0500"),
DateTime.new(2018, 2, 26, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 27, 23).change(:offset => "-0500"),
DateTime.new(2018, 3, 7, 23).change(:offset => "-0500")
]
User.all.each do |u|
# check if they are on women's tennis team
if u.team_id == 9
# check if current date is close (+/- 10 min) to one of the practice end times
practice_times.each do |t|
if ((DateTime.now - t) * 24 * 60).to_i > (-10) && ((DateTime.now - t) * 24 * 60).to_i < 10
UserMailer.post_practice_email(u).deliver_now
break
end
end
end
end
end
# Men's Tennis 8
def self.email_mtennis
# array of 30 minutes past practice end times for men's tennis
# parameters for DateTime object are year, month, day, hour, minute
# .change sets the DateTime object in our time zone (US Eastern)
practice_times = [
DateTime.new(2018, 2, 12, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 13, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 14, 19, 30).change(:offset => "-0500"),
DateTime.new(2018, 2, 15, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 18, 10, 30).change(:offset => "-0500"),
DateTime.new(2018, 2, 19, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 20, 23).change(:offset => "-0500"),
DateTime.new(2018, 2, 28, 23).change(:offset => "-0500"),
DateTime.new(2018, 3, 1, 23).change(:offset => "-0500"),
DateTime.new(2018, 3, 3, 9, 30).change(:offset => "-0500"),
DateTime.new(2018, 3, 5, 23).change(:offset => "-0500"),
DateTime.new(2018, 3, 6, 23).change(:offset => "-0500")
]
User.all.each do |u|
# check if they are on men's tennis team
if u.team_id == 8
# check if current date is close (+/- 10 min) to one of the practice end times
practice_times.each do |t|
if ((DateTime.now - t) * 24 * 60).to_i > (-10) && ((DateTime.now - t) * 24 * 60).to_i < -10
UserMailer.post_practice_email(u).deliver_now
break
end
end
end
end
end
def self.testMethod
puts User.all
end
end
| true |
0479029b5c97e0c3002548377f37792730aa20a1 | Ruby | christiano57/MyProject | /ruby/prework/day2.rb | UTF-8 | 89 | 3.171875 | 3 | [] | no_license | class Car
def say_broom
puts "Broom"
end
end
corvette = Car.new
corvette.say_broom | true |
284a717bceff427af3950f7ea7849b214d36d431 | Ruby | febbraiod/my_find_code_along-v-000 | /lib/my_find.rb | UTF-8 | 125 | 2.90625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def my_find(collection)
collection.each do |i|
if yield(i)
return i
end
end
nil
end | true |
eea8d5d1955b9ab2aa337cc1e5127642ff564d0d | Ruby | shadefinale/danebook | /spec/models/post_spec.rb | UTF-8 | 2,221 | 2.515625 | 3 | [] | no_license | require 'rails_helper'
describe Post do
let(:post) { create(:post) }
describe '#posted_on' do
it 'should respond to posted on method' do
expect(post).to respond_to(:posted_on)
end
# This test fails based on local time.
# it 'should have a human readable posted on date' do
# expect(post.posted_on).to eq("Posted on #{DateTime.now.strftime("%A %m/%d/%Y")}")
# end
end
describe '#has_likes?' do
it 'should have return false by default' do
expect(post.has_likes?).to be false
end
it 'should return true once the post has likes.' do
post_like = create(:liked_post)
post.likes << post_like
expect(post.has_likes?).to be true
end
end
context 'comment association' do
it 'should respond to comment association' do
expect(post).to respond_to(:comments)
end
end
context 'people who like association' do
it 'should respond to people_who_like association' do
expect(post).to respond_to(:people_who_like)
end
it 'should get an empty result by default' do
expect(post.people_who_like.count).to eq(0)
end
it 'should return results once it has likes' do
post.likes << create(:liked_post)
expect(post.people_who_like.count).to eq(1)
end
end
context 'author association' do
it 'should respond to author association' do
expect(post).to respond_to(:author)
end
it 'should return an author by defualt' do
expect(post.author).to be_a(User)
end
end
context 'post creation' do
let(:user) { build(:user) }
it 'should attribute a post to a user' do
create(:post, author: user)
expect(user.written_posts.count).to eq(1)
end
end
context 'commenting on posts' do
let(:user) { build(:user) }
let(:new_comment) { build(:commented_post) }
it 'should allow a user to have comments on posts' do
user.comments << new_comment
user.save
expect(user.comments.count).to eq(1)
end
it 'should allow a user to retrieve a post based on the comment' do
user.comments << new_comment
user.save
expect(user.posts_commented_on.first).to eq(new_comment.commentable)
end
end
end
| true |
ad44503ac8b73994505e0ad8b8aed065edf874cb | Ruby | miriamhit02/flash_cards | /spec/round_spec.rb | UTF-8 | 5,286 | 3.5 | 4 | [] | no_license | require 'pry'
require './lib/card'
require './lib/turn'
require './lib/deck'
require './lib/round'
RSpec.describe Round do
it 'exists' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
expect(round).to be_a(Round)
end
it 'has a deck' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
expect(round.deck).to eq(deck)
end
it 'has turns' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
expect(round.turns).to eq([])
end
it 'can give current card' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
expect(round.current_card).to eq(card_1)
end
it 'can take turns' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
expect(round.current_card).to eq(card_1)
new_turn = round.take_turn("Juneau")
# expect(new_turn.class).to eq(Turn)
expect(round.current_card).to eq(card_2)
end
it 'tells you number of correct guesses' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
new_turn = round.take_turn("Juneau")
new_turn = round.take_turn("Mars")
expect(round.number_correct).to eq(2)
end
it 'tells you number correct by category' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
new_turn = round.take_turn("Juneau")
new_turn = round.take_turn("Mars")
new_turn = round.take_turn("North north west")
expect(round.number_correct_by_category(:STEM)).to eq(2)
end
it 'tells you percent correct' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
new_turn = round.take_turn("Juneau")
new_turn = round.take_turn("Mars")
expect(round.percent_correct).to eq(100)
end
it 'tells you percent correct by category' do
card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
deck = Deck.new([card_1, card_2, card_3])
round = Round.new(deck)
# binding.pry
new_turn = round.take_turn("Juneau")
new_turn = round.take_turn("June")
new_turn = round.take_turn("North north west")
expect(round.percent_correct_by_category(:STEM)).to eq(50)
end
end
| true |
914593b9ca0ec98e5bbb25ad630b9720e924f6e8 | Ruby | APWilson97/Ruby-programming-intro | /Arrays/exercise6.rb | UTF-8 | 162 | 3.046875 | 3 | [] | no_license | 'The user is attempting to change the value of the margaret element in the names array using a string as a key but array indexes are integers.'
names[3] = 'jody' | true |
1e30f5703993dafbb837c9f3370198939aca69e3 | Ruby | tmtysk/mbmail | /lib/tmail/mail.rb | UTF-8 | 836 | 2.6875 | 3 | [
"MIT"
] | permissive | module TMail
# Mail 構築時に MessageIdHeader が正しく作成できない処理を修正
class Mail
def []=( key, val )
dkey = key.downcase
if val.nil?
@header.delete dkey
return nil
end
case val
when String
header = new_hf(key, val)
when HeaderField
# HeaderField が与えられた場合、そのままヘッダに代入する
header = val
when Array
ALLOW_MULTIPLE.include? dkey or
raise ArgumentError, "#{key}: Header must not be multiple"
@header[dkey] = val
return val
else
header = new_hf(key, val.to_s)
end
if ALLOW_MULTIPLE.include? dkey
(@header[dkey] ||= []).push header
else
@header[dkey] = header
end
val
end
end
end
| true |
b6ce95faa0bb5f522fe6cce4e74c99c9a57b913d | Ruby | chischaschos/tic-tac-toe-pairing-with-pollo | /lib/tictactoe/game.rb | UTF-8 | 222 | 2.640625 | 3 | [] | no_license | module Tictactoe
# Game is the persisted representation of a tictactoe game
class Game
attr_reader :id
def initialize(id: nil)
@id = id
end
def ==(other)
other.id == @id
end
end
end
| true |
c908e7fcec7d236834f875c03ace464a9f24a470 | Ruby | ashivkum/OpenWeatherApplication | /app/models/weather.rb | UTF-8 | 3,635 | 3.453125 | 3 | [] | no_license | require 'pry'
require 'net/http'
require 'json'
class Weather
@@CONVERSION_FACTOR = 1.8
@@KELVIN_FACTOR = 273.15
@@FARENHEIT_FACTOR = 32
# Approximate conversion factor m/s to mph, taken from Google
@@WIND_CONVERSION_FACTOR = 2.23694
=begin
The following methods handle the external dependencies and are just
wrappers for testing
=end
def _sanitize_input(city, country)
return city.upcase, country.upcase
end
def _setup_http_request(url)
return URI.parse(url)
end
def _make_http_request(url_object)
return Net::HTTP::get(url_object)
end
def _parse_json_payload(response_text)
return JSON.parse(response_text)
end
=begin
This method is a partial implementation of the Beaufort scale description
for winds, taken from https://en.wikipedia.org/wiki/Beaufort_scale#Modern_scale
=end
def _get_beaufort_scale_verbiage(speed)
if speed < 1 then
return 'calm'
elsif speed >= 1 && speed <= 4 then
return 'light air'
elsif speed > 4 && speed <= 8 then
return 'light breeze'
elsif speed > 8 && speed <= 13 then
return 'gentle breeze'
elsif speed > 13 && speed <= 19 then
return 'moderate breeze'
elsif speed > 19 && speed <= 25 then
return 'fresh breeze'
elsif speed > 25 && speed <= 32 then
return 'strong breeze'
else
return 'high winds'
end
end
=begin
The following are math methods that help convert certain metrics to imperial
units
=end
def _kelvin_to_farenheit(kelvin)
celsius = kelvin - @@KELVIN_FACTOR
return ((@@CONVERSION_FACTOR * celsius) + @@FARENHEIT_FACTOR).round
end
def _meter_per_second_to_mph(wind_speed)
return (wind_speed * @@WIND_CONVERSION_FACTOR).round
end
=begin
This is where the main computation is done
=end
def get_weather_response(city, country)
sanitized_city, sanitized_country = _sanitize_input(city, country)
# Generate the URL from the requested city and country, and the API key
query_string = '%s,%s' % [sanitized_city, sanitized_country]
request_url = ENV['BASE_WEATHER_URL'] % [query_string, ENV['API_KEY']]
# Get the URL request object from the requested url
url_request = _setup_http_request(request_url)
# Make the HTTP URL request
response_text = _make_http_request(url_request)
# Parse the response
response_payload = JSON.parse(response_text)
if response_payload['cod'].to_i == 404 then
raise ActiveRecord::RecordNotFound.new('City was not found!')
end
farenheit_temperature = _kelvin_to_farenheit(response_payload['main']['temp'])
wind_speed_mph = _meter_per_second_to_mph(response_payload['wind']['speed'])
beaufort_scale_verbiage = _get_beaufort_scale_verbiage(wind_speed_mph)
return {
:city => response_payload['name'],
:country => country,
:temperature => farenheit_temperature,
:wind => wind_speed_mph,
:wind_intensity => beaufort_scale_verbiage,
:wind_direction => response_payload['wind']['deg'],
:pressure => response_payload['main']['pressure'],
:humidity => response_payload['main']['humidity'],
:weather_description => response_payload['weather'][0]['description'],
:weather_main => response_payload['weather'][0]['main'],
:last_requested_utc => Time.now.utc.to_i
}
end
end | true |
c07451a0a6f7aaf70ad1704369d50ecd328077c7 | Ruby | ESCasson/Ruby_Project_The_Gym | /models/member.rb | UTF-8 | 1,569 | 3.4375 | 3 | [] | no_license | require_relative('../db/sql_runner.rb')
class Member
attr_reader :id
attr_accessor :first_name, :last_name, :premier_member
def initialize(details)
@id = details['id'].to_i if details['id']
@first_name = details['first_name']
@last_name = details['last_name']
@premier_member = details['premier_member']
end
def save()
sql = "INSERT INTO members (first_name, last_name, premier_member)
VALUES ($1, $2, $3) RETURNING id"
values = [@first_name, @last_name, @premier_member]
result = SqlRunner.run(sql, values)
@id = result[0]['id'].to_i()
end
def self.delete_all()
sql = "DELETE FROM members"
SqlRunner.run(sql)
end
def self.all()
sql = "SELECT * FROM members"
result = SqlRunner.run(sql)
return result.map{|member| Member.new(member)}
end
def self.membership_display(membership_details)
if membership_details == 't'
return 'Premier Member'
end
return 'Standard Member'
end
def self.find_by_id(id)
sql = "SELECT * FROM members WHERE id = $1"
values = [id]
member = SqlRunner.run(sql,values)
result = Member.new(member[0])
return result
end
def update()
sql = "UPDATE members SET (first_name, last_name, premier_member) =
($1, $2, $3) WHERE id = $4"
values = [@first_name, @last_name, @premier_member, @id]
SqlRunner.run(sql, values)
end
def delete()
sql = "DELETE FROM members WHERE id = $1"
values =[@id]
SqlRunner.run(sql, values)
end
def full_name()
return @first_name + " " + @last_name
end
end
| true |
1d2dfa5bbdb70e42b96b9d6203804e3903b22d0b | Ruby | LichP/multprimes | /lib/mult_primes/mult_table.rb | UTF-8 | 1,378 | 3.53125 | 4 | [
"MIT"
] | permissive | require File.join(File.dirname(__FILE__), 'mult_table', 'formatters')
class MultTable
attr :multipliers
def initialize(*multipliers)
@multipliers = multipliers.flatten.sort
end
# Compute a line of the multiplication table
#
# @param [Integer] i the number of the line to compute
# @return [Array<Integer>] of products calculated from the +i+th multiplier
# @return [Array<Integer>] of untouched multipliers if +i = 0+
# @return [nil] if +i+ is out of range or otherwise invalid
def line(i)
case i
when 0
self.multipliers
when 1..self.multipliers.length
self.multipliers.map { |m| m * self.multipliers[i - 1] }
else
nil
end
end
# Same as calling #line(0)
#
# @return [Array<Integer>]
def header_line
self.line(0)
end
# Generate all lines in the multiplication table (except for the header)
#
# @return [Array<Integer, Array<Integer>>] an array of lines, each line
# consisting of the multiplier and an array of products of that
# multiplier
def lines
1.upto(multipliers.length).collect do |i|
[self.multipliers[i - 1], self.line(i)]
end
end
# @return [Integer] the largest product in the table, i.e. the square of
# the last (therefore largest) multiplier
def largest_product
self.multipliers.last ** 2
end
end
| true |
2487884c3b7b642074210ca76ed950fd876ef5b6 | Ruby | nbudin/octopi | /lib/octopi/user.rb | UTF-8 | 2,755 | 2.828125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Octopi
class User < Base
include Resource
find_path "/user/search/:query"
resource_path "/user/show/:id"
# Finds a single user identified by the given username
#
# Example:
#
# user = User.find("fcoury")
# puts user.login # should return 'fcoury'
def self.find(username)
self.validate_args(username => :user)
super username
end
# Finds all users whose username matches a given string
#
# Example:
#
# User.find_all("oe") # Matches joe, moe and monroe
#
def self.find_all(username)
self.validate_args(username => :user)
super username
end
# Returns a collection of Repository objects, containing
# all repositories of the user.
#
# If user is the current authenticated user, some
# additional information will be provided for the
# Repositories.
def repositories
Repository.find_by_user(login)
end
# Searches for user Repository identified by
# name
def repository(name)
self.class.validate_args(name => :repo)
Repository.find(login, name)
end
def create_repository(name, opts = {})
self.class.validate_args(name => :repo)
Repository.create(self, name, opts)
end
# Adds an SSH Public Key to the user. Requires
# authentication.
def add_key(title, key)
raise APIError,
"To add a key, you must be authenticated" if @api.read_only?
result = @api.post("/user/key/add", :title => title, :key => key)
return if !result["public_keys"]
key_params = result["public_keys"].select { |k| k["title"] == title }
return if !key_params or key_params.empty?
Key.new(@api, key_params.first, self)
end
# Returns a list of Key objects containing all SSH Public Keys this user
# currently has. Requires authentication.
def keys
raise APIError,
"To add a key, you must be authenticated" if @api.read_only?
result = @api.get("/user/keys")
return unless result and result["public_keys"]
result["public_keys"].inject([]) { |result, element| result << Key.new(@api, element) }
end
# takes one param, deep that indicates if returns
# only the user login or an user object
%w[followers following].each do |method|
define_method(method) do
user_property(method, false)
end
define_method("#{method}!") do
user_property(method, true)
end
end
def user_property(property, deep)
users = []
property(property, login).each_pair do |k,v|
return v unless deep
v.each { |u| users << User.find(u) }
end
users
end
end
end
| true |
0491e01e0486f86d82e1b521bb948601d331bd28 | Ruby | vladiim/real_estate_mate | /lib/states/states.rb | UTF-8 | 447 | 2.65625 | 3 | [] | no_license | module States
def self.get_state_links(url)
index = Mechanize.new.get(url)
link_columns = index.search('.column')
add_link_to_urls link_columns
end
private
def self.add_link_to_urls(link_columns)
links = link_columns.search('dd')
links.inject([]) { |urls, link| urls << make_allhome_url(link) }
end
def self.make_allhome_url(link)
Allhomes::URL + link.search('a')[0].attributes['href'].value
end
end | true |
17e722ee54beac789ad1b3a19fd8ff59b6f17864 | Ruby | dcrosby42/conject | /spec/conject/extended_metaid_spec.rb | UTF-8 | 2,156 | 2.921875 | 3 | [
"MIT"
] | permissive | require File.expand_path(File.dirname(__FILE__) + "/../spec_helper")
#
# This set of specs isn't intended to exhaust metaid's functionality.
# Just to frame up something as a basis for test driving further mods.
#
describe "Extended metaid" do
# Not testing:
# Object#metaclass
# Object#meta_eval
# because we're not using them directly, don't plan to
# change them, they're long-standing, widely-used Ruby
# metaprogramming methods, and we're using and testing
# them indirectly through #metadef
describe "Object#meta_def" do
it "adds a method to an instance" do
obj = Object.new
obj2 = Object.new
obj.meta_def :berzerker do
37
end
obj.berzerker.should == 37
lambda do obj2.berzerker.should == 37 end.should raise_error
end
end
describe "Class#meta_def" do
subject do
Class.new do
def self.use_metaclass_method
try_me
end
end
end
it "adds a method to the metaclass of a class" do
subject.meta_def :try_me do "is nice" end
subject.try_me.should == "is nice"
subject.use_metaclass_method.should == "is nice"
end
end
# Not testing
# Module#module_def
# Module#module_def_private
# because we're not using them directly,
# so let's move onto the class stuff
describe "Class#class_def" do
subject do
Class.new
end
it "enables dynamic generation of new instance methods" do
obj = subject.new
subject.class_def :sgt do
"highway"
end
obj.sgt.should == "highway"
subject.new.sgt.should == "highway"
end
end
describe "Class#class_def_private" do
subject do
Class.new
end
it "enables dynamic generation of new PRIVATE instance methods" do
obj = subject.new
subject.class_def_private :sgt do "highway" end
# sgt is private so we shouldn't be able to call it outright
lambda do obj.sgt end.should raise_error(NoMethodError)
# Make a public method that can access it
subject.class_def :gunnery do sgt end
obj.gunnery.should == "highway"
end
end
end
| true |
30427e109d1b82b1acb9c28d4261feedddd7496d | Ruby | naoki-k/Ruby-Cherry-Book | /chapter2/2.3.1.rb | UTF-8 | 462 | 3.703125 | 4 | [] | no_license | # 文字列
# シングルクオートとダブルクオート
# 特殊文字や式展開をする場合はダブルクオート
name = 'Alice'
puts "Hello, #{name}!"
puts "こんにちは\nさようなら"
# バックスラッシュでエスケープ
puts "Hello, \#{name}!"
# 文字列の比較
# == != < <= > >= 関係が成立でtrue
# 大小関係は、文字コードが比較基準になる
'a' > 'b'
'abc' < 'abcd'
puts 'a' > 'b'
puts 'abc' < 'abcd'
| true |
65f0fe59e70b0b93776b36eb23c1f4d55950f4b1 | Ruby | kukushkin/aerogel-users | /app/helpers/auth.rb | UTF-8 | 1,560 | 2.59375 | 3 | [
"MIT"
] | permissive | # Redirects after authentication process to the most appropriate origin URL.
#
# Possible origins (URLs to redirect to) are tried in following order:
# explicit_origin
# request.env['omniauth.origin']
# request.params['origin']
# default_origin
#
def auth_redirect_to_origin( explicit_origin, default_origin = "/" )
url = explicit_origin || request.env['omniauth.origin'] || request.params['origin'] || default_origin
redirect url
end
def auth_login( user, opts = {} )
session[:user_id] = user.id
session[:remember_me] = opts[:remember_me].present?
user.authenticated!( opts )
auth_keepalive_session
end
def auth_logout
session[:user_id] = nil
session[:remember_me] = nil
session.options[:expire_after] = nil
end
def auth_keepalive_session
session.options[:expire_after] = 2592000 if session[:remember_me]
end
# Returns User object of the current authenticated user or +nil+.
#
def current_user
auth_keepalive_session
@current_user ||= ( session[:user_id] ? User.find( session[:user_id] ) : nil )
end
# Returns +true+ if user is authenticated, +false+ otherwise.
#
def current_user?
!current_user.nil?
end
# Gets or sets auth state.
# 'auth state' is a one-time used Hash used to store auth system data between requests.
#
def auth_state( value = nil )
if value
@auth_state = value
session[:auth_state] = value.to_json
return @auth_state
end
unless @auth_state
@auth_state = session[:auth_state].nil? ? {} : JSON.parse( session[:auth_state] )
session[:auth_state] = nil
end
@auth_state
end
| true |
8b0a7a015dbcea3a8640521a035f70a5a633dcdf | Ruby | timuruski/bench-test-suites | /bench.rb | UTF-8 | 933 | 2.578125 | 3 | [] | no_license | #! /usr/bin/env ruby
SUITES = {
'Bacon' => 'bacon -q spec/bacon_spec.rb',
'Cutest' => 'cutest spec/cutest_spec.rb',
'Minitest' => 'ruby spec/minitest_spec.rb',
'Riot' => 'ruby spec/riot_spec.rb',
'RSpec' => 'rspec spec/rspec_spec.rb'
}
PATTERN = /([0-9.]+) real +([0-9.]+) user +([0-9.]+) sys/
COUNT = 10
puts format "%8s %8s %8s", 'Suite', 'Avg real', 'Std dev'
puts format "-" * (3 * 8 + 2)
SUITES.each do |name, cmd|
times = Array.new(COUNT) {
result = %x(/usr/bin/time #{cmd} 2>&1 | tail -1)
_, real, user, sys = *result.match(PATTERN)
[real.to_f, user.to_f, sys.to_f]
}
real_avg, user_avg, sys_avg = times.map { |ts|
ts.inject(0,&:+) / ts.length }
real_std, user_std, sys_std = times.map { |ts|
mean = ts.inject(0,&:+) / ts.length
var = ts.inject { |t| (t - mean) ** 2 } / ts.length
Math.sqrt var
}
puts format "%8s %8.3f %8.3f", name, real_avg, real_std
end
| true |
e5d445911b1ca32b07a6f2a0a87bcfeb4e46e118 | Ruby | shsm385/ruby_pra | /2106.rb | UTF-8 | 251 | 2.625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
require 'rubygems'
require 'dbi'
dbh = DBI.connect('DBI:SQLite3:students01.db')
dbh.select_all( 'select * from students' ) do |row|
print "----\n"
print "name = #{row[0]}\n"
print "age = #{row[1]}\n"
end
dbh.disconnect | true |
3805e4579ebab63c3102f870aa8b98ac21b375e2 | Ruby | etienne-bourganel/moving_object | /board.rb | UTF-8 | 336 | 3.46875 | 3 | [] | no_license | # frozen_string_literal: true
class Board
attr_reader :matrix
def initialize(width, height)
@matrix = create_matrix(width, height)
end
def create_matrix(width, height)
matrix = []
(0..width-1).each do |x|
(0..height-1).each do |y|
matrix.push([x, y])
end
end
return matrix
end
end
| true |
404b03fc8be259540138858a417b605d0843abdc | Ruby | tarrinros/gallows | /spec/game_spec.rb | UTF-8 | 1,052 | 3.34375 | 3 | [] | no_license | require 'game'
require 'unicode_utils/downcase'
describe Game do
before :each do
word = 'batman'
@game = Game.new(word)
end
describe '#initialize' do
it 'should assign instance variables' do
expect(@game.errors).to eq 0
expect(@game.good_letters).to eq []
expect(@game.bad_letters).to eq []
expect(@game.status).to eq :in_progress
end
end
describe '#next_step' do
it 'sets @status == :won, when all letters are correct' do
%w(a t b m n).each do |letter|
@game.next_step(letter)
end
expect(@game.status).to eq :won
end
it 'sets @status == :lost, when @errors >= MAX_ERRORS' do
%w(s w j k o p d).each do |letter|
@game.next_step(letter)
end
expect(@game.status).to eq :lost
end
it 'keeps @status == :in_progress, when @errors < MAX_ERRORS' do
%w(s w j k o p).each do |letter|
@game.next_step(letter)
end
expect(@game.status).to eq :in_progress
end
end
end | true |
f8ba548d5cc3b5b8741be65688a0907fc0cd2da7 | Ruby | cbear1988uk/day_3_lab-hw | /models/artist.rb | UTF-8 | 1,161 | 3 | 3 | [] | no_license |
require_relative('../db/sql_runner')
class Artist
attr_accessor :name
attr_reader :artist_id
def initialize(options)
@name = options['name']
@artist_id = options['artist_id'].to_i
@id = options['id'].to_i if options['id']
end
def save()
sql = "INSERT INTO artists (name) Values ($1) RETURNING id"
values = [@name]
@id = SqlRunner.run(sql, values)[0]['id'].to_i
end
def update()
sql = " UPDATE artists SET (
name
) = (
$1
)
WHERE id = $2"
values = [@name, @artist_id]
SqlRunner.run(sql, values)
end
def delete()
sql = "DELETE FROM artists WHERE id = $1"
values = [@artist_id]
SqlRunner.run(sql, values)
end
def self.find(id)
sql = "SELECT * FROM artists WHERE id = $1"
values = [id]
results = SqlRunner.run(sql, values)
order_hash = results.first
order = Record.new(order_hash)
return order
end
def self.delete_all()
sql = "DELETE FROM artists"
SqlRunner.run(sql)
end
def self.all()
sql = "SELECT * FROM artists"
orders = SqlRunner.run(sql)
return orders.map { |order| Record.new(order) }
end
end
| true |
55eb469df6453d6da3fba31b0e8bf8a6f07e5885 | Ruby | aferreira44/HackSchooling | /stem/technology/backend/ruby/the-odin-project/ruby/book-learn-to-program/flow-control/leap_years.rb | UTF-8 | 215 | 3.59375 | 4 | [] | no_license | start_year = gets.chomp.to_i
end_year = gets.chomp.to_i
def leap_year?(year)
year % 400 == 0 || year % 4 == 0 && year % 100 != 0
end
(start_year..end_year).each do |year|
puts year if leap_year?(year)
end
| true |
188faf60beb468be1eb6f73d349aeb30eea5d458 | Ruby | jupiterjs/fitserver | /lib/jits_file_helper.rb | UTF-8 | 1,272 | 2.53125 | 3 | [] | no_license | require 'fileutils'
if RUBY_PLATFORM.include? "powerpc"
$slash='/'
elsif RUBY_PLATFORM.include? "x86_64-linux"
$slash='/'
else
$slash="\\"
end
def clean_files(dir, &block)
Dir.foreach(dir+$slash) { |filename|
next if filename == "." || filename == ".."
if File.file?(dir +$slash+ filename)
res = block.call(dir +$slash+ filename)
FileUtils.rm_r dir +$slash+ filename, :force => true if res
else
clean_files(dir+$slash+filename, &block)
end
}
end
def clean_folders(dir, &block)
Dir.foreach(dir+$slash) { |filename|
next if filename == "." || filename == ".."
unless File.file?(dir +$slash+ filename)
res = block.call(dir +$slash+ filename)
if res
FileUtils.rm_r dir +$slash+ filename, :force => true
else
clean_folders(dir+$slash+filename, &block)
end
end
}
#rescue
#end
end
def clean_versioning(dir)
clean_folders(dir){ |path|
if(path.include?(".svn"))
true
else
false
end
}
end
def clean_project(dir)
clean_files(dir){ |path|
if(path.include?(".project"))
true
else
false
end
}
end | true |
ef37670fd4cbebef006cfe1e084ddc95dcc919e7 | Ruby | ameriken/ruby_design_pattern | /02_strategy_pattern/report.rb | UTF-8 | 365 | 2.984375 | 3 | [] | no_license | require './html_formatter'
class Report
attr_reader :title, :text
attr_accessor :formatter
def initialize(formatter)
@title = '月時報告'
@text = ['順調', '最高の調子']
@formatter = formatter
end
def output_report
@formatter.output_report(@title, @text)
end
end
report = Report.new(HtmlFormatter.new)
report.output_report
| true |
761a349ec749563b84de05a5a095372a025b60a9 | Ruby | kharigai/ruby | /atcoder/abc132_a.rb | UTF-8 | 137 | 3.0625 | 3 | [] | no_license | h = Hash.new(0)
gets.strip.split('').each do |c|
h[c] += 1
end
puts h.size.eql?(2) && h.values.all? { |i| i.eql?(2) } ? 'Yes' : 'No'
| true |
d657dcb0f1ab0c2f85cdf8c9c42f05abbe11a3f2 | Ruby | peteyluu/coderbyte | /Easy/palindrome.rb | UTF-8 | 525 | 4.6875 | 5 | [] | no_license | =begin
Have the function palindrome(str) take the str parameter being passed and
return the string true if the parameter is a palindrome,
(the string is the same forward as it is backward) otherwise return the
string false. For example: "racecar" is also "racecar" backwards.
Punctuation and numbers will not be part of the string.
=end
def palindrome(str)
str = str.gsub(' ', '')
if str.reverse == str
return true
end
false
end
puts palindrome("never odd or even") # => "true"
puts palindrome("eye") # => "true" | true |
424c230d09f8186a26c438b98d368fdc12c42edb | Ruby | sergio91pt/faulty | /lib/faulty/events/filter_notifier.rb | UTF-8 | 1,015 | 2.71875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
class Faulty
module Events
# Wraps a Notifier and filters events by name
class FilterNotifier
# @param notifier [Notifier] The internal notifier to filter events for
# @param events [Array, nil] An array of events to allow. If nil, all
# {EVENTS} will be used
# @param exclude [Array, nil] An array of events to disallow. If nil,
# no events will be disallowed. Takes priority over `events`.
def initialize(notifier, events: nil, exclude: nil)
@notifier = notifier
@events = Set.new(events || EVENTS)
exclude&.each { |e| @events.delete(e) }
end
# Notify all listeners of an event
#
# If a listener raises an error while handling an event, that error will
# be captured and written to STDERR.
#
# @param (see Notifier)
def notify(event, payload)
return unless @events.include?(event)
@notifier.notify(event, payload)
end
end
end
end
| true |
8f1c1fef5c0c2a916be68c309e7df85e93637675 | Ruby | talkhouse/noyes | /lib/java_impl/speech_trimmer.rb | UTF-8 | 446 | 2.5625 | 3 | [
"BSD-2-Clause"
] | permissive | module NoyesJava
class SpeechTrimmer
def initialize frequency = 16000
@st = Java::talkhouse.SpeechTrimmer.new frequency
end
def << pcm
result = @st.apply(pcm.to_java(Java::double))
result.to_a if result
end
def enqueue pcm
@st.enqueue pcm.to_java(Java::double)
end
def dequeue
speech = @st.dequeue
speech.to_a if speech
end
def eos?
@st.eos
end
end
end
| true |
605de35bfcaf01315be998bb609b6820e5383942 | Ruby | RJ-Ponder/RB101 | /exercises/easy_1/reverse_it_2.rb | UTF-8 | 1,322 | 4.875 | 5 | [] | no_license | =begin
Problem
Write a method that takes one argument, a string containing one or more words,
and returns the given string with words that contain five or more characters reversed.
Each string will consist of only letters and spaces.
Spaces should be included only when more than one word is present.
Examples/Test Case
puts reverse_words('Professional') # => lanoisseforP
puts reverse_words('Walk around the block') # => Walk dnuora the kcolb
puts reverse_words('Launch School') # => hcnuaL loohcS
Data Structure
You may assume the argument is a valid string with words delimited by spaces.
Output a valid string with words also delimited by spaces. Words with 5+ characters are reversed.
Algorithm
Turn the string into an array with each word at an index using split(' ')
Iterate through array.
If word has 5+ characters, call the reverse method on it.
Join the array to make it one string again.
=end
def reverse_words(string)
string.split.each { |element| element.reverse! if element.length >= 5 }.join(' ')
end
puts reverse_words('Professional') # => lanoisseforP
puts reverse_words('Walk around the block') # => Walk dnuora the kcolb
puts reverse_words('Launch School') # => hcnuaL loohcS
puts reverse_words('this is my personal test of the method') | true |
21fead833c22a063435039fcba0727ce2b1f39a7 | Ruby | marciofrayze/indierank | /backend/app/controllers/services.rb | UTF-8 | 2,057 | 2.71875 | 3 | [
"MIT"
] | permissive | require 'json'
class SearchService < RackStep::Controller
def process_request
plate = request.params['plate']
print plate
ratings = Ranking.all(plate: plate)
ratings = [] if ratings == nil
ranking = {}
ranking['plate'] = plate
ranking['ratings'] = ratings
response.header['Access-Control-Allow-Credentials'] = 'true'
response.header['Access-Control-Allow-Origin'] = '*'
response.header['Access-Control-Allow-Headers'] = 'origin, content-type, accept, authorization, bearer'
response.header['Access-Control-Allow-Methods'] = 'GET, PUT, DELETE, HEAD, OPTIONS'
response.body = ranking.to_json
end
end
class AddService < RackStep::Controller
def process_request
# Input parameters
plate = request.params['plate']
score = request.params['score']
comment = request.params['comment']
# Just for log
print plate
print score
print comment
# Creating model and saving data
ranking = Ranking.new(plate: plate, score: score, comment: comment)
ranking.save!
# Return
response_body = {}
response_body['plate'] = plate
response_body['score'] = Integer(score)
response_body['comment'] = comment
response.header['Access-Control-Allow-Credentials'] = 'true'
response.header['Access-Control-Allow-Origin'] = '*'
response.header['Access-Control-Allow-Headers'] = 'origin, content-type, accept, authorization, bearer'
response.header['Access-Control-Allow-Methods'] = 'GET, PUT, DELETE, HEAD, OPTIONS'
response.body = response_body.to_json
end
end
class AllService < RackStep::Controller
def process_request
response_body = Ranking.all
response.header['Access-Control-Allow-Credentials'] = 'true'
response.header['Access-Control-Allow-Origin'] = '*'
response.header['Access-Control-Allow-Headers'] = 'origin, content-type, accept, authorization, bearer'
response.header['Access-Control-Allow-Methods'] = 'GET, PUT, DELETE, HEAD, OPTIONS'
response.body = response_body.to_json
end
end
| true |
79f1172184d1d329937adaed720f368e8be52967 | Ruby | USA-ChrisRichards/oo-basics-with-class-constants-chicago-web-062419 | /lib/book.rb | UTF-8 | 792 | 3.6875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Book
attr_accessor :author, :page_count
attr_reader :title, :genre
#1.Explicitly define the genre= method, to integrate our class constant into the method
#2.Remove the attr_accessor for :genre since we no longer need to generate a reader AND a writer.
#3.Add an attr_reader for :genre, since we still want Ruby to generate a reader for us.
GENRES = []
def initialize(title)
@title = title
end
def turn_page
puts "Flipping the page...wow, you read fast!"
end
# Explicitly define the genre= method, to integrate our class constant into the method
def genre=(genre) # create the writer for genre and add the logic for the class CONSTANT
@genre = genre
GENRES << genre
end
end
# hp = Book.new("harry potter")
# p hp
# hp.genre = "fantasy"
# p hp | true |
665335e644cb7c7f1df01b39a93c42a24626cefa | Ruby | ikemonn/AOJ | /ITP1/structured_program2/matrix_multiplication.rb | UTF-8 | 374 | 3.1875 | 3 | [] | no_license | n, m, l = gets.split.map(&:to_i)
a = []
b = []
n.times do |num|
a[num] = gets.split.map(&:to_i)
end
m.times do |num|
b[num] = gets.split.map(&:to_i)
end
b = b.transpose
ans = []
n.times do |n_num|
l.times do |l_num|
sum = 0
m.times do |m_num|
sum += a[n_num][m_num] * b[l_num][m_num]
end
print ' ' if l_num != 0
print sum
end
puts
end
| true |
b65a5ed319685eba6462852cedfa98d700a03987 | Ruby | stavro/viterbi | /three_tier/app.rb | UTF-8 | 513 | 2.71875 | 3 | [] | no_license | require 'pg'
require 'sinatra'
require 'thread'
conn = PG.connect(dbname: 'tweets')
mutex = Mutex.new
get '/' do
result = mutex.synchronize { conn.exec('select hashtag, count(*) from tweets group by hashtag') }
totals =
result
.map { |res| "#{res["hashtag"]}: #{res["count"]}"}
.join("<br>\n")
totals.empty? ? 'No known hashtags!' : totals
end
post '/track' do
mutex.synchronize { conn.exec("insert into tweets (hashtag, created_at) VALUES ($1, now());", [params[:hashtag]]) }
'OK'
end
| true |
f46b7676edbcd09f3da1db9185f23afd09e9faff | Ruby | asheren/euler | /lib/problem2/problem2.rb | UTF-8 | 1,016 | 4.25 | 4 | [] | no_license | # Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
## find all the fibonacci sequence numbers 0 to 4 million. then find the even ones. then add those together = solution
module Problem2
def self.fib(limit)
#create an array, then puts stuff into the array, and pushes that number onto the end of the array
arr = [] # create an empty array
a,b = 0,1 # puts stuff in the array
while a < limit #while the number is under the limit
arr << a # pushes a onto the end of the array
a, b = b, a + b #sets the recurrsion formula
end
sum = arr.select { |i| i.even? }.reduce(:+) #the sum is the array, where you then select only the even numbers and add them together
end
fib(4000000) #sets the limit
end | true |
df42a043f4a23ec6c9ec78d36610f5cc698ce120 | Ruby | hugopeixoto/rlua | /lib/rlua.rb | UTF-8 | 1,388 | 3.1875 | 3 | [
"MIT",
"LGPL-3.0-or-later"
] | permissive | require 'rlua.so'
module Lua
class Table
# Traverses the table using Lua::Table.next function.
def each(&block)
key = nil
loop {
key, value = *self.class.next(self, key)
break if key.nil?
block.call(key, value)
}
self
end
# Non-recursively converts table to hash.
def to_hash
hash = {}
each { |k, v| hash[k] = v }
hash
end
# Converts table to array. Only integer indexes are used.
def to_ary
ary = []
1.upto(__length) { |i|
if self[i]
ary << self[i]
else
break
end
}
ary
end
alias :to_a :to_ary
# Recursively pretty-prints the table properly handling reference loops.
#
# +trace+ argument is internal, do not use it.
def inspect(trace=[])
if to_hash.empty?
"L{}"
elsif trace.include? self
"L{...}"
else
trace << self
v = []
each { |key, value|
s = ""
if key.class == self.class
s += key.inspect(trace)
else
s += key.inspect
end
s += " => "
if value.class == self.class
s += value.inspect(trace)
else
s += value.inspect
end
v << s
}
"L{#{v.join ', '}}"
end
end
end
end
| true |
7fdb689a8aabdc856b4a7981a07d16361ec0b721 | Ruby | estebanmino/grupo-8 | /app/models/match.rb | UTF-8 | 1,668 | 2.578125 | 3 | [] | no_license | # == Schema Information
#
# Table name: matches
#
# id :integer not null, primary key
# date :date
# time :time
# created_at :datetime not null
# updated_at :datetime not null
# visit_team_id :integer
# home_team_id :integer
# tournament_id :integer
#
class Match < ApplicationRecord
validates :date, presence: true, allow_blank: false
validates :time, presence: true, allow_blank: false
validates :visit_team, presence: true, allow_blank: false
validates :home_team, presence: true, allow_blank: false
validates :tournament_id, presence: true, allow_blank: false
validates :visitor_goals, :numericality => { :greater_than_or_equal_to => 0 }
validates :local_goals, :numericality => { :greater_than_or_equal_to => 0 }
validates :played, inclusion: { in: [ true, false ] }
validates :place, presence: true, allow_blank: false
validates :address, presence: true, allow_blank: false
validates :commune, presence: true, allow_blank: false
belongs_to :visit_team, :class_name => 'Team', foreign_key: "visit_team_id"
belongs_to :home_team, :class_name => 'Team', foreign_key: "home_team_id"
belongs_to :tournament
has_many :pictures
has_many :performances
has_many :users, through: :performances
geocoded_by :location
after_validation :geocode
def winner
if played
if visitor_goals > local_goals
return visit_team
elsif local_goals > visitor_goals
return home_team
end
end
nil
end
def complete_date
"#{date.to_s} #{time.to_s[11,8]}"
end
def location
"#{address}, #{commune}, Chile"
end
end
| true |
e7c100a0215cd3dd14574df5f65b7097ce2326f3 | Ruby | DetectiveAzul/w3_d2_homework | /start_point/console.rb | UTF-8 | 1,624 | 2.90625 | 3 | [] | no_license | require_relative('./models/bounty')
require('pry')
bounty01_hash = {
'name' => 'Han Solo',
'species' => 'Human',
'bounty_value' => '30000',
'danger_level' =>'medium',
'last_known_location' =>'Tatooine',
'homeworld' =>'Coruscant',
'favorite_weapon' =>'Hand Blaster',
'cashed_in' => 'yes',
'collected_by' => 'Bobba Fett'
}
bounty02_hash = {
'name' => 'Chewbacca',
'species' => 'Wookie',
'bounty_value' => '50000',
'danger_level' => 'high',
'last_known_location' => 'Tatooine',
'homeworld' => 'Kashyyk',
'favorite_weapon' => 'Wookie Crossbow',
'cashed_in' => 'no'
}
bounty03_hash = {
'name' =>'Bulduga',
'bounty_value' => 25000,
'danger_level' => 'low',
'favorite_weapon' => 'Vibroknife',
'cashed_in' => 'no'
}
bounty04_hash = {
'name' =>'Greedo',
'species' =>'Rodian',
'bounty_value' =>20000,
'danger_level' =>'high',
'homeworld' =>'Rodian-2',
'cashed_in' =>'yes',
'collected_by' =>'Han Solo'
}
bounty01 = Bounty.new(bounty01_hash)
bounty02 = Bounty.new(bounty02_hash)
bounty03 = Bounty.new(bounty03_hash)
bounty04 = Bounty.new(bounty04_hash)
Bounty.delete_table()
Bounty.create_table()
bounty01.save()
bounty02.save()
bounty03.save()
bounty04.save()
# all_bounties_object = Bounty.all()
# my_bounty = all_bounties_object.last
# my_bounty.cashed_in = 'yes'
# my_bounty.collected_by = 'Pawel'
# my_bounty.update()
# deleting_bounty = all_bounties_object.first
# deleting_bounty.delete()
# Bounty.delete_all()
# bounty_found_by_name = Bounty.find_by_name("Jaime")
# bounty_found_by_name.delete()
# bounty_found_by_id = Bounty.find_by_id(3)
# bounty_found_by_id.delete()
| true |
e695cc8db73eb6ae2b03a51dd1631bf404d3d64e | Ruby | InternationalTradeAdministration/csl | /app/importers/concerns/versionable_resource.rb | UTF-8 | 1,835 | 2.546875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require "charlock_holmes"
module VersionableResource
extend ActiveSupport::Concern
included do
raise "Includee must be Importable" unless ancestors.include?(Importable)
send(:prepend, Prepend)
end
module Prepend
def import
if resource_changed?
super
update_metadata available_version
Rails.logger.info "#{self.class.name}: resource updated, new data indexed."
else
touch_metadata
Rails.logger.info "#{self.class.name}: resource unchanged, no new data indexed."
end
end
end
def initialize(resource = nil)
@resource = resource || (defined?(self.class::ENDPOINT) && self.class.const_get(:ENDPOINT))
# We want to call super if it exists, but it seems that if we haven't
# defined initialize in the ancestor tree ourselves, ruby will call
# Object's initialize, which fails as it expects no arguments, whereas
# we typically pass 1 argument to importers' initialize. So, we try calling
# super, and silently ignore ArgumentErrors.
begin
super
rescue ArgumentError
end
end
def loaded_resource
return super if defined?(super)
@loaded_resource ||= Array(@resource).map { |r| read_resource(r) }.join
end
def read_resource(r)
resource_content = open(r).read
detection = CharlockHolmes::EncodingDetector.detect resource_content
CharlockHolmes::Converter.convert resource_content, detection[:encoding], "UTF-8"
end
def available_version
@available_version ||= Digest::SHA1.hexdigest(loaded_resource.to_s)
end
def stored_version
model_class.find_or_create_metadata.version
end
def resource_changed?
stored_version != available_version
end
delegate :stored_metadata, :update_metadata, :touch_metadata, to: :model_class
end
| true |
7cd65272fbc330aceaa9362008e9f5603f9302c7 | Ruby | AZatsepa/autobase | /code/card_record.rb | UTF-8 | 1,054 | 3.046875 | 3 | [] | no_license | # Написать класс CardRecord
# минимальный набор полей:
# id пользователя
# номер автомобиля
# время когда машина выдана в прокат
# время когда машина была возвращенна
# статус (оплачено, возвр. но не оплачено)
# требования к функционалу:
# изменение статуса записи + возврат суммы долга
# минимальный набор ограничений:
# по собственному усмотрению
class CardRecord
attr_accessor :id,
:car_number,
:time,
:return_time,
:status
def initialize(id, car_number)
@id = id
@car_number = car_number
@time = Time.now
@status = :rent
end
def days
days = (((Time.now - @time) / 60 / 60 / 24) + 1).to_i
end
# def return_time
# @return_time = nil
# end
end
| true |
5c6452be6f1e178281162241f45d1bcab7e28a64 | Ruby | jawj/bulb-window-stickers | /build.rb | UTF-8 | 2,010 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env ruby
# note: sudo npm install -g clean-css html-minifier
require 'nokogiri'
def pipe cmd, stdin
IO.popen(cmd, 'w+') { |io| io.write(stdin); io.close_write; io.read }
end
def dataURIFor url
return url if url.match(%r{^data:|//$}) || ! url.match(/\.(gif|jpg|jpeg|png)$/i) || ! File.exist?(url) || File.size(url) > 2 ** 15 - 1 # IE8 32KB limit
fileext = url.match(/[^.]+$/)[0]
content = open(url, 'rb') { |f| f.read }
puts " - inlining #{url}"
"data:image/#{fileext};base64,#{[content].pack 'm0'}"
end
doc = Nokogiri::HTML File.open 'source.html'
# CSS
allcss = []
doc.css('link[rel="stylesheet"]').each do |tag|
href = tag.attributes['href'].value
puts "\n#{href}"
next if href.match %r{^data:|//}
css = File.read href
puts ' - minify'
css = pipe 'cleancss', css
css.gsub!(%r{(?<=url\()[^)]+(?=\))}) { |url| dataURIFor url }
tag.remove
allcss << css
end
doc.css('head').first.add_child %{<style>#{allcss.join "\n"}</style>}
# JS
alljs = []
doc.css('script').each do |tag|
src_att = tag.attributes['src']
js = if src_att
src = src_att.value
next if src.match %r{//} # don't touch remote scripts
puts "\n#{src}"
File.read src
else
puts "\nLocal JS"
tag.text
end
tag.remove
alljs << js
end
minjs = pipe 'java -jar /usr/local/closure-compiler/compiler.jar --compilation_level SIMPLE', alljs.join(";\n")
doc.css('body').first.last_element_child.add_next_sibling %{<script>#{minjs}</script>}
# Images
doc.css('img[src]').each do |tag|
src = tag.attributes['src'].value
puts "\n#{src}"
tag.attributes['src'].value = dataURIFor(src)
end
puts "\nInline styles"
doc.css('*[style]').each do |tag|
style = tag.attributes['style'].value
style.gsub!(%r{(?<=url\()[^)]+(?=\))}) { |url| dataURIFor url }
tag.attributes['style'].value = style
end
# HTML
html = pipe 'html-minifier --remove-comments --collapse-whitespace --remove-redundant-attributes', doc.to_html
open('docs/index.html', 'w') { |f| f.write html }
| true |
e8c28c1be320c948a7510c54db9d1e2b580dc298 | Ruby | saiury92/ba_chu_heo_con.rb | /BDD/ba_chu_heo_con_spec.rb | UTF-8 | 2,112 | 2.53125 | 3 | [] | no_license | # encoding: UTF-8
require_relative './ba_chu_heo_con'
require 'minitest/autorun'
describe 'Chuyện ba chú heo con' do
before(:all) do
@sói = Sói.new
@heo_út = Heo.new('út')
@heo_anh_nhì = Heo.new('anh nhì')
@heo_cả = Heo.new('anh cả')
end
describe 'Heo em út xây nhà' do
before(:all) do
@nhà_rơm = @heo_út.xây_nhà
end
it 'nhà phải bằng rơm' do
assert_instance_of Rơm, @nhà_rơm.vật_liệu
end
describe 'chó sói tấn công' do
describe 'chó sói thổi với sức gió 1' do
it 'nhà rơm bị đổ' do
assert @nhà_rơm.đổ?(@sói.thổi)
end
end
end
end
describe 'Heo anh nhì xây nhà' do
before(:all) do
@nhà_gỗ = @heo_anh_nhì.xây_nhà
end
it 'nhà phải bằng gỗ' do
assert_instance_of Gỗ, @nhà_gỗ.vật_liệu
end
describe 'chó sói tấn công' do
describe 'chó sói thổi với sức gió 1' do
it 'nhà gỗ không bị đổ' do
refute @nhà_gỗ.đổ?(@sói.thổi)
end
end
describe 'chó sói thổi với sức gió 2' do
it 'nhà gỗ bị đổ' do
assert @nhà_gỗ.đổ?(@sói.thổi(2))
end
end
end
end
describe 'Heo anh cả xây nhà' do
before(:all) { @nhà_gạch = @heo_cả.xây_nhà }
it 'nhà phải bằng gạch' do
assert_instance_of Gạch, @nhà_gạch.vật_liệu
end
describe 'chó sói tấn công' do
describe 'chó sói thổi với sức gió 1' do
it 'nhà gạch không bị đổ' do
refute @nhà_gạch.đổ?(@sói.thổi)
end
end
describe 'chó sói thổi với sức gió 2' do
it 'nhà gạch không bị đổ' do
refute @nhà_gạch.đổ?(@sói.thổi(2))
end
end
describe 'chó sói thổi với sức gió 3' do
it 'nhà gạch không bị đổ' do
refute @nhà_gạch.đổ?(@sói.thổi(3))
end
end
end
end
end | true |
02073200a50fafc5b916c2be077e94de0e738033 | Ruby | mawiegand/game_server | /app/controllers/action/military/found_home_base_actions_controller.rb | UTF-8 | 2,259 | 2.53125 | 3 | [] | no_license | class Action::Military::FoundHomeBaseActionsController < ApplicationController
layout 'action'
before_filter :authenticate
# Gives the "found home_base" command to the specified army,
# if prerequisits (character as well as army are able to
# found a home city now) are met. We also require a location_id
# to be send, also the army can only found a base at its
# present location. The redundant location_id is just to
# make sure, the player really intended to found a
# base at the present position of the army --- due to
# lag, the player could be thinking the army is in a
# different place right now.
#
# POST /action/military/found_home_base_actions.json
def create
raise BadRequestError.new('missing parameters') unless params.has_key? :found_home_base_action
settlement = nil
ActiveRecord::Base.transaction do # creating a home base is rather complex and dangerous stuff ;-) thus, wrap it in a transaction.
current_character.lock! # character needs to be locked for this task because it holds the settlement points...
army = Military::Army.find(params[:found_home_base_action][:army_id], :lock => true)
location = Map::Location.find(params[:found_home_base_action][:location_id], :lock => true)
army.details.lock! unless army.details.nil?
raise ForbiddenError.new('army is not at the location') unless army.location_id == location.id
raise ForbiddenError.new('tried to give a command to a foreign army') unless army.owner_id == current_character_id
raise ForbiddenError.new('army can not found home base') unless army.can_found_home_base?
raise ForbiddenError.new('character can not found home base') unless current_character.can_found_home_base?
raise ForbiddenError.new('its not possible to found an home base at that location') unless location.can_found_home_base_here?
settlement = army.found_home_base!
end
raise InternaServerError.new('Founding the settlement failed for unkown reason. please inform support.') if settlement.nil?
respond_to do |format|
format.json { render json: {}, status: :ok }
end
end
end
| true |
b60e9166e235141cf69e0faf9b434e7b5a88dcdd | Ruby | jasterix/advanced-hashes-hashketball-dumbo-web-career-042219 | /hashketball.rb | UTF-8 | 5,620 | 3.296875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here!
require 'pry'
def game_hash
game_hash = {
:home => {
team_name: "Brooklyn Nets",
colors: ["Black", "White"],
players: {
"Alan Anderson" => {
number: 0,
shoe:16,
points:22,
rebounds:12,
assists:12,
steals:3,
blocks:1,
slam_dunks: 1
},
"Reggie Evans"=>{
number: 30,
shoe:14,
points:12,
rebounds:12,
assists:12,
steals:12,
blocks:12,
slam_dunks: 7
},
"Brook Lopez" => {
number: 11,
shoe:17,
points:17,
rebounds:19,
assists:10,
steals:3,
blocks:1,
slam_dunks: 15
},
"Mason Plumlee" => {
number: 1,
shoe:19,
points:26,
rebounds:12,
assists:6,
steals:3,
blocks:8,
slam_dunks: 5
},
"Jason Terry"=> {
number: 31,
shoe:15,
points:19,
rebounds:2,
assists:2,
steals:4,
blocks:11,
slam_dunks: 1
}
}
},
:away =>
{
team_name: "Charlotte Hornets",
colors: ["Turquoise", "Purple"],
players:
{
"Jeff Adrien" => {
number: 4,
shoe: 18,
points: 10,
rebounds: 1,
assists: 1,
steals: 2,
blocks: 7,
slam_dunks: 2
},
"Bismak Biyombo" => {
number: 0,
shoe: 16,
points: 12,
rebounds: 4,
assists: 7,
steals: 7,
blocks: 15,
slam_dunks: 10
},
"DeSagna Diop"=> {
number: 2,
shoe: 14,
points: 24,
rebounds: 12,
assists: 12,
steals: 4,
blocks: 5,
slam_dunks: 5
},
"Ben Gordon" => {
number: 8,
shoe: 15,
points: 33,
rebounds: 3,
assists: 2,
steals: 1,
blocks: 1,
slam_dunks: 0
},
"Brendan Haywood"=> {
number: 33,
shoe: 15,
points: 6,
rebounds: 12,
assists: 12,
steals: 22,
blocks: 5,
slam_dunks: 12
}
}
}
}
end
#----------------------------------------Good
def num_points_scored(player)
game_hash.each do |location, details|
details.each do |detail, value|
if detail == :players
value.each do |person, data|
# binding.pry
if person == player
data.each do |id, stats|
if id == :points
return stats
# binding.pry
end
end
end
end
end
end
end
end
#----------------------------------------Good
def shoe_size(player)
game_hash.each do |location, details|
details.each do |detail, value|
if detail == :players
value.each do |person, data|
# binding.pry
if person == player
data.each do |id, stats|
if id == :shoe
return stats
# binding.pry
end
end
end
end
end
end
end
end
def find_the_team(team_name)
game_hash.values.find {|team| team.fetch(:team_name) == team_name}
# binding.pry
end
#----------------------------------------Good
def team_colors(team)
team = find_the_team(team)
colors = team.fetch(:colors)
# binding.pry
colors
end
#----------------------------------------Good
def team_names
game_hash.map do |location, data|
data[:team_name]
end
end
#----------------------------------------Good
def player_numbers(team)
find_the_team(team)[:players].map { |player_name, data| data[:number]}
end
#----------------------------------------Good
def player_stats(player)
game_hash.each do |location, details|
details[:players].collect do |name, stats|
return stats if name == player
end
end
end
def big_shoe_rebounds
shoe_size = {}
game_hash.each do |location, details|
details[:players].each do |name, stats|
shoe_size[stats[:shoe]] = stats[:rebounds]
end
end
shoe_size[shoe_size.keys.max]
end
# game_hash.collect do |location, details|
# details.each do |detail, value|
# if detail == :team_name && details[detail.to_sym] == team_name
# details[:players].each do |player|
# # binding.pry
# player[1][:number] #player 0 is the key, player[1] accesses the nested hash
# end
# end
# end
# end
#----------------------------------------Questions below
# game_hash[:home_team][:players].each do |current_player|
# if current_player[:name]== player
# current_player[:points]
# end
# end
# end
# def num_points_scored(name) #returning the full away hash. How do I convert hash to array with .flatten
# game_hash.each do |location, team_data|
# team_data[:players].each do |player_name, data|
# if player_name == name #check the name to match
# data[:points]
# end
# end
# end
# end
#num_points_scored("Brendan Haywood")
# def num_points_scored(player_name, game_hash)
# home = game_hash[:home].flatten
# away = game_hash[:away].flatten
# binding.pry
# game_hash.each {|team, points| team[player_name].include?(player) ?
# game_hash[:player_name][:points] : " "
# }
# end
# def num_points_scored(player_name)
# total_points = nil
# game_hash.each do |team, details_hash|
# player_details = details_hash[:players]
# player_details.each do |player, points|
# if player == player_name
# total_points = player_details[:points]
# return total_points
# end
# end
# end
# # game_hash[:player_name].fetch(:points)
# end
| true |
34781c78c3ae81b4645f0c9e0f7b22e73c52d14f | Ruby | earl-stephens/enigma | /lib/encryption.rb | UTF-8 | 1,135 | 3.28125 | 3 | [] | no_license | require './lib/shift'
class Encryption
include Shift
attr_reader :shift_pattern,
:alphabet,
:shifted_message,
:counter
def initialize
@shift_pattern = []
@shifted_message = ""
@counter = 0
end
def main_encrypt_method(message, keys, offsets)
create_shift_pattern(keys, offsets)
create_alphabet
breakdown_message_into_letters(message_to_downcase(message))
@shifted_message
end
def breakdown_message_into_letters(message)
message.each_char do |character|
counter = @counter
validate_letter(character, counter)
increment_counter(counter)
end
@shifted_message
end
def rotate_letter(character, counter)
placeholder = @alphabet.index(character)
rotated_alphabet = @alphabet.rotate(@shift_pattern[counter])
@shifted_message.concat(rotated_alphabet[placeholder])
@shifted_message
end
def validate_letter(character, counter)
if letter_in_alphabet?(character) == true
rotate_letter(character, counter)
else
@shifted_message.concat(character)
end
@shifted_message
end
end
| true |
79abe1bdf6cc2fd87a74afbe82c5042f6fbdad3c | Ruby | welshstew/basic-dashboard | /jobs/camel-springboot-data-post.rb | UTF-8 | 2,243 | 2.546875 | 3 | [] | no_license | require 'logger'
require 'net/http'
require 'uri'
require 'json'
require 'logger'
require 'openssl'
require 'date'
require 'kubeclient'
stats = ['Uptime', 'State', 'MinProcessingTime', 'MaxProcessingTime', 'LastProcessingTime', 'TotalRoutes', 'TotalProcessingTime']
stat_values = Hash.new({ value: 0 })
label = "project=camel-springboot-logger"
server = "https://10.1.2.2"
port = 8443
namespace = "dashing"
tokenFilename = "/var/run/secrets/kubernetes.io/serviceaccount/token"
postBody = '''{"attribute": ["Uptime","State","MinProcessingTime","MaxProcessingTime","LastProcessingTime","TotalRoutes","TotalProcessingTime"],"mbean": "org.apache.camel:context=MyCamel,type=context,name=\"MyCamel\"","type": "read"}'''
log = Logger.new(STDOUT)
log.level = Logger::INFO
log.info("checking for token file")
#get the token for kubernetes access in the pod..!
if File.exists?(tokenFilename) then
log.info("token file does exist")
token = IO.read(tokenFilename)
else
# just putting my current token here to test
token = "sKxDTx5qvwQAKV9GJ8CxDn9nsM2kihTD6BTt_gWtf00"
log.info("token file does not exist")
end
# setup kube client
ssl_options = { verify_ssl: OpenSSL::SSL::VERIFY_NONE }
auth_options = {
bearer_token: token
}
client = Kubeclient::Client.new "#{server}:#{port}/api/" , 'v1',
ssl_options: ssl_options, auth_options: auth_options
#every 10s
SCHEDULER.every '15s' do
podName = ""
#call kube api to get the pod name
kubepods = client.get_pods(namespace: namespace, label_selector: label)
metricValue = 0
kubepods.each do | item |
podName = item["metadata"]["name"]
uri = URI.parse("#{server}/api/v1/namespaces/#{namespace}/pods/https:#{podName}:8778/proxy/jolokia/")
http = Net::HTTP.new(uri.host, port)
http.use_ssl = (uri.scheme == 'https')
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Post.new(uri.path, {'Authorization' => "Bearer #{token}", 'Content-Type' => 'application/json'})
req.body = postBody
res = http.request(req)
log.info(res.body)
j = JSON[res.body]
stats.each do | stat |
stat_values[stat] = { label: stat, value: j["value"][stat] }
end
end
send_event('camelstats', { items: stat_values.values })
end | true |
a6909a96255cb72b4c67fffd40b16c9490ffc1b3 | Ruby | PhilipTimofeyev/LaunchSchool | /RB101/Small_Problems/Medium_2/small_problems_medium_2_Ex6.rb | UTF-8 | 486 | 3.515625 | 4 | [] | no_license | def triangle(s1, s2, s3)
angle_arr = [s1, s2, s3]
case
when angle_arr.reduce(&:+) != 180 || angle_arr.any? {|angle| angle == 0} then :invalid
when angle_arr.any? {|angle| angle == 90} then :right
when angle_arr.all? {|angle| angle < 90} then :acute
when angle_arr.any? {|angle| angle > 90} then :obtuse
end
end
triangle(60, 70, 50) == :acute
triangle(30, 90, 60) == :right
triangle(120, 50, 10) == :obtuse
triangle(0, 90, 90) == :invalid
triangle(50, 50, 50) == :invalid | true |
cdfe5c8925e43bb789faa4e7ace09f29adcab7b5 | Ruby | menor/dbc_advanced_ruby | /part1_ruby-drill-argv-basics-challenge/source/rpn-calculator-sample_01.rb | UTF-8 | 1,197 | 3.90625 | 4 | [] | no_license |
# INITIAL CODE:
# This is the first version of code to pass the rspec tests and get all green.
class RPNCalculator
attr_accessor :stack
def initialize
@stack = [0]
end
def push(value)
stack.unshift(value)
end
def add
nums = stack.shift + stack.shift
stack.unshift(nums)
end
def minus
nums = stack.shift - stack.shift
stack.unshift(nums)
end
def multiply
nums = stack.shift * stack.shift
stack.unshift(nums)
end
def evaluate(string)
string.split(" ").map do |x|
case x
when "+"
add
when "-"
minus
when "*"
multiply
else
push(x.to_i)
end
return stack
end
end
end
# REFACTORED CODE:
# see: http://sourcemaking.com/refactoring/introduction-to-refactoring
class RPNCalculator
def evaluate(string)
string.split(" ").inject([]) do |stack, element|
rest_of_stack = stack[2..stack.length]
case element
when "+"
[stack[1] + stack[0]] + rest_of_stack
when "-"
[stack[1] - stack[0]] + rest_of_stack
when "*"
[stack[1] * stack[0]] + rest_of_stack
else
[element.to_i] + stack
end
end.first
end
end
| true |
bcd1b6df7b1f7960c5cf89733552dc2ab347970a | Ruby | gmhawash/nablus-tech-talk | /ruby/107_files.rb | UTF-8 | 351 | 3.03125 | 3 | [] | no_license | #!/usr/bin/env ruby
# Files
begin # Read a file
content = File.read('000_references.txt')
puts content
puts "-------"
file = File.open('000_references.txt')
puts file.read
end
begin # Write a file
file = File.open('/tmp/file.txt', 'w')
file.write("hello\n")
File.open('/tmp/file2.txt', 'w') do |f|
f.puts("hello2\n")
end
end
| true |
1532673d3618fc9e3ebe5cdedf2261941f62d9de | Ruby | mukaer/chef-solo | /cookbooks/init_network/libraries/initconf.rb | UTF-8 | 901 | 3.15625 | 3 | [
"Apache-2.0"
] | permissive | class Initconf
@org_cont
@cont
def initialize ()
reset_cont()
end
def reset_cont()
@org_cont = Array.new
@cont = Hash.new
end
def load_file(path)
reset_cont()
@org_cont = File.read(path).split("\n") if File.exist? path
converter()
end
def load_str(str)
reset_cont()
@org_cont = str.split("\n")
converter()
end
def converter()
@org_cont.each do | str|
result = inport_key_value(str)
if result[0].length > 0
hash = {result[0] => result[1] }
@cont = @cont.merge(hash)
end
end
end
def inport_key_value(str)
result =str.match(/^[\s]?([\w\.-]*)[\s=]?['"]?([\w\.-\/]*)['"]?.*$/)
[result[1] ,result[2] ]
end
def get_value(name)
@cont.key?(name) ? @cont[name] : nil
end
def dump
@cont
end
end
| true |
b76fa6e742afa1d95a2198f5a71717b2974306c5 | Ruby | panteha/oystercard | /lib/oystercard.rb | UTF-8 | 1,291 | 3.578125 | 4 | [] | no_license | require_relative './station.rb'
require_relative './journey_log.rb'
# Oystercard class...
class Oystercard
attr_accessor :balance, :list_of_journeys
MAXIMUM_BALANCE = 90
MINIMUM_BALANCE = 1
def initialize(balance = 0)
@journey_log = JourneyLog.new(Journey)
@journey = nil
@balance = balance
@list_of_journeys = @journey_log.journeys
end
def top_up(amount)
raise 'Maximum balance exceeded!' if @balance + amount > MAXIMUM_BALANCE
@balance += amount
end
def deduct(amount)
@balance -= amount
end
def in_journey?
!@journey.nil? && !@journey.complete?
end
def tap_in(entry_station)
deduct(@journey.calculate_cost) if in_journey? # TODO: Check with Sam if this is ok
raise 'Not enough funds' if @balance < MINIMUM_BALANCE
@journey = @journey_log.start(entry_station)
end
def tap_out(exit_station)
@journey.finish(exit_station)
deduct(@journey.calculate_cost) # TODO: Check with Sam if this is ok
end
end
# Card and stations for ad-hoc feature tests in IDE:
card = Oystercard.new(20)
highgate = Station.new('Highgate', 3)
euston = Station.new('Euston', 1)
# One complete journey:
card.tap_in(highgate)
card.tap_out(euston)
# Unfinished journey:
card.tap_in(highgate)
card.tap_in(euston)
puts card.balance | true |
aa75de0071752a10b597aac5af615b5d3cfe3292 | Ruby | prasadsurase/hootcode | /lib/exercism/progress_bar.rb | UTF-8 | 489 | 2.8125 | 3 | [] | no_license | module Exercism
class ProgressBar
StepInstall = "install-cli"
StepSubmit = "submit-code"
StepDiscuss = "have-a-conversation"
StepNitpick = "pay-it-forward"
StepExplore = "explore"
def self.steps
[StepInstall, StepSubmit, StepDiscuss, StepNitpick, StepExplore]
end
def self.fill?(step, current)
steps.index(step) < steps.index(current)
end
def self.status(step, current)
if fill?(step, current)
"visited"
else
"todo"
end
end
end
end
| true |
f237bb82d411df0cef92472cbd91aa6c32812a01 | Ruby | mikeebert/user_records | /lib/user_record.rb | UTF-8 | 699 | 2.859375 | 3 | [] | no_license | require 'grape-entity'
class UserRecord
attr_reader :last_name,
:first_name,
:favorite_color,
:date_of_birth
def initialize(attributes)
@last_name = attributes[:last_name]
@first_name = attributes[:first_name]
@favorite_color = attributes[:favorite_color]
@date_of_birth = attributes[:date_of_birth]
end
def entity
Entity.new(self)
end
class Entity < Grape::Entity
format_with(:dd_mm_yyyy) do |date|
date.strftime('%d/%m/%Y')
end
expose :last_name
expose :first_name
expose :favorite_color
with_options(format_with: :dd_mm_yyyy) do
expose :date_of_birth
end
end
end
| true |
72c8de50c87d4559feff5c7be24d43e3f88e7f23 | Ruby | Belyenochi/Programming-Languages | /Ruby/ruby_example2.rb | UTF-8 | 243 | 3.828125 | 4 | [] | no_license | class Fixnum
def my_times
i = self
while i > 0
i = i - 1
yield
end
end
end
def call_block(&block)
block.call
end
def pass_block(&block)
call_block(&block)
end
pass_block {puts 'Hello, block'}
3.my_times {puts 'mangy moose'} | true |
bfd9da9cc61ae5fcae5dcc1900585d4039dd1fd4 | Ruby | RichCollinson/design-system | /content/confluence-to-markdown | UTF-8 | 727 | 2.625 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'find'
require 'fileutils'
require 'reverse_markdown'
SOURCE_DIR = 'docs'
TARGET_DIR = 'markdown'
puts "Create target directory"
FileUtils.mkdir_p(TARGET_DIR)
puts "Copy directores"
FileUtils.cp_r "#{SOURCE_DIR}/images", TARGET_DIR
FileUtils.cp_r "#{SOURCE_DIR}/styles", TARGET_DIR
FileUtils.cp_r "#{SOURCE_DIR}/attachments", TARGET_DIR
puts "Converting files"
md_head = <<-HEAD
---
layout: default
---
HEAD
Find.find(SOURCE_DIR).each do |f|
if File.extname(f) == '.html'
md_content = (md_head << ReverseMarkdown.convert(File.read(f)))
md_name = f.sub(SOURCE_DIR, TARGET_DIR).gsub(/html$/, 'md')
File.write(md_name, md_content)
puts "Converted #{f} -> #{md_name}"
end
end | true |
d3a96b032f7ffbcaf2b243dea5070d1b3137b7ac | Ruby | christinaminh/jump-start-live | /lessons/day1/code/bad_style_madlibs.rb | UTF-8 | 1,945 | 4.0625 | 4 | [] | no_license | # Takes in input from the user and outputs a madlib story
# Bad style example
# susan evans
# Last edited 11/25/2016
print "Welcome to my MadLib program. Please enter in some information below.\n\n" # Would be easier to puts instead of print with \n
# Add whitespace between each instance of reading user input and assigning that input to a variable.
print "name: "
var1= gets.chomp # Variable name should describe the value. Needs space before operator.
print "adjective: "
var2= gets.chomp # Variable name should describe the value. Needs space before operator.
print "noun: "
var3= gets.chomp # Variable name should describe the value. Needs space before operator.
print "adjective: "
var4 = gets.chomp # Variable name should describe the value. Needs just 1 space before operator.
print "food(plural): "
foodPlural=gets.chomp- # Should use snake_case for variable names like food_plural. Does not need the - at the end of chomp
print "noun(plural): "
var6= gets.chomp # Variable name should describe the value. Needs space before operator.
print "verb ending in -ed: "
var7= gets.chomp # Variable name should describe the value. Needs space before operator.
print "noun: "
var8=gets.chomp # Variable name should describe the value. Needs space before and after operator.
# Should add whitespace between the final madlib section to organize and separate code with different purposes.
print "\nHERE'S YOUR MADLIB.......\n\n"
# Should add whitespace and move parts after /n onto another line of code to make it more readable.
# May also puts each sentence instead of using /n since puts adds a newline.
puts "Come on over to #{var1}’s Pizza Parlor where you can enjoy your favorite #{var2}-dish pizza`s.\nYou can try our famous #{var3}-lovers pizza,\nor select from our list of #{var4} toppings,\nincluding delicious #{foodPlural}, #{var6}, and many more.\nOur crusts are hand-#{var7} and basted in #{var8} to make\nthem seem more hand-made."
| true |
d8f590e975f2a0a2ba9ca94aa9543400beef9f2c | Ruby | antonnur/Ruby-Shcool | /10(ARRAY, SYMBOL)/10.3.rb | UTF-8 | 678 | 3.90625 | 4 | [] | no_license | # добавление в массив
# each - передает каждый ее элемент в блок кода
puts "Пример 1:"
arr = []
loop do # аналагично while true
print "Кого добавить в список:"
name = gets.strip # получаем имя strip обрезаем лишние пробелы переносы
if name == ""
break # прерывает цикл, exit - выход из программы
end
arr << name # добовляем в массив
end
x = 0
arr.each do |name| # можно замени на each_with_index
x += 1
puts "#{x}. #{name}"
end
| true |
6ec002719b414c27240334940e38440f32630f02 | Ruby | Atul9/rubylearning56 | /7_week/1e_klass.rb | UTF-8 | 562 | 3.90625 | 4 | [] | no_license | =begin
Exercise1. Write a Ruby program named lesson7exercise1.rb that defines a class
called Klass which will be called in another program as follows:
obj = Klass.new("hello")
puts obj.say_hello
where say_hello is a method in that class, which returns the string sent when
an object of Klass is created. Write another program named lesson7exercise1a.rb
that creates an object of the class defined in program lesson7exercise1.rb and
then marshals it and then restores it.
=end
require_relative 'lesson7exercise1.rb'
obj = Klass.new("Hello")
puts obj.say_hello
| true |
607d7089cca4fe9b51dbdb9e380d8734f3aa2d7a | Ruby | cielavenir/procon | /codeforces/tyama_codeforces743A.rb | UTF-8 | 73 | 2.65625 | 3 | [
"0BSD"
] | permissive | #!/usr/bin/ruby
n,a,b,s=$<.read.split
p s[a.to_i-1]!=s[b.to_i-1] ? 1 : 0
| true |
092ea037fe97bf6bfb470f1ba85101d01822689c | Ruby | dummied/dgraphy | /lib/dgraphy/node.rb | UTF-8 | 817 | 2.65625 | 3 | [
"MIT"
] | permissive | module Dgraphy
class Node
attr_reader :starter, :filter, :fields, :results
def initialize(starter:, filter: nil, fields: [])
@starter = starter
@filter = filter
@fields = fields
end
def execute
puts build_query
end
def build_query
%Q(
{
dgraphy_query(func: #{starter})#{" @filter(#{filter})" if filter} {
#{build_nodes}
}
}
)
end
def build_nodes
fields.map{ |field| build_node(field) }.join("\n\n")
end
def build_node(field)
if field.is_a? String
field
elsif field.is_a? Dgraphy::Node
%Q(
#{field.starter}#{" @filter(#{field.filter})" if field.filter} {
#{field.build_nodes}
}
)
end
end
end
end
| true |
f29c8a2223bb1329effec28ac4aec8c3625e375b | Ruby | rlee0525/AlgorithmProjects | /Project2/raymond_lee/lib/p02_hashing.rb | UTF-8 | 600 | 3.25 | 3 | [] | no_license | class Fixnum
# Fixnum#hash already implemented for you
end
class Array
def hash
hashing = 0
self.each_with_index do |val, i|
hashing += (val * i).hash
end
hashing
end
end
class String
def hash
hashing = 0
self.chars.each_with_index do |char, i|
hashing += (char.ord * i).hash
end
hashing
end
end
class Hash
# This returns 0 because rspec will break if it returns nil
# Make sure to implement an actual Hash#hash method
def hash
hashing = 0
self.each do |k, v|
hashing += k.hash * v.hash
end
hashing
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.