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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8a76ad20a2ef8514a424ef671aca77839ac27de6
|
Ruby
|
SyxHyTex/Gerridae
|
/spec/helpers_spec.rb
|
UTF-8
| 2,458
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'spec_helper'
describe Helpers do
let(:dummy_class) { Class.new { include Helpers } }
subject(:skater) { }
describe "#create_filename" do
context "" do
end
end
describe "#ip_generate" do
let(:bad_ip_v) { 5 }
let(:not_ip_v) { 'jsiodjasipd' }
context "when improper IP version given" do
it "raises an error" do
expect { Helpers::ip_generate(bad_ip_v) }.to raise_error ArgumentError
expect { Helpers::ip_generate(not_ip_v) }.to raise_error ArgumentError
end
end
context "when IP version 4 is given" do
let(:result) { Helpers::ip_generate(4) }
it "generates correctly formatted IP" do
expect(result).to match_regex %r{^([0-9]{1,3}\.){3}[0-9]{1,3}$}
end
end
context "when IP version 6 is given" do
let(:result) { Helpers::ip_generate(6) }
it "generates correctly formatted IP" do
expect(result).to match_regex %r{^([0-9]{1,3}\.){5}[0-9]{1,3}$}
end
end
end
describe '#parse_time' do
context 'when time is generated' do
let(:the_given_time) { Helpers::parse_time }
it 'generates time as a string' do
expect(the_given_time).to be_a String
end
end
end
describe '#is_good_http_response?' do
context 'when HTTP code is supplied' do
it 'denies invalid HTTP codes' do
expect { Helpers::is_good_http_response?(662) }.to raise_error RangeError
expect { Helpers::is_good_http_response?(:purple) }.to raise_error ArgumentError
end
end
context 'when HTTP code is tested' do
it 'reports failed HTTP codes' do
expect(Helpers::is_good_http_response?(504)).to be false
end
it 'recognizes valid HTTP codes' do
(200..208).each do |code|
expect(Helpers::is_good_http_response?(code) ).to be true
end
end
end
end
describe '#rename_duplicate' do
context "when valid input is supplied" do
let(:filename) { "http://www.yahoo.com" }
subject(:renamed) { Helpers::rename_duplicate(filename) }
it "adds file number to filename" do
expect(filename).not_to eq(renamed)
end
end
context "when non-string file name given" do
let(:filename) { Hash.new( 1 => "the", 2 => "mg") }
it "raises exception" do
expect{ Helpers::rename_duplicate(filename) }.to raise_error TypeError
end
end
end
end
| true
|
4d062778bef44244572934d87462f125a2b82077
|
Ruby
|
cucumber-attic/cucumber-tmbundle
|
/support/spec/cucumber/mate/table_aligner_spec.rb
|
UTF-8
| 1,913
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
# encoding: utf-8
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/../../../lib/cucumber/mate/table_aligner'
module Cucumber
module Mate
describe TableAligner do
it "should align a simple table" do
unaligned = [
" | a |b|",
" |c| d |"
]
expected = [
" | a | b |",
" | c | d |"
]
TableAligner.new.align(unaligned).should == expected
end
it "should align multiple tables" do
unaligned = [
" | a |b|",
" |c| d |",
"",
" |x | y|zz|",
" |1|2|3|"
]
expected = [
" | a | b |",
" | c | d |",
"",
" | x | y | zz |",
" | 1 | 2 | 3 |"
]
TableAligner.new.align(unaligned).should == expected
end
it "should pad short rows out to the longest row" do
unaligned = [
"",
" |a|b|",
" |x|y|z",
" |",
""
]
expected = [
"",
" | a | b | |",
" | x | y | z |",
" | | | |",
""
]
TableAligner.new.align(unaligned).should == expected
end
it "should align a table with multi-byte UTF8 values" do
unaligned = [
" | aa |b|",
" |÷| d |"
]
expected = [
" | aa | b |",
" | ÷ | d |"
]
TableAligner.new.align(unaligned).should == expected
end
it "should align a table that has cells with no content" do
unaligned = [
" |a|b|",
" |||"
]
expected = [
" | a | b |",
" | | |"
]
TableAligner.new.align(unaligned).should == expected
end
end
end
end
| true
|
1e3384c5a067daf3fa06056bbc6d24409340555b
|
Ruby
|
mat2m10/guilder
|
/db/seeds.rb
|
UTF-8
| 2,470
| 2.984375
| 3
|
[] |
no_license
|
require 'faker'
require "open-uri"
require 'date'
puts "Destroying current bookings/crafts/users..."
Booking.destroy_all
Craft.destroy_all
User.destroy_all
today = DateTime.now
puts "Creating batman user..."
first = User.create(email: "b@t.man", username: "batman", first_name: "Bruce", last_name: "Wayne", password:'123456')
first.about = "I am Batman!!!"
first.save!
puts "Creating 10 other LOTR users..."
10.times do
about = ""
10.times do
about += "#{Faker::Movies::Hobbit.quote} "
end
user = User.create(email: Faker::Internet.email, username: Faker::Movies::LordOfTheRings.character, first_name: Faker::Movies::StarWars.planet, last_name: Faker::Movies::StarWars.droid, password:'123456')
coin = rand(2)+1
if coin == 1
file = URI.open("https://randomuser.me/api/portraits/women/#{rand(99)}.jpg")
else
file = URI.open("https://randomuser.me/api/portraits/men/#{rand(99)}.jpg")
end
user.about = about
user.photo.attach(io: file, filename: 'nes.png', content_type: 'image/jpg')
user.save!
end
puts "Creating 10 random crafts..."
10.times do
string = ""
address_array = ["Romeinsesteenweg 950, 1780 Wemmel","Avenue Charles Quint, 560 Parking Carrefour 1082, 8 Brussel","Rue du Progrès 76/1030, 1030 Brussel","Rue du Marché Aux Herbes 101, 1000 Bruxelles","Boulevard De La Woluwe 70 20 BE, b25, 1200 Brussel","Rue Veydt 43, 1050 Bruxelles","Gare du Midi 46 b 23, 1060 Bruxelles","Boulevard Boulevard Anspach 56-58 1000, 1 Bruxelles","Chaussée de Boondael 462 - Ixelles / Ixelles, 1050 Brussel","Rue Veydt 43, 1050 Bruxelles","Avenue de la Toison d'Or 4, 1050 Ixelles","Centraal Station, Rue de la Madeleine, 1000 Bruxelles","Leuvensesteenweg 12, 1932 Zaventem","Chaussée de Haecht 1420, 1130 Bruxelles"]
10.times do
string += "#{Faker::TvShows::GameOfThrones.quote} "
end
file = URI.open('https://picsum.photos/200')
craft = Craft.create(name: Faker::Commerce.department, price: rand(100), user_id: User.all.sample.id.to_i, description: string)
craft.photo.attach(io: file, filename: '.png', content_type: 'image/png')
craft.address = address_array.sample
craft.save!
end
puts "Creating 10 bookings..."
10.times do
date = today + rand(1000)
user = User.all.sample.id.to_i
craft = Craft.all.sample.id.to_i
text = ""
10.times do
text += "#{Faker::TvShows::HowIMetYourMother.quote} "
end
booking = Booking.create(date: date, user_id: user, craft_id: craft, description: text)
booking.save!
end
puts "Done bro!!!!!"
| true
|
c3cfbc85570528d6c4aa428d3b004098addd7b0b
|
Ruby
|
kiyotan815/atcorder
|
/beginners_selection/ruby/coins.rb
|
UTF-8
| 519
| 3.671875
| 4
|
[] |
no_license
|
text = <<-TEXT
500円玉をA 枚、100円玉をB枚、50円玉をC枚持っています。
これらの硬貨の中から何枚かを選び、
合計金額をちょうどX円にする方法が何通りあるかを出力します。
TEXT
puts text
print "A = "
a = gets.to_i
print "B = "
b = gets.to_i
print "C = "
c = gets.to_i
print "X = "
x = gets.to_i
cnt = 0
(0..a).each do |i|
(0..b).each do |j|
(0..c).each do |k|
cnt += 1 if i * 500 + j * 100 + k * 50 == x
end
end
end
puts cnt
| true
|
e6b231ac05f30fa00ba5f13922ebadc756d97e07
|
Ruby
|
kputnam/stupidedi
|
/lib/stupidedi/parser/instruction.rb
|
UTF-8
| 3,373
| 2.609375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# frozen_string_literal: true
module Stupidedi
using Refinements
module Parser
class Instruction
include Inspect
# The segment identifier to which this {Instruction} applies
#
# @return [Symbol]
attr_reader :segment_id
# The segment use contains helpful information about the context of the
# segment within a definition tree (eg the parent structure's definition).
# It also enumerates the allowed values for segment qualifiers, which is
# used to minimize non-determinism.
#
# @return [Schema::SegmentUse]
attr_reader :segment_use
# This indicates the number of levels to ascend and terminate within the
# tree before storing the segment.
#
# @return [Integer]
attr_reader :pop_count
# This controls the allowed order in which structures may occur, by
# indicating the number of instructions to remove from the beginning of
# the instruction table.
#
# Repeatable structures have a value that ensures that their instruction
# remains in the successor table.
#
# Sibling structures that have the same position (as defined by their
# {Schema::SegmentUse}) will have equal drop_count values such that all of
# the sibling instructions remain in the successor table when any one of
# them is executed.
#
# @return [Integer]
attr_reader :drop_count
# This indicates that a child node should be added to the tree, which
# will then contain the segment.
#
# When a segment indicates the start of a child structure, the class
# indicated by this attribute is expected to respond to `push` by
# creating a new {AbstractState}.
#
# @return [Zipper::AbstractCursor]
attr_reader :push
def initialize(segment_id, segment_use, pop, drop, push)
@segment_id, @segment_use, @pop_count, @drop_count, @push =
segment_id || segment_use.definition.id, segment_use, pop, drop, push
end
def hash
[Instruction, state].hash
end
# @return [Instruction]
def copy(changes = {})
Instruction.new \
changes.fetch(:segment_id, @segment_id),
changes.fetch(:segment_use, @segment_use),
changes.fetch(:pop_count, @pop_count),
changes.fetch(:drop_count, @drop_count),
changes.fetch(:push, @push)
end
# @return [void]
def pretty_print(q)
id = "% 3s" % @segment_id.to_s
unless @segment_use.nil?
width = 18
name = @segment_use.definition.name
# Truncate the segment name to `width` characters
if name.length > width - 2
id = id + ": #{name.slice(0, width - 2)}.."
else
id = id + ": #{name.ljust(width)}"
end
end
q.text "Instruction[#{"% 3s" % id}]"
q.group(6, "(", ")") do
q.breakable ""
unless @segment_use.nil?
q.text "position: #{@segment_use.position},"
q.breakable
end
q.text "pop: #{@pop_count},"
q.breakable
q.text "drop: #{@drop_count}"
end
end
private
def state
[@segment_id, @segment_use, @pop_count, @drop_count, @push].hash
end
end
end
end
| true
|
a71e8f103cc895e709d81949b3e896c2f89cb26b
|
Ruby
|
renanmaringolo/playing-logic
|
/salary_bonus.rb
|
UTF-8
| 833
| 3.671875
| 4
|
[] |
no_license
|
# Faça um programa que leia o nome de um vendedor, o seu salário fixo e o total de vendas efetuadas por ele no mês (em dinheiro). Sabendo que este vendedor ganha 15% de comissão sobre suas vendas efetuadas, informar o total a receber no final do mês, com duas casas decimais.
# Entrada
# O arquivo de entrada contém um texto (primeiro nome do vendedor) e 2 valores de dupla precisão (double) com duas casas decimais, representando o salário fixo do vendedor e montante total das vendas efetuadas por este vendedor, respectivamente.
# Saída
# Imprima o total que o funcionário deverá receber, conforme exemplo fornecido.
nome = gets.chomp
salario_fixo = gets.to_f
total_vendas = gets.to_f
comissao = 0.15
a_receber = total_vendas * comissao
total = salario_fixo + a_receber
puts "TOTAL = R$ #{'%.2f' % total}"
| true
|
40bb48191d7cfd6bf9a52e3625ec3ca33060f416
|
Ruby
|
msosland/TakeAHike
|
/app/helpers/make_markers_array.rb
|
UTF-8
| 161
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
def make_markers_array(places)
coords = places.map do |place|
hash = {lat: place[:latitude], lng: place[:longitude], name: place[:name]}
end
coords
end
| true
|
32f12eed645c8c057ea71360357f29438c5867c0
|
Ruby
|
armandofox/audience1st
|
/spec/support/custom_matchers.rb
|
UTF-8
| 1,435
| 2.9375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
module CustomMatchers
# test an enumerable to see if it includes a match for regex.
class IncludeMatchFor
include Enumerable
def initialize(regex)
@regex = regex
end
def matches?(target)
target.any? { |elt| elt.match(@regex) }
end
def failure_message
"expected #{@target.inspect} to include at least 1 element matching #{@regex.inspect}"
end
def failure_message_when_negated
"expected #{@target.inspect} not to include any element matching #{@regex.inspect}"
end
end
def include_match_for(regex)
IncludeMatchFor.new(regex)
end
# test if a voucher collection includes voucher(s) with certain attributes
class HaveVoucherMatching
def initialize(num,args)
@num = num
@attribs = args
end
def matches?(target)
@target = target
matches = target.select do |v|
@attribs.keys.all? { |k| v.send(k) == @attribs[k] }
end
@matched = matches.size
@matched == @num
end
def failure_message
"expected to find #{@num} vouchers matching #{@attribs.inspect}, but found #{@matched}"
end
def failure_message_when_negated
"expected not to find #{@num} vouchers matching #{@attribs.inspect}, but I did"
end
end
def have_voucher_matching(args)
HaveVoucherMatching.new(1, args)
end
def have_vouchers_matching(num, args)
HaveVoucherMatching.new(num, args)
end
end
| true
|
b52b0b7d7a2a9d37988c4a4ac8b306d4e1a620ac
|
Ruby
|
choonkeat/firehose
|
/lib/firehose/subscription.rb
|
UTF-8
| 2,850
| 2.5625
| 3
|
[] |
no_license
|
module Firehose
class Subscription
# Default TTL for how long a subscription should live on the server when the
# consumer disconnects.
# TODO should the Consumer handle TTL?
TTL = 15000
# Time to live for the amqp_queue on the server after the subscription is canceled. This
# is mostly for flakey connections where the client may reconnect after *ttl* and continue
# receiving messages.
attr_accessor :ttl
# Consumer and channel for the subscription.
attr_reader :consumer
# Channel that we'll use for the pub-sub activity. This probably maps to an URL
attr_reader :channel
def initialize(consumer, channel)
@consumer, @channel = consumer, channel
end
# TODO - Move the channel to an initializer so that we can force on AMQP subscription per one
# Firehose subscription. As it stands now, you could fire off multple subscriptions to diff amqp_channels
def subscribe(&block)
amqp_queue_name = "#{consumer.id}@#{channel}"
amqp_channel = AMQP::Channel.new(Firehose.amqp.connection).prefetch(1)
amqp_exchange = AMQP::Exchange.new(amqp_channel, :fanout, channel, :auto_delete => true)
amqp_queue = AMQP::Queue.new(amqp_channel, amqp_queue_name, :arguments => {'x-expires' => ttl})
amqp_queue.bind(amqp_exchange)
# When we get a message, we want to remove the consumer from the amqp_queue so that the x-expires
# ttl starts ticking down. On the reconnect, the consumer connects to the amqp_queue and resets the
# timer on x-expires... in theory at least.
@amqp_consumer = AMQP::Consumer.new(amqp_channel, amqp_queue, consumer.id)
@amqp_consumer.on_delivery do |metadata, message|
Firehose.logger.debug "AMQP delivering `#{message}` to `#{consumer.id}@#{channel}`"
block.call(message, self)
# The ack needs to go after the block is called. This makes sure that all processing
# happens downstream before we remove it from the amqp_queue entirely.
metadata.ack
end.consume
Firehose.logger.debug "AMQP subscribed to `#{consumer.id}@#{channel}`"
self # Return the subscription for chaining.
end
def unsubscribe
Firehose.logger.debug "AMQP unsubscribed"
@amqp_consumer.cancel if @amqp_consumer
@unsubscribe_callback.call self if @unsubscribe_callback
end
# Callback when consumer unsubscribes from subscription. The consumer uses this to remove
# subscriptions from itself when an unsubscribe happens.
def on_unsubscribe(&block)
@unsubscribe_callback = block
end
# The time that a amqp_queue should live *after* the client unsubscribes. This is useful for
# flakey network connections, like HTTP Long Polling or even broken web sockets.
def ttl
@ttl ||= TTL
end
end
end
| true
|
7a5be9f371159a0a40ea7c37a078b39ccdb52244
|
Ruby
|
mcivorsteiner/local-beat
|
/lib/seatgeek.rb
|
UTF-8
| 1,756
| 2.625
| 3
|
[] |
no_license
|
require 'multi_json'
require 'echonest'
module Seatgeek
extend self
def find_event_with_songkick_artist_id_and_date(songkick_artist_id, event_date)
seatgeek_artist_id = Echonest.get_seatgeek_id(songkick_artist_id)
unless seatgeek_artist_id == nil
event = performer_event_on_date(seatgeek_artist_id, event_date)
else
return nil
end
unless event == nil
seatgeek_url = event["url"]
ticket_details = event["stats"]
listing_count = ticket_details["listing_count"]
average_price = format_price(ticket_details["average_price"])
lowest_price = format_price(ticket_details["lowest_price"])
highest_price = format_price(ticket_details["highest_price"])
performers = event["performers"]
headliner = performers.first
return seatgeek_info = { seatgeek_url: seatgeek_url,
listing_count: listing_count,
average_price: average_price,
lowest_price: lowest_price,
highest_price: highest_price,
headliner_image_urls: headliner["images"]
}
else
return nil
end
end
private
def performer_event_on_date(artist_id, event_date)
date = Date.parse(event_date).strftime('%Y-%m-%d')
query_url = "http://api.seatgeek.com/2/events?performers.id=#{artist_id}&datetime_local=#{date}"
query_response = HTTParty.get(query_url).body
formatted_query_response = JSON.parse(query_response)
unless formatted_query_response["status"] == "error" || formatted_query_response["status"] == 400
return formatted_query_response["events"].first
else
nil
end
end
def format_price(price)
"%.2f" % [price] if price
end
end
| true
|
4bbd5928a0f80bb707d37614ff532d8328a8e704
|
Ruby
|
mattopps/phase-0
|
/week5/pad-array/My_pad_solution.rb
|
UTF-8
| 3,697
| 4.28125
| 4
|
[
"MIT"
] |
permissive
|
# 0. Pseudocode
# What is the input? an array of items, a minimum length for the array, a value to pad the array if needed
# What is the output? an array
# What are the steps needed to solve the problem?
=begin
Destructive
1. define a method to accept the input (an array, a minimum length requirement, and a default value to add to the array if needed to meet minimum length)
2. check the size of the array
3. compare array length to the minimum length requirement
4. if the array length is at least as long as the requirement - return the array unaltered
5. if the array length is too short - add default value(s) to the array to meet the requirement
6. return the original array
Non-Destructive
-Repeat above steps 1 - 4
5-if the array length is too short
create a new array.
add the contents of the input array to the new array
add default value(s) to the array to meet the requirement
6. return the original array
=end
=begin initial solution - Destructive
def pad!(array, min_size, value = nil) #destructive
if
array.length >= min_size
return array
else
while array.length < min_size
array.push(value)
end
return array
end
end
=end
def pad!(array, min_size, value = nil) #Refactor destructive
if array.length >= min_size
return array
else
for i in array.length...min_size
array[i] = value
end
end
array
end
=begin
# 1. Initial Solution
def pad(array, min_size, value = nil)
if
array.length >= min_size
return array
else
#while array.length < min_size
array.push(value)
end
return array
end
end
#(array.each do |item|
#if item != value
# array << value
#break if array.length == min_size
#end
#end
#end
#array
#end)#
### This method cannot handle an empty array.
=end
#Refactor #non-destructive
def pad(array, min_size, value = nil)
new_array = array.dup
#new_array = [].concat(array)
#new_array = Array.new.concat(array)
if new_array.length >= min_size
return new_array
else
for i in new_array.length...min_size
new_array[i] = value
end
end
new_array
end
=begin
Q- Were you successful in breaking the problem down into small steps?
A-Yes
Q- Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have?
A- Until we got to the part where we had to nondestructively create a new array to append to, which technically wasnt specifically addressed as a step in the psueodocode. maybe that was part of the issue.
Q - Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them?
A- yes for the destructive, no for the nondestructive. We couldn't figure out how to nondestructively accomplish what push accomplishes, nor to iterate over the array and add nondestructively. We were pretty sure the solution was an alt array. But we set it equal to the original array which was the problem.
Q- When you refactored, did you find any existing methods in Ruby to clean up your code?
A- yes. dup. dup was great. didn't find anything to refactor the second half of the code for each method yet.
Q- How readable is your solution? Did you and your pair choose descriptive variable names?
Seems good to me.
Q- What is the difference between destructive and non-destructive methods in your own words?
A - any changes made to an object in a nondestructive method do not alter the original structure of the object.
No matter what you do to it, it will return itself as it started at the end of your changes.
=end
| true
|
b9b0cfff6aea12be0c1ba455d2cb76d450575b70
|
Ruby
|
nathikazad/channel26
|
/app/controllers/application_controller.rb
|
UTF-8
| 10,060
| 2.578125
| 3
|
[] |
no_license
|
class ApplicationController < ActionController::Base
protect_from_forgery
@array=Array.new
@i=0
def generate_response(msg,student,twilio)
#authenticate
@array=(msg.downcase.split /[ _,-.''!?]|(\d+)/)
garbage=delete_useless()
if student.nil?
return "Sorry, I can't find you"
end
#find when
start=find_when()
#for duration
if(start==nil)
dur=5
start=Date.today
else
dur=1
end
@i=0
while @i < @array.length do
if(check4sim(["this","week"]))
dur=(7-Date.today.cwday)
if(dur<=2)
dur=7
start=Date.today+(8-Date.today.cwday)
end
elsif(check4sim(["next","week"]))
dur=7
start=Date.today+(8-Date.today.cwday)
end
@i=@i+1
end
#Find channels
if((channels=find_channels(student)).empty?)
channels=student.channels
end
original=@array
for @i in 0..(@array.size-1) do
@array[@i]=@array[@i].singularize
end
#find channel related material
channelmaterial=find_stuff(channels,start,(start+dur))
#create readable response
if(twilio)
if(channelmaterial[0].size>0)
return create_response(channelmaterial,garbage[0],student)
else
return "You dont have anything due till #{(start+dur)}"
end
else
channelmaterial[0]
end
end
def create_response(channelmaterial,first_word,student)
resp=""
if(first_word.eql?("do") || first_word.eql?("is") || first_word.eql?("any"))
resp.concat("Yes you do on the following \n")
end
atypes=["Class","Homework","Quiz","Midterm","Final"]
weekdays=["","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
currdate = Date.new(2000)
for i in 0..(channelmaterial[0].size-1) do
if(!(currdate.eql?(channelmaterial[0][i].due_date)))
if(channelmaterial[0][i].due_date.eql?(Date.today))
resp.concat("Today \n")
elsif(channelmaterial[0][i].due_date.eql?(Date.today+1))
resp.concat("Tomorrow \n")
elsif((diff=Integer(channelmaterial[0][i].due_date-Date.today))<=5 && diff>0)
resp.concat("On #{weekdays[channelmaterial[0][i].due_date.cwday]} \n ")
else
resp.concat("On #{channelmaterial[0][i].due_date.to_s} \n ")
end
currdate=channelmaterial[0][i].due_date
end
resp.concat("#{i+1}. #{atypes[channelmaterial[0][i].atype]} #{channelmaterial[0][i].serial} in #{channelmaterial[0][i].classroom.channel.name}\n ")
resp.concat("On #{channelmaterial[0][i].content} \n ")
end
return resp
end
def retrieve(word)
end
def find_when
for @i in 0..(@array.length-1) do
if(similar(@array[@i],"today")>=75)
@array.delete_at(@i)
return Date.today
end
if(similar(@array[@i],"yesterday")>=75)
@array.delete_at(@i)
return Date.today-1
end
if(similar(@array[@i],"dayaftertomorrow")>=75 || similar(@array[@i],"dayafter")>=75 ||
(similar(@array[@i],"day")>=75 && similar(@array[@i+1],"after")>=75 ))
@array.delete_at(@i)
return Date.today.tomorrow.tomorrow
end
if(similar(@array[@i],"tomorrow")>=75 || similar(@array[@i],"tom")>=75 || similar(@array[@i],"tmrw")>=75)
@array.delete_at(@i)
return Date.today.tomorrow
end
weekdays=[["monday","mon"],["tues","tuesday"],["wednesday","wed"],["thursday","thurs"],["friday","fri"],["saturday","sat"],["sunday","sun"]]
for j in 0..(weekdays.size-1) do
if(similar(@array[@i],weekdays[j][0])>=75 || similar(@array[@i],weekdays[j][1])>=75)
@array.delete_at(@i)
return day_date(j+1)
end
end
end
return nil
end
def find_channels(student)
stuchannels=student.channels
channels=Array.new(stuchannels.length)
@i=0
while @i < @array.size do
for j in 0..(stuchannels.size-1) do
if(channels[j]==nil)
sim=(stuchannels[j].channelable.dept.simwords | stuchannels[j].simwords )
for k in sim do
words=k.word.split
if(check4sim(words))
if(stuchannels[j].channelable_type.eql?("Classroom") && is_a_number?(@array[@i+1]))
if(stuchannels[j].channelable.class_no.eql?(@array[@i+1]) )
@array.delete_at(@i+1)
channels[j]=stuchannels[j]
end
else
channels[j]=stuchannels[j]
end
end
end
#by teacher's name
if(stuchannels[j].channelable_type.eql?("Classroom") && channels[j].nil? &&
(similar(@array[@i],stuchannels[j].leader.first_name)>75||similar(@array[@i],stuchannels[j].leader.last_name)>75||
similar(@array[@i],("#{stuchannels[j].leader.first_name}s"))>75||similar(@array[@i],"#{stuchannels[j].leader.last_name}s")>75))
channels[j]=stuchannels[j]
@array.delete_at(@i)
@i=@i-1
end
end
end
@i=@i+1
end
for @i in 0..(@array.size-1)
for j in 0..(stuchannels.size-1) do
if(channels[j].nil? && stuchannels[j].channelable.class_no.eql?(@array[@i]) )
@array.delete_at(@i)
@i=@i-1
channels[j]=stuchannels[j]
end
end
end
return channels.compact
end
def find_stuff(channels,start_date,end_date)
stuff=Array.new(2)
#test gets deleted
assignment_types=[["class","happened","happening"],["hw","home work"],["quiz"],["mid term"],["final"],["assignment"]] #assignment always at the end after the atypes
clubs=Array.new
classrooms=Array.new
@i=0
while @i < @array.size do
for j in 0..5 do
for m in assignment_types[j] do
words=m.split
if(check4sim(words))
if(is_a_number?(@array[@i+1]))
classrooms=classrooms | queryThat(channels,j,@array[@i+1],start_date,end_date,1)
@array.delete_at(@i+1)
@i=@i-1
else
limit=3
if(@array[@i].eql?("next"))
end_date=end_date+30
limit=1
elsif(@array[@i].eql?("all"))
end_date=end_date+30
limit=20
end
if(j==assignment_types.size-1)
classrooms=classrooms|queryThat(channels,nil,nil,start_date,end_date,limit)
else
classrooms=classrooms | queryThat(channels,j,nil,start_date,end_date,limit)
end
end
end
end
end
if(similar(@array[@i],"test")>75)
classrooms=classrooms | queryThat(channels,2,nil,start_date,end_date,3)
classrooms=classrooms | queryThat(channels,3,nil,start_date,end_date,3)
classrooms=classrooms | queryThat(channels,4,nil,start_date,end_date,3)
@array.delete_at(@i)
@i=@i-1
end
if(similar(@array[@i],"exam")>75)
classrooms=classrooms | queryThat(channels,3,nil,start_date,end_date,3)
classrooms=classrooms | queryThat(channels,4,nil,start_date,end_date,3)
@array.delete_at(@i)
@i=@i-1
end
@i=@i+1
end
for @i in 0..(@array.size-1)
if(similar(@array[@i],"anything")>75 || (classrooms.size==0 && similar(@array[@i],"due")>75 ) )
classrooms=classrooms|queryThat(channels,nil,nil,start_date,end_date,3)
@array.delete_at(@i)
@i=@i-1
end
end
stuff[0]=classrooms.sort! {|a,b| a.due_date <=> b.due_date}
stuff[1]=clubs
return stuff
end
def queryThat(channels,atype,serial,start_date,end_date,limit)
end_date=end_date-1
classrooms=Array.new
for k in 0..(channels.size-1) do
if(channels[k].channelable_type.eql?("Classroom"))
if(!(serial.nil?))
classrooms=classrooms | channels[k].channelable.assignments.where(:atype => atype, :serial => serial).limit(limit)
elsif(!(atype.nil?))
classrooms=classrooms | channels[k].channelable.assignments.where(:atype => atype, :due_date => start_date..end_date).limit(limit)
else
classrooms=classrooms | channels[k].channelable.assignments.where(:due_date => start_date..end_date).limit(limit).find(:all, :conditions => ["atype != ?", 0])
end
end
end
return classrooms
end
# helper methods
def check4sim(array2)
str=""
check=true
for l in 0..(array2.size-1) do
word=@array[@i+l]
check=check && (similar(array2[l],word)>75 )
str.concat("#{array2[l]}")
end
if(check)
for l in 0..(array2.size-1) do
@array.delete_at(@i)
end
@i=@i-1
return true
end
#clump all the words together and check
word=@array[@i]
if(similar(str,word)>75 )
@array.delete_at(@i)
@i=@i-1
return true
end
return false
end
def day_date(day)
tod=Date.today.cwday
nextday=@array[@i-1]
if(similar(nextday,"next")>=75)
@array.delete_at(@i-1)
return Date.today+(day-tod+7)
else
return Date.today+(day-tod)
end
end
def similar(a,b)
if(a.nil? || b.nil? ||(a.length+b.length<2 ))
return 0
end
a=a.downcase
b=b.downcase
#hack levenshtein to shorten runtime and make it scalable
100-(Levenshtein.distance(a,b)*100/((a.length+b.length)/2))
end
def is_a_number?(s)
s.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end
def delete_useless()
#leave nil gaps
garbage=Array.new
k=0
useless=["is","are","","when","my","there","in","on","what","have","i","do","any"]
for i in 0..(@array.size-1)
j=0
while j < useless.size do
if(@array[i].eql?(useless[j]))
garbage[k]=useless[j]
k=k+1
@array.delete_at(i)
j=-1
end
j=j+1
end
end
return garbage
end
end
| true
|
0219afe75aa4780dcaa91deac9889f6c9800cae0
|
Ruby
|
ender672/tiedye
|
/test/transform/test_fit.rb
|
UTF-8
| 681
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
require 'helper'
module TieDye
describe "Fit" do
before do
path = File.expand_path("../../samples/wagon.jpg", __FILE__)
@image = Image.read path
end
it "grows an image into a box that is larger than it is" do
fit = @image.fit 800, 800
f = fit.run
assert_equal 800, f.x_size
end
it "shrinks an image into a box that is smaller than it is" do
fit = @image.fit 50, 50
f = fit.run
assert_equal 50, f.x_size
end
it "does nothing to an image when the box matches its size" do
im = @image.run
fit = @image.fit im.x_size, im.y_size
assert_equal im.x_size, fit.run.x_size
end
end
end
| true
|
89acb3a54fe07f57ed34980128e1214d63dc828d
|
Ruby
|
ramirezpulidojavier/PDOO
|
/PRACTICAS/CAMBIAR_RUBY/RUBY2/Civitas/lib/dado.rb
|
UTF-8
| 1,037
| 3.140625
| 3
|
[] |
no_license
|
require "singleton"
module Civitas
class Dado
include Singleton
@@SalidaCarcel = 5
def initialize()
@random = Random.new
@ultimo_resultado = 0
@debug = true
end
def get_instance
return @instance
end
def tirar
if (@debug == false)
@random = rand(5) + 1
@ultimo_resultado = @random
return @random
else
@ultimo_resultado = 1
return 1
end
end
def salgo_de_la_carcel
if(tirar >= @@SalidaCarcel)
return true
else
return false
end
end
def quien_empieza (n)
return rand(n-1)
end
def set_debug (d)
@debug = d
if(@debug)
Diario.instance.ocurre_evento("Debug activado")
puts Diario.instance.leer_evento
else
Diario.instance.ocurre_evento("Debug desactivado")
puts Diario.instance.leer_evento
end
end
def get_ultimo_resultado
return @ultimo_resultado
end
end
end
| true
|
65172b83e0cc0bcbc82b07323eb89446d1d05176
|
Ruby
|
ryandhaase/The-Greasy-Spoon
|
/db/seeds.rb
|
UTF-8
| 577
| 2.515625
| 3
|
[] |
no_license
|
require 'faker'
# sample_image = Restaurant.find(2)
#
# 10.times do
# Restaurant.create!(
# name: Faker::Company.name,
# address: "#{Faker::Address.street_address}, #{Faker::Address.city}, #{Faker::Address.state_abbr} #{Faker::Number.number(5)}",
# phone: '555-555-5555',
# website: Faker::Internet.url,
# image: sample_image.image
# )
# end
restaurants = Restaurant.all
50.times do
Review.create!(
restaurant_id: restaurants.sample.id,
rating: Faker::Number.between(1, 5),
comment: Faker::Lorem.paragraph
)
end
puts "Seed Finished"
| true
|
cc696b59716d12e2d84f549c7fe38a6aa2edb54a
|
Ruby
|
pivotalexperimental/screw-unit-server
|
/vendor/js-test-core/vendor/lucky-luciano/spec/lucky_luciano/resource_spec.rb
|
UTF-8
| 9,746
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
require File.expand_path("#{File.dirname(__FILE__)}/../spec_helper")
module LuckyLuciano
module ResourceSpec
class Root < Resource
map "/"
end
class ResourceFixture < Resource
map "/foobar"
end
class ResourceFixtureWithSubPaths < Resource
map "/foobar/"
get "/baz" do
"Response from /foobar/baz"
end
get "/users/:user_id" do
"User id is #{params[:user_id]}"
end
end
class User < Resource
map "/users/:user_id"
get "/friends" do
"User #{params['user_id']} friends"
end
end
describe Resource do
include ResourceSpec
before do
ResourceFixture.recorded_http_handlers.clear
end
macro("http verb") do |verb|
describe ".#{verb}" do
context "" do
before do
ResourceFixture.send(verb, "/") do
"He sleeps with the fishes"
end
end
it "creates a route to #{verb.upcase} the given path that executes the given block" do
app.register(ResourceFixture.route_handler)
response = send(verb, "/foobar")
response.should be_http( 200, {}, "He sleeps with the fishes" )
end
end
context "when the base path is blank and the relative path is blank" do
before do
Root.send(verb, "") do
"Response from /"
end
end
it "creates a route to /" do
app.register(Root.route_handler)
response = send(verb, "/")
response.should be_http( 200, {}, "Response from /" )
end
end
context "when the relative path does not have a leading slash" do
before do
ResourceFixtureWithSubPaths.send(verb, "no_leading_slash") do
"Response from /foobar/no_leading_slash"
end
end
it "creates a route to #{verb.upcase} the given path that executes the given block" do
app.register(ResourceFixtureWithSubPaths.route_handler)
response = send(verb, "/foobar/no_leading_slash")
response.should be_http( 200, {}, "Response from /foobar/no_leading_slash" )
end
end
it "does not respond to another type of http request" do
ResourceFixture.send(verb, "/") do
""
end
app.register(ResourceFixture.route_handler)
get("/foobar").status.should == 404 unless verb == "get"
put("/foobar").status.should == 404 unless verb == "put"
post("/foobar").status.should == 404 unless verb == "post"
delete("/foobar").status.should == 404 unless verb == "delete"
end
describe "Instance behavior" do
attr_reader :evaluation_target
before do
evaluation_target = nil
ResourceFixture.send(verb, "/") do
evaluation_target = self
""
end
app.register(ResourceFixture.route_handler)
send(verb, "/foobar")
@evaluation_target = evaluation_target
end
it "evaluates the block in as a Resource" do
evaluation_target.class.should == ResourceFixture
end
it "sets app to be the Sinatra context" do
evaluation_target.app.class.should == Sinatra::Application
end
it "delegates methods to the #app" do
return_value = nil
mock.proxy(evaluation_target.app).params {|val| return_value = val}
evaluation_target.params.should == return_value
end
context "when the #app does not respond to the method" do
it "raises a NoMethodError from the Resource's perspective" do
lambda do
evaluation_target.i_dont_exist
end.should raise_error(NoMethodError, /ResourceFixture/)
end
end
end
end
end
send("http verb", "get")
send("http verb", "put")
send("http verb", "post")
send("http verb", "delete")
describe ".[][]" do
context "when passed nothing" do
it "returns the base_path" do
ResourceFixture[].should == "/foobar"
ResourceFixture[][].should == "/foobar"
end
end
context "when passed a sub path" do
it "merges the base_path into the sub path, regardless of a / in front" do
ResourceFixtureWithSubPaths["/baz"].to_s.should == "/foobar/baz"
ResourceFixtureWithSubPaths["baz"].to_s.should == "/foobar/baz"
end
context "when passed a multiple sub paths" do
it "joins the sub paths with '/'" do
ResourceFixtureWithSubPaths["users"][99].should == "/foobar/users/99"
end
end
context "when passed a hash as the last argument" do
context "when using a single path argument" do
it "creates url params from the hash" do
path = ResourceFixtureWithSubPaths["/users/:user_id"][:user_id => 99, :single_value_param => "single_value_param_value", 'multiple_value_param[]' => [1,2,3]]
path.should be_url("/foobar/users/99", [
"multiple_value_param[]=1",
"multiple_value_param[]=2",
"multiple_value_param[]=3",
"single_value_param=single_value_param_value",
])
end
end
context "when using multiple path arguments" do
it "creates url params from the hash" do
path = ResourceFixtureWithSubPaths["users"][99][:single_value_param => "single_value_param_value", 'multiple_value_param[]' => [1,2,3]]
path.should be_url("/foobar/users/99", [
"multiple_value_param[]=1",
"multiple_value_param[]=2",
"multiple_value_param[]=3",
"single_value_param=single_value_param_value",
])
end
end
def be_url(expected_path, expected_query_parts)
Spec::Matchers::SimpleMatcher.new("match url") do |actual|
uri = URI.parse(actual.to_s)
uri.path.should == expected_path
query_parts = uri.query.split("&")
query_parts.should =~ expected_query_parts
end
end
end
end
end
describe ".path" do
context "when passed nothing" do
it "returns the base_path" do
ResourceFixture.path.should == "/foobar"
end
end
context "when passed a sub path" do
it "merges the base_path into the sub path, regardless of a / in front" do
ResourceFixtureWithSubPaths.path("/baz").should == "/foobar/baz"
ResourceFixtureWithSubPaths.path("baz").should == "/foobar/baz"
end
context "when passed a multiple sub paths" do
it "joins the sub paths with '/'" do
ResourceFixtureWithSubPaths.path("users", 99).should == "/foobar/users/99"
end
end
context "when passed a hash as the last argument" do
context "when using a single path argument" do
it "creates url params from the hash" do
path = ResourceFixtureWithSubPaths.path(
"/users/:user_id", {:user_id => 99, :single_value_param => "single_value_param_value", 'multiple_value_param[]' => [1,2,3]}
)
uri = URI.parse(path)
uri.path.should == "/foobar/users/99"
query_parts = uri.query.split("&")
query_parts.should =~ [
"multiple_value_param[]=1",
"multiple_value_param[]=2",
"multiple_value_param[]=3",
"single_value_param=single_value_param_value",
]
end
end
context "when using multiple path arguments" do
it "creates url params from the hash" do
path = ResourceFixtureWithSubPaths.path(
"users", 99, {:single_value_param => "single_value_param_value", 'multiple_value_param[]' => [1,2,3]}
)
uri = URI.parse(path)
uri.path.should == "/foobar/users/99"
query_parts = uri.query.split("&")
query_parts.should =~ [
"multiple_value_param[]=1",
"multiple_value_param[]=2",
"multiple_value_param[]=3",
"single_value_param=single_value_param_value",
]
end
end
end
end
context "when the base_path contains a parameter" do
context "when not passed" do
it "raises an ArgumentError" do
lambda do
User.path
end.should raise_error(
ArgumentError,
%r{Expected :user_id to have a value}
)
end
end
context "when first argument is a hash" do
it "returns the full path with the base path param value" do
User.path("friends", :user_id => 99).should == "/users/99/friends"
end
end
end
end
end
end
end
| true
|
de355eab7b417d28832f36eb07a1bf86adf38a97
|
Ruby
|
cheljoh/feline_friends-y
|
/spec/spec_helper.rb
|
UTF-8
| 4,417
| 2.53125
| 3
|
[] |
no_license
|
module SpecHelpers
def create_integration
user = create_users[:user1]
order = create_orders[:order2]
cat = Cat.create(
name: "Chica",
age: 2,
description: "Actually a dog",
image: image_path,
price: 2000,
category_id: categories[0].id,
status: "inactive")
cat2 = Cat.create(
name: "Caia",
age: 8,
description: "Chelsea's other cat",
image: image_path,
price: 3000,
category_id: categories[0].id,
status: "active")
CatOrder.create(order_id: order.id, cat_id: cat.id)
CatOrder.create(order_id: order.id, cat_id: cat2.id)
user.orders << order
[user, order, cat, cat2]
end
def create_orders
{
order1: Order.create(status: 1,
cancelled_at: "2016-03-02 11:10:57 -0700"),
order2: Order.create(status: 0,
start_date: Date.new(2016, 03, 03),
end_date: Date.new(2016, 03, 04)),
order3: Order.create(status: 0,
start_date: Date.new(2016, 03, 03),
end_date: Date.new(2016, 03, 04)),
}
end
def create_address
Address.find_or_create_by(state: "CA",
city: "San Francisco",
street: "4325 W. Palm Beach Rd.",
zip: "94116",
country: "United States")
end
def create_users
address = create_address
{
user1: User.create(username: "adrienne",
password: "password",
name: "Adrienne",
address_id: address.id),
user2: User.create(username: "chelsea",
password: "password",
name: "Chelsea",
address_id: address.id),
user3: User.create(username: "allan",
password: "stinky",
name: "Allan",
address_id: address.id,
role: 1)
}
end
def create_user_orders
user1 = create_users[:user1]
user2 = create_users[:user2]
user3 = create_users[:user3]
order1 = user1.orders.create(status: 0)
order2 = user1.orders.create(status: 1)
order3 = user2.orders.create(status: 2)
order4 = user3.orders.create(status: 2)
[order1, order2, order3, order4]
end
def log_in_user(user)
fill_in "Username", with: user.username
fill_in "Password", with: "password"
click_on "Login Meow!"
end
def create_admin
User.create(username: "adrienne",
password: "password",
name: "bacon",
role: 1,
address_id: create_address.id)
end
def create_cat
Cat.create(
name: "Fido",
age: 2,
description: "Actually a dog",
image: image_path,
price: 2000,
category_id: categories[0].id,
status: "active")
end
def image_path
"http://data.whicdn.com/images/54126468/large.gif"
end
def create_cats
{
cat1: Cat.create(
name: "Chica",
age: 2,
description: "Actually a dog",
image: image_path,
price: 2000,
category_id: categories[0].id,
status: "inactive"),
cat2: Cat.create(
name: "Caia",
age: 8,
description: "Chelsea's other cat",
image: image_path,
price: 3000,
category_id: categories[0].id,
status: "active"),
cat3: Cat.create(
name: "Mena",
age: 4,
description: "Adrienne's cat",
image: image_path,
category_id: categories[1].id,
price: 4000),
cat4: Cat.create(
name: "Penny Lane",
age: 13,
description: "Chelsea's other cat",
image: image_path,
category_id: categories[2].id,
price: 4000)
}
end
def categories
[Category.find_or_create_by(name: "Fluffy"),
Category.find_or_create_by(name: "Friendly"),
Category.find_or_create_by(name: "Happy")]
end
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.include SpecHelpers
end
| true
|
baab253ea9be2ce29cdf27d4f072878c796654ed
|
Ruby
|
kiahjade/makers-bnb
|
/spec/units/calendar_spec.rb
|
UTF-8
| 2,008
| 2.6875
| 3
|
[] |
no_license
|
require 'calendar'
require 'reset_test_database'
describe Calendar do
describe '#initialize' do
it 'starts with a start day of 1' do
PG.connect(dbname: 'makersbnb_test')
calendar = Calendar.new
expect(calendar.start_day).to eq 1
end
it 'starts with a end day of 3' do
PG.connect(dbname: 'makersbnb_test')
calendar = Calendar.new
expect(calendar.end_day).to eq 3
end
it 'starts with month January' do
PG.connect(dbname: 'makersbnb_test')
calendar = Calendar.new
expect(calendar.month).to eq "January"
end
end
describe '#add_start_day' do
it 'replaces starting day' do
PG.connect(dbname: 'makersbnb_test')
calendar = Calendar.new
calendar.add_start_day(2)
expect(calendar.start_day).to eq 2
end
end
describe '#add_end_day' do
it 'replaces ending day' do
PG.connect(dbname: 'makersbnb_test')
calendar = Calendar.new
calendar.add_end_day(4)
expect(calendar.end_day).to eq 4
end
end
describe '#add_month' do
it 'replaces month' do
PG.connect(dbname: 'makersbnb_test')
calendar = Calendar.new
calendar.add_month('February')
expect(calendar.month).to eq 'February'
end
end
describe '#available?' do
it 'returns true if all dates are available' do
connection = PG.connect(dbname: 'makersbnb_test')
connection.exec("INSERT INTO calendar (property, month, day, availability) VALUES('House', 'January', '1', 'Y')")
calendar = Calendar.new
calendar.find_availability
expect(calendar.available?).to eq true
end
it 'returns false if date(s) are unavailable' do
connection = PG.connect(dbname: 'makersbnb_test')
connection.exec("INSERT INTO calendar (property, month, day, availability) VALUES('House', 'January', '1', 'N')")
calendar = Calendar.new
calendar.find_availability
expect(calendar.available?).to eq false
end
end
end
| true
|
9a872dcbfdaeec1b215849e75f311d9cfed9b814
|
Ruby
|
shadowbq/low-fi
|
/group/group_put
|
UTF-8
| 2,363
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
GROUP_PUT = 1.0
require 'optparse'
require 'inifile'
@sensors = []
@non_sensors = []
myini = IniFile.load("#{Dir.home}/.group.ini")
myini.each do |s,p,v|
if s == 'sensors'
@sensors << p
else
@non_sensors << p
end
end
@servers = @sensors + @non_sensors
@servers = @servers.sort.uniq
options = {
:destination => "~/"
}
optparse = OptionParser.new do |opts|
opts.banner = "GROUP_PUT (Version #{GROUP_PUT} )"
opts.separator " Usage: #$0 [options] \"filename.txt\""
opts.separator " Note: Commands must be escaped."
opts.separator ""
opts.separator " System Groups:"
opts.on( '-a', '--all', 'All Servers' ) do
options[:server] = @servers
end
opts.on( '-s', '--sensors', 'Sensors' ) do
options[:server] = @sensors
end
opts.separator ""
opts.separator " File Opertators:"
opts.on( '-D', '--destination=[val]', 'Destination Directory', "Default: #{options[:destination]}" ) do |directory|
options[:destination] = directory
end
opts.separator ""
opts.separator " Global Options:"
opts.on( '-x', '--root', 'Connect via root rather than current user' ) do
options[:root] = true
end
opts.on( '-z', '--sudo', 'Connect via current user and sudo' ) do
options[:sudo] = true
end
opts.on( '-v', '--verbose', 'Verbose Debugging Enabled' ) do
options[:verbose] = true
end
opts.on_tail( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
#Verrify the options
begin
raise unless ARGV.size > 0
optparse.parse!
#If options fail display help
rescue
puts optparse
exit
end
file = ARGV[0]
options[:server].each do |ip|
puts "use server #{ip}" if options[:verbose]
if options[:root]
puts "scp -q #{file} root\@#{ip}:#{options[:destination]}" if options[:verbose]
puts `scp -q #{file} root\@#{ip}:#{options[:destination]}`
elsif options[:sudo]
puts "scp -q #{file} #{ip}:/tmp/. " if options[:verbose]
puts `scp -q #{file} #{ip}:/tmp/. `
puts "ssh -q #{ip} -t sudo \"sh -c 'mv -u /tmp/#{file} #{options[:destination]}'\"" if options[:verbose]
puts `ssh -q #{ip} -t sudo \"sh -c 'mv -u /tmp/#{file} #{options[:destination]}'\"`
else
puts "scp -q #{file} #{ip}:#{options[:destination]}" if options[:verbose]
puts `scp -q #{file} #{ip}:#{options[:destination]}`
end
end
| true
|
58a3b5ba03bfacd473a70a2fb79c8923dde99606
|
Ruby
|
vonwenm/nlpltc
|
/nlpltc
|
UTF-8
| 1,943
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/ruby -w
# Generate a nice-looking printed LibraryThing catalogue
#
# William Denton <wtd@pobox.com>
require 'csv'
require 'erb'
require 'rubygems'
require 'htmlentities'
require 'json'
csv = ARGV[0]
if csv.nil?
puts "Please specify a LibraryThing CSV export file"
exit
end
tex_template = "template.tex.erb"
# Layout of the LibraryThing CSV export file:
# (Note that this is slightly different from the Excel file!)
#
# 0 'TITLE',
# 1 "'AUTHOR (first, last)'",
# 2 "'AUTHOR (last, first)'",
# 3 'DATE',
# 4 'LCC',
# 5 'DDC',
# 6 'ISBN',
# 7 "'PUBLICATION INFO'",
# 8 'COMMENTS',
# 9 'RATING',
# 10 'REVIEW',
# 11 "'ENTRY DATE'",
# 12 'COPIES',
# 13 'SUBJECTS',
# 14 'TAGS'
items = []
lt_data = File.read(csv)
# There may be UTF-8 encoding issues, and this back-and-forth should solve them.
lt_data.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
lt_data.encode!('UTF-8', 'UTF-16')
# This we use to turn any escaped HTML into real characters.
coder = HTMLEntities.new
CSV.parse(lt_data, {:headers => true, :header_converters => :symbol}) do |row|
if row[:author_last_first].nil? then row[:author_last_first] = "[unknown]" end
if row[:ddc].nil? then row[:ddc] = "[---]" end
row[:publication_info] = coder.decode(row[:publication_info]).gsub('&', '\\\&')
row[:author_last_first] = coder.decode(row[:author_last_first]).gsub('&', '\\\&')
row[:tags] = coder.decode(row[:tags]).gsub('&', '\\\&').gsub(/,/, ', ')
book = {
title: coder.decode(row[:title]).gsub('&', '\\\&'),
author: row[:author_last_first],
publication: row[:publication_info].to_s + ". " + row[:date].to_s,
ddc: row[:ddc],
tags: row[:tags]
}
items << book
end
STDERR.puts "Processed #{items.size} books"
lastauthor = ""
# puts items.to_json
# exit
tex = IO.read(tex_template)
template = ERB.new(tex, 0, "%<>")
catalogue = template.result
puts catalogue
| true
|
aa14120e3ef937e61fec6ea801a6de53100aac89
|
Ruby
|
id774/scripts
|
/now.rb
|
UTF-8
| 510
| 2.609375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
#
# == Synopsis
#
# Display the current date and time.
#
# == Usage
#
# now [ -h | --help ] [ -f | --fmt fmtstring ]
#
# == Author
#
# id774
#
# == Copyright
#
# Copyright (c) id774 <idnanashi@gmail.com>
# Licensed under the same terms as Ruby.
#
require 'optparse'
require 'rdoc/usage'
fmt = "%Y/%m/%d %X %a"
opts = OptionParser.new
opts.on("-h", "--help") { RDoc::usage }
opts.on("-f", "--fmt FMTSTRING") {|str| fmt = str}
opts.parse(ARGV) rescue RDoc::usage('usage')
puts Time.now.strftime(fmt)
| true
|
ddd7112262f51baac48d667d92de94d4d9fa724c
|
Ruby
|
chancancode/mruby-canada
|
/test/test_canada.rb
|
UTF-8
| 1,188
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
assert('dispatch eh? method to existing ? method') do
assert_true [].empty_eh?
assert_false [1,2,3].empty_eh?
end
assert('dispatch eh? methods to non-existing ? method') do
assert_raise(NoMethodError) do
[].not_there_eh?
end
end
assert('respond_to_eh?') do
yes = [:empty?, :empty_eh?, :respond_to?, :respond_to_eh?]
no = [:not_there, :not_there?, :not_there_eh, :not_there_eh?]
yes.each { |y| assert_true [].respond_to_eh?(y) }
no.each { |n| assert_false [].respond_to_eh?(n) }
end
assert('respond_to?') do
yes = [:empty?, :empty_eh?, :respond_to?, :respond_to_eh?]
no = [:not_there, :not_there?, :not_there_eh, :not_there_eh?]
yes.each { |y| assert_true [].respond_to?(y) }
no.each { |n| assert_false [].respond_to?(n) }
end
assert('aboot') do
cases = [
[],
[1,2,3],
{},
{a: 1, b: 2},
Object.new,
true,
false,
nil
]
cases.each { |c| assert_equal c.inspect, aboot(c) }
end
assert('Exception#to_s') do
assert_equal "I'm sorry, but something went wrong...", Exception.new('something went wrong...').to_s
assert_equal "I'm sorry, but something went wrong...", Exception.new('something went wrong...').message
end
| true
|
39b7e1e4beaac20c81a77be37d79bedb0d00aed9
|
Ruby
|
Jhowden/chess
|
/lib/user_commands.rb
|
UTF-8
| 1,868
| 3.375
| 3
|
[] |
no_license
|
class UserCommands
VALID_USER_MOVE_INPUT = /\A[a-h]{1}[1-8]{1}\s{1}[a-h]{1}[1-8]{1}\z/
VALID_QUEENSIDE_CASTLING_INPUT = /\A0-0-0\z/
VALID_KINGSIDE_CASTLING_INPUT = /\A0-0\z/
VALID_EN_PASSANT_EXPRESSION = /\A[a-h]{1}[1-8]{1}\s?[a-h]{1}[1-8]{1}\s?e.p.\z/
QUEEN_REPLACEMENT = /\AQueen\z/
KNIGHT_REPLACEMENT = /\AKnight\z/
ROOK_REPLACEMENT = /\ARook\z/
BISHOP_REPLACEMENT = /\ABishop\z/
VALID_REPLACEMENT_EXPRESSIONS = [QUEEN_REPLACEMENT, KNIGHT_REPLACEMENT, ROOK_REPLACEMENT,
BISHOP_REPLACEMENT]
VALID_EXPRESSIONS_COLLECTION = [VALID_USER_MOVE_INPUT, VALID_QUEENSIDE_CASTLING_INPUT,
VALID_KINGSIDE_CASTLING_INPUT, VALID_EN_PASSANT_EXPRESSION]
VALID_CASTLING_EXPRESSION = [VALID_QUEENSIDE_CASTLING_INPUT, VALID_KINGSIDE_CASTLING_INPUT]
def user_team_input
input = user_input
if ["white", "black"].any? { |color| color == input.downcase}
input.downcase
else
puts "That is not a valid color. Please choose again (white or black):"
user_team_input
end
end
def user_move_input
input = user_input
if VALID_EXPRESSIONS_COLLECTION.any? { |expression| input =~ expression }
input
else
puts "Please enter a correctly formatted move (ex: b3 b6, 0-0 to castle kingside, 0-0-0 to castle queenside), or b4 c3 e.p. to perform en_passant:"
user_move_input
end
end
def piece_promotion_input
puts "Choose between Queen, Rook, Bishop, and Knight to replace your pawn."
input = user_input
if VALID_REPLACEMENT_EXPRESSIONS.any? { |expression| input.capitalize =~ expression }
input.capitalize
else
puts "Please enter a valid replacement piece (Queen, Rook, Bishop, Knight)"
piece_promotion_input
end
end
private
def user_input
print "> "
gets.chomp
end
end
| true
|
6c40326d7d49593138ef882d0d1ed7e27a5d587e
|
Ruby
|
matchbookmac/save_princess
|
/spec/character_spec.rb
|
UTF-8
| 478
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
require 'character'
require 'board'
require 'rspec'
describe 'Character' do
before :each do
reader, writer = IO.pipe
writer.puts '3'
writer.puts Array.grid 3
board = Board.new reader
@character = board.mario
end
describe '.location' do
it 'knows its location on the board' do
expect(@character.location).to eql [1,1]
end
end
describe '.mark' do
it 'knows its mark' do
expect(@character.mark).to eql 'm'
end
end
end
| true
|
c72d5e892fbb55ee459588d37cce5e89330ce3dd
|
Ruby
|
RSijelmass/stringCalculator
|
/lib/string_calculator.rb
|
UTF-8
| 407
| 3.703125
| 4
|
[] |
no_license
|
class StringCalculator
def add(string)
delimiter = find_delimiter(string)
split_string = split_by_delimiter(string, delimiter)
split_string.inject(0) { |sum, char| sum + char.to_i }
end
def find_delimiter(string)
string[0..1] == '//' ? (return string[2]) : (return ',')
end
def split_by_delimiter(string, delimiter)
string.gsub!('\n', delimiter)
return string.split(delimiter)
end
end
| true
|
39b809c905021375a16f2acddc1b90568e59b447
|
Ruby
|
dbaynes/RubyFall2013
|
/week7/exercises/features/converter_steps.rb
|
UTF-8
| 1,461
| 2.96875
| 3
|
[
"Apache-2.0"
] |
permissive
|
Given(/^I have entered (\d+) into the converter$/) do |arg1|
#pending # express the regexp above with the code you wish you had
@converter = Converter.new(arg1)
end
Given(/^I set the type to Fahrenheit$/) do
#pending # express the regexp above with the code you wish you had
@converter.type = "Celcius"
end
When(/^I press convert$/) do
@result = @converter.convert
end
Then(/^the result returned should be (\d+)\.(\d+)$/) do |arg1, arg2|
@result.should eq "#{args1}.#{args2}"
end
Given(/^we have a puppy$/) do
# pending # express the regexp above with the code you wish you had
end
Given(/^its name is Fred$/) do
#pending # express the regexp above with the code you wish you had
end
When(/^we pet the puppy$/) do
#pending # express the regexp above with the code you wish you had
end
Then(/^the puppy wags its tail$/) do
#pending # express the regexp above with the code you wish you had
end
Given(/^its name is Bella$/) do
#pending # express the regexp above with the code you wish you had
end
When(/^we ring the bell$/) do
#pending # express the regexp above with the code you wish you had
end
When(/^it wags its tail$/) do
#pending # express the regexp above with the code you wish you had
end
Then(/^we must take it out$/) do
#pending # express the regexp above with the code you wish you had
end
Then(/^then it will not pee on the floor$/) do
#pending # express the regexp above with the code you wish you had
end
| true
|
c4cb8284d8ca38eabf48d2ba1396a912e89e1199
|
Ruby
|
KevinTriplett/accounting_101
|
/script/migrator.rb
|
UTF-8
| 2,884
| 2.9375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# Simple migration navigator for terminal.
#
# Install
# 1) Throw this code into script/migrator
# 2) chmod +x script/migrator
#
# Use
# script/migrator => show 10 latest migrations, choose one
# script/migrator 15 => show 15 latest migrations
# script/migrator -5 => show 5 oldest migrations
# script/migrator foo => grep all migrations using regexp /foo/
#
# After each command you can:
# — type the # of migration to migrate to it
# — type exit/quit/abort/stop (or press ctrl+c) to exit
require 'time'
migrations_dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'db', 'migrate'))
globbed_migrations = File.join(migrations_dir, "*.rb")
migrations = []
Dir.glob(globbed_migrations).each do |entry|
stamp, title = File.basename(entry).split('_', 2)
title.chomp!('.rb')
title.gsub!(/_/, ' ')
title.capitalize!
migrations << [stamp, title]
end
command = ARGV.join(' ')
run_migration = lambda do |stamp|
system("rake db:migrate VERSION=#{stamp}")
end
print_results = lambda do |results|
unless results.empty?
puts "\n"
results.each_with_index do |result, i|
created = Time.parse(result[0]).strftime("%b %d, %y")
puts "#{i + 1}. #{result[1]}. (#{created})"
end
puts "\n"
end
end
validate_choice = lambda do |results, choice|
unless (1..results.size).include?(choice.to_i)
puts "Exiting."
exit(0)
end
end
find = lambda do
results = migrations.select{|el| el[1] =~ Regexp.new(command)}
puts "Found #{results.size} migration(s):"
print_results.call(results)
unless results.empty?
print "Enter # to migrate to: "
choice = STDIN.gets.to_i
validate_choice.call(results, choice)
puts "Migrating to \"#{results[choice-1][1]}\""
run_migration.call(results[choice-1][0])
end
end
first = lambda do |number|
results = migrations.first(number)
puts "Showing oldest #{number} migrations:"
print_results.call(results)
unless results.empty?
print "Enter # to migrate to: "
choice = STDIN.gets.to_i
validate_choice.call(results, choice)
puts "Migrating to \"#{results[choice-1][1]}\""
run_migration.call(results[choice-1][0])
end
end
last = lambda do |number|
results = migrations.last(number)
puts "Showing latest #{number} migrations:"
print_results.call(results)
unless results.empty?
print "Enter # to migrate to: "
choice = STDIN.gets.to_i
validate_choice.call(results, choice)
puts "Migrating to \"#{results[choice-1][1]}\""
run_migration.call(results[choice-1][0])
end
end
case command
when /^\s*$/: last.call(10)
when /^(\d+)$/: last.call($1.to_i)
when /^-(\d+)$/: first.call($1.to_i)
else find.call
end
| true
|
98ac6910250705bffb32c0cca84c0eec08afe07f
|
Ruby
|
madhurinp3/inmarTests
|
/formfilling.rb
|
UTF-8
| 1,050
| 2.65625
| 3
|
[] |
no_license
|
#9. Write a Selenium script that fills the form www.practiceselenium.com/practice-form.html and submits the page. After submitting , verify that the page navigates to home page
require 'rubygems'
require 'watir'
require 'rspec'
@browser=Watir::Browser.new :chrome
@browser.window.maximize
@browser.goto "http://www.practiceselenium.com/practice-form.html"
@browser.text_field(:name=>"firstname").set('test')
@browser.text_field(:name=>"lastname").set('123')
@browser.radio(:value => "Female").set
@browser.radio(:value => "3").set
@browser.text_field(:id=>"datepicker").set('20/11/2018')
@browser.checkbox(:value => "Black Tea").set
@browser.checkbox(:value => "One of those things").set
@browser.select_list(:id => "continents").select 'Asia'
@browser.select_list(:name => "selenium_commands").select 'Switch Commands'
@browser.button(:id => "submit").click
# expect(@browser.title).to eql("Welcome")
@browser.text.include? 'Welcome'
homepage = @browser.text.include?("We're passionate about tea.")
# expect(homepage).to eql(true)
@browser.close
| true
|
adcd2670f0bbda378338b8473e7d412228cd4711
|
Ruby
|
kaist-plrg/jstar
|
/tests/compile/basic/recent/MemberExpression[2,0].Contains.spec
|
UTF-8
| 103
| 2.546875
| 3
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
1. If |MemberExpression| Contains _symbol_ is *true*, return *true*.
1. Return *false*.
| true
|
f75e65ab035a2f3ce0d6e5b9a311a37fceb5a4aa
|
Ruby
|
jmstacey/jprime
|
/legacy/jprime_client_worker_miller_rabin_optimized.rb
|
UTF-8
| 2,609
| 2.921875
| 3
|
[] |
no_license
|
# This second jprime worker implementation.
#
# Author:: Jon Stacey (mailto:jon@jonsview.com)
# Copyright:: Copyright (c) 2010 Jon Stacey
# License:: Distributes under the same terms as Ruby
require 'drb/drb'
require 'rinda/ring'
require 'rinda/tuplespace'
DRb.start_service
ts = Rinda::RingFinger.primary
# Not a creation by Jon
def modPow(x, r, m)
y = r
z = x
v = 1
while y > 0
u = y % 2
t = y / 2
if u == 1
v = (v * z) % m
end
z = z * z % m
y = t
end
return v
end
# Not a creation by Jon
def miller_rabin_pass(a, n)
# compute s and d
d = n - 1
s = 0
while d % 2 == 0 do
d >>= 1
s += 1
end
a_to_power = modPow(a, d, n)
if a_to_power == 1
return true
end
for i in 0...s do
if a_to_power == n - 1
return true
end
a_to_power = (a_to_power * a_to_power) % n
end
return (a_to_power == n - 1)
end
# IS a hacked creation by Jon as you can tell
def miller_rabin(n)
# Try shortcuts on small numbers before doing costly tests
# p_witnesses are potential witnesses for composites
if n < 1373653
p_witnesses = [2, 3]
elsif n < 9080191
p_witnesses = [32, 73]
elsif n < 4759123141
p_witnesses = [2, 7, 61]
elsif n < 2152302898747
p_witnesses = [2, 3, 5, 7, 11]
elsif n < 3474749660383
p_witnesses = [2, 3, 5, 7, 11, 13]
elsif n < 341550071728321
p_witnesses = [2, 3, 5, 7, 11, 13, 17]
elsif n > 341550071728321
puts "Ran out of shortcuts by Pomerance, Selfridge and Wagstaff and Jaeschke!"
puts "You must now use Miller-Rabin for an arbitrarily large number which is costly."
puts "Additionally, since it's not implemented, I'm just going to exit here and call it good"
puts "Have a nice day!"
exit
end
p_witnesses.each do |a|
if (!miller_rabin_pass(a, n))
return false
end
end
return true
end
def generate_primes(low, high)
puts "Generating primes between #{low} and #{high}"
# safety check
if low < 2
low = 2
end
# todo: speed boost by only generating array with odd numbers to start with
# and remvoing odd number checks from algorithm
primes = (low..high).to_a
primes.size.times do |i|
unless miller_rabin(primes[i])
primes[i] = nil
end
end
primes.compact
end
begin
while true
job = ts.take([:job, nil, nil, nil], 30) # wait 30 seconds before timing out
primes = generate_primes(job[2].to_i, job[3].to_i)
ts.write [:result, job[1], primes]
end
rescue Exception => e
p e
puts "No new jobs appeared so I'm exiting."
end
#jobs.each do |j|
# puts j
# end
Process::exit
| true
|
1b59c38041862cd8e6c39ddf6b2c080d50fce46c
|
Ruby
|
nami/chat-rails-redux
|
/db/seeds.rb
|
UTF-8
| 2,299
| 2.625
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
puts 'Cleaning database (messages, users and then channels)'
Message.destroy_all
User.destroy_all
Channel.destroy_all
puts 'Creating channels...'
channels_attributes = [
{ name: 'general' },
{ name: 'react' },
{ name: 'dogs' }
]
Channel.create!(channels_attributes)
puts 'Creating users...'
users_attributes = [
{
email: 'lego@dog.com',
password: '123456',
password_confirmation: '123456',
nickname: 'lego'
},
{
email: 'hacker@email.com',
password: '123456',
password_confirmation: '123456',
nickname: 'hacker'
},
{
email: 'chatty@email.com',
password: '123456',
password_confirmation: '123456',
nickname: 'chatty'
}
]
User.create!(users_attributes)
puts 'Creating messages...'
messages_attributes = [
{
channel_id: 1,
user_id: 1,
nickname: User.find(1).nickname,
content: "Hello! I'm new here!"
},
{
channel_id: 1,
user_id: 2,
nickname: User.find(2).nickname,
content: "Welcome!"
},
{
channel_id: 1,
user_id: 3,
nickname: User.find(3).nickname,
content: "Aww nice to meet you!"
},
{
channel_id: 2,
user_id: 1,
nickname: User.find(1).nickname,
content: "React is tough!"
},
{
channel_id: 2,
user_id: 2,
nickname: User.find(2).nickname,
content: "You just need more practice!"
},
{
channel_id: 2,
user_id: 3,
nickname: User.find(3).nickname,
content: "Redux is hard too!"
},
{
channel_id: 3,
user_id: 1,
nickname: User.find(1).nickname,
content: "I love dogs! Although cats are cool too."
},
{
channel_id: 3,
user_id: 2,
nickname: User.find(2).nickname,
content: "I like big dogs."
},
{
channel_id: 3,
user_id: 3,
nickname: User.find(3).nickname,
content: "I love pommies!"
}
]
Message.create!(messages_attributes)
puts 'Finished!'
| true
|
d9fce9b72ba59071d291257b4b23e99bf5bf4511
|
Ruby
|
lucanioi/exercism-ruby
|
/alphametics/alphametics/constraints/double_operand.rb
|
UTF-8
| 967
| 2.875
| 3
|
[] |
no_license
|
require_relative 'constraint'
module Alphametics
module Constraints
class DoubleOperand < Constraint
private
def find_negative_constraints
super.then(&method(:add_additive_id))
end
def add_additive_id(mapping)
mapping.dup.tap do |mapping|
(0...min_term_length).each do |position|
add_additive_id_at(position, mapping)
end
end
end
def add_additive_id_at(position, mapping)
op_1, op_2 = digits_at(position, operands)
result_digit = digit_at(position, result)
if [op_1, op_2].include?(result_digit)
letter = op_1 == result_digit ? op_2 : op_1
mapping[letter] += additive_id_constraint(position)
end
end
def additive_id_constraint(position)
position == 0 ? (1..9).to_set : (1..8).to_set
end
def min_term_length
all_terms.min_by(&:length).length
end
end
end
end
| true
|
e88c0155444c2e84e20d4994d5cab5963a52a335
|
Ruby
|
soulnafein/code-katas
|
/ruby/word_wrap/lib/word_wrapper.rb
|
UTF-8
| 769
| 3.5
| 4
|
[] |
no_license
|
class WordWrapper
def initialize(max_width)
@max_width = max_width
end
def wrap(text)
return text if last_line?(text)
this_line, rest = split_text(text)
this_line + "\n" + rest
end
private
def wrap_point(current_line)
separators = [" ", "!", "?", ",", ";", "."]
separator_pos = separators.map { |s| current_line.rindex(s) }.compact.max
first_line_break = current_line.index("Z")
first_line_break || separator_pos
end
def split_text(text)
current_line = text[0..@max_width]
wrap_point = wrap_point(current_line)
[text[0..wrap_point].strip, text[wrap_point+1..-1].strip]
end
def no_spaces(text)
text.gsub(/^[ ]*(.*)[ ]*$/, '\1')
end
def last_line?(text)
text.length < @max_width
end
end
| true
|
f4bb5a1e93e6fab33ebd5d7dbf6dda3b113d9431
|
Ruby
|
CMilligan26/project_record_shop_inventory
|
/record_shop_inventory/specs/genre_categorization_spec.rb
|
UTF-8
| 701
| 2.5625
| 3
|
[] |
no_license
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../models/genre_categorization')
class GenreCategorizationTest < MiniTest::Test
def setup
@genre_categorization = GenreCategorization.new({'id' => '1', 'record_id' => '2', 'genre_id' => '3'})
end
def test_genre_categorization_exists
assert_equal(GenreCategorization, @genre_categorization.class)
end
def test_genre_categorization_can_have_id
assert_equal(1, @genre_categorization.id)
end
def test_genre_categorization_has_record_id
assert_equal(2, @genre_categorization.record_id)
end
def test_genre_categorization_has_genre_id
assert_equal(3, @genre_categorization.genre_id)
end
end
| true
|
649cc863a93352d58666d5d9ff221ad6a30d74b0
|
Ruby
|
zachauten/bump
|
/formula.rb
|
UTF-8
| 727
| 3.296875
| 3
|
[] |
no_license
|
class Formula
attr_accessor :name
attr_accessor :current_version
attr_accessor :latest_version
attr_accessor :guessed
#TODO: Maybe when one version has a decimal and the other doesn't, invalidate the formula?
def initialize(name, current_version, latest_version, guessed)
@name = name
@current_version = current_version
@latest_version = latest_version
@guessed = guessed
end
def outdated()
current_version < latest_version
end
def eql?(other)
self.name == other.name
self.latest_version == other.latest_version
end
def to_s
"#{self.name} #{self.current_version} #{self.latest_version} #{guessed}"
end
end
| true
|
f3c34778fec19ec8a0532e7dc757aebcfcc2a190
|
Ruby
|
felipegruoso/sage_one
|
/lib/parsers/you_do_invoice.rb
|
UTF-8
| 1,418
| 2.953125
| 3
|
[] |
no_license
|
# encoding: utf-8
module Parsers
class YouDoInvoice < Parsers::BaseParser
PRODUCT = "PRODUTO"
PRODUCT_IDENTIFIER = "I"
#
# Parses the file content into an array of products.
#
# @return [Array] a list containing all products to be imported.
# @raise [TypeError] if the file content is not as expected.
#
def parse
header = decode_line(content.shift)
type, total = header.split('|')
raise TypeError if type != PRODUCT
products = []
content.each do |line|
values = decode_line(line.chomp).split("|").map(&:to_s)
if values.first == PRODUCT_IDENTIFIER
bar_code = values[9]
unity = values[10]
value = values[11]
bar_code = values[3] if bar_code.blank?
unity = values[7] if unity.blank?
value = values[8] if value.blank?
product = {
code: values[1],
description: values[2],
bar_code: bar_code,
ncm: values[4],
ipi: values[5],
gender: values[6],
unity: unity,
selling_values: [value],
stock: values[12]
}
products << product
end
end
products
end
end
end
| true
|
0184bb8020cf399b10dda1dc242e0405852a2b82
|
Ruby
|
jpgazmuri/Syllabus
|
/Ayudantías/1. Ruby/01_io.rb
|
UTF-8
| 253
| 3.9375
| 4
|
[] |
no_license
|
# Get user input
data = gets.chomp # gets = input (leaves the "\n" character), chomp = strip
# Print user input previously recieved
puts data
# Print user input without the "/n" character
print data
print ", esto se imprime en la misma linea"
p data
| true
|
bca474917b49a5f03f14ba152f19505084670003
|
Ruby
|
RomainSai/CSV_scrapper
|
/app.rb
|
UTF-8
| 469
| 2.75
| 3
|
[] |
no_license
|
load 'lib/scrapper.rb'
require "csv"
def create_new_csv
CSV.open("db/annuaire.csv", "wb") do |csv|
csv << ["city", "email"]
end
return 0
end
def add_infos_to_csv
list = get_the_email_of_a_townhal_from_its_webpage(get_all_the_urls_of_val_doise_townhalls)
list.each do |hash|
CSV.open("db/annuaire.csv", "a+") do |csv|
csv << [hash[:name], hash[:email]]
end
end
return 0
end
def perform
create_new_csv
add_infos_to_csv
end
perform
| true
|
02de3faed35f6afc05d9e17ac9121055f087798c
|
Ruby
|
Mahaswami/stupidedi
|
/lib/stupidedi/versions/functional_groups/004010/element_types/fixnum_val.rb
|
UTF-8
| 9,558
| 2.9375
| 3
|
[] |
no_license
|
module Stupidedi
module Versions
module FunctionalGroups
module FortyTen
module ElementTypes
class Nn < SimpleElementDef
# @return [Integer]
attr_reader :precision
def initialize(id, name, min_length, max_length, precision, description = nil, parent = nil)
super(id, name, min_length, max_length, description, parent)
if precision > max_length
raise ArgumentError,
"precision cannot be greater than max_length"
end
@precision = precision
end
# @return [Nn]
def copy(changes = {})
Nn.new \
changes.fetch(:id, @id),
changes.fetch(:name, @name),
changes.fetch(:min_length, @min_length),
changes.fetch(:max_length, @max_length),
changes.fetch(:precision, @precision),
changes.fetch(:description, @description),
changes.fetch(:parent, @parent)
end
# @return [void]
def pretty_print(q)
q.text "N#{@precision}[#{@id}]"
end
def companion
FixnumVal
end
end
#
# @see X222.pdf A.1.3.1.1 Numeric
#
class FixnumVal < Values::SimpleElementVal
def numeric?
true
end
def too_long?
false
end
def too_short?
false
end
#
#
#
class Invalid < FixnumVal
# @return [Object]
attr_reader :value
def initialize(value, usage, position)
@value = value
super(usage, position)
end
def valid?
false
end
def empty?
false
end
# @return [String]
def inspect
id = definition.bind do |d|
"[#{'% 5s' % d.id}: #{d.name}]".bind do |s|
if usage.forbidden?
ansi.forbidden(s)
elsif usage.required?
ansi.required(s)
else
ansi.optional(s)
end
end
end
ansi.element("Nn.invalid#{id}") << "(#{ansi.invalid(@value.inspect)})"
end
# @return [String]
def to_s
""
end
# @return [Boolean]
def ==(other)
eql?(other) or
(other.is_a?(Invalid) and @value == other.value)
end
end
#
# Empty numeric value. Shouldn't be directly instantiated -- instead
# use the {FixnumVal.value} and {FixnumVal.empty} constructors.
#
class Empty < FixnumVal
def valid?
true
end
def empty?
true
end
# @return [String]
def inspect
id = definition.bind do |d|
"[#{'% 5s' % d.id}: #{d.name}]".bind do |s|
if usage.forbidden?
ansi.forbidden(s)
elsif usage.required?
ansi.required(s)
else
ansi.optional(s)
end
end
end
ansi.element("Nn.empty#{id}")
end
# @return [String]
def to_s
""
end
# @return [Boolean]
def ==(other)
other.is_a?(Empty)
end
end
#
# Non-empty numeric value. Shouldn't be directly instantiated --
# instead, use the {FixnumVal.value} constructors.
#
class NonEmpty < FixnumVal
include Comparable
# @return [BigDecimal]
attr_reader :value
delegate_stupid :to_i, :to_d, :to_f, :to => :@value
def initialize(value, usage, position)
@value = value
super(usage, position)
end
# @return [NonEmpty]
def copy(changes = {})
NonEmpty.new \
changes.fetch(:value, @value),
changes.fetch(:usage, usage),
changes.fetch(:position, position)
end
def valid?
true
end
def empty?
false
end
# @return [Array(NonEmpty, Numeric)]
def coerce(other)
if other.respond_to?(:to_d)
# Re-evaluate other.call(self) as self.op(other.to_d)
return self, other.to_d
else
# Fail, other.call(self) is still other.call(self)
raise TypeError, "#{other.class} can't be coerced into FixnumVal"
end
end
# @return [String]
def inspect
id = definition.bind do |d|
"[#{'% 5s' % d.id}: #{d.name}]".bind do |s|
if usage.forbidden?
ansi.forbidden(s)
elsif usage.required?
ansi.required(s)
else
ansi.optional(s)
end
end
end
ansi.element("Nn.value#{id}") << "(#{to_s})"
end
# @return [String]
def to_s
# The number of fractional digits is implied by usage.precision
(@value * (10 ** definition.precision)).to_i.to_s
end
# @group Mathematical Operators
#################################################################
# @return [NonEmpty]
def /(other)
copy(:value => (@value / other).to_d)
end
# @return [NonEmpty]
def +(other)
copy(:value => (@value + other).to_d)
end
# @return [NonEmpty]
def -(other)
copy(:value => (@value - other).to_d)
end
# @return [NonEmpty]
def **(other)
copy(:value => (@value ** other).to_d)
end
# @return [NonEmpty]
def *(other)
copy(:value => (@value * other).to_d)
end
# @return [NonEmpty]
def %(other)
copy(:value => (@value % other).to_d)
end
# @return [NonEmpty]
def -@
copy(:value => -@value)
end
# @return [NonEmpty]
def +@
self
end
# @return [NonEmpty]
def abs
copy(:value => @value.abs)
end
# @return [-1, 0, +1]
def <=>(other)
a, b = coerce(other)
a.value <=> b
end
# @endgroup
#################################################################
end
end
class << FixnumVal
# @group Constructors
###################################################################
# @return [FixnumVal]
def empty(usage, position)
self::Empty.new(usage, position)
end
# @return [FixnumVal]
def value(object, usage, position)
if object.blank?
self::Empty.new(usage, position)
elsif object.respond_to?(:to_d)
# The number of fractional digits is implied by usage.precision
factor = 10 ** usage.definition.precision
self::NonEmpty.new(object.to_d / factor, usage, position)
else
self::Invalid.new(object, usage, position)
end
rescue ArgumentError
self::Invalid.new(object, usage, position)
end
# @return [FixnumVal]
def parse(string, usage, position)
if string.blank?
self::Empty.new(usage, position, position)
else
# The number of fractional digits is implied by usage.precision
factor = 10 ** usage.definition.precision
self::NonEmpty.new(string.to_d / factor, usage, position)
end
rescue ArgumentError
self::Invalid.new(string, usage, position)
end
# @endgroup
###################################################################
end
# Prevent direct instantiation of abstract class FixnumVal
FixnumVal.eigenclass.send(:protected, :new)
FixnumVal::Empty.eigenclass.send(:public, :new)
FixnumVal::Invalid.eigenclass.send(:public, :new)
FixnumVal::NonEmpty.eigenclass.send(:public, :new)
end
end
end
end
end
| true
|
ce674529562ef040535ae95c7819bfb6eb07d67d
|
Ruby
|
livmaina/ruby_oct_2018
|
/evelyn_chavez/ruby_exercises/ruby_puzzles.rb
|
UTF-8
| 2,312
| 4.65625
| 5
|
[] |
no_license
|
# Create an array with the following values: 3,5,1,2,7,9,8,13,25,32. Print the sum of all numbers in the array. Also have the function return an array that only include numbers that are greater than 10 (e.g. when you pass the array above, it should return an array with the values of 13,25,32 - hint: use reject or find_all method)
# ary = [3,5,1,2,7,9,8,13,25,32]
# puts ary.reduce(:+)
# puts ary.reject { |number| number < 10 }
# Create an array with the following values: John, KB, Oliver, Cory, Matthew, Christopher. Shuffle the array and print the name of each person. Have the program also return an array with names that are longer than 5 characters.
# persons_array = ["John", "KB", "Oliver", "Cory", "Matthew", "Christopher"]
# puts persons_array.select { |person| person.length > 5 }
# persons_array.shuffle.each { |person| puts person}
# Create an array that contains all 26 letters in the alphabet (this array must have 26 values). Shuffle the array and display the last letter of the array. Have it also display the first letter of the array. If the first letter in the array is a vowel, have it display a message..
# letters_array = ("a".."z").to_a
# puts letters_array.shuffle.last
# puts letters_array.shuffle.first
# shuffled = letters_array.shuffle
# puts "#{shuffled.first} is a vowel" if ["a","e","i","o","u"].include? shuffled.first
# Generate an array with 10 random numbers between 55-100.
# random_array = []
# 10.times { random_array << rand(55..100) }
# puts random_array
# Generate an array with 10 random numbers between 55-100 and have it be sorted (showing the smallest number in the beginning). Display all the numbers in the array. Next, display the minimum value in the array as well as the maximum value
# random_array = []
# 10.times { random_array << rand(55..100) }
# puts random_array.sort
# # puts random_array.max
# # puts random_array.min
# # Create a random string that is 5 characters long (hint: (65+rand(26)).chr returns a random character; use a map function and a range to do this).
# str = ""
# 5.times { str << rand(65..90).chr }
# puts str
# # Generate an array with 10 random strings that are each 5 characters long
# string_array = []
# 10.times do
# str = ""
# 5.times { str << rand(65..90).chr }
# string_array << str
# end
# puts string_array
| true
|
b573cba6c93f713eb21693624b0b01331b91b202
|
Ruby
|
satbirdd/PianoServer
|
/lib/accepting.rb
|
UTF-8
| 716
| 2.796875
| 3
|
[] |
no_license
|
module Accepting
# handshank = Accepting::HandShank.new(room.acceptings)
# handshank.accepting(current_user)
# handshank.is_single?
#
# handshank.is_
#
class HandShank
def initialize(record, key)
@target = record
if record.send(key).nil?
record.send("#{key}=".to_sym, {})
record.save()
end
@acceptings = @target.send(key)
end
def accepting(user_id, time = Time.now)
puts @acceptings, @acceptings[user_id.to_s]
@acceptings[user_id.to_s.to_sym] = {
time: time
}
@target.save
end
def is_single?
@acceptings.keys.count <= 1
end
def is_double?
@acceptings.keys.count > 1
end
end
end
| true
|
094097bb55af6822a96420ae6740be79673d104e
|
Ruby
|
timpalpant/bioruby-genomic-file
|
/spec/sparse_array_spec.rb
|
UTF-8
| 8,989
| 2.828125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#
# compact_array_spec.rb
# bioruby-genomic-file
#
# Created by Timothy Palpant on 6/25/11.
# Copyright 2011 UNC. All rights reserved.
#
require 'spec_helper'
require 'sparse_array'
describe SparseArray do
context "without data" do
before do
@test = SparseArray.new
end
it "should have nil contiguousness" do
@test.contiguous?.should be_nil
end
it "should have nil start" do
@test.start.should be_nil
end
it "should have nil stop" do
@test.stop.should be_nil
end
it "should have nil length" do
@test.length.should be_nil
end
it "should have 0 coverage" do
@test.coverage.should == 0
end
it "should have nil sum" do
@test.sum.should be_nil
end
it "should have nil total" do
@test.total.should be_nil
end
it "should have nil mean" do
@test.mean.should be_nil
end
it "should have nil stdev" do
@test.stdev.should be_nil
end
end
context "with default span (= 1)" do
before do
@test = SparseArray.new
@test.set(1, 1.0)
@test.set(2, 1.0)
@test.set(5, 2.0)
@test.set(10, 3.0)
end
it "should allow setting data" do
@test.set(1_000, 4.0)
@test[1_001] = 4.0
end
it "should raise an error when attempting to set negative indices" do
lambda { @test.set(-3, 3) }.should raise_error
lambda { @test[-3] = 5 }.should raise_error
end
it "should allow getting data" do
@test.get(5).should == 2.0
@test[5].should == 2.0
end
it "should raise an error when attempting to get data with negative indices" do
lambda { @test.get(-4) }.should raise_error
lambda { @test[-4] }.should raise_error
end
it "should allow querying for ranges of data" do
@test[1..2].should == [1.0, 1.0]
@test[1...3].should == [1.0, 1.0]
@test[1...2].should == [1.0]
@test[2..7].should == [1.0, nil, nil, 2.0, nil, nil]
@test[1,3].should == [1.0, 1.0, nil]
end
it "should return an empty Array when slicing with length 0" do
@test[4,0].should == []
end
it "should raise an error when attempting to query for a range with negative indices" do
lambda { @test[-4..-2] }.should raise_error
lambda { @test[3..-2] }.should raise_error
end
it "should allow iterating over values" do
count = 0
@test.each { |value| count += 1 }
count.should == 4
end
it "should return the indices stored" do
@test.indices.should == [1, 2, 5, 10]
@test.keys.should == [1, 2, 5, 10]
end
it "should return the values stored" do
@test.values.should == [1.0, 1.0, 2.0, 3.0]
end
it "should have start = 1" do
@test.start.should == 1
@test.low.should == 1
end
it "should have stop = 10" do
@test.stop.should == 10
@test.high.should == 10
end
it "should dynamically update start and stop" do
@test[0] = 4
@test.start.should == 0
@test.low.should == 0
@test[15] = 2
@test.stop.should == 15
@test.high.should == 15
end
it "should have length = 10" do
@test.length.should == 10
end
it "should have coverage = 4" do
@test.coverage.should == 4
end
it "should have sparsity 0.4" do
@test.sparsity.should == 0.4
end
it "should not be contiguous" do
@test.should_not be_contiguous
end
it "should cover indices 1..10" do
(1..10).each { |i| @test.cover?(i).should be_true }
@test.cover?(1,10).should be_true
end
it "should not cover other indices" do
@test.cover?(0).should be_false
@test.cover?(-3).should be_false
@test.cover?(11).should be_false
@test.cover?(nil).should be_false
@test.cover?(0,4).should be_false
@test.cover?(-4,1).should be_false
@test.cover?(0,0).should be_false
@test.cover?(8,11).should be_false
@test.cover?(14, 15).should be_false
end
it "should include indices 1,2,5,10" do
[1,2,5,10].each { |i| @test.include?(i).should be_true }
@test.include?(1,2).should be_true
end
it "should not include other indices" do
@test.include?(4).should be_false
@test.include?(1,10).should be_false
@test.include?(-1).should be_false
@test.include?(11).should be_false
end
it "should be able to add a scalar to all elements" do
sum = @test + 4.0
sum[1].should == 5.0
sum[2].should == 5.0
sum[5].should == 6.0
sum[10].should == 7.0
sum = @test + (-4)
sum[1].should == -3.0
sum[2].should == -3.0
sum[5].should == -2.0
sum[10].should == -1.0
end
it "should be able to subtract a scalar to all elements" do
difference = @test - 4.0
difference[1].should == -3.0
difference[2].should == -3.0
difference[5].should == -2.0
difference[10].should == -1.0
end
it "should be able to multiply a scalar to all elements" do
product = @test * 4
product[1].should == 4.0
product[2].should == 4.0
product[5].should == 8.0
product[10].should == 12.0
product = @test * -4.0
product[1].should == -4.0
product[2].should == -4.0
product[5].should == -8.0
product[10].should == -12.0
end
it "should be able to divide a scalar to all elements" do
product = @test / 4
product[1].should == 0.25
product[2].should == 0.25
product[5].should == 0.5
product[10].should == 0.75
product = @test / -4.0
product[1].should == -0.25
product[2].should == -0.25
product[5].should == -0.5
product[10].should == -0.75
end
it "should be able to add another SparseArray" do
other = SparseArray.new
other[1] = 3
other[2] = 4
other[6] = 1
sum = @test + other
sum[1].should == 4
sum[2].should == 5
lambda { sum[5] }.should raise_error
lambda { sum[6] }.should raise_error
lambda { sum[10] }.should raise_error
sum.start.should == 1
sum.stop.should == 2
sum.length.should == 2
sum.coverage.should == 2
end
it "should be able to subtract another SparseArray" do
other = SparseArray.new
other[1] = 3
other[2] = 4
other[6] = 1
difference = @test - other
difference[1].should == -2
difference[2].should == -3
lambda { difference[5] }.should raise_error
lambda { difference[6] }.should raise_error
lambda { difference[10] }.should raise_error
difference.start.should == 1
difference.stop.should == 2
difference.length.should == 2
difference.coverage.should == 2
end
it "should be able to multiply another SparseArray" do
other = SparseArray.new
other[1] = 3
other[2] = 4
other[6] = 1
product = @test * other
product[1].should == 3
product[2].should == 4
lambda { product[5] }.should raise_error
lambda { product[6] }.should raise_error
lambda { product[10] }.should raise_error
product.start.should == 1
product.stop.should == 2
product.length.should == 2
product.coverage.should == 2
end
it "should be able to divide another SparseArray" do
other = SparseArray.new
other[1] = 3
other[2] = 4
other[6] = 1
product = @test / other
product[1].should be_within(1e-14).of(1.0/3)
product[2].should be_within(1e-14).of(0.25)
lambda { product[5] }.should raise_error
lambda { product[6] }.should raise_error
lambda { product[10] }.should raise_error
product.start.should == 1
product.stop.should == 2
product.length.should == 2
product.coverage.should == 2
end
it "should compute the correct sum" do
@test.sum.should be_within(1e-14).of(7)
end
it "should compute the correct mean" do
@test.mean.should be_within(1e-14).of(1.75)
end
it "should compute the correct standard deviation" do
@test.stdev.should be_within(1e-14).of(0.82915619758885)
end
it "should convert to an Array" do
@test.to_a.should == [nil, 1.0, 1.0, nil, nil, 2.0, nil, nil, nil, nil, 3.0]
end
it "should convert to a Hash" do
h = @test.to_hash
h.length.should == 4
h[1].should == 1.0
h[2].should == 1.0
h[5].should == 2.0
h[10].should == 3.0
end
end
context "when contingous" do
before do
@test = SparseArray.new
@test.set(1, 5.0)
@test.set(2, 10.3)
@test.set(3, 40.5)
end
it "should be contiguous" do
@test.should be_contiguous
end
end
end
| true
|
3f7e8b70ac4afac124039a26d92a5cf4615fb188
|
Ruby
|
crismali/magic_carpet
|
/app/helpers/magic_carpet/js_fixtures_helper.rb
|
UTF-8
| 2,686
| 3.03125
| 3
|
[
"Apache-2.0"
] |
permissive
|
module MagicCarpet
module JsFixturesHelper
attr_accessor :models
NIL = "nil"
def hydrate(value)
if array?(value)
hydrate_array(value)
elsif date?(value)
hydrate_date(value)
elsif time?(value)
hydrate_time(value)
elsif datetime?(value)
hydrate_datetime(value)
elsif model?(value)
hydrate_model(value)
elsif number?(value)
hydrate_number(value)
elsif array_as_hash?(value)
hydrate_array(value.values)
elsif hash?(value)
hydrate_hash(value)
elsif is_nil?(value)
nil
elsif true?(value)
true
elsif false?(value)
false
else
value
end
end
private
def hydrate_hash(hash)
hash.each do |key, value|
hash[key] = hydrate(value)
end
end
def hydrate_array(array)
array.map do |element|
hydrate(element)
end
end
def hydrate_number(hash)
number = hash[:number]
hash[:integer] ? number.to_i : number.to_f
end
def hydrate_date(hash)
Date.parse(hash[:date])
end
def hydrate_time(hash)
time = Time.parse(hash[:time])
time = time.utc if hash.key?(:utc)
time
end
def hydrate_datetime(hash)
DateTime.parse(hash[:datetime])
end
def hydrate_model(hash)
hydrate_hash(hash)
model_name = hash.delete(:model)
model = get_model(model_name)
model.new(hash)
end
def get_model(model_name)
self.models ||= {}
self.models[model_name] ||= self.class.const_get(model_name)
end
def hash?(value)
value.is_a?(Hash)
end
def array?(value)
value.is_a?(Array)
end
def array_as_hash?(value)
if hash?(value) && value.present?
keys = value.keys.sort
keys.each_with_index.all? do |key, i|
key.to_s == i.to_s
end
else
false
end
end
def model?(value)
hash_with_key?(value, :model)
end
def number?(value)
hash_with_key?(value, :number)
end
def date?(value)
hash_with_key?(value, :date)
end
def time?(value)
hash_with_key?(value, :time)
end
def datetime?(value)
hash_with_key?(value, :datetime)
end
def hash_with_key?(value, key)
hash?(value) && value.key?(key)
end
def is_nil?(value)
same_string?(value, NIL)
end
def true?(value)
same_string?(value, true)
end
def false?(value)
same_string?(value, false)
end
def same_string?(value, string)
value.is_a?(String) && value == string.to_s
end
end
end
| true
|
9de644c0672a45a5fb2bb5278f7c3c9e24192f17
|
Ruby
|
pritckat/ruby-class-variables-and-class-methods-lab-v-000
|
/lib/song.rb
|
UTF-8
| 845
| 3.421875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Song
attr_accessor :name, :artist, :genre
@@count = 0
@@genres = []
@@artists = []
@@song_names = []
def initialize(name, artist, genre)
@name = name
@artist = artist
@genre = genre
@@count += 1
@@genres << genre
@@artists << artist
@@song_names << name
end
def self.count
@@count
end
def self.genres
@@genres.uniq!
end
def self.artists
@@artists.uniq!
end
def self.genre_count
genre_count = {}
unique_genres = @@genres.uniq
unique_genres.each do |ugen|
genre_count[ugen] = @@genres.count {|gen| gen == ugen}
end
genre_count
end
def self.artist_count
artist_count = {}
unique_artists = @@artists.uniq
unique_artists.each do |uart|
artist_count[uart] = @@artist.count {|art| art == uart}
end
artist_count
end
| true
|
cfef48952a1ec0456e012a8617350b71c1cbd44d
|
Ruby
|
SeaRbSg/little-schemer
|
/sotoseattle/sandbox/mathless_calc/spec/mathless_calculator_spec.rb
|
UTF-8
| 1,071
| 2.921875
| 3
|
[] |
no_license
|
require 'spec_helper'
describe 'MathlessCalculator' do
let(:calc) { MathlessCalculator.new }
it { calc.compute('(2 + 2)').must_equal '4' }
it { calc.compute('(2 + (1 + 1))').must_equal '4' }
it { calc.compute('(((1 + 1) + (1 + 1)) + (1 + 1))').must_equal '6' }
it { calc.compute('(3 x 2)').must_equal '6' }
it { calc.compute('((1 x (1 x (1 x (1 x (1 x 1))))) x 1)').must_equal '1' }
it { calc.compute('((1 x (1 x (1 x (1 x (1 x 1))))) x 0)').must_equal '0' }
it { calc.compute('((2 x (1 x (1 x (1 x (1 x 1))))) x 1)').must_equal '2' }
it { calc.compute('(2 ^ 3)').must_equal '8' }
it { calc.compute('(1 ^ 10)').must_equal '1' }
it { calc.compute('(1 ^ 0)').must_equal '1' }
# it { calc.compute('(2 ^ 9)').must_equal '512' } # a bit slow
it { calc.compute('((1 + 1) ^ 3)').must_equal '8' }
it { calc.compute('((2 x 2) ^ (1 + 1))').must_equal '16' }
it { calc.compute('(3 - 2)').must_equal '1' }
it { calc.compute('((4 - 1) - (3 - 1))').must_equal '1' }
it { calc.compute('(((2 ^ 2) - (1 x 1)) - (3 - (0 + 1)))').must_equal '1' }
end
| true
|
a8bf57d822753e44b4ddb9fc7c567c921768811d
|
Ruby
|
gradyzhu/W2D3
|
/TDD_testing/lib/w2d3_testing.rb
|
UTF-8
| 770
| 3.515625
| 4
|
[] |
no_license
|
class Array
def my_uniq
self.reduce([]) do |uniqs, el|
unless uniqs.include?(el)
uniqs.push(el)
else
uniqs
end
end
end
def two_sum
pairs = []
i = 0
while i < self.length - 1
j = i + 1
while j < self.length
pairs << [i ,j] if self[i] + self[j] == 0
j += 1
end
i += 1
end
return pairs.my_uniq
end
def my_transpose #[[1,2],[3,4],[5,6]]
transpose_array = Array.new(self[0].length) { [] }
(0...self.length).each do |row_idx| #self.length == 3
(0...self[row_idx].length).each do |col_idx| #self[row_idx].length == 2
transpose_array[col_idx][row_idx] = self[row_idx][col_idx]
end
end
transpose_array
end
end
| true
|
14e372d9a8593f333751828a820fe1d002ed406d
|
Ruby
|
morganp/s1-e2
|
/example/example1.rb
|
UTF-8
| 802
| 2.75
| 3
|
[] |
no_license
|
# examples/example1.rb
require '../lib/git_badge'
# In this example Anne and Dave create some Repositories (no commits)
app = GitBadge::Core.new
anne = app.new_person("Anne")
dave = app.new_person("Dave")
anne.new_repository("RMU-entance-exam")
anne.new_repository("RMU-s1-e1")
anne.new_repository("RMU-s1-e2")
anne.new_repository("RMU-final-exam")
require 'pp'
anne.repositories.each do |repo|
msg_start = ("Repository: " + repo.name).ljust(30)
puts msg_start + " Commits: " + repo.commit_count.to_s
end
#Dave has a go
dave.new_repository("RMU-entance-exam")
dave.new_repository("RMU-s1-e1")
dave.new_repository("RMU-s1-e2")
dave.new_repository("RMU-final-exam")
# Anne tries to reach level 2 repo master
anne.new_repository("RMU-Project")
anne.new_repository("RMU-s1-e3")
app.report
| true
|
7dd2f6727358a83f72e8569e0afd6fa25b1e302f
|
Ruby
|
mmish321/typeSpeed
|
/main.rb
|
UTF-8
| 3,437
| 3.28125
| 3
|
[] |
no_license
|
require 'gosu'
require_relative "word"
require_relative "z_order"
require_relative "compound_word"
class GameWindow < Gosu::Window
WIDTH = 1200
HEIGHT= 500
def initialize
super WIDTH, HEIGHT
self.caption = "TYPESPEED"
@background_image = Gosu::Image.new("media/background.jpeg", :tileable => true)
@font = Gosu::Font.new(20)
@bigfont= Gosu::Font.new(40)
@biggestfont = Gosu::Font.new(100)
data = File.read("words.txt")
@words_on_screen = []
@words = data.split(", ")
@health = 100
@score = 0
@time = Gosu::milliseconds
@beep = Gosu::Sample.new("media/beep.wav")
@explosion_sound = Gosu::Sample.new("media/explosion.wav")
self.text_input =Gosu::TextInput.new
end
def update
check_words_at_bottom
move_words
check_time
check_health
compare_user_input_to_word
end
def draw
@background_image.draw(0, 0, 0)
@bigfont.draw("TYPESPEED", 10, 10, ZOrder::UI, 1.0, 1.0, 0xff_00ffff )
@font.draw("Score: #{@score}", 10, 50, ZOrder::UI, 1.0, 1.0, 0xff_ffffff)
@font.draw("Health: #{@health}",10, 70, ZOrder::UI, 1.0, 1.0, 0xff_ffffff)
@words_on_screen.each {|word| word.draw}
if @health <= 0
@biggestfont.draw("GAME OVER", 300, 150, ZOrder::UI, 1.0, 1.0, 0xff_ff0000)
@biggestfont.draw("Final Score : #{@score}", 300, 300, ZOrder::UI, 1.0, 1.0, 0xff_ff0000 )
end
end
def button_down(id)
if id == Gosu::KbReturn && @health <= 0 #Restart function
initialize
elsif id == Gosu::KbEscape
close
end
end
private
def move_words
@words_on_screen.each { |word|
word.move
}
end
def check_words_at_bottom
@words_on_screen.each { |word|
if word.explode_drawn?
@explosion_sound.play
@health -= 10
@words_on_screen.delete(word)
end
}
end
def check_time
if (Gosu::milliseconds - @time) >= 60000 #once time is greater than a minute then game gets harder
if (Gosu::milliseconds - @time) % 6000 <= self.update_interval #adds a compound and normal word every 6 seconds
@words_on_screen.push(Word.new(@words[(rand(@words.length-1)).to_i]))
@words_on_screen.push(CompoundWord.new(@words[(rand(@words.length-1)).to_i] + @words[(rand(@words.length-1)).to_i]))
elsif (Gosu::milliseconds - @time) % 3000 <= self.update_interval #adds a normal word every 3 seconds
@words_on_screen.push(Word.new(@words[(rand(@words.length-1)).to_i]))
end
elsif (Gosu::milliseconds - @time) % 3000 <= self.update_interval # under a minute, only add 1 normal word every 3 seconds
@words_on_screen.push(Word.new(@words[(rand(@words.length-1)).to_i]))
end
end
def check_health
if @health <= 0
@words_on_screen.clear
end
end
def compare_user_input_to_word
if Gosu::button_down? Gosu::KbReturn #once enter is pressed, the text input is compared to words on the screen
@words_on_screen.each { |word|
if self.text_input.text.eql? word.string
@score += word.points
@beep.play
@words_on_screen.delete(word)
end
}
self.text_input = nil
self.text_input =Gosu::TextInput.new #reseting the user input after they press enter for next typed word
end
end
end
window = GameWindow.new
window.show
| true
|
ac3ffa7343121d27cd642f8eb2b7ec6d1d442c23
|
Ruby
|
magnet-inc/blue_print
|
/lib/blue_print/context.rb
|
UTF-8
| 1,560
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
require 'active_support/inflector'
require 'blue_print'
require 'blue_print/active_if'
class BluePrint::Context
def self.resolve(name)
if name.respond_to?(:active?)
return name
else
name.to_s.classify.sub(/(Context)?$/, 'Context').safe_constantize
end
end
def self.active_ifs
@active_ifs ||= []
end
def self.active_if(*names, &logic)
active_ifs.concat(
names.map { |name| BluePrint::ActiveIf.resolve(name) }.reject(&:nil?)
)
active_ifs.push(BluePrint::ActiveIf.new(&logic)) if logic
end
def self.context_name
@context_name ||= name.to_s.underscore.to_sym
end
def self.active?
BluePrint.env.fetch(context_name) do
!!active_ifs.inject(active_ifs.first.try(:active?)) do |memo, active_if|
memo && active_if.active?
end
end
end
def self.deactive?
!active?
end
def self.activate!
BluePrint.env[context_name] = true
end
def self.deactivate!
BluePrint.env[context_name] = false
end
def self.casting
@casting ||= Hash.new { |casting, klass| casting[klass] = [] }
end
def self.cast(actor, as: [])
as = [as] unless as.kind_of?(Array)
as.map! { |role| role.is_a?(Module) ? role : role.to_s.safe_constantize }
casting[actor] = casting[actor] | as
reaction!
end
def self.action!
return if @acted
casting.each_pair do |klass, roles|
roles.each do |role|
klass.send(:prepend, role)
end
end
@acted = true
end
def self.reaction!
@acted = false
action!
end
end
| true
|
2c26c42b86632254ae9b36fc8709417adf136ddf
|
Ruby
|
arfo90/game-of-life-Ruby
|
/lib/seeder.rb
|
UTF-8
| 487
| 2.890625
| 3
|
[] |
no_license
|
require_relative 'tools'
class Seeder
attr_accessor :land_grid
def initialize(land_grid)
raise ArgumentError, "Land Grid is not yet set. should pass 2d array" unless land_grid.is_a?(Array)
@land_grid = land_grid
end
def seed
seeded_world = @land_grid
tools = Tools.new()
@land_grid[0].size.times do |i|
@land_grid[0].size.times do |j|
seeded_world[i][j] = tools.rand_seed
end
end
seeded_world
end
def seeded_world
self.seed
end
end
| true
|
20779b940493ae2daf3138a0fd1017156475e339
|
Ruby
|
houweifeng/itunes_receipt_encoder
|
/lib/itunes_receipt_encoder/in_app.rb
|
UTF-8
| 2,884
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require 'itunes_receipt_encoder/utils'
require 'itunes_receipt_encoder/asn1'
##
# ItunesReceiptEncoder
module ItunesReceiptEncoder
##
# ItunesReceiptEncoder::InApp
class InApp
include Utils
attr_accessor :quantity, :product_id, :transaction_id,
:original_transaction_id, :web_order_line_item_id, :item_id
timestamp_accessor :purchase_date, :original_purchase_date, :expires_date,
:cancellation_date
def initialize(attrs = {})
attrs.each { |key, val| send("#{key}=", val) }
end
def to_asn1_set
ASN1.set [
asn1_quantity,
asn1_product_id,
asn1_transaction_id,
asn1_original_transaction_id,
asn1_web_order_line_item_id,
(asn1_purchase_date if purchase_date),
(asn1_original_purchase_date if original_purchase_date),
(asn1_expires_date if expires_date),
(asn1_cancellation_date if cancellation_date)
]
end
def to_plist_hash(options = {})
hash = {
'quantity' => quantity,
'product-id' => product_id,
'item-id' => item_id,
'transaction-id' => transaction_id,
'original_transaction-id' => original_transaction_id,
'web-order-line-item-id' => web_order_line_item_id,
'purchase-date' => gmt_time(purchase_date),
'original-purchase-date' => gmt_time(original_purchase_date),
'expires-date-formatted' => gmt_time(expires_date)
}
hash.merge!(
'purchase-date-ms' => ms_time(purchase_date),
'original-purchase_date_ms' => ms_time(original_purchase_date),
'expires-date' => gmt_time(expires_date)
) unless options[:no_ms_dates]
hash.merge!(
'purchase-date-pst' => pst_time(purchase_date),
'original-purchase-date-pst' => pst_time(original_purchase_date),
'expires-date-pst' => pst_time(expires_date)
) unless options[:no_pst_dates]
hash
end
private
def asn1_quantity
ASN1.sequence quantity, 1701, :integer
end
def asn1_product_id
ASN1.sequence product_id, 1702, :utf8_string
end
def asn1_transaction_id
ASN1.sequence transaction_id, 1703, :utf8_string
end
def asn1_original_transaction_id
ASN1.sequence original_transaction_id, 1705, :utf8_string
end
def asn1_web_order_line_item_id
ASN1.sequence web_order_line_item_id || 0, 1711, :integer
end
def asn1_purchase_date
ASN1.sequence asn1_time(purchase_date), 1704, :ia5_string
end
def asn1_original_purchase_date
ASN1.sequence asn1_time(original_purchase_date), 1706, :ia5_string
end
def asn1_expires_date
ASN1.sequence asn1_time(expires_date), 1708, :ia5_string
end
def asn1_cancellation_date
ASN1.sequence asn1_time(cancellation_date), 1712, :ia5_string
end
end
end
| true
|
6a2a8a4cad048b73df8c043e6006d4293336d58f
|
Ruby
|
gropax/gramz
|
/spec/gramz/cfg/grammar_spec.rb
|
UTF-8
| 1,661
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
module Gramz::CFG
describe Grammar do
include DSL
let(:gram) {
grammar(:S) {
rule "S -> SN V"
rule "SN -> 'Jean'"
rule "V -> dort"
}
}
describe "#non_terms" do
it "should return the non terminal symbols used in rules" do
expect(gram.non_terms.map(&:to_sym)).to match_array [:S, :SN, :V]
end
end
describe "#terms" do
it "should return the terminal symbols used in rules" do
expect(gram.terms.map(&:to_sym)).to match_array [:JEAN, :DORT]
end
end
describe "#==" do
it "should return true if grammars have same rules whatever their order" do
other = grammar(:S) {
rule "S -> SN V"
rule "V -> dort"
rule "SN -> 'Jean'"
}
expect(gram == other).to be true
end
it "should return false if grammars have different rules" do
other = grammar(:S) {
rule "S -> V SN"
rule "V -> dort"
rule "SN -> 'Jean'"
}
expect(gram == other).to be false
end
end
describe "#dup" do
it "should return a copy of self" do
expect(gram.dup).to eq gram
expect(gram.dup).not_to be gram
end
it "should also duplicate the @rules instance variable" do
hsh = gram.dup.send :rules_hash
expect(hsh).to eq gram.send :rules_hash
expect(hsh).not_to be gram.send :rules_hash
end
end
describe "#format" do
it "should return a string representation of self" do
expect(gram.format).to be_kind_of String
end
end
end
end
| true
|
6ea196f6d5c5e1782b42b665a71bcf8b95d78600
|
Ruby
|
kinjalchotaliya/RubyPractice
|
/6thFeb/customex.rb
|
UTF-8
| 316
| 3.65625
| 4
|
[] |
no_license
|
#custom Exception
puts "enter number1"
a = gets.chomp.to_i
puts "enter number2"
b = gets.chomp.to_i
class MyException < StandardError
def initialize(msg)
super
end
end
begin
raise MyException.new("number2 can't be zero") if b == 0
rescue => ex
puts ex
else
div = a / b
puts "division = #{div}"
end
| true
|
68c0ee01ace79f75d9bf7ea4b6df7cacfe0ccef1
|
Ruby
|
AdamPrusse/Coding-Exercises
|
/SmallOrder.rb
|
UTF-8
| 181
| 3.5625
| 4
|
[] |
no_license
|
puts "what would you like to order?"
answer = gets.chomp
p "You ordered #{answer}"
puts "what else would you like"
answer2 = gets.chomp
p "You ordered #{answer} and #{answer2}"
| true
|
df94be294095152f1fdf7be224f0d25df936441c
|
Ruby
|
melliemello/Rails-Girls
|
/01-Simple-Idea-App-wSinatra/models/model.rb
|
UTF-8
| 1,185
| 2.640625
| 3
|
[] |
no_license
|
class Model
attr_reader :id
def initialize(attributes = {}, id = nil)
self.attributes = attributes
@id = id
end
def self.db
Database.new("./database/#{name.downcase}s.yaml")
end
def self.all
db.all.map do |id, attributes|
new(attributes, id)
end
end
def self.find(id)
attributes = db.all[id]
new(attributes, id) if attributes
end
def self.delete_many(array_if_ids)
array_if_ids.each do |id|
find(id.to_i).delete
end
end
def attributes
@attributes ||= {}
end
def attributes=(new_attributes = {})
filtered_attributes = new_attributes.select {|key, _| self.class.attribute_names.include? key}
@attributes = self.attributes.merge(filtered_attributes)
end
def save
self.class.db.save(self.attributes, id)
end
def delete
self.class.db.delete(id)
end
def method_missing(method_name, *args)
attribute_name = method_name.to_s.chomp("=").to_sym
if not self.attributes.include?(attribute_name)
return super
elsif method_name.to_s.end_with?("=")
self.attributes[attribute_name] = args[0]
else
self.attributes[method_name]
end
end
end
| true
|
31529cf3f72b44f81cbe8a227d97d23ad492e0bb
|
Ruby
|
ChuckBTaylor/triangle-classification-web-082817
|
/lib/triangle.rb
|
UTF-8
| 736
| 3.578125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Triangle
attr_reader :sides
def initialize(side1, side2, side3)
@sides = [side1, side2, side3]
end
def valid?
sorted = self.sides.sort
if sorted.any? {|side| side <= 0}
false
else
sorted[0] + sorted [1] <= sorted[2] ? false : true
end
end
def check_type
sorted = self.sides.sort
if sorted[0] == sorted[2]
:equilateral
elsif sorted[1] == sorted[2] || sorted[0] == sorted[1]
:isosceles
else
:scalene
end
end
def kind
if self.valid?
self.check_type
else
begin
raise TriangleError
end
end
end
end
class TriangleError < StandardError
def message
"Invalid Triangle"
end
end
| true
|
e95ba7746a0fc4edee4f8c5896a98d870bd929df
|
Ruby
|
smhaggerty/CodeQuizzes_solutions
|
/ruby/beginner/quiz_3.rb
|
UTF-8
| 3,453
| 4.65625
| 5
|
[] |
no_license
|
# What does this code print?
# x = "HELLO"
# if true
# puts x
# end
"HELLO"
# What does this code print?
# if true
# y = "Baaaaah"
# end
# puts y
"Baaaaah"
# Identify the elements of this code:
# def my_name()
# return("Zoo Lander")
# end
# "def my_name()" is the function declation statement, which indicates that we are
# defining a function named my_name. "def" is the function declaration keyword. "return("Zoo Lander")"
# is the statement executed in the body of the function, which
# returns the string "Zoo Lander". "end" is a keyword indicating the end of the function definition
# What is the difference between the code in the previous example and this code?
# def my_name
# "Zoo Lander"
# end
# The semantics are the same. In Ruby, if there is no return statement, then
# a method will return the value returned by the last statement. Furthermore, if
# a method takes no arguments then the parentheses can be omitted from the definition.
# What does the following code print?
# def my_name()
# return("Zoo Lander")
# end
# puts my_name()
"Zoo Lander"
# What does the following code return?
# def add(x, y)
# return(x + y)
# end
# add(3, 5)
8
# What does the following code print?
# y = 10
# def add_one_to_variable(variable)
# variable += 1
# return(variable)
# end
# puts add_one_to_variable(y)
11
# What does the following code print.
# cool = "Beans"
# def dinner_plans()
# puts cool
# end
# dinner_plans()
# Raises an error because 'cool' is not defined in the scope of the function
NameError: undefined local variable or method
# What does the following code print?
# def blah()
# my_var = "my_var has been defined"
# end
# puts my_var
# my_var is not defined in the scope of the puts call
NameError: undefined local variable or method 'my_var'
# What does the following code print?
# def cray()
# lyric = "Stuff is cray cray"
# puts lyric
# end
# cray()
# lyric is defined in scope of cray() so there is no error
"Stuff is cray cray"
# What does the following code print?
# def first_name()
# return("Otto")
# end
# def last_name()
# return("Mation")
# end
# def full_name()
# first_name() + " " + last_name()
# end
# puts full_name()
"Otto Mation"
# What does the following code print?
# def square_of_number(number)
# return(number * number)
# end
# def cube_of_number(number)
# return(number * square_of_number(number))
# end
# puts cube_of_number(2)
8
# Define a method that multiplies two numbers together.
def multiply(a, b)
a * b
end
# Define a method called silly_check() that takes a number argument and returns "The number is less than 5" if
# the argument is less than 5 and "The number is greater than or equal to 5" otherwise.
def silly_check(num)
num < 5 ? "The number is less than 5" : "The number is greater than or equal to 5"
end
# Define a method called funify() that takes an array as an argument and adds the word "fun" to the end of the array.
def funify(array)
array << "fun"
end
# Define a method called more_fun() that replaces the first element of an array with the word "FUN FUN".
def more_fun(array)
array[0] = "FUN FUN"
return array
end
# Define a method called increment_variable() that takes a variables as an argument and adds one to it.
def increment_variable(variable)
variable += 1
end
| true
|
8c7a159b206b550d09e325432ed705a48e69a8b7
|
Ruby
|
coremessage/evil_events
|
/spec/support/spec_support/fake_data_generator.rb
|
UTF-8
| 2,402
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module SpecSupport::FakeDataGenerator
module_function
BOOL_VARIANTS = [true, false].freeze
INT_RANGE = (0..100)
FLOAT_RANGE = (0.0..100.0)
STR_LENGTH = 10
STR_LETTERS = (('a'..'z').to_a | ('A'..'Z').to_a).freeze
FACTORY_METHODS = %i[
gen_int
gen_float
gen_str
gen_obj
gen_bool
gen_symb
gen_class
gen_proc
gen_lambda
].freeze
EVENT_ATTR_CONSTRAINTS = {
primitive: nil,
strict: '::Strict',
coercible: '::Coercible',
form: '::Form',
json: '::Json',
maybe_strict: '::Maybe::Strict',
maybe_coercible: '::Maybe::Coercible'
}.freeze
EVENT_ATTR_TYPES = {
primitive: %i[
Any Nil Symbol Class True False Bool Int Float Decimal String Date DateTime Time Array Hash
].freeze,
strict: %i[
Nil Symbol Class True False Bool Int Float Decimal String Date DateTime Time Array Hash
].freeze,
coercible: %i[
String Int Float Decimal Array Hash
].freeze,
form: %i[
Nil Date DateTime Time True False Bool Int Float Decimal Array Hash
].freeze,
json: %i[
Nil Date DateTime Time Decimal Array Hash
].freeze,
maybe_strict: %i[
Class String Symbol True False Int Float Decimal Date DateTime Time Array Hash
].freeze,
maybe_coercible: %i[
String Int Float Decimal Array Hash
].freeze
}.freeze
def gen_int(range = INT_RANGE)
rand(range)
end
def gen_float(range = FLOAT_RANGE)
rand(range)
end
def gen_str(max_len: STR_LENGTH, only_letters: false)
only_letters ? Array.new(STR_LENGTH) { STR_LETTERS.sample }.join : SecureRandom.hex(max_len)
end
def gen_obj
Object.new
end
def gen_bool
BOOL_VARIANTS.sample
end
def gen_symb(max_len: STR_LENGTH, only_letters: false)
gen_str(max_len: max_len, only_letters: only_letters).to_sym
end
def gen_seed
send(FACTORY_METHODS.sample)
end
def gen_class
Class.new
end
def gen_proc
proc {}
end
def gen_lambda
-> {}
end
def gen_event_attr_type(constraint = :primitive)
type_name = EVENT_ATTR_TYPES[constraint].sample
type_constraint = EVENT_ATTR_CONSTRAINTS[constraint]
type_const = "EvilEvents::Shared::Types#{type_constraint}::#{type_name}"
Object.const_get(type_const)
end
end
| true
|
89c88b72119bb612db5cd6277ba5b8bf3a9504d9
|
Ruby
|
joegnelson/swagger-codegen
|
/samples/client/petstore/ruby/lib/pet_api.rb
|
UTF-8
| 11,368
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require "uri"
class PetApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Update an existing pet
#
# @param body Pet object that needs to be added to the store
# @return void
def self.updatePet (body, opts={})
query_param_keys = []
headerParams = {}
# set default values and merge with input
options = {
:'body' => body
}.merge(opts)
#resource path
path = "/pet".sub('{format}','json')
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = ['application/json', 'application/xml', ]
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
# http body (model)
post_body = nil
if body != nil
if body.is_a?(Array)
array = Array.new
body.each do |item|
if item.respond_to?("to_body".to_sym)
array.push item.to_body
else
array.push item
end
end
post_body = array
else
if body.respond_to?("to_body".to_sym)
post_body = body.to_body
else
post_body = body
end
end
end
# form parameters
form_parameter_hash = {}
Swagger::Request.new(:PUT, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make
end
# Add a new pet to the store
#
# @param body Pet object that needs to be added to the store
# @return void
def self.addPet (body, opts={})
query_param_keys = []
headerParams = {}
# set default values and merge with input
options = {
:'body' => body
}.merge(opts)
#resource path
path = "/pet".sub('{format}','json')
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = ['application/json', 'application/xml', ]
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
# http body (model)
post_body = nil
if body != nil
if body.is_a?(Array)
array = Array.new
body.each do |item|
if item.respond_to?("to_body".to_sym)
array.push item.to_body
else
array.push item
end
end
post_body = array
else
if body.respond_to?("to_body".to_sym)
post_body = body.to_body
else
post_body = body
end
end
end
# form parameters
form_parameter_hash = {}
Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make
end
# Finds Pets by status
# Multiple status values can be provided with comma seperated strings
# @param status Status values that need to be considered for filter
# @return array[Pet]
def self.findPetsByStatus (status, opts={})
query_param_keys = [:status]
headerParams = {}
# set default values and merge with input
options = {
:'status' => status
}.merge(opts)
#resource path
path = "/pet/findByStatus".sub('{format}','json')
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = []
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
# http body (model)
post_body = nil
# form parameters
form_parameter_hash = {}
response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make.body
response.map {|response| Pet.new(response) }
end
# Finds Pets by tags
# Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
# @param tags Tags to filter by
# @return array[Pet]
def self.findPetsByTags (tags, opts={})
query_param_keys = [:tags]
headerParams = {}
# set default values and merge with input
options = {
:'tags' => tags
}.merge(opts)
#resource path
path = "/pet/findByTags".sub('{format}','json')
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = []
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
# http body (model)
post_body = nil
# form parameters
form_parameter_hash = {}
response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make.body
response.map {|response| Pet.new(response) }
end
# Find pet by ID
# Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
# @param pet_id ID of pet that needs to be fetched
# @return Pet
def self.getPetById (pet_id, opts={})
query_param_keys = []
headerParams = {}
# set default values and merge with input
options = {
:'pet_id' => pet_id
}.merge(opts)
#resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = []
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
# http body (model)
post_body = nil
# form parameters
form_parameter_hash = {}
response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make.body
Pet.new(response)
end
# Updates a pet in the store with form data
#
# @param pet_id ID of pet that needs to be updated
# @param name Updated name of the pet
# @param status Updated status of the pet
# @return void
def self.updatePetWithForm (pet_id, name, status, opts={})
query_param_keys = []
headerParams = {}
# set default values and merge with input
options = {
:'pet_id' => pet_id,
:'name' => name,
:'status' => status
}.merge(opts)
#resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = ['application/x-www-form-urlencoded', ]
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
# http body (model)
post_body = nil
# form parameters
form_parameter_hash = {}
form_parameter_hash["name"] = name
form_parameter_hash["status"] = status
Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make
end
# Deletes a pet
#
# @param api_key
# @param pet_id Pet id to delete
# @return void
def self.deletePet (api_key, pet_id, opts={})
query_param_keys = []
headerParams = {}
# set default values and merge with input
options = {
:'api_key' => api_key,
:'pet_id' => pet_id
}.merge(opts)
#resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = []
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
headers[:'api_key'] = api_key
# http body (model)
post_body = nil
# form parameters
form_parameter_hash = {}
Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make
end
# uploads an image
#
# @param pet_id ID of pet to update
# @param additional_metadata Additional data to pass to server
# @param file file to upload
# @return void
def self.uploadFile (pet_id, additional_metadata, file, opts={})
query_param_keys = []
headerParams = {}
# set default values and merge with input
options = {
:'pet_id' => pet_id,
:'additional_metadata' => additional_metadata,
:'file' => file
}.merge(opts)
#resource path
path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# pull querystring keys from options
queryopts = options.select do |key,value|
query_param_keys.include? key
end
# header parameters
headers = {}
_header_accept = 'application/json, application/xml'
if _header_accept != ''
headerParams['Accept'] = _header_accept
end
_header_content_type = ['multipart/form-data', ]
headerParams['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'
# http body (model)
post_body = nil
# form parameters
form_parameter_hash = {}
form_parameter_hash["additionalMetadata"] = additional_metadata
form_parameter_hash["file"] = file
Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body, :form_params => form_parameter_hash }).make
end
end
| true
|
d632782e2f6373a6f6ba9f1f079396ddf8b58c64
|
Ruby
|
codewithirene567/prime-ruby-onl01-seng-ft-050420
|
/prime.rb
|
UTF-8
| 523
| 3.625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
binding"pry"
def prime?(integer)
lowest_prime_number = 2
if integer > 1
range = (lowest_prime_number...integer-1).to_a
range.none? {|testing| integer % testing == 0 }
else
false
end
end
#if Prime.prime?(@nth_value)
#puts ("#{@nth_value} is prime")
#else
# puts ("This is not a prime number.")
#end
#(1..10).to_a
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#A number is prime if they are only divisible by themselves and one
#new_array.each { |number| (number % number || number % 1)}
| true
|
01acbfb3a99d80cd63feeb402311389db20218f9
|
Ruby
|
BettinaBF/rails-yelp-mvp
|
/db/seeds.rb
|
UTF-8
| 300
| 2.859375
| 3
|
[] |
no_license
|
require 'faker'
puts 'Creating 5 fake restaurants...'
5.times do
restaurant = Restaurant.create!(
name: "\"The #{Faker::Hipster.word}\"",
address: Faker::Address.street_address,
category: ['chinese', 'italian', 'japanese', 'french', 'belgian'].sample(1)[0]
)
end
puts 'Finished!'
| true
|
008d16eaa37deb0c5686354d086a4db9114a4422
|
Ruby
|
mark-rushakoff/cf-interface
|
/spec/component_announcement_message_spec.rb
|
UTF-8
| 2,980
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
require "spec_helper"
require "cf_message_bus/mock_message_bus"
require "cf/interface"
require "cf/interface/component_announcement_message"
describe CF::Interface::ComponentAnnouncementMessage do
subject(:message) do
described_class.new(
component_type: "component_type",
index: 99,
host: "192.0.2.1",
credentials: {
user: "a_username",
password: "a_password"
}
)
end
let(:valid_serialization_hash) do
{
type: "component_type",
index: 0,
host: "192.0.2.1",
credentials: ["user", "password"]
}
end
it "has the right channel" do
expect(described_class.channel).to eq("vcap.component.announce")
end
it "raises if initialized with unknown keys" do
expect {
described_class.new(
some_unknown_key: "foo"
)
}.to raise_error(ArgumentError, /some_unknown_key/)
end
describe "#is_valid?" do
it "is true for the valid serialization" do
valid_obj = described_class.deserialize(valid_serialization_hash.to_json)
expect(valid_obj).to be_valid
end
%w(component_type index host credentials).each do |key|
it "is false if the attr '#{key}' is nil" do
message.public_send("#{key}=", nil)
expect(message).to_not be_valid
end
end
it "is false when credentials[:user] is nil" do
message.credentials.delete(:user)
expect(message).to_not be_valid
end
it "is false when credentials[:password] is nil" do
message.credentials.delete(:user)
expect(message).to_not be_valid
end
end
describe "malformed serializations" do
%w(type index host credentials).each do |key|
it "raises if the key '#{key}' is missing" do
invalid_hash = valid_serialization_hash.dup
invalid_hash.delete(key.to_sym)
expect {
described_class.deserialize(invalid_hash.to_json)
}.to raise_error(/#{key}/)
end
end
it "raises if given invalid JSON" do
expect {
described_class.deserialize(":)")
}.to raise_error
end
end
describe "with a message bus" do
let(:message_bus) { ::CfMessageBus::MockMessageBus.new }
let(:interface) { ::CF::Interface.new(message_bus) }
it "can be transmitted" do
interface = CF::Interface.new(CfMessageBus::MockMessageBus.new)
received = false
described_class.on_receive(interface) do |component_announcement_message, error|
expect(error).to be_nil
expect(component_announcement_message.component_type).to eq("component_type")
expect(component_announcement_message.index).to eq(99)
expect(component_announcement_message.host).to eq("192.0.2.1")
expect(component_announcement_message.credentials).to eq(
user: "a_username",
password: "a_password"
)
received = true
end
message.broadcast(interface)
expect(received).to eq(true)
end
end
end
| true
|
b0a707a7a33761d2304ab2fce6c78132b6fd33c0
|
Ruby
|
stormpath/stormpath-rails
|
/lib/stormpath/rails/facebook_auth_code_exchange.rb
|
UTF-8
| 1,191
| 2.515625
| 3
|
[] |
no_license
|
module Stormpath
module Rails
class FacebookAuthCodeExchange
FACEBOOK_EXCHANGE_URL = URI('https://graph.facebook.com/v2.7/oauth/access_token')
attr_reader :root_url, :code
def initialize(root_url, code)
raise(NoFacebookAuthorizationError) if code.nil?
@root_url = root_url
@code = code
end
def access_token
@access_token ||= fetch_access_token(exchange_auth_code.body)
end
private
def exchange_auth_code
http_client.post(FACEBOOK_EXCHANGE_URL, encoded_params)
end
def fetch_access_token(response_body)
JSON.parse(response_body)['access_token']
end
def encoded_params
URI.encode_www_form(
client_id: Stormpath::Rails.config.web.facebook_app_id,
client_secret: Stormpath::Rails.config.web.facebook_app_secret,
redirect_uri: URI.join(root_url, Stormpath::Rails.config.web.social.facebook.uri).to_s,
code: code
)
end
def http_client
client = Net::HTTP.new(FACEBOOK_EXCHANGE_URL.host, FACEBOOK_EXCHANGE_URL.port)
client.use_ssl = true
client
end
end
end
end
| true
|
6788b0e7fb5414817468603d097bc2ce9beb4caf
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/hamming/2f131292c4cb4ff6b7f69e816df1c05b.rb
|
UTF-8
| 295
| 3.375
| 3
|
[] |
no_license
|
class Hamming
def Hamming.compute(strand_x, strand_y)
[strand_x.size,strand_y.size].min.times.map{ |c|
Hamming.diff(strand_x[c], strand_y[c])
}.reduce(0,:+)
end
private
def Hamming.diff(char_x, char_y)
if(char_x != char_y)
1
else
0
end
end
end
| true
|
6028e38c06d3c46e612ebb286c421a0004ede566
|
Ruby
|
harhogefoo/AtCoder_Ruby
|
/ABC033/C.rb
|
UTF-8
| 133
| 2.640625
| 3
|
[] |
no_license
|
n = gets.chomp.split("+")
count = 0
n.each do |input|
next if input == "0"
next if eval(input) == 0
count += 1
end
puts count
| true
|
ad57f9b759bf79dae7c569bf30ea0dfb1c3f452e
|
Ruby
|
barnzdan/ruby
|
/example3.rb
|
UTF-8
| 218
| 3.765625
| 4
|
[] |
no_license
|
#!/usr/bin/env ruby
class Square
def initialize(side_length)
@side_length = side_length
end
def area
@side_length * @side_length
end
end
a = Square.new(10)
b = Square.new(5)
puts a.area
puts b.area
| true
|
3aad615ce8d5cc50c000055cb5f61ac31ef93072
|
Ruby
|
SimonDein/launch
|
/course_101/exercises/easy_7/combine_two_lists.rb
|
UTF-8
| 1,086
| 4.53125
| 5
|
[] |
no_license
|
# Write a method that combines two Arrays passed in as arguments,
# and returns a new Array that contains all elements from both Array arguments, with the elements taken in alternation.
# You may assume that both input Arrays are non-empty, and that they have the same number of elements.
# solution 1
def interleave(arr1, arr2)
index = 0
combined_arr = []
loop do
combined_arr << arr1[index]
combined_arr << arr2[index]
index += 1
break if index >= arr1.length
end
combined_arr
end
# solution 2
def interleave(arr1, arr2)
combined_arr = []
arr1.each_with_index { |arr1_object, index| combined_arr << [arr1_object, arr2[index]]}
combined_arr.flatten
end # This can be shortened down like the following:
def interleave(arr1, arr2)
combined_arr = []
arr1.each_with_index { |obj, index| combined_arr << obj << arr2[index]}
combined_arr
end
# further exploration
# See if you can rewrite interleave to use zip.
def interleave(arr1, arr2)
arr1.zip(arr2).flatten
end
puts interleave([1, 2, 3], ['a', 'b', 'c']) == [1, 'a', 2, 'b', 3, 'c']
| true
|
87ffb5784fbc39e3ac5f4220d76a464b0bf6f507
|
Ruby
|
cjferm16/RB101
|
/Exercises/Easy 9/grocery_list.rb
|
UTF-8
| 260
| 3.828125
| 4
|
[] |
no_license
|
def buy_fruit(array)
newarr = []
array.map do |array|
array[1].times do
newarr << array[0]
end
end
p newarr
end
p buy_fruit([["apples", 3], ["orange", 1], ["bananas", 2]]) ==
["apples", "apples", "apples", "orange", "bananas","bananas"]
| true
|
9fc23e505974eb620020ea879388530c59e1b0d5
|
Ruby
|
TimothyFell/enigma
|
/lib/date_offsets.rb
|
UTF-8
| 437
| 3.609375
| 4
|
[] |
no_license
|
## date_offsets.rb
require 'pry'
require 'date'
class DateOffsets
attr_reader :date
def initialize(date)
@date = date
end
# Input: date object
# Output: array of 4 date-based offset integers
def convert_date
(@date.strftime('%d') + @date.strftime('%m') + @date.strftime('%y')).to_i
end
def square_date
(convert_date ** 2)
end
def date_offset_array
square_date.digits.reverse[-4..-1]
end
end
| true
|
5ffe41684a5d090003b99cff9762255d6630914e
|
Ruby
|
Shinya-Org-SS/localmap
|
/db/seeds.rb
|
UTF-8
| 1,153
| 2.625
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'csv'
# 駅CSVファイルパス
STATION_PATH = "db/data/stations.csv"
# 駅カラム指定定数
STATION_CSVROW_STATION_ID = 0
STATION_CSVROW_NAME = 2
STATION_CSVROW_LINE_ID = 5
STATION_CSVROW_ADDRESS = 8
STATION_CSVROW_LNG = 9
STATION_CSVROW_LAT = 10
# 駅CSVを読み込みテーブルに保存
CSV.foreach(STATION_PATH) do |row|
station_id = row[STATION_CSVROW_STATION_ID]
name = row[STATION_CSVROW_NAME]
line_id = row[STATION_CSVROW_LINE_ID]
address = row[STATION_CSVROW_ADDRESS]
lng = row[STATION_CSVROW_LNG]
lat = row[STATION_CSVROW_LAT]
Station.find_or_create_by(
:station_id => station_id,
:line_id => line_id,
:name => name,
:address => address,
:lat => lat,
:lng => lng
)
end
| true
|
d2b9a1c580cde1c7e752c9ad7d61436d32c6700b
|
Ruby
|
AntonioJacksonII/futbol
|
/test/season_stats_test.rb
|
UTF-8
| 1,906
| 2.84375
| 3
|
[] |
no_license
|
require_relative 'test_helper'
class SeasonStatsTest < Minitest::Test
def setup
@season_stats = SeasonStats.new('./data/teams.csv', './test/fixtures/truncated_game_stats2.csv')
end
def test_initialization
assert_instance_of SeasonStats, @season_stats
end
def test_season_stat_percentage
assert_equal 0.67, @season_stats.season_stat_percentage("20122013", "Mike Babcock", :win).round(2)
assert_equal 0.22, @season_stats.season_stat_percentage("20122013", 3, :shot).round(2)
end
def test_winningest_coach
assert_equal "Claude Julien", @season_stats.winningest_coach("20122013")
end
def test_worst_coach
assert_equal "John Tortorella", @season_stats.worst_coach("20122013")
end
def test_most_accurate_team
assert_equal "LA Galaxy", @season_stats.most_accurate_team("20122013")
end
def test_least_accurate_team
assert_equal "New England Revolution", @season_stats.least_accurate_team("20122013")
end
def test_most_tackles
assert_equal "FC Dallas", @season_stats.most_tackles("20122013")
end
def test_fewest_tackles
assert_equal "New England Revolution", @season_stats.fewest_tackles("20122013")
end
def test_info_by_season
names = ["John Tortorella", "Claude Julien", "Mike Babcock", "Joel Quenneville"]
ids = [3, 6, 17, 16]
tackles = {3=>114, 6=>115, 17=>97, 16=>82}
shots = {3=>23, 6=>28, 17=>19, 16=>25}
goals = {3=>5, 6=>8, 17=>6, 16=>4}
wins = {6=>3, 16=>1, 17=>2}
games = @season_stats.games_by_season("20122013", @season_stats.game_stats)
assert_equal names ,@season_stats.coaches_by_season(games)
assert_equal ids ,@season_stats.team_ids_by_season(games)
assert_equal tackles ,@season_stats.team_tackles_by_season(games)
assert_equal shots ,@season_stats.team_shots_by_season(games)
assert_equal goals ,@season_stats.team_goals_by_season(games)
assert_equal wins ,@season_stats.team_wins_by_season(games)
end
end
| true
|
f1de5a4d95c1e1296b7bdc2cdb00d980da030f2f
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/difference-of-squares/b04e27c093db47689ecdaec1b665237e.rb
|
UTF-8
| 260
| 3.640625
| 4
|
[] |
no_license
|
class Squares
def initialize value
@value = value
end
def square_of_sums
(1..@value).inject(:+)**2
end
def sum_of_squares
(1..@value).collect { |v| v**2 }.inject(:+)
end
def difference
square_of_sums - sum_of_squares
end
end
| true
|
0abe7c8998f513c12fdbc9e2ba322e3402b7afbc
|
Ruby
|
jennianelson/pokemon-scraper-v-000
|
/lib/pokemon.rb
|
UTF-8
| 731
| 3.296875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Pokemon
attr_accessor :name, :type, :db, :id, :hp
def initialize (name:, type:, db:, id:, hp: nil)
@name = name
@type = type
@db = db
@id = id
@hp = hp
end
def self.save(name, type, db)
sql = <<-SQL
INSERT INTO pokemon(name, type)
VALUES (?, ?)
SQL
db.execute(sql, name, type)
end
def self.find(id_num, db)
sql = <<-SQL
SELECT * FROM pokemon
WHERE id = ?
SQL
pokemon_row = db.execute(sql, id_num).flatten
self.new(id: pokemon_row[0], name: pokemon_row[1], type: pokemon_row[2], db: db)
end
def alter_hp(new_hp, db)
sql = <<-SQL
UPDATE pokemon SET hp = ? WHERE id = ?
SQL
db.execute(sql, new_hp, self.id)
end
end
| true
|
d09908bf423bf57a5b2c28f856ea731357ab35ad
|
Ruby
|
CedrickFlocon/AdventOfCode
|
/2015/day_07/operation.rb
|
UTF-8
| 417
| 3.578125
| 4
|
[
"WTFPL"
] |
permissive
|
class Operation
def initialize(action, values)
@values = values
@action = action
end
def compute
case @action
when 'LSHIFT'
@values[0] << @values[1]
when 'RSHIFT'
@values[0] >> @values[1]
when 'AND'
@values[0] & @values[1]
when 'OR'
@values[0] | @values[1]
when 'NOT'
~@values[0]
else
@values[0]
end
end
end
| true
|
2fd70955a1aaebe4588453e6455dd72ca8574ca4
|
Ruby
|
ESTCOSMO/mitsumottaro
|
/app/models/dst_item_form.rb
|
UTF-8
| 578
| 2.546875
| 3
|
[] |
no_license
|
class DstItemForm
include ActiveModel::Model
attr_accessor :name, :category_id, :sub_category_id, :type
validates :name, presence: true
validates :type, presence: true
with_options if: :sub_category? do |sub_category|
sub_category.validates :category_id, presence: true
end
with_options if: :story? do |story|
story.validates :category_id, presence: true
story.validates :sub_category_id, presence: true
end
private
def sub_category?
self.type == 'sub_category'
end
def story?
self.type == 'story'
end
end
| true
|
0398b27024d70e8c9e1b313dc57a59afd9f84fa9
|
Ruby
|
knollt/square_array-v-000
|
/square_array.rb
|
UTF-8
| 290
| 3.578125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def square_array(array)
new_array = []
array.each {|arr|
new_array.push (arr * arr)}
return new_array
end
# OPTION 2
# def square_array(array)
# squared_array = []
# array.each do |num|
# square = num ** 2
# squared_array << square
# end
# squared_array
# end
| true
|
c5e3755784b91dcfb331763b6a4f832c9640d537
|
Ruby
|
infrablocks/ruby_terraform
|
/spec/ruby_terraform/models/list_spec.rb
|
UTF-8
| 11,114
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'spec_helper'
# rubocop:disable Layout/LineContinuationLeadingSpace
describe RubyTerraform::Models::List do
describe '#value' do
it 'returns the underlying array with values still boxed' do
value = [V.known(1), V.known(2), V.known(3)]
list = described_class.new(
value,
sensitive: true
)
expect(list.value).to(eq(value))
end
end
describe '#unbox' do
it 'returns underlying array after unboxing scalar items' do
list = described_class.new(
[V.known(1), V.known(2), V.known(3)],
sensitive: true
)
expect(list.unbox).to(eq([1, 2, 3]))
end
it 'returns underlying array after unboxing list items' do
list = described_class.new(
[V.list([V.known(1), V.known(2)]), V.list([V.known(3)])],
sensitive: true
)
expect(list.unbox).to(eq([[1, 2], [3]]))
end
it 'returns underlying array after unboxing map items' do
list = described_class.new(
[
V.map(
{
first: V.known(1),
second: V.known(2)
}
),
V.map(
{
third: V.known(3)
}
)
],
sensitive: true
)
expect(list.unbox).to(eq([{ first: 1, second: 2 }, { third: 3 }]))
end
end
describe '#known?' do
it 'returns true' do
list = described_class.new(
[V.known(1), V.known(2), V.known(3)],
sensitive: true
)
expect(list).to(be_known)
end
end
describe '#sensitive?' do
it 'returns true when sensitive' do
list = described_class.new(
[V.known(1), V.known(2), V.known(3)],
sensitive: true
)
expect(list).to(be_sensitive)
end
it 'returns false when not sensitive' do
list = described_class.new(
[V.known(1), V.known(2), V.known(3)],
sensitive: false
)
expect(list).not_to(be_sensitive)
end
it 'returns false by default' do
list = described_class.new(
[V.known(1), V.known(2), V.known(3)]
)
expect(list).not_to(be_sensitive)
end
end
describe '#render' do
it 'returns [] on one line when list is empty' do
value = []
list = described_class.new(value)
expect(list.render).to(eq('[]'))
end
it 'returns a string of the rendered scalar item over three lines ' \
'when list has one scalar item' do
item = V.known('some-value')
value = [item]
list = described_class.new(value)
expect(list.render)
.to(eq(
"[\n" \
" #{item.render}\n" \
']'
))
end
it 'returns a string of the rendered scalar items over many lines ' \
'when list has many items' do
item1 = V.known('some-value-1')
item2 = V.known('some-value-2')
item3 = V.known('some-value-3')
value = [item1, item2, item3]
list = described_class.new(value)
expect(list.render)
.to(eq(
"[\n" \
" #{item1.render},\n" \
" #{item2.render},\n" \
" #{item3.render}\n" \
']'
))
end
it 'returns a string of the rendered list-valued items over ' \
'many lines, correctly indented when list has many list-valued ' \
'entries' do
value1 = V.list([V.known('some-value-1'), V.known('some-value-2')])
value2 = V.list([V.known('some-value-3'), V.known('some-value-4')])
list = described_class.new([value1, value2])
expect(list.render)
.to(eq(
"[\n" \
" [\n" \
" \"some-value-1\",\n" \
" \"some-value-2\"\n" \
" ],\n" \
" [\n" \
" \"some-value-3\",\n" \
" \"some-value-4\"\n" \
" ]\n" \
']'
))
end
it 'returns a string of the rendered map-valued items over ' \
'many lines, correctly indented when list has many map-valued entries' do
sub_key1 = :some_key1
sub_key2 = :some_key2
value1 = V.known('some-value-1')
value2 = V.known('some-value-2')
item1 = V.map({
sub_key1 => value1,
sub_key2 => value2
})
item2 = V.map({
sub_key1 => value1,
sub_key2 => value2
})
list = described_class.new([item1, item2])
expect(list.render)
.to(eq(
"[\n" \
" {\n" \
" some_key1 = \"some-value-1\"\n" \
" some_key2 = \"some-value-2\"\n" \
" },\n" \
" {\n" \
" some_key1 = \"some-value-1\"\n" \
" some_key2 = \"some-value-2\"\n" \
" }\n" \
']'
))
end
it 'returns a string of the rendered complex nested valued items over ' \
'many lines, correctly indented when list has many complex nested ' \
'valued items' do
sub_key1 = :some_key1
sub_key2 = :some_key2
value1 = V.known('some-value-1')
value2 = V.known('some-value-2')
child1 = V.map({
sub_key1 => value1,
sub_key2 => value2
})
child2 = V.map({
sub_key1 => value1,
sub_key2 => value2
})
item1 = V.list([child1, child2])
list = described_class.new([item1])
expect(list.render)
.to(eq(
"[\n" \
" [\n" \
" {\n" \
" some_key1 = \"some-value-1\"\n" \
" some_key2 = \"some-value-2\"\n" \
" },\n" \
" {\n" \
" some_key1 = \"some-value-1\"\n" \
" some_key2 = \"some-value-2\"\n" \
" }\n" \
" ]\n" \
']'
))
end
it 'correctly renders omitted values in lists' do
value1 = V.omitted
value2 = V.known('some-value-1')
value3 = V.known('some-value-2')
value4 = V.omitted
list = described_class.new([value1, value2, value3, value4])
expect(list.render)
.to(eq(
"[\n" \
" ...,\n" \
" \"some-value-1\",\n" \
" \"some-value-2\",\n" \
" ...\n" \
']'
))
end
it 'adds single unit of extra indentation when level is 1' do
item = V.known('some-value')
value = [item]
list = described_class.new(value)
expect(list.render(level: 1))
.to(eq(
"[\n" \
" #{item.render}\n" \
' ]'
))
end
it 'adds multiple units of extra indentation when level is ' \
'greater than 1' do
item = V.known('some-value')
value = [item]
list = described_class.new(value)
expect(list.render(level: 3))
.to(eq(
"[\n" \
" #{item.render}\n" \
' ]'
))
end
it 'uses the provided indent when specified' do
item = V.known('some-value')
value = [item]
list = described_class.new(value)
expect(list.render(indent: ' '))
.to(eq(
"[\n" \
" #{item.render}\n" \
']'
))
end
it 'correctly combines level and indent' do
item = V.known('some-value')
value = [item]
list = described_class.new(value)
expect(list.render(level: 1, indent: ' '))
.to(eq(
"[\n" \
" #{item.render}\n" \
' ]'
))
end
end
describe '#==' do
it 'returns true when the state and class are the same' do
value1 = described_class.new(%w[some-value-1 some-value-2])
value2 = described_class.new(%w[some-value-1 some-value-2])
expect(value1).to(eq(value2))
end
it 'returns false when the value is different' do
value1 = described_class.new(%w[some-value-1 some-value-2])
value2 = described_class.new(%w[some-value-2 some-value-3])
expect(value1).not_to(eq(value2))
end
it 'returns false when sensitive is different' do
value1 = described_class.new(
%w[some-value-1 some-value-2], sensitive: true
)
value2 = described_class.new(
%w[some-value-1 some-value-2], sensitive: false
)
expect(value1).not_to(eq(value2))
end
it 'returns false when the classes are different' do
value1 = described_class.new(
%w[some-value-1 some-value-2], sensitive: true
)
value2 = Class.new(described_class)
.new(%w[some-value-1 some-value-2], sensitive: true)
expect(value1).not_to(eq(value2))
end
end
describe '#hash' do
it 'has the same result when the state and class are the same' do
value1 = described_class.new(%w[some-value-1 some-value-2])
value2 = described_class.new(%w[some-value-1 some-value-2])
expect(value1.hash).to(eq(value2.hash))
end
it 'has a different result when the value is different' do
value1 = described_class.new(%w[some-value-1 some-value-2])
value2 = described_class.new(%w[some-value-2 some-value-3])
expect(value1.hash).not_to(eq(value2.hash))
end
it 'has a different result when sensitive is different' do
value1 = described_class.new(
%w[some-value-1 some-value-2], sensitive: true
)
value2 = described_class.new(
%w[some-value-1 some-value-2], sensitive: false
)
expect(value1.hash).not_to(eq(value2.hash))
end
it 'has a different result when the classes are different' do
value1 = described_class.new(
%w[some-value-1 some-value-2], sensitive: true
)
value2 = Class.new(described_class).new(
%w[some-value-1 some-value-2], sensitive: true
)
expect(value1.hash).not_to(eq(value2.hash))
end
end
describe '#inspect' do
it 'returns the underlying value with non-sensitive by default' do
list = described_class.new(
[V.known(1)]
)
expect(list.inspect)
.to(eq('[1 (known, non-sensitive)] (non-sensitive)'))
end
it 'returns the underlying value with non-sensitive when not sensitive' do
list = described_class.new(
[V.known(1)],
sensitive: false
)
expect(list.inspect)
.to(eq('[1 (known, non-sensitive)] (non-sensitive)'))
end
it 'returns the underlying value with sensitive when sensitive' do
list = described_class.new(
[V.known(1)],
sensitive: true
)
expect(list.inspect)
.to(eq('[1 (known, non-sensitive)] (sensitive)'))
end
end
end
# rubocop:enable Layout/LineContinuationLeadingSpace
| true
|
7f2b3f0e860b92375e78f029c7b64b1d28b8f10d
|
Ruby
|
omkz/algorithms-in-ruby
|
/lib/arrays_and_strings/dutch_national_flag_test.rb
|
UTF-8
| 365
| 2.578125
| 3
|
[] |
no_license
|
require_relative "../../test_helper"
require_relative "dutch_national_flag"
describe DutchNationalFlag do
describe "regular cases" do
it "should sort the array properly" do
expected = [3, 3, 2, 4, 4, 4, 4, 6, 8, 6, 5]
actual = DutchNationalFlag.run([3, 5, 2, 6, 8, 4, 4, 6, 4, 4, 3], 5)
expect(actual).must_equal expected
end
end
end
| true
|
75a3861c9c860faf8910a22c4e8e69e03a52885b
|
Ruby
|
d0nn13/VolcanoFTP
|
/lib/volcano_ftp/command/type.rb
|
UTF-8
| 479
| 2.609375
| 3
|
[] |
no_license
|
# ==== TYPE ====
# Sets the transfer mode
class FTPCommandType < FTPCommand
def initialize(arg)
super()
@code = 'TYPE'
@args << arg unless arg.nil?
end
def do(client)
begin
session = client.session
raise FTP530 unless session.logged?
session.set_mode(@args[0]) unless @args.length.zero?
FTPResponse200.new
rescue FTP530; FTPResponse.new(530, "Ya ain't logged.")
ensure
session.set_previous_cmd(self)
end
end
end
| true
|
dd93562e80b43fe7cd1435120bdd7396f9e2894d
|
Ruby
|
xuwupeng2000/rent
|
/spec/models/rent_history_spec.rb
|
UTF-8
| 1,179
| 2.53125
| 3
|
[] |
no_license
|
require File.dirname(__FILE__) + '/../spec_helper'
describe RentRecord do
def app
RentController
end
describe '#process_dataset' do
# We know it is valid so there is no point to test this
context 'CSV is invalid' do
it "should raise error" do
end
end
context 'valid CSV' do
before do
@data = RentRecord.process_dataset
@entry = @data.first
end
it "should retuan an array of hash" do
expect(@data).to be_a(Array)
expect(@entry).to be_a(Hash)
end
it "should parse the date string into date object" do
date = @entry.fetch(:date)
expect(date).to be_a(Date)
end
end
end
describe '#find' do
context 'with matched area' do
it "should return results" do
# area need to be exact match eg: Auckland is not going to find the result of auckland
results = RentRecord.find('auckland')
expect(results).not_to be_empty
end
end
context 'WITHOUT matched area' do
it "should return empty array" do
results = RentRecord.find('Nowhere')
expect(results).to eq []
end
end
end
end
| true
|
756f021f1e4f78b96f459063ff593d17218d2e26
|
Ruby
|
babyshoes/8th-light-tic-tac-toe
|
/lib/board.rb
|
UTF-8
| 2,213
| 3.53125
| 4
|
[] |
no_license
|
class Board
attr_reader :dimension
attr_accessor :squares, :turn_num, :copy, :winner, :game
def initialize(dimension = 3, squares = [], turn_num = 0)
@dimension = dimension
@squares = squares
@turn_num = turn_num
@dimension = dimension
populate_board if squares.all? {|row| row.empty?}
end
def populate_board
dimension.times { |i| squares << make_row(i) }
end
def make_square(row_num, i)
(row_num * dimension) + i
end
def make_row(id)
row = []
dimension.times { |i| row << make_square(id, i)}
row
end
def horizontal_win
row = squares.find do |row|
row.uniq.length == 1
end
@winner = row.first if row
end
def vertical_win
squares.first.each_with_index.find do |square, y|
squares_to_compare = []
dimension.times {|x| squares_to_compare << squares[x][y]}
win = squares_to_compare.uniq.length == 1
@winner = squares_to_compare.first if win
end
end
def diagonal_win
diagonal_win_right || diagonal_win_left
end
# CALLBACK HERE?
def diagonal_win_right
squares_to_compare = []
dimension.times {|x| squares_to_compare << squares[x][x]}
win = squares_to_compare.uniq.length == 1
@winner = squares_to_compare.first if win
end
def diagonal_win_left
squares_to_compare = []
dimension.times {|x| squares_to_compare << squares[x][dimension - x - 1]}
win = squares_to_compare.uniq.length == 1
@winner = squares_to_compare.first if win
end
def game_is_over
game_is_won || tie
end
def game_is_won
!!diagonal_win || !!vertical_win || !!horizontal_win
end
def tie
available_spaces.empty?
end
def available?(set)
set.select { |square| square.is_a? Integer }
end
def available_spaces
available?(squares.flatten)
end
def available_corners
corners = [squares[0][0], squares[0][dimension - 1], squares[dimension - 1][0], squares[dimension - 1][dimension - 1]]
available?(corners)
end
def get_position(id)
x = id / dimension
y = id % dimension
[x, y]
end
def make_copy
copy_of_squares = squares.map {|row| row.dup }
Board.new(dimension, copy_of_squares, turn_num)
end
end
| true
|
fee7ebda6c43a9b71543f2b2a80ba32c878670a0
|
Ruby
|
redfiche/WebKeno
|
/KenoRunner.rb
|
UTF-8
| 1,063
| 2.84375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require './Keno.rb'
require './KenoSerializer.rb'
first_race = ARGV[0].to_i
race_interval = ARGV[1].to_i
pick_interval = ARGV[2].to_i
puts "#{DateTime.now} starting KenoRunner"
logger = Logger.new 'keno.log'
keno = Keno.new
serializer = KenoSerializer.new
serializer.del_keno
next_race_time = Time.now + first_race
next_pick_time = Time.now + pick_interval
puts "First race at #{next_race_time}"
serializer.set_next_race_time next_race_time
started = false
while true do
if Time.now >= next_race_time then
started = true
puts "Starting race number: #{keno.next_race}"
keno = serializer.get_keno
keno.start_race
serializer.set_keno keno
next_race_time = Time.now + race_interval
serializer.set_next_race_time next_race_time
next_pick_time = Time.now
end
if Time.now >= next_pick_time and started then
puts "#{DateTime.now} Choosing next number"
keno = serializer.get_keno
keno.get_current_race.get_next
serializer.set_keno keno
next_pick_time += pick_interval
end
sleep 1
end
| true
|
565c6b9139108402db817bf6ed40b596cc19e581
|
Ruby
|
mdub/trunction
|
/spec/trunction_spec.rb
|
UTF-8
| 1,487
| 2.828125
| 3
|
[] |
no_license
|
# encoding: utf-8
require 'trunction'
describe Trunction do
let(:full_text) { Nokogiri::HTML::DocumentFragment.parse(input).text }
let(:total_words) { full_text.split.length }
let(:ellipsis) { "…" }
include Trunction
let(:result) do
truncate_html(input, max_words).gsub("\n", '')
end
describe "#truncate_html" do
context "given multiple paragraphs" do
let(:input) { "<p>One two three.</p> <p>Four five six.</p>" }
context "with max-length longer than input" do
let(:max_words) { total_words + 1 }
it "returns input intact" do
result.should == input
end
end
context "with max-length shorter than input" do
let(:max_words) { total_words - 1 }
it "drops block elements until beneath max-length" do
result.should == "<p>One two three.</p>"
end
end
context "with max-length shorter than first paragraph" do
let(:max_words) { 1 }
it "returns empty String" do
result.should == ""
end
end
end
context "given multiple paragraphs, wrapped in a div" do
let(:input) { "<div><p>One two three.</p> <p>Four five six.</p></div>" }
context "with max-length shorter than input" do
let(:max_words) { total_words - 1 }
it "drops elements until beneath max-length" do
result.should == "<div><p>One two three.</p></div>"
end
end
end
end
end
| true
|
130e04b039bf3234721a93e35437d793abad5398
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/cs169/combine_anagrams_latest/15919.rb
|
UTF-8
| 248
| 3.125
| 3
|
[] |
no_license
|
def combine_anagrams(words)
res={}
words.each do |word|
key=word.split('').sort.join
res[key] ||= []
res[key] << word
end
p res.values
end
combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'])
| true
|
3f449af40fa7c01ac97b02d482db43bf7d827dcb
|
Ruby
|
bantu4fun/nbp_rates
|
/lib/tasks/get_nbp_rates.rake
|
UTF-8
| 559
| 2.515625
| 3
|
[] |
no_license
|
require 'open-uri'
namespace :nbp do
desc "Get current year NBP exchange rates"
task :get_nbp_rates => :environment do
open("http://www.nbp.pl/kursy/xml/dir.txt", "r:utf-8") do |f|
files = f.readlines.map { |line| line.strip! }.select { |line| line =~ /^c[0-9]{3}z[0-9]{6}$/ }
files.each do |filename|
xml_parser = XmlParser.new(filename: "#{filename}.xml")
data = xml_parser.get_data
puts "Save exchange for: #{data[:exchanges][:name]}"
Exchange.new.save_current_rates(data)
end
end
end
end
| true
|
05d33f040e51041ce0911deaab5fa162afaa70c3
|
Ruby
|
Noirbot/advent
|
/2017/d13/sol.rb
|
UTF-8
| 320
| 3.109375
| 3
|
[] |
no_license
|
input = File.read("input.txt").split("\n").map { |line| line.split(': ').map(&:to_i) }
delay = 0
loop do
caught = false
input.each do |gate|
layer, range = gate
if (layer + delay) % ((range * 2) - 2) == 0
caught = true
break
end
end
break if !caught
delay = delay + 1
end
puts delay
| true
|
c6852994d4283dfb920fa98c5ae0666793e96510
|
Ruby
|
fidothe/box_dividers
|
/lib/box_dividers/pdf.rb
|
UTF-8
| 666
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'transformations'
require 'prawn'
module BoxDividers
class Pdf
include Prawn::View
attr_reader :bounding_box
def initialize(bounding_box)
@bounding_box = bounding_box
end
def draw_path(path)
points = path.points.dup
first_point = points.shift
close_and_stroke do
move_to first_point.x, first_point.y
points.each do |point|
line_to point.x, point.y
end
line_to first_point.x, first_point.y
end
end
def draw_divider
bounding_box.transform(Transformations.mm_to_pt).paths.each do |path|
draw_path(path)
end
end
end
end
| true
|
d73b6fe9adb2e44ba0c56e1a303ddb671b64aa93
|
Ruby
|
hack4reno2011/Reno-Collective
|
/app.rb
|
UTF-8
| 1,728
| 2.515625
| 3
|
[] |
no_license
|
require 'rubygems'
require 'sinatra'
require 'tropo-webapi-ruby'
require 'httparty'
require 'logger'
require 'net/http'
require 'uri'
use Rack::Session::Pool
get '/' do
"Hello World"
end
post '/start.json' do
tropo_session = Tropo::Generator.parse request.env["rack.input"].read
session[:callid] = tropo_session[:session][:id]
session[:truck_name] = 'not found'
tropo = Tropo::Generator.new do
ask( :name => 'truck', :bargein => true, :timeout => 60, :attempts => 2,
:say => [{:event => "timeout", :value => "Sorry, I did not hear anything."},
{:event => "nomatch:1 nomatch:2", :value => "Oops, I don't recognize that food truck'."},
{:value => "Which food truck do you want?"}],
:choices => { :value => "ken-jeez, calvins, gordmelt"})
on :event=>'continue', :next => "/process_truck.json"
end
tropo.response
end
post '/hangup.json' do
say "Thanks for nomming."
end
post '/the_answer.json' do
say "Test Answer"
end
post '/process_truck.json' do
tropo_session = Tropo::Generator.parse request.env["rack.input"].read
truck = tropo_session[:result][:actions][:truck][:value]
puts "Chosen truck: " + truck
tropo = Tropo::Generator.new do
say "You chose " + truck
if truck == "ken-jeez" then
foodtruckId = "4e4b3ef6aeb72792c3381b27"
puts "KENJI Routing..."
urlToGo = "http://api.foursquare.com/v2/venues/" +foodtruckId + "?client_id=" + ENV['FOURSQUARE_CLIENT_ID'] + "&client_secret=" + ENV['FOURSQUARE_CLIENT_SECRET']
puts "URLTOGO: " + urlToGo
foursquareInfo = JSON.parse(open(urlToGo).read)
puts "FOURSQUAREINFO: " + foursquareInfo
end
end
tropo.response
end
| true
|
c7a2dc9543a47ce0084899158cf73ebdc578786e
|
Ruby
|
howardbdev/regex-lab-v-000
|
/lib/regex_lab.rb
|
UTF-8
| 411
| 3.234375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def starts_with_a_vowel?(word)
word.scan(/\b[aeiouAEIOU]\w*/) != []
end
def words_starting_with_un_and_ending_with_ing(text)
text.scan(/\bun\w*ing\b/)
end
def words_five_letters_long(text)
text.scan(/\b\w{5}\b/)
end
def first_word_capitalized_and_ends_with_punctuation?(text)
text.scan(/\A[A-Z].*[.,?!]\z/) != []
end
def valid_phone_number?(phone)
phone.scan(/\(*\d{3}\s*[)-]*\s*\d{4}/) != []
end
| true
|
df9a6047e1422f2bead1747e02df568ab0d2b93e
|
Ruby
|
AllPurposeName/everyone_probably_calls_this_chatter
|
/app/services/new_message_service.rb
|
UTF-8
| 644
| 2.75
| 3
|
[] |
no_license
|
class NewMessageService
attr_reader :body, :chat_room, :filters, :user
def initialize(body:, user:, chat_room:, filters: default_filters)
@body = body
@chat_room = chat_room
@filters = filters
@user = user
end
def self.create!(body:, user:, chat_room:)
new(body: body, user: user, chat_room: chat_room).create!
end
def create!
Message.create!(body: filtered_body, user_id: user.id, chat_room_id: chat_room.id)
end
def filtered_body
filters.reduce(body) do |bod, filter|
bod = filter.filter(bod)
bod
end
end
def default_filters
[EmojiFilterService]
end
end
| true
|
91c6c479a75eaf9d2b4358e77b41d0fd5c96a79d
|
Ruby
|
SS-X-Ray/Xchedule-API
|
/services/update_activity.rb
|
UTF-8
| 324
| 2.5625
| 3
|
[] |
no_license
|
# Service object to update activity information
class UpdateActivity
def self.call(update_data:)
old_record = Activity[update_data['activity_id']]
update_data.keys.each do |key|
if key != 'activity_id'
old_record.send("#{key}=", update_data[key])
old_record.save
end
end
end
end
| true
|
2c8b7eb618adf584b0367db705ed5898ac017145
|
Ruby
|
StylesTrip/head-first-ruby
|
/get_number.rb
|
UTF-8
| 962
| 4.46875
| 4
|
[] |
no_license
|
# Get My Number Game
# Written by: me
puts "Welcome to 'Get My Number!'"
print "What's your name? "
input = gets
name = input.chomp
puts "Welcome, #{name}!"
#p input # same as puts input.inspect
# Store a random number for the player to guess
puts "I've got a random number between 1 and 100."
puts "Can you guess it?"
target = rand(100) + 1
num_guesses = 0
guessed_it = false
until num_guesses == 10 || guessed_it
puts "You've got #{10 - num_guesses} guesses left."
print "Make a guess: "
guess = gets.to_i
num_guesses += 1
# Compare the guess to the target.
# Print the appropriate message
if guess < target
puts "Oops. Your guess was LOW"
elsif guess > target
puts "Oops. Your guess was HIGH"
elsif guess == target
puts "Good job, #{name}!"
puts "You guessed my number in #{num_guesses} guesses!"
guessed_it = true
end
end
unless guessed_it
puts "Sorry. You didn't get my number. (It was #{target}.)"
end
| true
|
a55e6ecfdb3385ff83bf10296b7376e85164c79b
|
Ruby
|
isabellademetz/kwk-l1-ruby-object-attributes-lab-kwk-students-l1-la-070918
|
/lib/dog.rb
|
UTF-8
| 276
| 3.390625
| 3
|
[] |
no_license
|
# dog.rb
class Dog
def initalize(name,breed)
@name = name
@breed = breed
end
def name
@name = "Fido"
end
def name=(new_name)
@name = new_name
end
def breed
@breed = "Beagle"
end
def breed=(new_breed)
@breed = new_breed
end
end
| true
|
66a705dc8b868e7c5540cca54edc0071b718fa07
|
Ruby
|
sjmckinney/gruyere-test-demo
|
/features/support/base_page.rb
|
UTF-8
| 2,236
| 3.015625
| 3
|
[] |
no_license
|
require_relative 'utilities'
include Utilities
class BasePage
def initialize(driver)
@driver = driver
end
def visit(url)
@driver.get(url)
end
def find(locator)
begin
@driver.find_element(locator)
rescue Exception => e
$LOG.info("Error has occurred in : #{__FILE__} @ line #{__LINE__}")
$LOG.error("Error.message: #{e.message}")
$LOG.debug("Error.backtrace: #{e.backtrace}")
Utilities.take_screenshot(__FILE__, __LINE__)
raise
end
end
def find_all(locator)
@driver.find_elements(locator)
end
def enter_text(locator, text)
find(locator).send_keys(text)
end
def click_element(locator)
begin
@driver.find_element(locator).click
rescue Exception => e
$LOG.info("Error has occurred in : #{__FILE__} @ line #{__LINE__}")
$LOG.error("Error.message: #{e.message}")
$LOG.debug("Error.backtrace: #{e.backtrace}")
Utilities.take_screenshot(__FILE__, __LINE__)
raise
end
end
def click_button(locator)
click_element(locator)
$LOG.info("Clicked on #{locator.values[0]} button")
end
def click_link(locator)
click_element(locator)
$LOG.info("Clicked on #{locator.values[0]} link")
end
def get_text(locator)
begin
@driver.find_element(locator).text
rescue Exception => e
$LOG.info("Error has occurred in : #{__FILE__} @ line #{__LINE__}")
$LOG.error("Error.message: #{e.message}")
$LOG.debug("Error.backtrace: #{e.backtrace}")
Utilities.take_screenshot(__FILE__, __LINE__)
raise
end
end
def wait_for(seconds = 15, period = 0.2)
begin
Selenium::WebDriver::Wait.new(:timeout => seconds, :interval => period).until { yield }
rescue Exception => e
$LOG.info("Error has occurred in : #{__FILE__} @ line #{__LINE__}")
$LOG.error("Error.message: #{e.message}")
$LOG.debug("Error.backtrace: #{e.backtrace}")
Utilities.take_screenshot(__FILE__, __LINE__)
raise
end
end
def is_displayed?(locator)
begin
@driver.find_element(locator).displayed?
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
end
end
| true
|
d16de3f927a7173eeb868f67ae76c27d562dc19a
|
Ruby
|
PizzaPowered/firering
|
/lib/firering/instantiator.rb
|
UTF-8
| 1,024
| 2.609375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module Firering
module Instantiator
def instantiate(conn, data, base_key = nil, &callback)
instance = new
instance.connection = conn
attributes = data.is_a?(Hash) ? data : Yajl::Parser.parse(data, :symbolize_keys => true)
attributes = attributes[base_key] if base_key
attributes ||= Hash.new
attributes.each do |key, val|
setter = "#{key}="
value = ( key.to_s =~ /(_at|_on)$/ ) ? (Time.parse(val) rescue val) : val
if instance.respond_to?(setter)
instance.send(setter, value)
else
warning = "WARNING: Tried to set #{setter} #{value.inspect} on a #{instance.class} instance but it didn't respond. Probably the API got updated, please report this! (https://github.com/EmmanuelOga/firering/issues)"
if conn && conn.logger
conn.logger.warn warning
else
Kernel.warn warning
end
end
end
callback.call(instance) if callback
instance
end
end
end
| true
|
1fcd87d557f74547efddf6df97581b341513eadd
|
Ruby
|
chasenyc/bigO
|
/two_sum.rb
|
UTF-8
| 1,724
| 3.734375
| 4
|
[] |
no_license
|
def bad_two_sum?(arr, target_sum)
possibilites = []
(arr.length-1).times do |idx|
idy = 1 + idx
while idy < arr.length
possibilites << [arr[idx],arr[idy]]
idy += 1
end
end
possibilites.each do |pair|
return true if pair.first + pair.last == target_sum
end
false
end
arr = [0, 1, 5, 7]
bad_two_sum?(arr, 6)
bad_two_sum?(arr, 10)
# This is O(n^2 + n^2) AKA O(n^2)
def okay_two_sum?(arr, target_sum)
arr.sort
arr.each do |el|
new_target = target_sum - el
return true unless binary_search((arr - [el]), new_target).nil?
end
false
end
def binary_search(arr, target)
return nil if arr.size == 0
split = arr.size / 2
case target <=> arr[split]
when -1
binary_search(arr.take(split), target)
when 0
arr[split]
when 1
result = binary_search(arr.drop(split + 1), target)
(result.nil?) ? nil : (split + 1) + result
end
end
def pair_sum?(arr, target_sum)
# arr.sort
nums = Hash.new(0)
arr.each do |el|
nums[el] += 1
end
arr.each do |first|
new_target = target_sum - first
nums[first] -= 1
return true if nums[new_target] > 0
end
false
end
arr = [0, 1, 5, 7]
pair_sum?(arr, 6)
pair_sum?(arr, 10)
def four_sum?(arr, target_sum)
arr.sort
new_target = 0
nums = Hash.new(0)
arr.each do |el|
nums[el] += 1
end
arr.each do |first|
new_target = target_sum - first
nums[first] -= 1
end
arr.each do |second|
new_target = new_target - second
nums[second] -= 1
end
arr.each do |third|
new_target = new_target - third
p new_target
nums[third] -= 1
end
return true if nums[new_target] > 0
false
end
arr = [0, 1, 5, 7]
four_sum?(arr, 6)
four_sum?(arr, 13)
| true
|
4985abfafe3a8915a76b640afac9106424cd886a
|
Ruby
|
marinmari/Ruby_exo
|
/exo_09.rb
|
UTF-8
| 189
| 3.5625
| 4
|
[] |
no_license
|
puts "Quelle est ton année de naissance"
annee = gets.chomp.to_i
if annee < 2021
while annee <= 2021
puts "#{annee}"
annee += 1
end
else
puts "Impossible"
end
| true
|
26f2bde28c6bce3dc3c186e0205a4e64864dd740
|
Ruby
|
judesamp/simple_circle
|
/spec/app/entities/issue_spec.rb
|
UTF-8
| 1,826
| 2.640625
| 3
|
[] |
no_license
|
require_relative '../../spec_helper'
require_relative '../../../app/entities/issue'
require_relative '../../../app/entities/article'
require_relative '../../../app/entities/event'
require_relative '../../../app/entities/newsletter'
describe "Issue" do
let(:newsletter) {Newsletter.process({:title => "Original Newsletter Name"})}
let(:issue) {Issue.process}
let(:issue2) {Issue.process}
let(:article) {Article.process_and_create_draft({:title => "generic title"})}
let(:event) {Event.process_and_create_event_draft({:event_name => "event name"})}
let(:valid_attributes) {{:publish_on => Date.today}}
describe "validations" do
end
describe "initialization" do
it "creates an issue and sets the id" do
expect(issue.id).to eq 1
end
it "should have a issue number field" do
expect(issue.issue_number).to eq nil
end
it "should have a publish on date field" do
expect(issue.publish_on).to eq nil
end
it "should have a published on date field" do
expect(issue.published_on).to eq nil
end
end
describe "#add_article" do
it "adds an article to the issue" do
issue.add_article(article)
expect(issue.articles).to_not be_empty
end
it "adds an event to the issue" do
issue.add_event(event)
expect(issue.events).to_not be_empty
end
end
describe "#edit" do
it "sets the title field" do
issue.edit(valid_attributes)
expect(issue.publish_on).to eq Date.today
end
end
describe "issue added to newsletter" do
it "an issue is added to the organization's newsletter" do
newsletter.add_issue(issue)
expect(newsletter.issues.class).to eq DataMapper::Associations::OneToMany::Collection
end
end
end
| true
|
54c9cfe8f56de3f35a8a7611873d2ec7417bcea2
|
Ruby
|
Yamini-Gahlot/parrot-ruby-cb-gh-000
|
/parrot.rb
|
UTF-8
| 126
| 3.234375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Create method `parrot` that outputs a given phrase and
# returns the phrase
def parrot(st = "Squawk!")
puts st
return st
end
| true
|
9e8ec43d9092548bd2cb7044c5add24a901976f9
|
Ruby
|
lienne/BelleLearnsRuby
|
/loops_and_arrays.rb
|
UTF-8
| 1,389
| 4.625
| 5
|
[] |
no_license
|
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
# in a more traditional style found in other languages
for number in the_count
puts "This is count #{number}"
end
# same as above, but in a more Ruby style
# this and the next one are the preferred way
# Ruby for-loops are written
fruits.each do |fruit|
puts "A fruit of type: #{fruit}"
end
# also we can go through mixed lists too
# note this is yet another style, exactly like above
# but a different syntax
change.each {|i| puts "I got #{i}"}
# we can also build lists, first start with an empty one
elements = []
# then use the range operator to do 0 to 5 counts
(0..5).each do |i|
puts "adding #{i} to the list."
# pushes the i variable on the *end* of the list
elements.push(i)
end
# Note on Range Operators:
# two dots ".." are inclusive of both numbers.
# three dots "..." exclude the higher bound number.\
# Ex.:
# (1..5) ===> 1, 2, 3, 4, 5
# (1...5) ===> 1, 2, 3, 4
# ('a'..'d') ===> 'a', 'b', 'c', 'd'
#now we can print them out too
elements.each {|i| puts "Element was: #{i}"}
# First for-loop in this file, but in a Ruby style:
the_count.each do |number|
puts "This is count #{number} x2"
end
# Again:
the_count.each {|number| puts "This is count #{number} x3"}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.