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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
87f305b049062c4f9d4ba82f63a33b24e001cfa5 | Ruby | scalone/design-patterns-builder | /lib/design/patterns/builder/computer.rb | UTF-8 | 343 | 2.625 | 3 | [
"MIT"
] | permissive | module Design
module Patterns
module Builder
class Computer
attr_accessor :display, :motherboard, :drives
def initialize(display = :crt, motherboard = Motherboard.new, drives = [])
@display = display
@motherboard = motherboard
@drives = drives
end
end
end
end
end
| true |
ed215bf9678898cb83dbcf60467759a48e4cf7d3 | Ruby | edgcastillo/Programming_Challenges | /HackerRank/test_n.rb | UTF-8 | 167 | 3.796875 | 4 | [] | no_license | def reverse(str)
ar = []
(0..str.length).each do |x|
ar.push(str[str.length - x])
end
return ar.join('')
end
puts reverse("string")
puts reverse("Hello! World") | true |
0402ad3d666e496c646c014db6954248b52e8fd6 | Ruby | eljefesun/learn_ruby | /10_temperature_object/temperature.rb | UTF-8 | 1,797 | 4.6875 | 5 | [] | no_license | # Did not know what an options was or how to implement it. Found the use case on stack overflow and was able to implement it here. STill a little confusing but I get the general idea to have the option to use a has as an argument in your fuction. I was also able to re-use code from the previous temperature section.
class Temperature
attr_accessor :f, :c
def initialize (options={}) #Utilized options hash for fahrenheit/celsius methods
@f = options[:f]
@c = options[:c]
if f
@c = Temperature.ftoc(@f) #Converts fahrenheit to celsius using the Temperature.ftoc. Reused
else
@f = Temperature.ctof(@c) #Converts celcius to fahrenheit using the Temperature.ctof. Reused
end
end
def in_fahrenheit
@f
end
def in_celsius
@c
end
# method to convert fahrenheit to celsius where 1 degree F is 5/9 of 1 degree C. Re-used this code from the first exercise. Took some trial and error to get *self to work but was able to implement. I understand it's useful when there are instance methods, class methods and variables in order to distinguish your class method. Still not 100% clear on it but makes sense in this example.
def self.ftoc(f)
(f-32) * (5.0/9)
end
# method to convert celcius to fahrenheit
def self.ctof(c)
(c * (9/5.0)) + 32
end
# Factory Methods
def self.from_fahrenheit(temp)
self.new(:f => temp) #called on the Temperature class
end
def self.from_celsius(temp)
self.new(:c => temp) #called on the Temperature class
end
end
class Fahrenheit < Temperature #Fahrenheit subclass
def initialize(temp)
@f = temp
@c = Temperature.ftoc(@f)
end
end
class Celsius < Temperature #Celsius subclass
def initialize(temp)
@c = temp
@f = Temperature.ctof(@c)
end
end | true |
97335160a56c8459b989e432cb94323cf3076158 | Ruby | ArthuruhtrA/Spring-2015 | /Practicum-1/measure.rb | UTF-8 | 737 | 3.1875 | 3 | [] | no_license | require_relative 'measure_util'
# Measurement Conversion Main Driver
# For each line of CSV input from $stdin:
# - parse the input line into appropriate fields
# - convert the measurements to TSP
# - perform the computation if requested
# - output the result as "Result = xx TSP"
$stdin.each do |line|
## FILL IN ##
line = parse_line(line)
line[1] = line[1].to_i
case line.length
when 2
puts "Result = " + convert(line[0], line[1]).to_s + "TSP"
when 5
line[3] = line[3].to_i
puts "Result = " + compute(line[4].chomp, convert(line[0], line[1]),
convert(line[2], line[3])).to_s + "TSP"
else
raise ArgumentError, "Invalid amount of input"
end
end
| true |
1d298c50449c5f7e8011c02e094404129532413c | Ruby | SindhuVempati/restaurant-foods | /lib/support/string_extend.rb | UTF-8 | 145 | 3.078125 | 3 | [] | no_license | class String
#capitalizes the first letter of every word
def titelize
self.split(' ').collect{|word| word.capitalize}.join(" ")
end
end
| true |
52dfc56fa2b3b6b9c7160652a72f51761bdddae2 | Ruby | beck03076/monee | /lib/monee/comparison.rb | UTF-8 | 457 | 3.140625 | 3 | [
"MIT"
] | permissive | module Monee
# modularizing the comparison of money objects method in a separate module
module Comparison
include Comparable
# this is the spaceship operator overriding, this will take care of >, <, ==
#
# @params other [Money, Numeric]
# @return [Boolean]
def <=>(other)
if currency == other.currency
cents <=> other.cents
else
cents <=> other.convert_to_cents(currency)
end
end
end
end
| true |
e4050d49d6973b373a4fb0f3a4ad504e3d5f8823 | Ruby | StephenVarela/ruby_fundamentals1 | /exercise4.rb | UTF-8 | 1,285 | 4.25 | 4 | [] | no_license | ## Exercise 4
puts "Please Enter a Number"
user_number = gets.chomp.to_i
if(user_number >= 100)
puts "Thats a big number!"
else
puts "Why not dream bigger?"
end
## Part 2 identifying difference in age
puts "Tell me yo age foo!"
user_age = gets.chomp.to_i
if(user_age > 105)
puts "Im not sure i believe you!"
elsif(user_age > 25)
puts "you are #{user_age - 25} years older"
elsif(user_age == 25)
puts "We are the same age!"
elsif(user_age < 25 && user_age > 0)
puts "I am #{25 - user_age} years older"
else
puts "Oops Something is wrong"
end
## part 3 Name check
my_name = "Stephen".upcase
puts "Tell me yo name foo!"
user_name = gets.chomp.upcase
if(my_name == user_name)
puts "we have the same name"
else
puts "we do NOT have the same name"
end
## part4 checking name length
puts "Tell me your name again"
user_name = gets.chomp.upcase
if(user_name.length > 10)
puts "hi #{user_name}"
elsif(user_name.length < 10)
puts "hello #{user_name}"
else
puts "hey #{user_name}"
end
# Part 5 Secret number
puts "pick a number from 1 to 10"
secret_number = 7
user_guess = gets.chomp.to_i
if(secret_number == user_guess)
puts "you win!"
elsif((user_guess == secret_number) + 1 || (user_guess == secret_number) - 1)
puts "So close!"
else
puts "Try again"
end
| true |
25c45586e7351ad5d09f4bef8c55d43d0fe5d506 | Ruby | tiffaniechia/Learning-Ruby-4-Roman-Numerals | /lib/roman.rb | UTF-8 | 1,714 | 4.1875 | 4 | [] | no_license |
def divisible_by_1000(num)
num / 1000
end
def divisible_by_500(num)
remainder_1000=num%1000
remainder_1000 / 500
end
def divisible_by_100(num)
remainder_1000=num%1000
remainder_500=remainder_1000%500
remainder_500 / 100
end
def divisible_by_50(num)
remainder_1000=num%1000
remainder_500=remainder_1000%500
remainder_100=remainder_500%100
remainder_100/50
end
def divisible_by_10(num)
remainder_1000=num%1000
remainder_500=remainder_1000%500
remainder_100=remainder_500%100
remainder_50=remainder_100%50
remainder_50/10
end
def divisible_by_5(num)
remainder_1000=num%1000
remainder_500=remainder_1000%500
remainder_100=remainder_500%100
remainder_50=remainder_100%50
remainder_10=remainder_50%10
remainder_10/5
end
def divisible_by_1(num)
remainder_1000=num%1000
remainder_500=remainder_1000%500
remainder_100=remainder_500%100
remainder_50=remainder_100%50
remainder_10=remainder_50%10
remainder_5=remainder_10%5
end
def special_numbers(initial_result)
special_cases = {'DCCCC' => 'CM', 'CCCC' => 'CD', 'LXXXX' => 'XC', 'XXXX' => 'XL', 'VIIII' => 'IX', 'IIII' => 'IV'}
special_cases.each do |find, replace|
initial_result.gsub!(find, replace)
#method2:special_cases.each{|key,value| initial_result.gsub!(key,value})}
end
initial_result
end
puts "Please type a number between 1-8000".center(80)
input = gets.chomp.to_i
puts "This is how it would look like in roman numerals:".center(80)
arr= [
"M" * divisible_by_1000(input),
"D" * divisible_by_500(input),
"C" * divisible_by_100(input),
"L" * divisible_by_50(input),
"X" * divisible_by_10(input),
"V" * divisible_by_5(input),
"I" * divisible_by_1(input)
]
string = arr.join('')
puts special_numbers(string)
| true |
98b96eecad84639f067d56353837eee854e7dd6b | Ruby | apires89/food-delivery-reboot-767 | /app/views/sessions_view.rb | UTF-8 | 293 | 2.546875 | 3 | [] | no_license | require_relative "base_view"
class SessionsView < BaseView
def print_element(element,index)
puts "#{index + 1} -- #{element.username} -- #{element.role}"
end
def print_wrong_credentials
#print this if user inputs wrong password
puts "Wrong password... try again!"
end
end
| true |
7ee7bc0c736da2ae875c4bf2233d4453fabd0d21 | Ruby | jonmagic/git-gc-msgpack-object-experiment | /script/run | UTF-8 | 3,501 | 2.625 | 3 | [] | no_license | #!/usr/bin/env ruby
require "fileutils"
require "lorem"
require "msgpack"
require "open3"
require "pathname"
require "pry"
require "rugged"
class Runner
def initialize
@results_in_bytes = {
:parent_oid => [],
:oid => []
}
@obj = {}
@counter = nil
end
attr_reader :results_in_bytes
def project_root
Pathname(`pwd`.strip)
end
def tmp
project_root.join("tmp")
end
def bootstrap(key_count=1_000)
key_count.times do |n|
@counter = n
@obj["key_#{n}"] = Lorem::Base.new("words", rand(1..10)).output
end
File.open(project_root.join("fixture.msgpack"), "wb") do |file|
msg = MessagePack.pack(@obj)
file.write(msg)
end
end
def git(args)
Dir.chdir(tmp) do
stdout, status = Open3.capture2("git #{args}")
if status.success?
stdout
else
raise "git #{args} - failed :("
end
end
end
def object_size(oid)
results = git("verify-pack -v #{packfile_path}").split("\n")
lines = results.grep(/\A#{oid}/)
raise "more than one line" if lines.size > 1
line = lines.first
bytes = line.split(/\s/)[4]
bytes.to_f
rescue => error
binding.pry
raise error
end
def packfile_path
raise "More than one pack" if Dir[tmp.join(".git/objects/pack/*.pack")].size > 1
Dir[tmp.join(".git/objects/pack/*.pack")].first
end
def filename
"big_hash.msgpack"
end
def setup
FileUtils.mkdir_p(tmp)
FileUtils.cp(project_root.join("fixture.msgpack"), tmp.join(filename))
end
def repo
@repo ||= Rugged::Repository.init_at(tmp.to_s)
end
def make_commit
oid = Rugged::Blob.from_workdir(repo, filename)
index = repo.index
index.add(:path => filename, :oid => oid, :mode => 0100644)
options = {}
options[:tree] = index.write_tree(repo)
options[:author] = {
:email => "jonmagic@gmail.com",
:name => "JonMagic",
:time => Time.now
}
options[:committer] = options[:author]
options[:message] = "write #{filename}"
options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
options[:update_ref] = "HEAD"
commit = Rugged::Commit.create(repo, options)
index.write
oid
end
def make_change
@counter ||= @obj.keys.last.match(/key_(\d)/)[1].to_i
@obj["key_#{@counter+=1}"] = Lorem::Base.new("words", rand(1..10)).output
File.open(tmp.join(filename), "wb") do |file|
msg = MessagePack.pack(@obj)
file.write(msg)
end
end
def gc_and_print_kb(oids)
git("gc --quiet")
parent_oid, oid = Array(oids)
puts "parent oid: #{parent_oid}"
print parent_oid_bytes = object_size(parent_oid).to_i
puts " bytes"
@results_in_bytes[:parent_oid] << parent_oid_bytes
puts
return unless oid
puts "oid: #{oid}"
print oid_bytes = object_size(oid).to_i
puts " bytes"
@results_in_bytes[:oid] << oid_bytes
puts
end
def teardown
FileUtils.rm_r(tmp)
end
end
runner = Runner.new
begin
if key_count = ARGV.shift
runner.bootstrap(key_count.to_i)
end
runner.setup
parent_oid = runner.make_commit
runner.gc_and_print_kb(parent_oid)
puts "Packfile is #{File.size(runner.packfile_path)} bytes"
puts "-" * 60
100_000.times do |n|
runner.make_change
oid = runner.make_commit
runner.gc_and_print_kb([parent_oid, oid])
parent_oid = oid
puts "Packfile is #{File.size(runner.packfile_path)} bytes"
puts "-" * 60
end
ensure
runner.teardown
end
| true |
008de1f871133defb3623892412fa6c6ee207f42 | Ruby | clouder/learn_ruby | /04_simon_says/simon.rb | UTF-8 | 287 | 3.65625 | 4 | [] | no_license | def echo(text)
text
end
def shout(text)
text.upcase
end
def repeat(text, times = 2)
((text + ' ') * times).chop
end
def start_of_word(word, num)
word[0..num-1]
end
def first_word(text)
text.split[0]
end
def capitalize(word)
"Obama"
end
def titleize(text)
"Barack Obama"
end | true |
88e671a17756045fe137af70f8fb9876b5eb59b2 | Ruby | nekokat/codewars | /7kyu_1/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer.rb | UTF-8 | 339 | 3.4375 | 3 | [
"Unlicense"
] | permissive | #Kata: Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer
#URL: https://www.codewars.com/kata/5827bc50f524dd029d0005f2
def get_first_python(users)
res = users.keep_if{|i| i[:language] == "Python"}.first
res.nil? ? "There will be no Python developers" : "#{res[:first_name]}, #{res[:country]}"
end | true |
d575bb4f35d388117af9589564f9d6713de5d317 | Ruby | reneedv/antikythera | /lib/antikythera.rb | UTF-8 | 238 | 2.515625 | 3 | [
"MIT"
] | permissive | module BeforeAndAfter
def before?(time)
self < time
end
def after?(time)
self > time
end
end
class Time
include BeforeAndAfter
end
class DateTime
include BeforeAndAfter
end
class Date
include BeforeAndAfter
end | true |
7ec2d4def00b4a8e2b6048f7a54d84a614508920 | Ruby | inokappa/kaminari | /mrblib/kaminari/verify.rb | UTF-8 | 738 | 2.96875 | 3 | [] | no_license | module Kaminari
class Verify
def initialize(path)
@path = path
end
def verify
puts "分割した #{@path} を検証します.".color(:blue)
return 'Verification error.'.color(:red) unless merge_files == read_orignal_file
'Verified.'.color(:green)
end
def read_orignal_file
original = ""
File.open(@path, "r") do |f|
original = f.read
end
original
end
def merge_files
# 苦肉の策...
files = `ls #{@path}-*`
contents = []
files.split("\n").each do |file|
File.open(file, "r") do |f|
contents << f.read.tr("\n", "")
end
end
splited = contents.join(",")
splited
end
end
end
| true |
e44853e67680f454f4a875170c2f9f825b667c11 | Ruby | dragonnova5091/flashdrivebackup | /Projects in Programming/AI/text interpretation/text_interpretation.rb | UTF-8 | 1,332 | 3.390625 | 3 | [] | no_license |
class Reader
def initialize(sentence)
begin
@meanings = File.open("oldMeanings.txt", "a+")
@meanings_array = IO.readlines("oldMeanings.txt")
rescue
@meanings = File.new("oldMeanings.txt", "a+")
@meanings_array = IO.readlines("oldMeanings.txt")
end
#meaning = "P|this is a test"
found = false #used for later testing
count = 0
#puts "---" + sentence #test
#puts meanings_array
for line in @meanings_array
line = line.split(" -- ")
if sentence == line[0]
found = true
match = count
puts "match"
end
count += 1
end
if found == true
#puts "match" #test
puts "@@" + @meanings_array[match]
meaning = @meanings_array[match]
respond(meaning)
else
print "I need to learn what to do. Please tell me: "
meaning = gets.chomp
@meanings.syswrite("#{sentence} -- #{meaning}\n")
respond(meaning)
end
#if the prior responses are unfindable/a new file was created
if @meanings_array.length ==0
print "I need to learn what to do. Please tell me: "
meaning = gets.chomp
@meanings.syswrite("#{sentence} -- #{meaning}\n")
end
#meanings = File.close
end
def respond(meaning)
meaning = meaning.split("|")
if meaning[0] == "P"
puts meaning[1]
end
end
end
test = Reader.new("test sentence2")
sleep 3 | true |
976209849305674abd59728f5ba96364edfb3c86 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/filtered-submissions/befeebf2999e487c8b31b5e06bbed85b.rb | UTF-8 | 224 | 3.046875 | 3 | [] | no_license | def compute(str1 = "", str2 = "")
sequence_1, sequence_2, distance = str1.chars, str2.chars, 0
sequence_1.zip(sequence_2).each do |n1, n2|
distance += 1 unless (n1 == n2) or n2.nil?
end
distance
end | true |
c34184239d6102b2e662de30d607aa5e9a0f1518 | Ruby | markryall/lwnn | /lib/lwnn/operation.rb | UTF-8 | 291 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'lwnn/trace'
module Lwnn
class Operation
include Trace
def initialize name, &block
@name, @block = name, block
end
def evaluate state
trace "calling operation #{@name}"
@block.call state
end
def to_s
@name.to_s
end
end
end
| true |
183a5545ea698bdecc75f61c3b6128e31d4d5687 | Ruby | cavery8989/myrecipes | /test/models/recipe_test.rb | UTF-8 | 1,574 | 2.640625 | 3 | [] | no_license | require 'test_helper'
class RecipeTest < ActiveSupport::TestCase
def setup
@chef = Chef.create(name: "bob", email: "bob@bobby.com")
@recipe = @chef.recipes.build(name:"chicken hat", summary: "this is ha food and ha hat", description:"what you gonna do when they come for you chicken hat chicken hat")
end
test "Recipe should be valid" do
assert @recipe.valid?
end
test "chef_id should be present" do
@recipe.chef_id = nil
assert_not @recipe.valid?
end
test "Name should be present" do
@recipe.name = ""
assert_not @recipe.valid?
end
test "name should not be too long" do
@recipe.name = "a" * 101
assert_not @recipe.valid?
end
test "name lenghth should not be too short " do
@recipe.name = "aaaa"
assert_not @recipe.valid?
end
test "Summary must be present" do
@recipe.summary=""
assert_not @recipe.valid?
end
test "Summary lenght must not be too long" do
@recipe.summary = "a" * 151
assert_not @recipe.valid?
end
test "Summary length should not be too short" do
@recipe.name = "aaa"
assert_not @recipe.valid?
end
test "description must be present" do
@recipe.description=""
assert_not @recipe.valid?
end
test "description must not be too long " do
@recipe.description = "a" * 501
assert_not @recipe.valid?
end
test "Desription must not be too short" do
@recipe.description = "a" * 19
assert_not @recipe.valid?
end
end | true |
f809876b8d826385702009fa4996fc7c5525473c | Ruby | randyher/deck-of-cards-dumbo-web-100818 | /solution.rb | UTF-8 | 537 | 3.46875 | 3 | [] | no_license | require 'pry'
class Card
attr_reader :rank, :suit
def initialize(suit,rank)
@rank = rank
@suit = suit
end
end
class Deck
attr_reader :cards, :suit, :rank
def initialize
@suit = ["Spade", "Heart", "Club", "Diamond"]
@rank = ["A", "2", "3", "4", "5", "6","7", "8", "9","10", "J", "Q", "K"]
@cards = []
@rank.each do |rank|
@suit.each do |suit|
@cards << Card.new(suit, rank)
end
end
end
def choose_card
pull = self.cards.sample
self.cards.delete(pull)
end
end
| true |
ee0529ca1c6d6ad42cc8e64dafdf3719fdbc11b3 | Ruby | tbpgr/ruby_samples | /object/object_send.rb | UTF-8 | 1,005 | 2.5625 | 3 | [] | no_license | require 'tbpgr_utils'
class Hoge
def public_hoge
return "public_hoge" unless block_given?
yield
end
protected
def protected_hoge
return "protected_hoge" unless block_given?
yield
end
private
def private_hoge
return "private_hoge" unless block_given?
yield
end
end
hoge = Hoge.new
bulk_puts_eval binding, <<-EOS
hoge.send(:public_hoge)
hoge.send(:protected_hoge)
hoge.send(:private_hoge)
hoge.send(:public_hoge) { |e|p "block public_hoge" }
hoge.send(:protected_hoge) { |e|p "block protected_hoge" }
hoge.send(:private_hoge) { |e|p "block private_hoge" }
hoge.__send__(:public_hoge)
hoge.__send__(:protected_hoge)
hoge.__send__(:private_hoge)
hoge.__send__(:public_hoge) { |e|p "block public_hoge" }
hoge.__send__(:protected_hoge) { |e|p "block protected_hoge" }
hoge.__send__(:private_hoge) { |e|p "block private_hoge" }
EOS
__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval
https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
| true |
0174e507d97c7c2949fa00d87dad1fcfe902774e | Ruby | danielperzales/deli-counter-001-prework-web | /deli_counter.rb | UTF-8 | 500 | 3.828125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here
def line(katz_deli)
if katz_deli == []
puts "The line is currently empty."
else
puts "The line is currently: 1. Logan 2. Avi 3. Spencer"
end
end
def take_a_number(katz_deli, name)
katz_deli.push(name)
num = katz_deli.size
puts "Welcome, #{name}. You are number #{num} in line."
end
def now_serving(katz_deli)
if katz_deli == []
puts "There is nobody waiting to be served!"
else
name = katz_deli.shift
puts "Currently serving #{name}."
end
end
| true |
fa0cdf6bf83cca39b11e22d3f4e4b0635dce597f | Ruby | Smack247/BeastStreet | /app/controllers/posts_controller.rb | UTF-8 | 1,456 | 2.59375 | 3 | [] | no_license | class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy, :upvote, :downvote] #Cool this method inside of find_post will get the post by its parameters and only display for edit, destroy,
before_action :authenticate_user!, except: [:index, :show] #You need to sign up thank to devise
def index # def index make template
@posts = Post.all.order("created_at DESC")
end
def show
@comments = Comment.where(post_id: @post)
@random_post = Post.where.not(id: @post).order("RANDOM()").first
end
def new
@post = current_user.posts.build #redefining a post. We are saying that a post is created by a user
end
def create
@post = current_user.posts.build(post_params) #Makes sure the user id column in the posts table is filled in when we create a post
if @post.save
redirect_to @post #if it successfully saves redirect to post
else
render 'new' #if it doesn't keep showing them the new form
end
end
def edit
end
def update
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
def upvote
@post.upvote_by current_user
redirect_to :back
end
def downvote
@post.downvote_by current_user
redirect_to :back
end
private
def find_post
@post = Post.find(params[:id]) #we want this for the edit destory and update action
end
def post_params
params.require(:post).permit(:title, :link, :description, :image)
end
end
| true |
33b08faae3b8181c76949314149edf589236df14 | Ruby | chrisbgalileo/Ruby | /Lab1/Computer.rb | UTF-8 | 973 | 3.1875 | 3 | [] | no_license | class Computer
@@users = {}
def initialize username, password
@username = username
@password = password
@files = {}
end
def create nombre
if (@files.key?(nombre))
puts "Error"
else
@files[nombre] = Time.now
end
end
def rm nombre
if (@files.key?(nombre))
@files.delete(nombre)
else
puts "Error archivo no existente"
end
end
def ls *hash
if (hash[0] != nil)
if (hash[0].key?("sort"))
if (hash[0]["sort"] == "desc")
temp = @files.keys.sort.reverse
else
temp = @files.keys.sort
end
end
else
temp = @files.keys.sort
end
temp.size.times do |x|
print temp[x]
print " created at "
puts @files[temp[x]]
end
end
end
#Test
#computer = Computer.new("Chrisb", "achu")
#hash = Hash.new
#hash["sort"] = "desc"
#computer.create("bachos.rb")
#computer.create("lala.rb")
#computer.create("achui.rb")
#computer.rm("lala.rb")
#computer.ls(hash) | true |
0a950ef14bfc2e8293146b435eb4259ab58eff99 | Ruby | mjbotes/Expert_Systems_Ruby | /main.rb | UTF-8 | 4,692 | 2.59375 | 3 | [] | no_license | #!/usr/bin/ruby -w
require "./toRPN"
require "./solveRPN"
require "./colorize"
puts "██╗ ██╗███████╗██╗ ██████╗ ██████╗ ███╗ ███╗███████╗ ████████╗ ██████╗
██║ ██║██╔════╝██║ ██╔════╝██╔═══██╗████╗ ████║██╔════╝ ╚══██╔══╝██╔═══██╗
██║ █╗ ██║█████╗ ██║ ██║ ██║ ██║██╔████╔██║█████╗ ██║ ██║ ██║
██║███╗██║██╔══╝ ██║ ██║ ██║ ██║██║╚██╔╝██║██╔══╝ ██║ ██║ ██║
╚███╔███╔╝███████╗███████╗╚██████╗╚██████╔╝██║ ╚═╝ ██║███████╗ ██║ ╚██████╔╝
╚══╝╚══╝ ╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝
███████╗██╗ ██╗██████╗ ███████╗██████╗ ████████╗ ███████╗██╗ ██╗███████╗████████╗███████╗███╗ ███╗
██╔════╝╚██╗██╔╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝ ██╔════╝╚██╗ ██╔╝██╔════╝╚══██╔══╝██╔════╝████╗ ████║
█████╗ ╚███╔╝ ██████╔╝█████╗ ██████╔╝ ██║ ███████╗ ╚████╔╝ ███████╗ ██║ █████╗ ██╔████╔██║
██╔══╝ ██╔██╗ ██╔═══╝ ██╔══╝ ██╔══██╗ ██║ ╚════██║ ╚██╔╝ ╚════██║ ██║ ██╔══╝ ██║╚██╔╝██║
███████╗██╔╝ ██╗██║ ███████╗██║ ██║ ██║ ███████║ ██║ ███████║ ██║ ███████╗██║ ╚═╝ ██║
╚══════╝╚═╝ ╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝"
print "\n\nEnter file name: "
name = gets.strip!
print "Turn on Conflicts? (y/n)"
conf = gets.strip!
puts "Processing..."
file = IO.readlines(name)
vars = Array.new(26, 0)
qries = []
stmt = []
file.each do |str|
str.strip!
if str[0] === '#'
elsif str[0] === '='
i = 1
while str[i]
vars[str[i].ord - 'A'.ord] = 1
i+=1
end
else
if (str[0] === '?')
i = 1
while str[i]
qries.push(str[i].ord - 'A'.ord)
i+=1
end
elsif str != ""
stmt.push(str)
end
end
end
RULE = Struct.new(:input_e, :out_e)
rules = []
stmt.each do |rle|
arr = rle.split("<=>")
if arr.length === 2
con = arr[0].split("+")
con.each do |conc|
conc = conc.strip!
end
rpn = RPNExpression.from_infix arr[1]
rules.push(RULE.new(rpn, con))
else
arr = rle.split("=>")
end
con = arr[1].split("+")
con.each do |conc|
conc = conc.strip!
end
rpn = RPNExpression.from_infix arr[0]
rules.push(RULE.new(rpn, con))
end
change = 1
while change === 1
change = 0
confl = 0
rules.each do |rule|
rule["out_e"].each do |bb|
tmp = solveRPN(rule["input_e"], vars)
if (tmp === 1)
if vars[bb[0].ord - 'A'.ord] === 0
vars[bb[0].ord - 'A'.ord] = 1
change = 1
end
else
if (conf === "y" || conf === "Y") && vars[bb[0].ord - 'A'.ord] === 1
confl = 1
end
end
end
end
end
if (confl === 1)
abort("CONFLICT found")
end
qries.each do |qry|
alpha = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
if vars[qry] === 1
puts "#{alpha[qry]} is TRUE".green
else
puts "#{alpha[qry]} is FALSE".red
end
end | true |
d1f816bee613cf1eee4cb79d0e5a5a31cc092193 | Ruby | ryanmmhmm/algorithm-solutions | /balancing-brackets/solution1.rb | UTF-8 | 614 | 4.25 | 4 | [] | no_license | ## Counter method for determining single-type bracket closure
def balanced?(string)
stack = []
closure = 0
string.each_char do |c|
if c == "("
closure += 1
elsif c == ")"
closure -= 1
end
break if closure < 0
end
closure == 0
end
string = "()"
puts "#{string} is #{balanced?(string)}"
string = "())"
puts "#{string} is #{balanced?(string)}"
string = "()(("
puts "#{string} is #{balanced?(string)}"
string = "(()())"
puts "#{string} is #{balanced?(string)}"
string = ")(" ## this case requires a break command if closure < 0
puts "#{string} is #{balanced?(string)}"
| true |
3d1a691fe5923a4a245cc8f44ccc9ff7aeb51d8e | Ruby | Nexproc/App-Academy | /projects/HashMap Algorithms/lib/p01_int_set.rb | UTF-8 | 855 | 3.46875 | 3 | [] | no_license | class MaxIntSet
def initialize(max)
@store = Array.new(max, false)
end
def insert(num)
raise "Out of bounds" if num > @store.size || num < 0
@store[num] = true
end
def remove(num)
@store[num] = false
end
def include?(num)
@store[num]
end
end
class IntSet
def initialize(length = 20)
@store = Array.new(length) { Array.new }
end
def insert(num)
@store[key(num)] << num
end
def remove(num)
@store[key(num)].delete(num)
end
def include?(num)
@store[key(num)].include?(num)
end
def key(num)
num % @store.length
end
end
class ResizingIntSet < IntSet
attr_reader :count
def initialize(length = 20)
@count = 0
super(length)
end
def insert(num)
@count += 1
super(num)
resize! if @count == @store.size
end
private
def resize!
end
end
| true |
c960c7192d55f72a31e01ffc6c81e7c22e041726 | Ruby | sunkibaek/log_analysis | /array.rb | UTF-8 | 487 | 3.5625 | 4 | [] | no_license | # Monkeypatching Array for mean, median, and mode.
# Mode returns the element of smallest index if there are more than one
class Array
def mean
return nil if empty?
reduce(:+).to_f / length
end
def median
return nil if empty?
mid_index = ((length.odd? ? length + 1 : length) / 2) - 1
sort[mid_index]
end
def mode
return nil if empty?
counter = Hash.new(0)
each { |e| counter[e] += 1 }
counter.sort_by { |_k, v| -v }[0][0]
end
end
| true |
899cbdf9308c0d26537dd7a28b56fa375486dbba | Ruby | dankb82/battleship | /human_player.rb | UTF-8 | 166 | 2.890625 | 3 | [] | no_license | require './player.rb'
require './computer_player.rb'
class HumanPlayer < Player
def initialize(name = "Dave")
@name = name
end
def name
@name
end
end
| true |
3ca189ef4ea42f392cd8f553ad72586b6b5c3ace | Ruby | Drenmi/push-up-bot-demo | /lib/bot.rb | UTF-8 | 604 | 3.171875 | 3 | [] | no_license | # This is our initial bot implementation. It works by listening for messages
# and checking them against a regular expression that matches a number followed
# by a bang, e.g. "36!". This is how users will report their push ups in the
# Slack channel.
class Bot < SlackRubyBot::Bot
PUSH_UP_COUNT = /^\s*(?<count>\d+)!\s*$/
match PUSH_UP_COUNT do |client, data, match|
count = match[:count].to_i
PushUpRecord.create(user: data.user, count: count)
total = PushUpRecord.sum(:count)
client.say(channel: data.channel, text: "Well done! The team has done #{total} push ups.")
end
end
| true |
fba3bbe2b3890057270f324643c053a1a307719d | Ruby | abdibogor/Ruby | /3.Smartherd/Ruby/60.Difference between Procs and lambda/difference_proc.rb | UTF-8 | 237 | 3.15625 | 3 | [] | no_license | # Difference Between Procs and Lambda
# Program of a Proc
def my_method
puts "before proc"
my_proc = proc{
puts "Inside proc"
#return
}
my_proc.call
puts "after proc"
end
my_method | true |
075882bb1909dc1e52731ce356ef7b8c1b978e5f | Ruby | chessbyte/chess | /board.rb | UTF-8 | 2,177 | 3.46875 | 3 | [] | no_license | require 'piece'
class Board
def setup
@board = Hash.new
@board['a1'] = Piece.new(:rook, :white)
@board['b1'] = Piece.new(:knight, :white)
@board['c1'] = Piece.new(:bishop, :white)
@board['d1'] = Piece.new(:queen, :white)
@board['e1'] = Piece.new(:king, :white)
@board['f1'] = Piece.new(:bishop, :white)
@board['g1'] = Piece.new(:knight, :white)
@board['h1'] = Piece.new(:rook, :white)
@board['a2'] = Piece.new(:pawn, :white)
@board['b2'] = Piece.new(:pawn, :white)
@board['c2'] = Piece.new(:pawn, :white)
@board['d2'] = Piece.new(:pawn, :white)
@board['e2'] = Piece.new(:pawn, :white)
@board['f2'] = Piece.new(:pawn, :white)
@board['g2'] = Piece.new(:pawn, :white)
@board['h2'] = Piece.new(:pawn, :white)
@board['a7'] = Piece.new(:pawn, :black)
@board['b7'] = Piece.new(:pawn, :black)
@board['c7'] = Piece.new(:pawn, :black)
@board['d7'] = Piece.new(:pawn, :black)
@board['e7'] = Piece.new(:pawn, :black)
@board['f7'] = Piece.new(:pawn, :black)
@board['g7'] = Piece.new(:pawn, :black)
@board['h7'] = Piece.new(:pawn, :black)
@board['a8'] = Piece.new(:rook, :black)
@board['b8'] = Piece.new(:knight, :black)
@board['c8'] = Piece.new(:bishop, :black)
@board['d8'] = Piece.new(:queen, :black)
@board['e8'] = Piece.new(:king, :black)
@board['f8'] = Piece.new(:bishop, :black)
@board['g8'] = Piece.new(:knight, :black)
@board['h8'] = Piece.new(:rook, :black)
end
def show
ranks = (1..8).to_a.reverse
files = ('a'..'h').to_a
ranks.each do |rank|
puts "+-------------------------------+"
files.each do |file|
square = "#{file}#{rank}"
piece = @board[square]
show_square(square, piece)
end
puts "|"
end
puts "+-------------------------------+"
end
def show_square(square, piece)
# puts "PIECE: #{piece.inspect}"
if piece.nil?
display = ' '
else
display = piece.symbol_with_color
end
# puts "DISPLAY: #{display.inspect}"
putc "|"
putc " "
putc display
putc " "
end
end
| true |
e7ed4fe1214b5b37b8de9c2513fe52e89a68777b | Ruby | kvnchu2/Two-O-Player-Math-Game | /player_turn.rb | UTF-8 | 137 | 3.328125 | 3 | [] | no_license | class PlayerTurn
attr_accessor :turn
def initialize(turn)
@turn = turn
end
def switch(turn)
self.turn = turn
end
end | true |
b5eebc1944326a636e03537f20c2702c41b59512 | Ruby | JordanLong1/programming-univbasics-4-array-simple-array-manipulations-online-web-prework | /lib/intro_to_simple_array_manipulations.rb | UTF-8 | 625 | 3.046875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def using_push(array, string)
array.push(string)
end
def using_unshift(array, string)
array.unshift(string)
end
def using_pop(array)
array.pop
end
def pop_with_args(array)
array.pop(2)
end
def using_shift(array)
array.shift
end
def shift_with_args(array)
array.shift(2)
end
def using_concat(array, new_array)
array.concat(new_array)
end
def using_insert(array, item)
array.insert(4, item)
end
def using_uniq(array)
array.uniq()
end
def using_flatten(array)
array.flatten()
end
def using_delete(array, string)
array.delete(string)
end
def using_delete_at(array, integer)
array.delete(array[integer])
end
| true |
90fe1d275214cd0a9e8d283edea6e9036d3ac468 | Ruby | CristopherVidalMachado/reservations | /spec/models/report_spec.rb | UTF-8 | 4,240 | 2.515625 | 3 | [
"MIT",
"AGPL-3.0-or-later"
] | permissive | # frozen_string_literal: true
require 'spec_helper'
describe Report, type: :model do
before(:each) do
@report = Report.new
end
describe Report::Column do
it 'can be constructed from arrays' do
column = Report::Column.arr_to_col ['Name', :scope, :type, :field]
expect(column.name).to eq('Name')
expect(column.filter).to eq(:scope)
expect(column.data_type).to eq(:type)
expect(column.data_field).to eq(:field)
end
end
describe Report::Row do
it 'can be constructed from Equipment Models' do
em = FactoryGirl.create(:equipment_model)
row = Report::Row.item_to_row em
expect(row.name).to eq(em.name)
expect(row.item_id).to eq(em.id)
expect(row.link_path).to eq(Rails.application.routes.url_helpers
.subreport_path(id: em.id,
class: 'equipment_model'))
end
it 'can be constructed from Reservations' do
u = FactoryGirl.build(:reservation)
u.save(validate: false)
row = Report::Row.item_to_row u
expect(row.name).to eq(u.name)
expect(row.item_id).to eq(u.id)
expect(row.link_path).to eq(Rails.application.routes.url_helpers
.reservation_path(id: u.id))
end
end
describe '.average2' do
it 'returns N/A for arrays of size 0' do
expect(Report.average2([])).to eq('N/A')
end
it 'returns N/A for arrays consisting of nil' do
expect(Report.average2([nil, nil])).to eq('N/A')
end
it 'calculates averages correctly' do
expect(Report.average2([1, 2, 3])).to eq(2)
end
it 'throws out nils' do
expect(Report.average2([1, 2, 3, nil])).to eq(2)
end
it 'rounds to 2 decimal places' do
expect(Report.average2([0.12, 1.799, 4.3])).to eq(2.07)
end
end
describe '.get_class' do
it 'converts equipment_item_id to EquipmentItem' do
expect(Report.get_class(:equipment_item_id)).to eq(EquipmentItem)
end
it 'works on :reserver_id' do
expect(Report.get_class(:reserver_id)).to eq(User)
end
it 'returns Reservation when given :id' do
expect(Report.get_class(:id)).to eq(Reservation)
end
end
describe '.build_new' do
DEFAULT_COLUMNS = [['Total', :all, :count],
['Reserved', :reserved, :count],
['Checked Out', :checked_out, :count],
['Overdue', :overdue, :count],
['Returned On Time', :returned_on_time, :count],
['Returned Overdue', :returned_overdue, :count],
['User Count', :all, :count, :reserver_id]].freeze
before(:each) do
@id = :equipment_item_id
@class = EquipmentItem
@report = Report.build_new(@id)
end
it 'returns a report object' do
expect(@report.class).to eq(Report)
end
it 'sets the row_item_type' do
expect(@report.row_item_type).to eq(@id)
end
it 'has the correctly headed columns' do
@report.columns.each_with_index do |col, i|
col.name = DEFAULT_COLUMNS[i][0]
col.filter = DEFAULT_COLUMNS[i][1]
col.data_type = DEFAULT_COLUMNS[i][2]
col.data_field = DEFAULT_COLUMNS[i][3]
end
end
it 's columns res_sets have the correct number of elements' do
@report.columns.each_with_index do |col, _i|
expect(col.res_set.count).to eq Reservation.send(col.filter).count
end
end
it 's columns res_sets are of type array' do
# important that they're not AR:Relation for speed purposes
@report.columns.each do |col|
expect(col.res_set.class).to eq Array
end
end
it 's columns res_sets are just ids under the right circumstances' do
@report.columns.each_with_index do |col, _i|
next unless col.data_field.nil? && col.data_type == :count
expect(col.res_set).to eq(Reservation.send(col.filter)
.collect(&@id))
end
end
it 'has the correctly headed rows' do
items = @class.all
items.each do |item|
expect(@report.rows).to include?(Report::Row.item_to_row(item))
end
end
end
end
| true |
e8ff5c7f743efd8212175384eb502ffbf458bdfa | Ruby | commuterjoy/BBC-News-Mobile-Search | /spec/search_spec.rb | UTF-8 | 2,843 | 2.859375 | 3 | [] | no_license | require 'app/lib/news/search.rb'
require 'spec_helper.rb'
describe Search do
it "should contain no results before a search" do
search = Search.new
search.results.should have(0).things
end
it "should return a list of results" do
search = Search.new
search.fetch('cats')
search.results.should have(20).things
end
it "should return a list of results from a specific page" do
search = Search.new
search.fetch('cats', 3)
search.results.should have(20).things
search.page.should eq(4) # 4th page
end
it "should return no results for an empty serach result set" do
search = Search.new
search.fetch('adsgasdgadsg')
search.results.should have(0).things
search.page.should eq(0)
end
it "should return uri, title, term, section and text for each result" do
search = Search.new
search.fetch('cats')
search.results.first.title.should == "In pictures: Mogadishu's fish market"
search.results.first.uri.should == 'news/in-pictures-17404466'
search.results.first.text.should include "and children now play"
search.results.first.section.should == "In Pictures"
search.results.first.term.should eq('cats')
end
it "should return the number of the next page of search results" do
search = Search.new
search.fetch('cats')
search.page.should eq(2)
end
it "should combine several searches in to a chronologically ordered list" do
search = Search.new
search.fetch('cats')
search.fetch('mushrooms')
search.results.should have(40).things
# chronology check
original = search.results.map do |result|
Time.now - result.date
end
original.should eq original.sort
end
it "should combine several searches and remove any duplicate results" do
search = Search.new
search.fetch('cats')
search.fetch('cats')
search.results.should have(20).things
end
it "should gracefully handle errors from the BBC search API" do
search = Search.new
search.fetch('onions')
end
it "should highlight the searched term in the results text" do
search = Search.new
search.fetch('cats')
search.results.first.text.should include "where <b>cats</b> and children"
end
it "should highlight multiple searched term in the results text" do
search = Search.new
search.fetch('the')
search.results.first.text include "called <b>the</b> most dangerous city in <b>the</b>"
end
end
describe String do
it "should ignore case when highlighting terms" do
"the Cats the cats".highlight include "the <b>Cats</b> the <b>cats</b>"
end
end
| true |
6f73262844d2711f3f8bd1a7538364a463651bf9 | Ruby | stelligent/SWFpoc | /lib/setup.rb | UTF-8 | 469 | 2.625 | 3 | [] | no_license | def usage_config
puts <<USAGE
To run the samples, put your credentials in config.yml as follows:
access_key_id: YOUR_ACCESS_KEY_ID
secret_access_key: YOUR_SECRET_ACCESS_KEY
USAGE
exit 1
end
def setup
config_path = File.expand_path(File.dirname(__FILE__)+"/../config/aws.yml")
unless File.exist?(config_path)
usage_config
end
config = YAML.load(File.read(config_path))
unless config.kind_of?(Hash)
usage_config
end
AWS.config(config)
end
| true |
65a8322b5e7a9e8f196aac9a5448348f069c831c | Ruby | hakonb/TimeFlux | /app/controllers/reporting.rb | UTF-8 | 3,338 | 2.734375 | 3 | [
"MIT"
] | permissive | module Reporting
private
def setup_calender
if params[:calender]
year = params[:calender]["date(1i)"].to_i
month = params[:calender]["date(2i)"].to_i
else
year = params[:year].to_i if params[:year] && params[:year] != ""
month = params[:month].to_i if params[:month] && params[:month] != ""
end
relevant_date = Date.today - 7
@day = Date.new(year ? year : relevant_date.year, month ? month : relevant_date.month, 1)
@years = (2007..Date.today.year).to_a.reverse
@months = []
@month_names = %w{ January Febrary March April May June July August September October November December}
@month_names.each_with_index { |name, i| @months << [ i+1, name ] }
end
# Sets the date to the last in month if the supplied date is higher.
# Example 2009,2,31 returns Date.civil(2009,2,28)
#
def set_date(year, month, day)
puts "Setting date: #{year}-#{month}-#{day}"
max_day = Date.civil(year,month,1).at_end_of_month.mday
Date.civil(year,month, day > max_day ? max_day : day)
end
# Finds the instance of class <tt>symbol<tt>, with the id of params[symbol]
# Example for symbol :user -> returns User.find(params[:user]) or nil if param or user does not exsist
#
def param_instance(symbol)
Kernel.const_get(symbol.to_s.camelcase).find(params[symbol]) if params[symbol] && params[symbol] != ""
end
# Sets prawn arguments, and disables cache for explorer (prior to v. 6.0)
# so that it too can download pdf documents
def initialize_pdf_download(filename)
prawnto :prawn => prawn_params, :filename=> filename
#if request.env["HTTP_USER_AGENT"] =~ /MSIE/
# response.headers['Cache-Control'] = ""
#end
end
def project_hours_for_customers(customers)
project_hours = []
customers.each do |customer|
customer.projects.each do |project|
project_hours << [customer,project, TimeEntry.between(@from_day, @to_day).for_project(project).sum(:hours), customer.billable]
end
end
project_hours
end
# Takes a list of customers, and a date representing a month
# Returns 1. a list in the format ["what to display", "what to select", empty?, has_hours?]
# 2. a list of customers that doesnt start on any of the letters between A and Z.
def extract_customers_by_letter( customers, day )
letters = []
('A'..'Z').each do |letter|
customers_on_letter = customers.select { |customer| customer.name.index(letter) == 0 }
customers -= customers_on_letter
if customers_on_letter
unbilled_hours = customers_on_letter.any? {|customer| customer.has_unbilled_hours_between(day,day.at_end_of_month) }
end
letters << [letter, letter, customers_on_letter.empty?, unbilled_hours ]
end
other_hours = customers.any? {|customer| customer.has_unbilled_hours_between(day,day.at_end_of_month) }
other = ['Other', '#', customers.empty?, other_hours ]
all = ['All', '*', false, letters.any?{|letter| letter[3] == true} || other[3] == true ]
return [all] + letters + [other], customers
end
# Prawnto arguments for creating a plain A4 page with sensible margins
#
def prawn_params
{
:page_size => 'A4',
:left_margin => 50,
:right_margin => 50,
:top_margin => 24,
:bottom_margin => 24 }
end
end | true |
e79ea1b0b4918a17017238af251d15550ac2c608 | Ruby | traday/prr_activerecord_querying_examples | /db/seeds.rb | UTF-8 | 4,748 | 2.796875 | 3 | [] | no_license | #
# A bunch of users to test find_each and find_in_batches
#
(1..10000).each do
name = Faker::Name.name
User.create!(name: name,
username: Faker::Internet.user_name(name))
end
#
# The Join exmple models
#
Category.create!([{name: "Technical"}, {name: "Gossip"}, {name: "Politics"}])
tech = Category.where(name: "Technical").first
gossip = Category.where(name: "Gossip").first
politics = Category.where(name: "Politics").first
Article.create!({title: "Everything you ever wanted to know about querying with Active Record", body: "If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.", category: tech})
Article.create!({title: "Active Record queries sometimes return an Active Relation", body: "And that can be confusing at times", category: tech})
Article.create!({title: "Taylor Swift", body: "I saw a concert about 4 years ago with my daughter and I was impressed with her singing and her message", category: gossip})
Article.create!({title: "Katy Perry", body: "Saw her at the superbowl", category: gossip})
Article.create!({title: "Political campaigns are getting crazy!", body: "Money + antics, this is going to be a very interesting political election", category: politics})
Article.create!({title: "There are so many candidates", body: "How is anybody supposed to pick one!", category: politics})
tech_articles = Article.where(category: tech)
a1 = tech_articles.first
a2 = tech_articles.last
gossip_articles = Article.where(category: gossip)
a3 = gossip_articles.first
a4 = gossip_articles.last
politics_articles = Article.where(category: politics)
a5 = politics_articles.first
a6 = politics_articles.last
Tag.create!([{name: "Funny", article: a4},
{name: "Interesting", article: a1},
{name: "Outrageous", article: a5},
{name: "Confusing", article: a2},
{name: "Infuriating", article: a6},
{name: "Cool", article: a3}])
adjectives1 = %w{aggressive agile agitated agonizing agreeable ajar alarmed alarming alert alienated alive altruistic}
adjectives1.each{|adjective| Tag.create!(name: adjective, article:a1)}
adjectives2 = %w{cloudy clueless clumsy cluttered coarse cold colorful colorless colossal comfortable common compassionate competent complete}
adjectives2.each{|adjective| Tag.create!(name: adjective, article:a2)}
adjectives3 = %w{embellished eminent emotional empty enchanted enchanting energetic enlightened enormous}
adjectives3.each{|adjective| Tag.create!(name: adjective, article:a3)}
adjectives4 = %w{gloomy glorious glossy glum golden good good-natured gorgeous graceful}
adjectives4.each{|adjective| Tag.create!(name: adjective, article:a4)}
adjectives5 = %w{impeccable impartial imperfect imperturbable impish impolite important impossible impractical impressionable impressive improbable}
adjectives5.each{|adjective| Tag.create!(name: adjective, article:a5)}
adjectives6 = %w{kaleidoscopic keen key kind kindhearted kindly klutzy knobby knotty knowledgeable knowing known kooky kosher}
adjectives6.each{|adjective| Tag.create!(name: adjective, article:a6)}
(1..18).each do |i|
id = (i % 6) + 1
article = Article.find(id)
comment = Comment.create!(article: article, body: Faker::Lorem.sentence(2, true, 6))
Guest.create!(name: Faker::Name.first_name, comment: comment)
end
#
# Clients and such
#
(1..10).each {Role.create!(name: Faker::Commerce.color)}
(1..20).each do
name = Faker::Company.name
Client.create!(name: name, first_name: name, locked: false)
end
generator = Random.new
Client.all.each do |client|
client.address = Address.create!(addr1: Faker::Address.street_address,
city: Faker::Address.city,
state: Faker::Address.state,
zip: Faker::Address.zip)
ids = []
(generator.rand(5) + 1).times do
ids << generator.rand(10) + 1 #Makes it 1 - 10
end
client.roles = Role.find(ids.uniq)
generator.rand(3).times do
order = Order.new(product_name: Faker::Commerce.product_name,
quantity: generator.rand(10) +1,
client: client,
price: generator.rand(1000.00))
if order.price <= 300.00
order.status = 'shipped'
elsif order.price <= 700.00
order.status = 'awaiting_approval'
else
order.status = 'paid'
end
order.save!
end
client.viewable_by = User.find(generator.rand(5) + 1).name
client.orders_count = client.orders.count
client.locked = true if client.orders_count % 2 == 0
client.save!
end
| true |
14551d35b97e1f24806cdd92fabb360e653716a2 | Ruby | cjwind/booksr | /lib/booksr/api_handler.rb | UTF-8 | 931 | 2.8125 | 3 | [] | no_license | #encoding: utf-8
class ApiHandler
GOOGLE_MAX_RESULTS = 40 # const
def search_by_google(query_string, query_type)
responses = Array.new
parser = Parser.new
# https://www.googleapis.com/books/v1/volumes?q=field:qeury_string&startIndex=#{start_index}&maxResults=#{GOOGLE_MAX_RESULTS}
query_string = URI::escape(query_string)
api_uri = "https://www.googleapis.com/books/v1/volumes"
query = "?q="
if query_type == :title
query += "intitle:"
elsif query_type == :author
query += "inauthor:"
elsif query_type == :isbn
query += "isbn:"
end
query += query_string
start_index = 0
begin
subquery = "&startIndex=#{start_index}&maxResults=#{GOOGLE_MAX_RESULTS}"
response = RestClient.get api_uri + query + subquery
responses.push(response)
data = parser.parse_json(response)
start_index += GOOGLE_MAX_RESULTS
end while data.size == GOOGLE_MAX_RESULTS
return responses
end
end | true |
a9655b96648858d998b293aa83882201ebd1d371 | Ruby | jayniz/lacerda | /lib/lacerda/conversion/data_structure/member/type.rb | UTF-8 | 3,207 | 2.8125 | 3 | [] | no_license | module Lacerda
module Conversion
class DataStructure
class Member
class Type
def initialize(type_definition, is_required, scope)
@type_definition = type_definition
@scope = scope
@type_name = type_definition['element']
@is_required = is_required
end
def object?
@type_name == 'object'
end
# A type is transformed to json schema either as a primitive:
# { "type" => ["string"] }
# { "type" => ["string", "null"] }
# Or as a oneOf. $ref are always within a oneOf
# {"oneOf"=>[{"$ref"=>"#/definitions/tag"}, {"type"=>"null"}]}
def to_hash
if PRIMITIVES.include?(@type_name)
primitive(@type_name, required?)
else
oneOf([@type_name], required?)
end
end
# bui
# As there are specied types in the array, `nil` should not be a valid value
# and therefore required should be true.
def array_type
return unless array?
if nested_types.size == 1 && PRIMITIVES.include?(nested_types.first)
primitive(nested_types.first, true)
else
oneOf(nested_types, true)
end
end
private
def array?
@type_name == 'array'
end
# A basic type is either a primitive type with exactly 1 primitive type
# {'type' => [boolean] }
# a reference
# { '$ref' => "#/definitions/name" }
# or an object if the type in not there
# { 'type' => object }
# Basic types don't care about being required or not.
def basic_type(type_name, is_required = required?)
if PRIMITIVES.include?(type_name)
primitive(type_name, is_required)
else
reference(type_name)
end
end
def oneOf(types, is_required)
types = types.map { |type_name| basic_type(type_name,is_required) }
types << { 'type' => 'null' } unless is_required
{
'oneOf' => types.uniq
}
end
def reference(type_name)
{'$ref' => "#/definitions/#{Lacerda::Conversion::DataStructure.scope(@scope, type_name)}" }
end
def primitive(type_name, is_required)
types = [type_name]
types << 'null' unless is_required
if type_name == 'enum'
enum_values = @type_definition['content'].map { |i| i['content'] }
{ 'type' => types, 'enum' => enum_values }
else
{ 'type' => types }
end
end
def required?
@is_required
end
def nested_types
error_msg = "This DataStructure::Member is a #{@type_name}, not "\
'an array, so it cannot have nested types'
raise error_msg unless array?
@type_definition['content'].map{|vc| vc['element'] }.uniq
end
end
end
end
end
end
| true |
16096e8b1c3ba9c9aed32a2e30407b9c868ee9ac | Ruby | mkrahu/launchschool-courses | /101_programming_foundations/03_practice_problems/03_medium_1/question6.rb | UTF-8 | 257 | 3.65625 | 4 | [] | no_license | answer = 42
def mess_with_it(some_number)
some_number += 8
end
new_answer = mess_with_it(answer)
p answer - 8 # => 34 - integers are immutable (and assignment does not mutate
# the caller, mess_with_it does not affect the value of the variable answer)
| true |
52983c3411daf0d4bf453c32013b861e5cb9eb49 | Ruby | seyitals/Enigma | /characters.rb | UTF-8 | 110 | 2.8125 | 3 | [] | no_license | class Characters
def character_map
('a'..'z').to_a.concat(("0".."9").to_a).push(" ", ".", ",")
end
end | true |
daa8169807639001542453e549f47b4bb8e3d9ff | Ruby | handwerger/ruby_challenges | /piglatin.rb | UTF-8 | 1,527 | 4.0625 | 4 | [] | no_license | # test first letter of word begins with vowel go to method to add ay and that is result
# else:
# itterate through letters as the ones that are consenants get added to the end of the word then ay
# qu must also need to be moved
# squ must be moved
# x followed by consenant does not get moved
require 'pry'
class PigLatin
def self.translate(word)
if word.include?(" ")
phrase(word)
else
if word[0].match(/[aeiou]/)
add_ay(word)
elsif word[0..1].match(/(x|y)[^aeiou]/)
add_ay(word)
elsif word[0..1].match(/qu/)
case_qu(word)
elsif word[0..2].match(/[^aeiou]qu/)
case_qu(word)
else
begins_with_consenant(word)
end
end
end
def self.phrase(word)
words = word.split(" ")
words.map! { |word| PigLatin.translate(word) }
words.join(" ")
end
def self.case_qu(word)
letters = word.chars
word[0..2].match(/[^aeiou]qu/) ? popped_letters = letters.shift(3) : popped_letters = letters.shift(2)
letters << popped_letters
new_word = letters.flatten.join
add_ay(new_word)
end
def self.begins_with_consenant(word)
letters = word.chars
popped_letters = ""
letters.size.times do |letter|
#binding.pry
if letters[0].match(/[aeoiu]/)
break
else
popped_letters << letters.shift
end
end
letters << popped_letters
add_ay(letters.join)
end
def self.add_ay(word)
word << "ay"
end
end
PigLatin.translate('quick fast run') | true |
8105b1ffe079b63f72e0f8d57444fb37ead3739c | Ruby | lianwangtao/CHUniqueLinkedList | /CHUniqueLinkedList.rb | UTF-8 | 1,493 | 3.75 | 4 | [] | no_license | #!/usr/bin/ruby
require_relative './CHNode'
require 'set'
class CHUniqueLinkedList
def initialize()
@head = nil
@set = Set.new()
end
def add(value)
if value == nil
return
end
if @head == nil
@head = CHNode.new(value, nil)
@set.add(value)
return
end
if @set.include?(value)
return
else
@set.add(value)
curr = @head
while curr.get_next() != nil
curr = curr.get_next()
end
curr.set_next(CHNode.new(value, nil))
end
end
def remove(value)
if @head == nil
return
elsif @head.get_data() == value
@head = @head.get_next()
return
end
curr = @head
while curr.get_next() != nil
if curr.get_next().get_data() == value
curr.set_next = curr.get_next().get_next()
@set.remove(value)
end
curr = curr.get_next()
end
end
def print()
curr = @head
while curr != nil
puts curr.get_data()
curr = curr.get_next()
end
puts "-"
end
end
# Simple tests
list = CHUniqueLinkedList.new
puts "-- New Unique Linked List Created (no duplicates) --"
puts "Adding 1, 1, 2, 3, 3"
list.add(1)
list.add(1)
list.add(2)
list.add(3)
list.add(3)
list.print()
puts "After removing 1"
list.remove(1)
list.print()
list.remove(2)
puts "After removing 2"
list.print()
list.remove(2)
puts "Try to remove 2 again"
list.print()
list.remove(3)
list.remove(10)
puts "No items should be left"
list.print()
| true |
b3a7eaa45632088fa940a834c68007fa69d6e9cd | Ruby | learn-co-students/nyc-web-071618 | /04-oo-one-to-many/user.rb | UTF-8 | 682 | 3.078125 | 3 | [] | no_license | class User
attr_accessor :username
@@all = []
def initialize(username)
@username = username
@@all << self
end
def tweets
# ask Tweet.all for the tweets authored by self
Tweet.all.select do |tweet_instance|
tweet_instance.user == self
end
end
def post_tweet(message)
# user_instance.post_tweet('great # coffee')
Tweet.new(self, message)
end
def self.find_by_username(username)
@@all.find do |user_instance|
user_instance.username == username
end
end
# methods created by attr_accessor :username
# def username
# @username
# end
#
# def username=(username)
# @username = username
# end
end
| true |
5627d49d72de859ed84af67d14e418e6f98d5e92 | Ruby | energon-a-secas/enerbot-slack | /scripts/feedback.rb | UTF-8 | 783 | 2.65625 | 3 | [
"MIT"
] | permissive | module Feedback
def self.quote
quotes = [
'Lo hiciste excelente durante el año. *Bajo lo esperado*',
'Jugaste fifa todo el año. *Excepcional*, sigue así',
'Jugaste magic en la oficina. *Bajo lo esperado*',
'Tomaste desayuno en la oficina 2 veces en el año. *Bajo lo esperado*',
'Eres parte de la comunidad de seguridad. *Excepcional*',
'No incluiste ninguna palabra en ingles en tus frases. *Bajo lo esperado*',
'Pusiste solo emojis tristes en slack. *Bajo lo esperado*',
'Saliste 2 veces en el _NEWS_ hablando sobre la importancia de los terraplanistas. *Excepcional*',
'Fuiste el mejor en el baile para romper el hielo en el workshop. *Excepcional*'
]
<<-HEREDOC
> #{quotes.sample}
HEREDOC
end
end
| true |
2590e54609d93d63d5330d14859b10297c1fa2af | Ruby | jessiebaude/ttt-10-current-player-v-000 | /lib/current_player.rb | UTF-8 | 293 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def turn_count(board)
counter = 0
board.each do |icon|
if icon == "X" || icon == "O"
counter += 1
end
end
return counter
end
def current_player(board)
turn_number = turn_count(board) + 1
if turn_number.even? == true
return "O"
else
return "X"
end
end
| true |
f03afec89f0aab1d5e74696e9d544904a4404b1f | Ruby | rfrm/uninortehorarios | /lib/subject_getter.rb | UTF-8 | 724 | 2.671875 | 3 | [] | no_license | require_relative 'getter'
class SubjectGetter < Getter
def get_subjects(subject_code)
r = Typhoeus.post "http://guayacan.uninorte.edu.co/registro/resultado_codigo.asp",
body: form_values(subject_code)
subjects = {}
doc = Nokogiri::HTML(r.body)
doc.css("div").each do |div|
data = div.content.strip.split("\n").map(&:strip).reject(&:empty?)
name = data[0]
/Materia: (?<code>\w{3}\d{4})/ =~ data[1]
subjects[code] = name
end
subjects
end
private
def form_values(subject_code)
{'valida' => 'OK', 'mat' => subject_code, 'BtnCodigo' => 'Buscar',
'datos_periodo' => current_period, 'nom_periodo' => current_period_name}
end
end
| true |
31197e45ce7082833231cac177a5b6b5ac772129 | Ruby | mariapacana/etherealpath | /app/models/twilio_client.rb | UTF-8 | 351 | 2.5625 | 3 | [] | no_license | class TwilioClient
attr_accessor :client
def initialize
@client = Twilio::REST::Client.new Rails.application.secrets.TWILIO_ACCOUNT_SID, Rails.application.secrets.TWILIO_AUTH_TOKEN
@twilio_phone = '+16506459949'
end
def send_message(phone, message)
@client.messages.create from: @twilio_phone, to: phone, body: message
end
end | true |
a1b6763981497c50d464521cc580766a7704847c | Ruby | Shengliang/language | /ruby/arr.rb | UTF-8 | 196 | 3.71875 | 4 | [] | no_license |
array = [1,3,4,71,11]
num = 5
def isSum(array, sum)
array.each do |x|
array.each do |y|
return "yes:",x,y if sum == (x+y) and x!= y
end
end
return "no"
end
puts isSum(array, num)
| true |
7ee73b435ea0c84b0d3c436d59ae03b9f46654a0 | Ruby | mpochwat/Test-First-Ruby | /09_timer/timer.rb | UTF-8 | 365 | 3.578125 | 4 | [] | no_license | class Timer
def initialize
@seconds = 0
end
def seconds=(num)
@seconds = num
end
def seconds
@seconds
end
def time_string
hours = @seconds / 3600
minutes = (@seconds % 3600) / 60
seconds = @seconds % 60
padded(hours) + ":" + padded(minutes) + ":" + padded(seconds)
end
def padded(time)
time < 10 ? "0" + time.to_s : time.to_s
end
end | true |
ceec9fb50b1cd3198db1f12517962661fa6efed6 | Ruby | jimbojambo91/Week_2_Day_3_Snakes-Ladders | /player.rb | UTF-8 | 495 | 3.875 | 4 | [] | no_license | class Player
attr_reader :name, :position
def initialize(name, position)
@name = name
@position = position
end
def move_position(dice)
@position += dice.roll
end
def win(position)
if @position >= 100
return "You win"
end
return false
end
def snake(position)
if @position == 20
@position = 10
end
return @position
end
def ladder(position)
if @position == 45
@position = 51
end
return @position
end
end | true |
18944508ce43dbd2d038ba286f7c5f78980d8c10 | Ruby | tyronepost/command_line_games | /tictactoe/lib/tictactoe/main.rb | UTF-8 | 1,818 | 3.125 | 3 | [] | no_license | require_relative 'menus/main_menu'
require_relative 'general/board'
require_relative 'menus/layout_menu'
require_relative 'menus/game_mode_menu'
require_relative 'menus/player_menu_factory'
require_relative 'menus/player_order_menu'
require_relative 'menus/symbol_menu'
require_relative 'menus/difficulty_menu'
require_relative 'general/player_order_selector'
require_relative 'general/game'
require_relative 'general/game_loop'
require_relative 'rules'
module TicTacToe
class Main
attr_reader :game_loop, :game_settings
def initialize(io_device)
@io_device = io_device
@game_loop = GameLoop.new
@game_settings = {io_device: @io_device}
end
def run
run_menu
raise "Must run menu first" unless menu_ran?
Game.new(self, @io_device).run
end
def run_menu
@game_settings.merge! main_menu.run_menu
@menu_ran = true
end
def new_game
raise "Must run menu first" unless menu_ran?
player_order_selector = PlayerOrderSelector.new(game_settings[:players])
player_order_selector.set_first(game_settings[:first_player])
game_settings.merge! initialize_board
end
private
def main_menu
MainMenu.new(
io_device: @io_device,
layout_menu: LayoutMenu.new(@io_device),
game_mode_menu: GameModeMenu.new(@io_device),
player_menu_factory: PlayerMenuFactory.new,
player_order_menu: PlayerOrderMenu.new(@io_device),
symbol_menu: SymbolMenu.new(@io_device),
difficulty_menu: DifficultyMenu.new(@io_device))
end
def initialize_board
board = new_board
{board: board,
rules: Rules.new(board)}
end
def new_board
Board.new size: 3, default: " "
end
def menu_ran?
@menu_ran
end
end
end
| true |
78a394e6b552227f0dc229b1a2f7415b6d41c999 | Ruby | salrepe/katas | /poker_hands/spec/card_spec.rb | UTF-8 | 334 | 2.640625 | 3 | [] | no_license | require_relative '../card'
describe Card do
describe '#suit' do
it 'returns the suit of the card' do
card = Card.new('2H')
expect(card.suit).to eq('H')
end
end
describe '#value' do
it 'returns the value of the card' do
card = Card.new('2H')
expect(card.value).to eq('2')
end
end
end
| true |
cef6a333a6574201048206b5a4112c7c94ed6edc | Ruby | acockell/confidentqa_cucumber | /features/lib/pythagorean.rb | UTF-8 | 840 | 3.6875 | 4 | [] | no_license | class Pythagorean
attr_accessor :final
def initialize
@final = 0
@a = 0
@b = 0
end
def check_non_real n
if n.to_i >= 0
return n
else
@final = -1
end
end
def side_one a
a = check_non_real a
@a = a.to_i
end
def side_two b
b = check_non_real b
@b = b.to_i
end
def order
if @a > @b
x = @a
y = @b
else
x = @b
y = @a
end
return square_of_sums x, y, true
end
def hypotenuse
if @final >= 0
@final = square_of_sums @a, @b, false
end
return @final
end
def side
if @final >= 0
@final = order
end
return @final
end
def square_of_sums x, y, subtract
minus = 1
if subtract
minus = -1
end
square = Math.sqrt(x**2 + (minus) * (y**2))
return square
end
end
| true |
67a924f35824640a9dec8195a5bb74cfcb9d3c34 | Ruby | whoward/budget | /lib/budget/awesome_nested_set_tree.rb | UTF-8 | 1,573 | 2.84375 | 3 | [
"MIT"
] | permissive |
# frozen_string_literal: true
module Budget
class AwesomeNestedSetTree
include Enumerable
def self.from_nodes(nodes)
by_id = Hash[nodes.map { |n| [n.id, n] }]
# TODO: zomg the dirty dirty
populate = lambda do |n|
nodes.select { |c| c.parent_id == n.node.id }
.map do |c|
x = Container.new(c, n, nil)
x.children = populate.call(x)
x
end
end
roots =
nodes.reject { |n| by_id.keys.include?(n.parent_id) }
.map do |n|
x = Container.new(n, nil, nil)
x.children = populate.call(x)
x
end
new(roots: roots)
end
attr_reader :roots
def initialize(roots: [])
@roots = roots
end
def each
return to_enum(:each) unless block_given?
visit = lambda do |n|
yield n
n.children.each { |c| yield(c) }
end
@roots.each { |n| visit.call(n) }
end
Container = Struct.new(:node, :parent, :children) do
def root?
parent.nil?
end
def leaf?
children.empty?
end
def ancestors
result = [self]
result << result.last.parent while result.last.parent
result
end
def inspect
type =
if root?
'Root'
elsif leaf?
'Leaf'
else
'Container'
end
"<#{type}: (#{children.length} children)>"
end
alias_method :to_s, :inspect
alias_method :to_str, :inspect
end
end
end
| true |
4cc897c328fdc65043d50aa13dd42cc497a9b847 | Ruby | knlynda/status-page-ruby | /lib/status_page_ruby/services/build_history_table.rb | UTF-8 | 676 | 2.546875 | 3 | [] | no_license | module StatusPageRuby
module Services
class BuildHistoryTable
HEADINGS = %w[Service Status Time].freeze
attr_reader :status_repository
def initialize(status_repository)
@status_repository = status_repository
end
def call(service = nil)
Terminal::Table.new(
headings: HEADINGS,
rows: build_rows(service)
).to_s
end
private
def build_rows(service)
find_records(service).map(&:history_record)
end
def find_records(service)
return status_repository.all if service.nil?
status_repository.where(service: service)
end
end
end
end
| true |
d5a033062561d5029438aebc74649bace5b5e590 | Ruby | kerryb/goos-ruby | /lib/xmpp/auction_message_translator.rb | UTF-8 | 1,592 | 2.65625 | 3 | [] | no_license | module Xmpp
class AuctionMessageTranslator
def initialize sniper_id, listener, failure_reporter
@sniper_id, @listener, @failure_reporter = sniper_id, listener, failure_reporter
end
def handle_message message
event = AuctionEvent.from message
case event.type
when "PRICE"
@listener.current_price event.current_price, event.increment, event.is_from?(@sniper_id)
when "CLOSE"
@listener.auction_closed
end
rescue => e
@failure_reporter.cannot_translate_message @sniper_id, message.body, e
@listener.auction_failed
end
class AuctionEvent
class MissingValueException < RuntimeError; end
class BadlyFormedMessageException < RuntimeError; end
def initialize fields
@fields = fields
end
def self.from message
new fields_in(message.body)
end
def type
field "Event"
end
def current_price
Integer(field "CurrentPrice")
end
def increment
Integer(field "Increment")
end
def is_from? sniper_id
field("Bidder") == sniper_id ? :from_sniper : :from_other_bidder
end
private
def self.fields_in body
fields = body.split ";"
name_value_pairs = fields.flat_map {|a| a.split ":" }.map(&:strip)
Hash[*name_value_pairs]
rescue
raise BadlyFormedMessageException.new body
end
private_class_method :fields_in
def field key
@fields.fetch(key) { raise MissingValueException.new(key) }
end
end
end
end
| true |
01247ef31c01a24edd1294b1b47e48b47e21db9e | Ruby | SergeyBerdnikovich/airplanes_monitor | /app/services/fly_queue/append_service.rb | UTF-8 | 516 | 2.53125 | 3 | [] | no_license | class FlyQueue::AppendService
attr_reader :airplane, :fly_queue
def initialize(params)
@fly_queue = FlyQueue.new(params)
@airplane = fly_queue.airplane
end
def append!
raise Exception.new('Airplane is already in queue') if airplane_in_queue?
ActiveRecord::Base.transaction do
fly_queue.save!
Airplanes::StatusChanger.new(airplane, AirplaneStatus::QUEUE).change!
end
end
private
def airplane_in_queue?
FlyQueue.where(airplane_id: airplane.id).present?
end
end
| true |
25757f805b84eab8966b2d0aa474ba5cfed85384 | Ruby | anjalirai13/RubyLearning | /Pattern_1.rb | UTF-8 | 234 | 3.359375 | 3 | [] | no_license | # Draw half diamond in downward pattern
j = -1
9.downto(1) { |i|
# Print the * for every odd number
if (i%2 !=0)
if(j >= 0)
for k in 0..j
printf " "
end
end
for i in 1..i
printf "*"
end
j = j + 1
end
puts
} | true |
7d62e2444652fb472b2536008eb3c6f76297a01f | Ruby | cxn03651/writeexcel | /lib/writeexcel/write_file.rb | UTF-8 | 1,343 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # -*- coding: utf-8 -*-
class WriteFile
def initialize
@data = ''
@datasize = 0
@limit = 8224
# Open a tmp file to store the majority of the Worksheet data. If this fails,
# for example due to write permissions, store the data in memory. This can be
# slow for large files.
@filehandle = Tempfile.new('writeexcel')
@filehandle.binmode
# failed. store temporary data in memory.
@using_tmpfile = @filehandle ? true : false
end
###############################################################################
#
# _prepend($data)
#
# General storage function
#
def prepend(*args)
data = join_data(args)
@data = data + @data
data
end
###############################################################################
#
# _append($data)
#
# General storage function
#
def append(*args)
data = join_data(args)
if @using_tmpfile
@filehandle.write(data)
else
@data += data
end
data
end
private
def join_data(args)
data =
ruby_18 { args.join } ||
ruby_19 { args.compact.collect{ |arg| arg.dup.force_encoding('ASCII-8BIT') }.join }
# Add CONTINUE records if necessary
data = add_continue(data) if data.bytesize > @limit
@datasize += data.bytesize
data
end
end
| true |
e626accaa33ef736c0a7842b97f275998deb8b06 | Ruby | gizele22/Day2 | /game.rb | UTF-8 | 1,639 | 3.71875 | 4 | [] | no_license | # Force Flush Ruby
old_sync = $stdout.sync
$stdout.sync = true
# set initial values
@easy_secret = rand(1..10)
@medium_secret = rand(51..70)
@hard_secret = rand(71..100)
@count = 1
@previous_tries = [] # << Array
@history = {} # << Hash
@chances = 6
# start here
puts "Welcome to Numix-Lucky Number"
puts "Enter Your Name"
@player_name = gets.chomp
def run_game
puts "Choose Your Level"
puts "1 - Easy"
puts "2 - Medium"
puts "3 - Hard"
choice = gets.to_i
if choice == 1
secret_number = @easy_secret
elsif choice == 2
secret_number = @medium_secret
elsif choice == 3
secret_number = @hard_secret
end
puts "Guess Your lucky Number. You Have #{@chances} Chances"
#puts "Secret: #{secret_number}"
guess = gets.chomp.to_i
while @count < @chances
if secret_number != guess
@previous_tries << guess
puts "Keep Calm and Try Again"
puts "#{@previous_tries}"
@count += 1
guess = gets.to_i
else
puts "Congratulations! You Got It"
score = @chances - @count
@history[@player_name] = score
puts "LEADERBOARD"
puts @history
break
end
if @count == @chances
puts "Game Over"
puts "The Mystery Lucky Number Will be: #{secret_number}"
score = @chances - @count
@history[@player_name] = score
puts "SCOREBOARD"
puts @history
end
end
repeat_game
end
def repeat_game
puts "Do You Want To Repeat Game?"
puts "Y - Yes"
puts "N - No"
puts "0 - Exit Game"
choice = gets.chomp
if choice.upcase == 'Y'
run_game
else
puts "Thank You"
exit
end
end
run_game
| true |
26f511049e856da92109d9b51a1de371ac07cd3b | Ruby | joeainsworth/ls-tick-tac-toe | /tic_tac_toe.rb | UTF-8 | 4,319 | 3.984375 | 4 | [] | no_license | require 'pry'
MAX_ROUNDS = 5
INITIAL_MARKER = ' '
PLAYER_MARKER = 'X'
COMPUTER_MARKER = 'O'
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8],
[3, 6, 9], [1, 5, 9], [7, 5, 3]]
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize
def display_board(board)
system 'clear'
puts "Player is a [#{PLAYER_MARKER}] Computer is a [#{COMPUTER_MARKER}]"
puts ''
puts ' | | '
puts " #{board[1]} | #{board[2]} | #{board[3]} "
puts ' | | '
puts '-----------------'
puts ' | | '
puts " #{board[4]} | #{board[5]} | #{board[6]} "
puts ' | | '
puts '-----------------'
puts ' | | '
puts " #{board[7]} | #{board[8]} | #{board[9]} "
puts ' | | '
puts ''
end
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
def initialize_board
new_board = {}
(1..9).each { |num| new_board[num] = INITIAL_MARKER }
new_board
end
def empty_squares(board)
board.keys.select { |num| board[num] == INITIAL_MARKER }
end
def player_turn!(board)
square = ''
loop do
puts "Choose a square #{joinor(empty_squares(board))}"
square = gets.chomp.to_i
break if empty_squares(board).include?(square)
puts 'Sorry this is not a valid square.'
end
board[square] = PLAYER_MARKER
end
def two_in_a_row?(line, board, marker_type)
board.values_at(*line).count(marker_type) == 2
end
def computer_select_square(line, board, marker_type)
return unless two_in_a_row?(line, board, marker_type)
board.select { |k, v| line.include?(k) && v == INITIAL_MARKER }.keys.first
end
def assess_computer_options(square, board, marker_type)
WINNING_LINES.each do |line|
square = computer_select_square(line, board, marker_type)
return square unless square.nil?
end
square
end
def computer_turn!(board)
square = nil
square = assess_computer_options(square, board, PLAYER_MARKER)
square = assess_computer_options(square, board, COMPUTER_MARKER) unless square
square = empty_squares(board).sample unless square
board[square] = COMPUTER_MARKER
end
def board_full?(board)
empty_squares(board).empty?
end
def detect_winner(board)
WINNING_LINES.each do |line|
if board.values_at(*line).count(PLAYER_MARKER) == 3
return 'Player'
elsif board.values_at(*line).count(COMPUTER_MARKER) == 3
return 'Computer'
end
end
nil
end
def someone_won?(board)
detect_winner(board)
end
def round_score_msg(player_score, computer_score)
"Player [#{player_score}] v [#{computer_score}] Computer"
end
def game_winner_msg(player_score, computer_score)
if player_score > computer_score
'Player won the game!'
else
'Computer won the game!'
end
end
def joinor(array, delimeter = ', ', word = 'or')
string = ''
array.each_index do |index|
if index < array.count
string = string + array[index].to_s + delimeter
else
string = string + word + ' ' + array[index].to_s
end
end
string
end
def place_piece!(board, current_player)
current_player == 'player' ? player_turn!(board) : computer_turn!(board)
end
def alternate_player(player)
player == 'player' ? 'computer' : 'player'
end
board = initialize_board
player_score = 0
computer_score = 0
# Keeping playing until user chooses to quit
loop do
# Play game until player or computer wins 5 rounds
loop do
current_player ||= 'player'
loop do
display_board(board)
place_piece!(board, current_player)
current_player = alternate_player(current_player)
break if someone_won?(board) || board_full?(board)
end
display_board(board)
if someone_won?(board)
round_winner = detect_winner(board)
puts "#{round_winner} won the round!"
round_winner == 'Player' ? player_score += 1 : computer_score += 1
else
puts 'Round was tied!'
end
puts round_score_msg(player_score, computer_score)
break if player_score == MAX_ROUNDS || computer_score == MAX_ROUNDS
puts 'Press any key to play the next round'
gets.chomp
board = initialize_board
end
puts game_winner_msg(player_score, computer_score)
puts 'Would you like to play another game? [Y]es or [N]o'
break unless gets.chomp.downcase.start_with?('y')
end
puts 'Thank you for playing. Good bye!'
| true |
20e3af10d743aacfe634e650feb5270a581660e0 | Ruby | ValdemarTeodoro/bootcamp_ruby_exchange | /lib/app.rb | UTF-8 | 821 | 2.734375 | 3 | [] | no_license | require 'faker'
require_relative 'file_process/file_process'
require_relative 'billings/billing_partners'
require_relative 'billings/billing'
require_relative 'exchange/exchange'
require_relative 'exchange/exchange_file'
billing_partners = BillingPartners.new
billing_partners.process_data
billing = Billing.new("Leonard Mackenzie", Faker::Internet.email, Faker::Company.name, Faker::Number.decimal(l_digits: 3, r_digits: 2))
billing.add_billing_line
value = 123.45
value_exchanged = Exchange.new('USD', 'BRL', value).perform
puts value
puts value_exchanged
puts "\n"
puts "\n"
puts "\n"
puts ">" * 100
file = "assets/investments.txt"
exchange_file = ExchangeFile.new
data = exchange_file.read_and_process_file(file)
exchange_file.process_info(file, data)
puts "\n"
puts "\n"
puts "\n"
puts "." * 100
puts File.open(file).read | true |
81a3c4a8f866f69c9cc3b832e5f0f01e64b9bcb2 | Ruby | brasten/field_ex | /lib/field_ex.rb | UTF-8 | 950 | 2.53125 | 3 | [
"MIT"
] | permissive | require "field_ex/version"
# FieldEx parses field query expressions
#
# @see FieldEx::Parser.parse
#
module FieldEx
SEPARATOR = ","
NESTING = "()"
WILDCARD = "*"
NEGATION = "!"
# Helper method for filtering options hashes provided to as_json(opts)
# methods.
#
# @param [Hash] options
# @param [String] key
# @return [Hash] new options hash
#
def self.options_for(options, key)
options = options.dup
if fields = options.delete(:fields)
if f = fields.node_for(key)
options[:fields] = f
end
end
options
end
def self.parse(*exp)
parser = Parser.new()
exp.map { |e| e.kind_of?(Node) ? e : parser.parse(e) }.reduce(:+)
end
def json_options_for(options={}, key)
FieldEx.options_for(options, key)
end
end
require 'field_ex/extractor'
require 'field_ex/filter'
require 'field_ex/node'
require 'field_ex/param'
require 'field_ex/parser'
require 'field_ex/partial'
| true |
e35395d604798841c6a41d41335c637ee21aec47 | Ruby | gionaufal/rubymonk | /chapters/strings.rb | UTF-8 | 926 | 3.640625 | 4 | [] | no_license | rubymonk = "Ruby Monk"
puts rubymonk
# to use placeholders, the string has to be with double quotes
puts "This string has #{rubymonk.length} characters"
def string_length_interpolater(incoming_string)
"The string you just gave me has a length of #{incoming_string.length}"
end
# methods that return boolean values usually end with ?
puts "[Luke:] I can’t believe it. [Yoda:] That is why you fail.".include?("Yoda")
puts "Ruby is a beautiful language".start_with?("Ruby")
puts "I am a Rubyist".index("R")
puts 'This is Mixed CASE'.downcase
puts "ThiS iS A vErY ComPlEx SenTeNcE".swapcase
puts 'Fear is the path to the dark side'.split(' ')
puts 'Ruby' + 'Monk' == 'Ruby'.concat('Monk')
puts "I should look into your problem when I get time".sub('I','We')
puts "I should look into your problem when I get time".gsub('I','We')
# Repleaces every capital case for 0
puts 'RubyMonk Is Pretty Brilliant'.gsub(/[A-Z]/,'0')
| true |
28f91335d73713d43c9b003e397d6a878b1b6b7e | Ruby | ankane/pghero | /lib/pghero/methods/explain.rb | UTF-8 | 2,086 | 2.5625 | 3 | [
"MIT"
] | permissive | module PgHero
module Methods
module Explain
# TODO remove in 4.0
# note: this method is not affected by the explain option
def explain(sql)
sql = squish(sql)
explanation = nil
# use transaction for safety
with_transaction(statement_timeout: (explain_timeout_sec * 1000).round, rollback: true) do
if (sql.sub(/;\z/, "").include?(";") || sql.upcase.include?("COMMIT")) && !explain_safe?
raise ActiveRecord::StatementInvalid, "Unsafe statement"
end
explanation = select_all("EXPLAIN #{sql}").map { |v| v[:"QUERY PLAN"] }.join("\n")
end
explanation
end
# TODO rename to explain in 4.0
# note: this method is not affected by the explain option
def explain_v2(sql, analyze: nil, verbose: nil, costs: nil, settings: nil, buffers: nil, wal: nil, timing: nil, summary: nil, format: "text")
options = []
add_explain_option(options, "ANALYZE", analyze)
add_explain_option(options, "VERBOSE", verbose)
add_explain_option(options, "SETTINGS", settings)
add_explain_option(options, "COSTS", costs)
add_explain_option(options, "BUFFERS", buffers)
add_explain_option(options, "WAL", wal)
add_explain_option(options, "TIMING", timing)
add_explain_option(options, "SUMMARY", summary)
options << "FORMAT #{explain_format(format)}"
explain("(#{options.join(", ")}) #{sql}")
end
private
def explain_safe?
select_all("SELECT 1; SELECT 1")
false
rescue ActiveRecord::StatementInvalid
true
end
def add_explain_option(options, name, value)
unless value.nil?
options << "#{name}#{value ? "" : " FALSE"}"
end
end
# important! validate format to prevent injection
def explain_format(format)
if ["text", "xml", "json", "yaml"].include?(format)
format.upcase
else
raise ArgumentError, "Unknown format"
end
end
end
end
end
| true |
f0014c1ef7272278e682be4e68eda42aca5629be | Ruby | TakahiroTanaka-dev/Test-Drills | /14.rb | UTF-8 | 219 | 3.5625 | 4 | [] | no_license | def police_trouble(a, b)
if (a == true && b == true) or (a == false && b == false)
puts "True"
else
puts "False"
end
end
police_trouble(true, false)
police_trouble(true, true)
police_trouble(false, false) | true |
034d397d1a989acf7a281b0cb075f2e93f0b861d | Ruby | tbeeley/Q-R- | /spec/quarter_spec.rb | UTF-8 | 954 | 2.71875 | 3 | [] | no_license | require 'quarter'
describe Quarter do
let(:quarter1) { Quarter.new(data1) }
let(:data1) { {:AGILENT_TECHNOLOGIES_INC => 455, :ALCOA_INC => 322, :AARONS_INC => 636} }
let(:quarter2) { Quarter.new(data2) }
let(:data2) { {:AGILENT_TECHNOLOGIES_INC => 1104, :ASSET_ACCEP_CAP_CORP => 86, :APPLE_INC => 1215} }
context 'when initialized' do
it 'should have common stock positions' do
expect(quarter1.common_stock_positions).to be_an_instance_of Hash
end
end
context 'Quarter should know' do
it 'the total value of CSM_positions' do
expect(quarter1.total_value).to eq 1413
end
it 'its five largest holdings' do
expect(quarter1.biggest_positions(1)). to eq [[:AARONS_INC, 636]]
end
it 'how to make a comparison' do
expect(quarter2.comparison(quarter2)).to eq 'loss'
end
it 'its new stocks' do
expect(quarter2.new_stocks(quarter1)).to eq ({:ASSET_ACCEP_CAP_CORP => 86, :APPLE_INC => 1215})
end
end
end
| true |
8248dbe854c8fd5fcff5163462e51963f96b2f95 | Ruby | all-your-database/HSTracker | /app/log/log_reader_manager.rb | UTF-8 | 2,286 | 2.578125 | 3 | [
"MIT"
] | permissive | class LogReaderManager
TimeoutRead = 0.5
def start
log :reader_manager, starting: true
init_readers
@starting_point = get_starting_point
start_log_readers
end
def init_readers
log :reader_manager, init_readers: true
@power = LogReader.new('Power',
self,
starts_filters: ['GameState.'],
contains_filters: ['Begin Spectating', 'Start Spectator', 'End Spectator'])
@bob = LogReader.new('Bob', self)
@readers = [@power, @bob]
%w(Rachelle Asset Arena).each do |name|
@readers << LogReader.new(name, self)
end
@readers << LogReader.new('Zone', self, contains_filters: ['zone from'])
end
def get_starting_point
power_entry = @power.find_entry_point('GameState.DebugPrintPower() - CREATE_GAME')
bob_entry = @bob.find_entry_point('legend rank')
if power_entry.is_a?(Time)
power_entry = power_entry.to_r
end
if bob_entry.is_a?(Time)
bob_entry = bob_entry.to_r
end
log :reader_manager,
power_entry: power_entry,
bob_entry: bob_entry,
diff: power_entry > bob_entry
power_entry > bob_entry ? power_entry : bob_entry
end
def start_log_readers
log :reader_manager, starting_readers: @starting_point
@readers.each do |reader|
Dispatch::Queue.concurrent(:high).async do
reader.start(@starting_point)
end
end
end
def stop
log :reader_manager, stopping: true
if @readers
@readers.each do |reader|
reader.stop
end
end
end
def restart
log :reader_manager, restarting: true
if @readers
stop
@starting_point = get_starting_point
start_log_readers
else
start
end
end
def process_new_line(line)
Dispatch::Queue.main.async do
case line.namespace
when 'Power'
PowerGameStateHandler.handle(line.line)
when 'Zone'
ZoneHandler.handle(line.line)
when 'Asset'
AssetHandler.handle(line.line)
when 'Bob'
BobHandler.handle(line.line)
when 'Rachelle'
RachelleHandler.handle(line.line)
when 'Arena'
ArenaHandler.handle(line.line)
end
end
end
end
| true |
3d75e095185aa501eba72fedf9433ad244f11498 | Ruby | natenorberg/monstercheckout_rails | /app/models/reservation_equipment.rb | UTF-8 | 1,042 | 2.65625 | 3 | [] | no_license | # == Schema Information
#
# Table name: reservation_equipment
#
# id :integer not null, primary key
# reservation_id :integer
# equipment_id :integer
# quantity :integer
#
class ReservationEquipment < ActiveRecord::Base
self.table_name = 'reservation_equipment' # Tries to default to reservation_equipments
belongs_to :reservation, class_name: 'Reservation'
belongs_to :equipment, class_name: 'Equipment'
validates :quantity, numericality: {only_integer: true, greater_than: 0}, if: 'quantity != nil'
validate :quantity_should_be_less_than_total_quantity, if: 'quantity != nil'
# Not raising presence validation errors here because it seems to have some issues with the reservation forms
# This model has no controller so these relationships should only be created or updated from reservation_controller
private
def quantity_should_be_less_than_total_quantity
errors.add(:in_time, "can't be more than the total quantity") if
quantity > equipment.quantity
end
end
| true |
a828d404f81b80d0f97d63c4eedc4979b7f44a81 | Ruby | Adong520/stockpicker | /stock_picker.rb | UTF-8 | 308 | 3.171875 | 3 | [] | no_license | def stock_picker (stock)
revenue = stock[1] - stock[0]
pick = stock[0..1]
for i in 0..stock.length-1
for j in i+1..stock.length-1
rev = stock[j]-stock[i]
if rev > revenue
pick = [i,j]
revenue = rev
end
end
end
return pick
end
###############################################
| true |
cbab8575e5a6a985f863248e99cd41c8401f7b9e | Ruby | heydanhey/fun_tests | /prime_number.rb | UTF-8 | 1,502 | 3.71875 | 4 | [] | no_license | require 'rspec'
class PrimeNumber
def is_prime?(number)
if number == 1
return false
else
i = number - 1
while i > 1
if number % i == 0
return false
else
i -= 1
end
end
end
return true
end
def highest_prime_number_under(number)
until is_prime?(number)
number -=1
end
return number
end
end
RSpec.describe PrimeNumber do
describe '#is_prime?' do
let(:prime_number){PrimeNumber.new}
it 'should return "false" if given 1' do
expect(prime_number.is_prime?(1)).to eq(false)
end
it 'should return "true" if given 2' do
expect(prime_number.is_prime?(2)).to eq(true)
end
it 'should return "true" if given 3' do
expect(prime_number.is_prime?(3)).to eq(true)
end
it 'should return "false" if given 4' do
expect(prime_number.is_prime?(4)).to eq(false)
end
it 'should return "true" if given 5' do
expect(prime_number.is_prime?(5)).to eq(true)
end
end
describe '#highest_prime_number_under' do
let(:prime_number){PrimeNumber.new}
it 'should return "7" if given 10' do
expect(prime_number.highest_prime_number_under(10)).to eq(7)
end
it 'should return "839" if given 850' do
expect(prime_number.highest_prime_number_under(850)).to eq(839)
end
it 'should return "1699" if given 1700' do
expect(prime_number.highest_prime_number_under(1700)).to eq(1699)
end
end
end | true |
364cef6569b7c2e33edbb71e821a0a4bc5fb5e92 | Ruby | Drashti92/Hackerank-Solutions | /Day5_Loops.rb | UTF-8 | 147 | 2.78125 | 3 | [] | no_license | n = gets.strip.to_i
i = 1
while i<=10
d=n*i
puts "#{n} x #{i} = #{d}"
i = i+1
# this will cause execution to exit the loop
end
| true |
92dd0b72bc81972100142ec3b19cc452e28d9ffe | Ruby | cassiejdelacruz/course101 | /small_problems/easy_set_1/easy1_9.rb | UTF-8 | 178 | 3.609375 | 4 | [] | no_license | def sum(integer)
array = integer.to_s.chars
array.map! { |n| n.to_i }
array.reduce(:+)
end
puts sum(23) == 5
puts sum(496) == 19
puts sum(123_456_789) == 45
puts sum(456) | true |
0c3b9e83bbe180bb734ccdaeb3834a8f18d0fd24 | Ruby | classHANA/likelion | /ruby/scraper.rb | UTF-8 | 539 | 2.96875 | 3 | [] | no_license | require 'mechanize'
require 'pry'
require 'csv'
print '뭘 찾을까요?? : '
input = gets.chomp
agent = Mechanize.new
agent.user_agent_alias = 'Mac Safari'
page = agent.get('https://www.amazon.com')
search_form = page.form
search_form['field-keywords'] = input
page = search_form.submit
items = page.search('.s-result-item')
items.each do |item|
title = item.css('h2').text
price = item.css('.a-offscreen').text
CSV.open('./amazon.csv', 'a+') do |csv|
csv << [title, price]
end
end
puts '성공'
| true |
d50e1d2133f494c5c2c9c937a21d9f1c8c0d5375 | Ruby | vincent-psarga/ruby-tap-parser | /lib/tap-parser.rb | UTF-8 | 1,749 | 2.875 | 3 | [
"MIT"
] | permissive | module TapParser
class Test
attr_reader :passed, :skipped, :number, :description, :directive, :diagnostic
def initialize(passed, number, description = '', directive = '', diagnostic = '')
@passed = passed
@number = number
@description = description
@directive = directive
@diagnostic = diagnostic
@skipped = !(directive =~ /^skip.*/i).nil?
end
def failed
!@passed
end
def add_diagnostic(line)
return if /\s*?\.\.\./.match(line)
if @diagnostic.empty?
@diagnostic = line
else
@diagnostic = "#{@diagnostic}\n#{line}"
end
@diagnostic = @diagnostic.strip
end
end
class TapParser
attr_reader :test_count, :tests
def self.from_text(txt)
parser = TapParser.new(txt)
parser.read_lines()
parser
end
def initialize(content)
@content = content
@test_count = 0
@tests = []
end
def read_lines()
@content.split("\n").each {|l| read_line(l)}
end
def read_line(line)
/1\.\.(\d+)/.match(line) do |match|
@test_count = match.captures[0].to_i
return
end
/^(?<status>ok|not ok)\s*(?<test_number>\d*)\s*-?\s*(?<test_desc>[^#]*)(\s*#\s*(?<test_directive>.*))?/.match(line) do |match|
@tests << Test.new(
match[:status] == 'ok',
match[:test_number] ? match[:test_number].to_i : nil,
match[:test_desc] ? match[:test_desc].strip : '',
match[:test_directive]
)
return
end
/^(#\s*)?(?<test_diagnostic>.*)$/.match(line) do |match|
unless @tests.empty?
@tests.last.add_diagnostic(match[:test_diagnostic])
end
end
end
end
end
| true |
727f7592494863c8670157abb0fd3fade9458d9d | Ruby | Skylonatron/magic_statistics | /app/models/deck.rb | UTF-8 | 1,767 | 2.765625 | 3 | [] | no_license | class Deck < ApplicationRecord
validates :name, presence: true
has_many :decks_cards, class_name: "DecksCards", foreign_key: "deck_id", dependent: :destroy
has_many :cards, through: :decks_cards
belongs_to :user
def cards_with_sideboard
self.cards.select("cards.*, decks_cards.sideboard")
end
def get_colors
color_hash = self.cards.mainboard.group(:color).count.sort_by(&:last).reverse.to_h
color_hash.delete("C")
color_hash.delete("L")
colors_array = color_hash.keys.flat_map do |c|
if c.length > 1
c.split('')
else
c
end
end
colors_array.uniq
end
def self.create_from_file(file, name: nil)
d = Deck.new(name: file.original_filename)
cards = []
CSV.foreach(file.path, headers: true) do |row|
# collecting win loss data from the first row
if $. == 2
match_wins = row[8]
match_losses = row[9]
game_wins = row[10]
game_losses = row[11]
if match_wins.present?
d.match_wins = match_wins
d.match_losses = match_losses
d.game_wins = game_wins
d.game_losses = game_losses
end
end
name = row[0]
next unless name.present?
quantity = row[1]
magic_id = row[2]
rarity = row[3]
set = row[4]
collector_number = row[5]
premium = row[6]
sideboard = row[7]
card = Card.find_or_create_by(
name: name,
magic_id: magic_id,
rarity: rarity.parameterize.underscore,
set: set,
collector_number: collector_number,
premium: premium.parameterize
)
d.decks_cards.new(card: card, sideboard: sideboard.downcase)
end
return d
end
end
| true |
604c771727b4c6cae1d4daa36b856cd203c5b3b7 | Ruby | paullewallencom/ruby-978-1-78439-295-6 | /02/02-custom_matchers-v1.rb | UTF-8 | 893 | 3.203125 | 3 | [] | no_license | # v1 : custom error message without a custom matcher
class Customer
def initialize(opts)
# assume opts = { discounts: { "foo123" => 0.1 } }
@discounts = opts[:discounts]
end
def has_discount_for?(product_code)
@discounts.has_key?(product_code)
end
def discount_amount_for(product_code)
@discounts[product_code] || 0
end
end
describe "product discount" do
let(:product) { "foo123" }
let(:discounts) { { product => 0.1 } }
subject(:customer) { Customer.new(discounts: discounts) }
it "detects when customer has a discount" do
actual = customer.discount_amount_for(product)
expect(actual).to eq(0.2)
end
it "has a custom error message" do
actual = customer.discount_amount_for(product)
if actual != 0.2
fail "Expected discount amount to equal 0.2 not #{actual}"
end
end
end | true |
b0c9cd6d8b7aee4a7a8c0b7d246dad66f2dcdb3f | Ruby | wgreenberg/larceny | /app/models/simulation.rb | UTF-8 | 247 | 2.625 | 3 | [] | no_license | class Simulation < ApplicationRecord
def self.current_time
Simulation.last.sim_time
end
def self.next_time
Simulation.current_time + 1
end
def self.advance
sim = Simulation.last
sim.sim_time += 1
sim.save
end
end
| true |
1830b0610c026845a359837373fc3ebf3cf8708e | Ruby | parkermatheson/study_group | /vowel.rb | UTF-8 | 170 | 3.703125 | 4 | [] | no_license | vowel = ['a', 'e', 'i', 'o', 'u']
count = 0
str = 'Hello, this is Parker'
arr = str.split('')
arr.map do |i|
if vowel.include?(i)
count += 1
end
end
puts count
| true |
4240a9d7cf43bc502973ae86a205d7143cd3e0fb | Ruby | DavidEGrayson/redstone-bot2 | /lib/redstone_bot/brain.rb | UTF-8 | 766 | 3.140625 | 3 | [] | no_license | require 'thread'
module RedstoneBot
class Brain
attr_reader :synchronizer
def initialize(synchronizer)
@synchronizer = synchronizer
end
def start
stop
@thread = Thread.new do
@synchronizer.synchronize do
begin
yield
ensure
@thread = nil
end
end
end
nil
end
def stop
if @thread
@thread.terminate
@thread = nil
end
end
def alive?
(@thread and @thread.alive?) ? true : false
end
def running?
Thread.current == @thread
end
def require(&proc)
if running?
true
else
start(&proc)
false
end
end
end
end | true |
743a7974986b01be43afb780489097e16a23a3d0 | Ruby | atruby-team/internship-18-summer | /at-luantran/Week3/2018_07_03_exercise2_rubyday2.rb | UTF-8 | 64 | 3.125 | 3 | [] | no_license | a = [1, 2, 3, 1]
a.map! { |x| x.even? ? 'even' : 'odd' }
puts a
| true |
0d5808a2337bad37054b5c0ff51dfeb45225d0b4 | Ruby | justonemorecommit/puppet | /acceptance/lib/puppet/acceptance/service_utils.rb | UTF-8 | 7,212 | 2.625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | require 'puppet/acceptance/common_utils'
module Puppet
module Acceptance
module ServiceUtils
# Return whether a host supports the systemd provider.
# @param host [String] hostname
# @return [Boolean] whether the systemd provider is supported.
def supports_systemd?(host)
# The Windows MSI doesn't put Puppet in the Ruby vendor or site dir, so loading it fails.
return false if host.platform.variant == 'windows'
ruby = Puppet::Acceptance::CommandUtils.ruby_command(host)
suitable = on(host, "#{ruby} -e \"require 'puppet'; puts Puppet::Type.type(:service).provider(:systemd).suitable?\"" ).stdout.chomp
suitable == "true" ? true : false
end
# Construct manifest ensuring service status.
# @param service [String] name of the service
# @param status [Hash] properties to set - can include 'ensure' and 'enable' keys.
# @return [String] a manifest
def service_manifest(service, status)
ensure_status = "ensure => '#{status[:ensure]}'," if status[:ensure]
enable_status = "enable => '#{status[:enable]}'," if status[:enable]
%Q{
service { '#{service}':
#{ensure_status}
#{enable_status}
}
}
end
# Alter the state of a service using puppet apply and assert that a change was logged.
# Assumes the starting state is not the desired state.
# @param host [String] hostname.
# @param service [String] name of the service.
# @param status [Hash] properties to set - can include 'ensure' and 'enable' keys.
# @return None
def ensure_service_change_on_host(host, service, status)
# the process of creating the service will also start it
# to avoid a flickering test from the race condition, this test will ensure
# that the exit code is either
# 2 => something changed, or
# 0 => no change needed
apply_manifest_on host, service_manifest(service, status), :acceptable_exit_codes => [0, 2] do
assert_match(/Service\[#{service}\]\/ensure: ensure changed '\w+' to '#{status[:ensure]}'/, stdout, 'Service status change failed') if status[:ensure]
assert_match(/Service\[#{service}\]\/enable: enable changed '\w+' to '#{status[:enable]}'/, stdout, 'Service enable change failed') if status[:enable]
end
end
# Ensure the state of a service using puppet apply and assert that no change was logged.
# Assumes the starting state is the ensured state.
# @param host [String] hostname.
# @param service [String] name of the service.
# @param status [Hash] properties to set - can include 'ensure' and 'enable' keys.
# @return None
def ensure_service_idempotent_on_host(host, service, status)
# ensure idempotency
apply_manifest_on host, service_manifest(service, status) do
assert_no_match(/Service\[#{service}\]\/ensure/, stdout, 'Service status not idempotent') if status[:ensure]
assert_no_match(/Service\[#{service}\]\/enable/, stdout, 'Service enable not idempotent') if status[:enable]
end
end
# Alter the state of a service using puppet apply, assert that it changed and change is idempotent.
# Can set 'ensure' and 'enable'. Assumes the starting state is not the desired state.
# @param host [String] hostname.
# @param service [String] name of the service.
# @param status [Hash] properties to set - can include 'ensure' and 'enable' keys.
# @param block [Proc] optional: block to verify service state
# @return None
def ensure_service_on_host(host, service, status, &block)
ensure_service_change_on_host(host, service, status)
assert_service_status_on_host(host, service, status, &block)
ensure_service_idempotent_on_host(host, service, status)
assert_service_status_on_host(host, service, status, &block)
end
# Checks that the ensure and/or enable status of a service are as expected.
# @param host [String] hostname.
# @param service [String] name of the service.
# @param status [Hash] properties to set - can include 'ensure' and 'enable' keys.
# @param block [Proc] optional: block to verify service state
# @return None
def assert_service_status_on_host(host, service, status, &block)
ensure_status = "ensure.+=> '#{status[:ensure]}'" if status[:ensure]
enable_status = "enable.+=> '#{status[:enable]}'" if status[:enable]
on host, puppet_resource('service', service) do
assert_match(/'#{service}'.+#{ensure_status}.+#{enable_status}/m, stdout, "Service status does not match expectation #{status}")
end
# Verify service state on the system using a custom block
if block
yield block
end
end
# Refreshes a service.
# @param host [String] hostname.
# @param service [String] name of the service to refresh.
# @return None
def refresh_service_on_host(host, service)
refresh_manifest = %Q{
service { '#{service}': }
notify { 'Refreshing #{service}':
notify => Service['#{service}'],
}
}
apply_manifest_on(host, refresh_manifest)
end
# Runs some common acceptance tests for nonexistent services.
# @param service [String] name of the service
# @return None
def run_nonexistent_service_tests(service)
step "Verify that a nonexistent service is considered stopped, disabled and no logonaccount is reported" do
on(agent, puppet_resource('service', service)) do |result|
{ enable: false, ensure: :stopped }.each do |property, value|
assert_match(/#{property}.*#{value}.*$/, result.stdout, "Puppet does not report #{property}=#{value} for a non-existent service")
end
assert_no_match(/logonaccount\s+=>/, result.stdout, "Puppet reports logonaccount for a non-existent service")
end
end
step "Verify that stopping and disabling a nonexistent service is a no-op" do
manifest = service_manifest(service, ensure: :stopped, enable: false)
apply_manifest_on(agent, manifest, catch_changes: true)
end
[
[ :enabling, [ :enable, true ]],
[ :starting, [ :ensure, :running ]]
].each do |operation, (property, value)|
manifest = service_manifest(service, property => value)
step "Verify #{operation} a non-existent service prints an error message but does not fail the run without detailed exit codes" do
apply_manifest_on(agent, manifest) do |result|
assert_match(/Error:.*#{service}.*$/, result.stderr, "Puppet does not error when #{operation} a non-existent service.")
end
end
step "Verify #{operation} a non-existent service with detailed exit codes correctly returns an error code" do
apply_manifest_on(agent, manifest, :acceptable_exit_codes => [4])
end
end
end
end
end
end
| true |
476a0d90a7fc8e666fbc59d44cbe30bdfb841f51 | Ruby | elan690/learning-ruby-on-hard-way | /ex28.rb | UTF-8 | 971 | 3.6875 | 4 | [] | no_license | puts true and true
true
puts false and true
false
puts1 == 1 and 2 == 1
true
puts "test" == "test"
true
puts 1 == 1 or 2 != 1
true
puts true and 1 == 1
true
puts false and 0 != 0
false
puts true or 1 == 1
true
puts "test" == "testing"
false
puts 1 != 0 and 2 == 1
false
puts "test" != "testing"
true
puts "test" == 1
false
puts not (true and false)
true
puts not (1 == 1 and 0 != 1)
false
puts not (10 == 1 or 1000 == 1000)
false
puts not (1 != 10 or 3 == 4)
false
puts not ("testing" == "testing" and "Zed" == "Cool Guy")
true
puts 1 == 1 and not ("testing" == 1 or 1 == 0)
true
puts "chunky" == "bacon" and not (3 == 4 or 3 == 3)
false
puts 3 == 3 and not ("testing" == "testing" or "Ruby" == "Fun")
false
| true |
306f03e574e0d6a3143c910a864ca1d9f2f26d3e | Ruby | jebediahelliott/sinatra-mvc-lab-v-000 | /models/piglatinizer.rb | UTF-8 | 589 | 3.328125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class PigLatinizer
def piglatinize(input)
new_string = ""
input = input.split
input.each do |word|
# binding.pry
new_word = word.split(/([aeiouAEIOU].*)/)
if new_word[0] == ""
new_word[0] = "way"
new_word[0], new_word[1] = new_word[1], new_word[0]
else
new_word[0] = "#{new_word[0]}ay"
new_word[0], new_word[1] = new_word[1], new_word[0]
end
if input.count == 1
new_string << new_word.join
else
new_string << "#{new_word.join} "
end
end
new_string.strip
end
end
| true |
eed60581714cf753868445696cf11f06da4f4551 | Ruby | Sophie5/Boris-bikes-final- | /lib/docking_station.rb | UTF-8 | 704 | 3.328125 | 3 | [] | no_license | require_relative 'bike'
class DockingStation
# Docking station starts empty. Bike is created outside
DEFAULT_CAPACITY = 20
attr_reader :capacity
def initialize(capacity = DEFAULT_CAPACITY)
@capacity = capacity
@bikes_arr = []
end
def release_bike
fail "no bikes" if empty?
@bikes_arr.pop if @bike.working?
end
def dock_bike(bike)
# This method will send error if 20 bikes have been docked
# and it therefore cannot accept any more.
fail "I iz full" if full?
@bike = bike
@bikes_arr << @bike
end
private
def full?
@bikes_arr.length >= @capacity ? true : false
end
def empty?
@bikes_arr.empty? ? true : false
end
end
| true |
40377db16bb94939d5170399042125b850142297 | Ruby | jimberlage/tictactoe | /lib/computer_player.rb | UTF-8 | 408 | 3.203125 | 3 | [] | no_license | require './lib/tree_node'
class ComputerPlayer
def initialize(symbol, board)
super(symbol, board)
@tree_root = TreeNode.new
end
def make_game_tree(root)
end
def is_winning_node?(node)
node.value[:board].winning_board?(@symbol)
end
def is_losing_node?(node)
node.value[:board].losing_board?(@symbol)
end
def switch_symbols(symbol)
symbol == :x ? :o : :x
end
end | true |
5f36df333fed02a17421bc7e8177c0a153a955ac | Ruby | bkichler/chessapp | /spec/models/knight_spec.rb | UTF-8 | 1,237 | 2.8125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Knight, type: :model do
it 'is created with populate_game method' do
game = FactoryBot.create(:game)
expect(game.pieces.where(type: "Knight").size).to be(4)
end
it 'has a valid_move? method that returns true for a 2-to-1 move in any direction' do
game = FactoryBot.create(:game)
user = FactoryBot.create(:user)
game.black_player_user_id = user.id
game.populate_game!
knight = game.pieces.where("x_pos = ? AND y_pos = ?", 1, 7).first
expect(knight.valid_move?(2, 5)).to eq(true)
expect(knight.valid_move?(0, 5)).to eq(true)
expect(knight.valid_move?(6, 3)).to eq(false)
expect(knight.valid_move?(6, 4)).to eq(false)
expect(knight.valid_move?(5, 3)).to eq(false)
end
it 'should be able to move 2-1 to around the board using move_to!' do
Game.destroy_all
User.destroy_all
Piece.destroy_all
game = FactoryBot.create(:game)
user = FactoryBot.create(:user)
game.black_player_user_id = user.id
game.populate_game!
Knight.first.move_to!(5, 2)
Knight.first.move_to!(4, 4)
expect(game.pieces.where("x_pos = ? AND y_pos = ?", 4, 4).first.id).to eq(Knight.first.id)
end
end | true |
a57808fe9bc3d9b0eb4a1f270a6723269109ac0b | Ruby | jochenseeber/calificador | /lib/calificador/key.rb | UTF-8 | 1,992 | 2.546875 | 3 | [
"MIT"
] | permissive | # typed: strict
# frozen_string_literal: true
require "minitest"
module Calificador
# Test subject key
class Key
include Util::EscapeHatch
NO_TRAIT = :"<none>"
DEFAULT_TRAIT = :"<default>"
class << self
sig { params(type: Module, trait: T.nilable(Symbol)).returns(Key) }
def [](type, trait = NO_TRAIT)
new(type: type, trait: trait)
end
end
sig { returns(Module) }
attr_reader :type
sig { returns(Symbol) }
attr_reader :trait
sig { params(type: Module, trait: T.nilable(Symbol)).void }
def initialize(type:, trait: NO_TRAIT)
@type = type
@trait = T.let(trait || NO_TRAIT, Symbol)
end
sig { returns(T::Boolean) }
def trait?
@trait != NO_TRAIT && @trait != DEFAULT_TRAIT
end
sig { returns(T::Boolean) }
def default_trait?
@trait == DEFAULT_TRAIT
end
sig { returns(Integer) }
def hash
(@type.hash * 31) + @trait.hash
end
sig { params(other: BasicObject).returns(T::Boolean) }
def ==(other)
if class_of(other) == Key
key = T.cast(other, Key)
(@type == key.type) && (@trait == key.trait) ? true : false
else
false
end
end
alias_method :eql?, :==
sig { params(base_module: T.nilable(Module)).returns(String) }
def to_s(base_module: nil)
type_name = @type.name_without_common_parents(base: base_module) || "<anonymous>"
@trait == NO_TRAIT ? type_name : "#{type_name} (#{@trait})"
end
alias_method :inspect, :to_s
sig { params(trait: T.nilable(Symbol)).returns(Key) }
def with(trait)
case trait
when nil, DEFAULT_TRAIT
self
else
trait == @trait ? self : Key.new(type: @type, trait: trait)
end
end
sig { params(key: Key).returns(Key) }
def with_default(key)
if @trait == DEFAULT_TRAIT && @trait != key.trait
Key[@type, key.trait]
else
self
end
end
end
end
| true |
a6f1b3a9d256ab4860847581120036b108001b29 | Ruby | s-daoud/w1 | /w1d1/iteration_review.rb | UTF-8 | 897 | 3.859375 | 4 | [] | no_license | def factors(num)
(1..num).select{ |el| num % el == 0 }
end
def substrings(string)
subs = []
(string.length).times do |x|
(string[x..-1].length).times do |y|
subs << string[x..x + y] unless subs.include?(string[x..x + y])
end
end
subs
end
def subwords(word, dictionary)
words = substrings(word)
words.select do |el|
dictionary.include?(el)
end
end
class Array
def bubble_sort!(&prc)
prc ||= Proc.new { |x, y| x <=> y }
sorted = false
until sorted
sorted = true
self.each_index do |idx|
break if idx + 1 == self.length
if prc.call(self[idx], self[idx + 1]) == 1
self[idx], self[idx + 1] = self[idx + 1], self[idx]
sorted = false
end
end
end
self
end
def bubble_sort(&prc)
self.dup.bubble_sort!(&prc)
end
end
p [1, 2, 3, 4, 5].shuffle.bubble_sort! { |x, y| y <=> x }
| true |
6391abd36bd5d8ea159e1d59c09f8e030a4c9691 | Ruby | nikhgupta/handlisted | /spec/support/matchers/merit_badge_matcher.rb | UTF-8 | 1,971 | 2.546875 | 3 | [] | no_license | module CustomMatchersForCapybara
class HaveBadge
def initialize(*expected)
name, level = [expected].flatten
@badge = Merit::Badge.find_by_name_and_level(name, level)
end
def matches?(page_or_model)
@page_or_model = page_or_model
is_page? ? page_has_badge? : model_has_badge?
end
def failure_message
is_page? ? failure_message_when_page : failure_message_when_model
end
def failure_message_when_negated
@negated = true
failure_message
end
def special
@special = true
self
end
def unique
@unique = true
self
end
def with_difficulty(diff)
@difficulty = diff
self
end
private
def is_page?
@page_or_model.is_a?(Capybara::Session)
end
def badge_name
@badge.name.humanize.titleize + (@badge.level ? " L#{@badge.level}" : "")
end
def page_has_badge?
valid = true
badge = @page_or_model.all("a.badge", text: badge_name).first
valid &&= badge.present?
valid &&= badge[:title] == @badge.description
valid &&= badge[:class].include?("special") if @special
valid &&= badge.has_selector?("i.fa.fa-bolt") if @unique
valid &&= badge[:class].include?(@difficulty) if @difficulty.present?
valid
end
def model_has_badge?
@page_or_model.reload.badges.include?(@badge)
end
def failure_message_when_page
attributes = []
attributes << "unique" if @unique
attributes << "special" if @special
attributes << @difficulty if @difficulty.present?
"expected #{@page_or_model.current_path}#{@negated ? " not" : ""} to have #{attributes.join(" ")} badge #{badge_name}"
end
def failure_message_when_model
"expected #{@page_or_model.class.name} #{@page_or_model}#{@negated ? " not" : ""} to have badge #{badge_name}"
end
end
def have_badge(*expected)
HaveBadge.new(*expected)
end
end
| true |
5e16122b6b33bcf205cec12df288a4f4227352c2 | Ruby | dball/acts_as_calendar | /spec/models/calendar_spec.rb | UTF-8 | 2,363 | 2.625 | 3 | [] | no_license | require File.dirname(__FILE__) + '/../spec_rails_plugin_helper'
describe Calendar, "when empty" do
before(:each) do
@calendar = Factory(:calendar)
end
it "should have no dates" do
@calendar.dates.should == []
@calendar.dates.values.should == []
end
it "should have no events" do
@calendar.events.should == []
end
it "should fill with dates" do
dates = (Date.parse('2008-01-01') .. Date.parse('2008-01-02'))
@calendar.fill_dates(dates)
@calendar.dates.values.should == dates.to_a
end
end
describe Calendar, "when created for certain dates" do
before(:each) do
@dates = (Date.today .. 6.days.since(Date.today))
@calendar = Calendar.create_for_dates(@dates.first, @dates.last)
end
it "should have those dates" do
@calendar.dates.values.should == @dates.to_a
end
it "should find no events for one date" do
@calendar.events.find_by_dates(@dates.first).should == []
end
it "should find no events for a range of dates" do
@calendar.events.find_by_dates(@dates.first, @dates.last).should == []
end
it "should find an event on the first date" do
event = @calendar.events.create
event.occurrences << @calendar.dates.find_by_value(@dates.first)
@calendar.events.find_by_dates(@dates.first).should == [event]
end
it "should find an event on the first and last dates" do
events = [@dates.first, @dates.last].map do |date|
event = @calendar.events.create
event.occurrences << @calendar.dates.find_by_value(date)
event
end
@calendar.events.find_by_dates(@dates.first, @dates.last).should == events
end
it "should create single date events" do
event = @calendar.events.create_for(@dates.first)
event.dates.map {|cdate| cdate.value}.should == [@dates.first]
end
it "should create date range events" do
event = @calendar.events.create_for(@dates.first, @dates.last)
event.dates.map {|cdate| cdate.value}.should ==
(@dates.first .. @dates.last).to_a
end
it "should create multi-day events from enumerables" do
event = @calendar.events.create_for(@dates)
event.dates.map {|cdate| cdate.value}.should == @dates.to_a
end
it "should create multi-day events from varargs" do
event = @calendar.events.create_for(*@dates)
event.dates.map {|cdate| cdate.value}.should == @dates.to_a
end
end
| true |
13dc5476ca12f667ae75ccda9e18309d401bea5d | Ruby | oliverpople/battle_canace | /lib/player.rb | UTF-8 | 250 | 3.28125 | 3 | [] | no_license | require_relative 'game.rb'
class Player
attr_reader :name, :hp_value
DEFAULT_HP_VALUE = 60
def initialize(name, hp_value = DEFAULT_HP_VALUE)
@name = name
@hp_value = hp_value
end
def receive_damage
@hp_value -= 10
end
end
| true |
1023fb0e8c9e61c47418ed3c6aade037e6b651f0 | Ruby | kalanchoej/check_upload_queues | /check_queue.rb | UTF-8 | 2,659 | 3.015625 | 3 | [] | no_license | #!/usr/bin/ruby
# The purpose of this script is to check the size of the queues to central.
# It uses the Expect module to log in to the server and go to monitor upload
# queue.
require 'pty'
require 'expect'
host = ARGV[0]
login = ARGV[1]
pass = ARGV[2]
site = ARGV[3]
ARGV[4] ? timeout = ARGV[4].to_i : timeout = 5
def check_queue(host, login, pass, site, timeout) # TODO: return something useful on timeouts
# Pattern to return the site and number of items in the queue
# Watch out for [[:cntrl:]] which matches an invisible character in the output
site_pat = %r/#{site}[[:cntrl:]]\[\d+;\d+H(\d+)/io
size = ''
PTY.spawn("ssh #{login}@#{host}") do |ssh_out, ssh_in|
ssh_out.sync = true
ssh_out.expect(/password:/, timeout) { |r| ssh_in.puts pass }
ssh_out.expect(/Choose one.*M.*/, timeout) { |r| ssh_in.puts "m" }
ssh_out.expect(/Choose one.*M.*/, timeout) { |r| ssh_in.puts "m" }
ssh_out.expect(/Choose one.*U.*/, timeout) { |r| ssh_in.puts "u" }
#Process the final screen where our numbers are. Double timeout value for the long load
ssh_out.expect(/Get CURRENT data/, timeout * 2) do |output|
if site == "all"
site_pat = %r/6[a-z]{4}[[:cntrl:]]\[\d+;\d+H(\d+)/io
#scan the output then sum the items contained within 2 nested arrays
size = output.to_s.scan(site_pat).flatten!.collect!{|s| s.to_i}.inject(:+)
else
queue = site_pat.match(output.to_s)
queue ? size = queue[1].to_i : abort("The pattern did not return a value. Check your site code")
end
end
# Exits the script. TODO: There may be a better way to clean up the connection
ssh_out.expect(/Choose one.*Q/, timeout) { |r| ssh_in.puts "q" }
ssh_out.expect(/Choose one.*Q/, timeout) { |r| ssh_in.puts "q" }
ssh_out.expect(/Choose one.*Q/, timeout) { |r| ssh_in.puts "q" }
ssh_out.expect(/Choose one.*X/, timeout) { |r| ssh_in.puts "x" }
end
size
end
def help()
STDOUT.flush
STDOUT.puts <<-EOF
A ruby utility to check the status of upload queues for an InnReach system. This
script will return an integer
Usage:
check_queue host login pass site [timeout]
Required Parameters:
host: The Millennium host to connect to
login: A username that will open Millennium telnet on host
pass: Password associated with login
site: The sitecode to check, or use "all" to return the total (from the first page)
Optional Parameters
timeout: An optional timeout value in seconds for processing of individual screens.
Default: 5
EOF
end
if ARGV.length < 4
help
abort("Missing parameters")
end
p check_queue(host, login, pass, site, timeout)
| true |
66ac3d44fa6b795830a0550c8716483a3ba257b9 | Ruby | learn-academy-2021-bravo/week-6-assessment-hexflores87 | /rails-commenting.rb | UTF-8 | 1,697 | 2.65625 | 3 | [] | no_license | # ASSESSMENT 6: Rails Commenting Challenge
# Add comments to the Rails Blog Post Challenge
# Explain the purpose and functionality of the code directly below the 10 comment tags
# FILE: app/controller/blog_posts_controller.rb
# ---1)
# This purpose represents creating a controller called BlogPostsController. In a standard rails application all the apps controllers are inherited from the ApplicationController.
class BlogPostsController < ApplicationController
def index
# ---2)
# represents the instance variable from the controller method.
@posts = BlogPost.all
end
def show
# ---3) Lists one item in the model
#
@post = BlogPost.find(params[:id])
end
# ---4) Shows a form to the user.
def new
@post = Post.new
end
def create
# ---5) This will add info to the DB
@post = BlogPost.create(blog_post_params)
if @post.valid?
redirect_to blog_post_path(@post)
else
redirect_to new_blog_post_path
end
end
# ---6) This will edit the DB
def edit
@post = BlogPost.find(params[:id])
end
def update
@post = BlogPost.find(params[:id])
# ---7) Changes the DB.
@post.update(blog_post_params)
if @post.valid?
redirect_to blog_post_path(@post)
else
redirect_to edit_blog_post_path
end
end
def destroy
@post = BlogPost.find(params[:id])
if @post.destroy
redirect_to blog_posts_path
else
# ---8) This will remove ino from DB
redirect_to blog_post_path(@post)
end
end
# ---9) Private is used to protect the params.
private
def blog_post_params
# ---10)
params.require(:blog_post).permit(:title, :content)
end
end
| true |
192b26289ffae094e3019bd1f20121d3d17f6bf6 | Ruby | adk9/citadown | /citadown | UTF-8 | 15,003 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env ruby
# == Synopsis
# This is a simple CLI utility to download (BibTex) citations
# of known authors from DBLP.
#
# == Usage
# citadown [options]
#
# Options:
# -h, --help Display this help message
# -V, --version Display the version
# -v, --verbose Verbose output
# -a, --author NAME Name of the author (eg. filinski)
# -k, --key ID DBLP ID for the bibTex entry (eg. conf/padl/LiT10)
# -c, --conf NAME Name of the conference (eg. POPL)
# -t, --citation (NAME, YEAR) Citation including the author and year (eg. (moggi, 1991))
# -i, --input FILE File to read the entries from (default input.cit)
# -o, --output FILE File to write the bib output to (default dblp.bib)
# -C, --check Sanity check for the input
# -w, --keyword WORD Keyword search (author, title, conference) on DBLP
#
# == Description
# Here are some examples of how to use citadown:
# citadown -v -a "per martin lof" -a "grigori mints"
# citadown -k "conf/popl/2010"
# citadown -c icfp
# citadown -i bib.cit -o paper.bib
# citadown -t "(moggi, 1991)"
# citadown -w continuations
#
# All the (author and key) entries to read the citations from can be
# specified in an input file passed as a runtime parameter to citadown.
# The format of the input file is:
# author=author1
# author=author2
# key=DBLPkey1
#
# The DBLP citations often are very verbose and include details like
# the page numbers (from the journal that the paper appeared in), the
# source, the link to the electronic edition etc. citadown allows you
# to define a set of tags that you would like to ignore and exclude from
# the generated bibTex file. By default, it looks for a file ignore.cit in
# the CWD for the keywords to ignore.
#
# == Author
# Abhishek Kulkarni
#
# == Copyright
# Copyright (c) 2011 Abhishek Kulkarni. Licensed under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'optparse'
require 'rdoc/usage'
require 'ostruct'
require 'net/http'
require 'rexml/document'
begin
require 'progressbar' # sudo gem install progressbar
rescue LoadError
class ProgressBar
attr_reader :msg
attr_reader :limit
attr_reader :cur
def initialize(msg, limit)
@msg = msg
@limit = limit
@cur = 0
$stderr.print "#{@msg}:\t#{@cur}%"
end
def inc
@cur += 1
$stderr.print "\r"
$stderr.print "#{@msg}:\t#{(@cur * 100)/@limit}%"
end
def finish
$stderr.print "\n"
end
end
end
class Citadown
VERSION = '0.2.2'
DBLP_SERVER = "http://dblp.uni-trier.de/"
DBLP_DB = DBLP_SERVER + "db/indices/a-tree/"
DBLP_AUTHORS = DBLP_SERVER + "rec/pers/"
DBLP_CONF = DBLP_SERVER + "db/conf/"
DBLP_BIBTEX = DBLP_SERVER + "rec/bibtex/"
DBLP_MIRROR = "http://dblp.mpi-inf.mpg.de/dblp-mirror/"
attr_reader :options
def initialize(arguments, stdin)
@arguments = arguments
@stdin = stdin
@options = OpenStruct.new
@options.verbose = false
@options.check = false
@options.author = []
@options.key = []
@options.conf = []
@options.keyword = []
@options.citation = []
@options.input = "input.cit"
@options.output = "dblp.bib"
end
def run
if parsed_options? && arguments_valid?
process_args
else
output_usage
end
end
protected
def parsed_options?
# Specify options
opts = OptionParser.new
opts.on('-V', '--version') { output_version ; exit 0 }
opts.on('-h', '--help') { output_help }
opts.on('-v', '--verbose') { @options.verbose = true }
opts.on('-a', '--author NAME') { |a| @options.author << a }
opts.on('-k', '--key ID') { |k| @options.key << k }
opts.on('-c', '--conf NAME') { |c| @options.conf << c }
opts.on('-w', '--keyword WORD') { |w| @options.keyword << w }
opts.on('-i', '--input FILE') { |f| @options.input = f }
opts.on('-o', '--output FILE') { |f| @options.output = f }
opts.on('-t', '--citation (NAME, YEAR)') { |t| @options.citation << t }
opts.on('-C', '--check') { |c| @options.check = true }
opts.parse!(@arguments) rescue return false
true
end
# True if required arguments were provided
def arguments_valid?
true if @options.author.length >= 1 or @options.key.length >= 1 or
@options.conf.length >= 1 or @options.keyword.length >= 1 or @options.input != nil
end
# Output a detailed help message
def output_help
output_version
RDoc::usage()
end
# Output the usage (with options)
def output_usage
RDoc::usage('usage')
end
# Output the current version
def output_version
puts "#{File.basename(__FILE__)} v#{VERSION}"
end
# Fetch the body given a URL to the web page
def fetch_body(url)
url = URI.escape(url)
content = Net::HTTP.get_response(URI.parse(url))
case content
when Net::HTTPSuccess
return content.body
else
content.error!
end
end
# Method to check the status of the given author
def check_author(author)
authors = get_authors(author)
if authors.length < 1
puts "% Author #{author}\t\t\t\t.. NOT FOUND"
elsif authors.length > 1
puts "% Author #{author}\t\t\t\t.. AMBIGUOUS"
puts "%%% multiple matches: (#{authors.join(', ')})\n"
else
puts "% Author #{author} (#{authors[0]})\t\t\t.. OK"
end
return authors
end
# Method to check the status of the given DBLP key
def check_key(key)
bibentries = get_bibtex(key)
if bibentries.length > 0
puts "% bibTex entry #{key}\t\t\t\t.. OK"
else
puts "% bibTex entry #{key}\t\t\t\t.. NOT FOUND"
end
return bibentries
end
# Method to check the status of the given conference
def check_conf(conf)
keys = get_conf(conf)
if keys.length > 0
puts "% Conference name #{conf}\t\t\t\t.. OK"
else
puts "% Conference name #{conf}\t\t\t\t.. NOT FOUND"
end
return keys
end
# Method to check the status of given citation key
def check_citation(citation)
keys = []
if citation =~ /^\((.+),\s*(\d+)\)$/
author, year = $1, $2
authors = get_authors(author)
if authors.length < 1
puts "% Citation key (#{author}, #{year})\t\t\t.. NOT FOUND"
else
authors.each do |author|
k = get_keys_by_year(author, year)
if k.length > 0
puts "% Citation key (#{author}, #{year})\t\t\t.. OK"
keys += k
else
puts "% Citation key (#{author}, #{year})\t\t\t.. NOT FOUND"
end
end
end
else
puts "% Citation key (#{author}, #{year})\t\t\t.. INVALID"
end
return keys
end
def interrupted(bibentries)
print "\n"
print_entries(bibentries) if bibentries.length > 0 and not @options.check
exit
end
# Process input arguments
def process_args
bibentries = []
trap("INT") { interrupted(bibentries) }
if @options.author.length >= 1
@options.author.each do |a|
authors = check_author(a)
return if @options.check or authors.length != 1
keys = get_keys(authors[0])
bar = ProgressBar.new("#{keys.length} papers", keys.length)
keys.each {|key|
bibentries += get_bibtex(key)
bar.inc
}
bar.finish
end
elsif @options.key.length >= 1
@options.key.each do |k|
bibentries += check_key(k)
return if @options.check or bibentries.length == 0
end
elsif @options.conf.length >= 1
@options.conf.each do |c|
keys = check_conf(c)
return if @options.check or keys.length == 0
bar = ProgressBar.new("#{keys.length} papers", keys.length)
keys.each {|key|
bibentries += get_bibtex(key)
bar.inc
}
bar.finish
end
elsif @options.keyword.length >= 1
return if @options.check
@options.keyword.each do |k|
keys = get_keys_by_keyword(k)
bar = ProgressBar.new("#{keys.length} papers", keys.length)
keys.each {|key|
bibentries += get_bibtex(key)
bar.inc
}
bar.finish
end
elsif @options.citation.length >= 1
@options.citation.each do |c|
keys = check_citation(c)
return if @options.check or keys.length == 0
keys.each {|key| bibentries += get_bibtex(key)}
end
elsif @options.input
if not File.exists?(@options.input)
puts "% Invalid input file #{@options.input}"
output_usage
end
entries = File.open(@options.input, "r") { |f| f.read }
entries.each do |entry|
next if entry =~ /^#.*$/
next if entry =~ /^$/
if entry =~ /^\s*author=(.+)$/
authors = check_author($1)
next if @options.check or authors.length != 1
keys = get_keys(authors[0])
bar = ProgressBar.new("#{keys.length} papers", keys.length)
keys.each {|key|
bibentries += get_bibtex(key)
bar.inc
}
bar.finish
elsif entry =~ /^\s*key=(.+)$/
bibentries += check_key($1)
elsif entry =~ /^\s*conf=(.+)$/
keys += check_conf($1)
next if @options.check or keys.length < 1
bar = ProgressBar.new("#{keys.length} papers", keys.length)
keys.each {|key|
bibentries += get_bibtex(key)
bar.inc
}
bar.finish
elsif entry =~ /^\s*citation=(.+)$/
keys = check_citation($1)
keys.each {|key| bibentries += get_bibtex(key)} if keys
elsif entry =~ /^\s*keyword=(.+)$/
keys += get_keys_by_keyword($1)
next if @options.check or keys.length < 1
bar = ProgressBar.new("#{keys.length} papers", keys.length)
keys.each {|key|
bibentries += get_bibtex(key)
bar.inc
}
bar.finish
else
puts "% Ignoring invalid entry #{$1}"
end
end
else
output_usage
end
print_entries(bibentries) if bibentries.length > 0 and not @options.check
end
# Fetch all the authors from the DBLP database
def get_authors(author)
authors = []
if author =~ /\w\/.*:.*$/
authors << author
else
body = fetch_body(DBLP_SERVER + "search/author?xauthor=" + author)
doc = REXML::Document.new(body) if body
doc.elements.each('authors/author') {|e| authors << e.attributes['urlpt']}
end
return authors
end
# Fetch all the DBLP keys associated with a given author from the DBLP database
def get_keys(author)
return nil if not author
puts "% Downloading citations for author #{author}." if @options.verbose
dblpkeys = []
body = fetch_body(DBLP_AUTHORS + author + "/xk")
doc = REXML::Document.new(body) if body
doc.elements.each('dblpperson/dblpkey') {|e| dblpkeys << e.text}
return dblpkeys
end
# Fetch all the keys associated with a keyword from the DBLP database
def get_keys_by_keyword(keyword)
return nil if not keyword
puts "% Downloading citations for keyword #{keyword}." if @options.verbose
dblpkeys = []
body = fetch_body(DBLP_MIRROR + "index.php?query=#{keyword}&qp=H1.60")
body.each do |line|
hits = $1 if line =~ /^\s*AC\.result\.H_boxes\[1\]=(.+)$/
hits.gsub(/href=\\"#{DBLP_BIBTEX}([^\\]+)\\"/) {|l| dblpkeys << $1} if hits
end
return dblpkeys
end
# Fetch all the DBLP keys for a given author from a specified year
def get_keys_by_year(author, year)
return nil if not author or not year
puts "% Downloading citations (#{author}, #{year})." if @options.verbose
dblpkeys = []
body = fetch_body(DBLP_DB + author + ".html")
chunk = $1 if body =~ /<tr><th><\/th><th colspan="2" bgcolor="#FFFFCC">#{year}<\/th><\/tr>(.+?)<\/th><\/tr>.+/m
chunk.each {|line| dblpkeys << $1 if line =~ /^.*<a href="#{DBLP_BIBTEX}([^>]+)\.xml">.*$/ } if chunk
return dblpkeys
end
# Fetch the bibTex entry associated with a DBLP key
def get_bibtex(key)
entries = []
key = $1 if key =~ /^\w*:(.+)$/
body = fetch_body(DBLP_BIBTEX + key)
entry = $1 if body =~ /<pre>(.*)<\/pre>/m
if entry
# get rid of the html tags
entry = entry.gsub(/(<(\w+)[^>]*>)|(<\/\w+>)/m, '')
entries += entry.split(/^$/)
else
puts "% No entry found for ID #{key}." if @options.verbose
end
return entries
end
# Fetch all the bibTex entries associated with a conference
def get_conf(conf)
dblpkeys = []
puts "% Downloading all entries for conference #{conf}." if @options.verbose
body = fetch_body(DBLP_CONF + conf.downcase + "/index.html")
if @options.check
dblpkeys << true
else
body.gsub(/"([^\/]+\.html)">Contents/) do |l|
page = fetch_body(DBLP_CONF + conf.downcase + "/" + $1)
page.gsub(/"#{DBLP_BIBTEX}([^>]+)\.xml"/) {|k| dblpkeys << $1} if page
end
end
return dblpkeys
end
# Print the bibTex entries to the output file
def print_entries(entries)
entry_keys = []
dblp = File.new(@options.output, "w")
if File.exists?("ignore.cit")
ignore_entries = File.open("ignore.cit", "r") { |f| f.read }
entries.each do |entry|
key = $1 if entry.first =~ /^@\w+\{(.+),$/
next if entry_keys.include?(key)
a = entry.to_a
ignore_entries.each do |ie|
a.reject!{|l| l =~ /^\s*#{ie.chomp}\s*=.*$/}
end
sle = a[-2]
sle[sle.length - 2] = '' if sle[sle.length - 2] == 44
dblp.print a.join
# premature knuth is the optimisation of all evil.
entry_keys << key
end
else
dblp.print entries
end
dblp.close()
puts "Wrote #{@options.output}"
end
end
citadown = Citadown.new(ARGV, STDIN)
citadown.run
| true |
7eb53000c9448ee4735267c0da968b140d61efc0 | Ruby | keydunov/maglev | /lib/maglev/support/transformer.rb | UTF-8 | 1,236 | 2.6875 | 3 | [] | no_license | module Maglev
module Support
class Transformer
# Maglev::Transformer.to(NSString) do |value, reversed|
# end
def self.to(klass, params = {}, &transform_value)
if !transform_value || ![1,2].member?(transform_value.arity)
raise Maglev::Error::BlockRequiredError, "Need to include a block with one or two arguments for Maglev::Transformer.to"
end
ns_transformer = Maglev::Support.make_class("#{klass}Transformer#{transform_value.object_id}", NSValueTransformer)
ns_transformer.define_singleton_method("transformedValueClass") do
klass
end
reversable = transform_value.arity == 2
ns_transformer.define_singleton_method("allowsReverseTransformation") do
reversable
end
ns_transformer.send(:define_method, "transformedValue") do |value|
if reversable
transform_value.call(value, nil)
else
transform_value.call(value)
end
end
if reversable
ns_transformer.send(:define_method, "reverseTransformedValue") do |value|
transform_value.call(nil, value)
end
end
ns_transformer
end
end
end
end | true |
4cc486720c9ed05b55b3d836478d9b8e95c10de7 | Ruby | pesekvik/MI-RUB | /cviceni_3_ukol.rb | UTF-8 | 3,066 | 3.453125 | 3 | [] | no_license |
class Graph
attr_reader :number_of_vertices
def initialize(number_of_vertices)
@number_of_vertices = number_of_vertices
@vertices = Array.new
@number_of_vertices.times{|i|
@vertices[i + 1] = Vertex.new(i + 1) #start index with 1
}
end
def get_vertex(pos)
return @vertices[pos];
end
def bfs(start)
queue = Array.new
visited = Array.new
queue.push( get_vertex(start));
while(!queue.empty?)#not aplicable for large due to memory issues
# puts "ahoj"
current = queue.shift
visited.push(current)
print "#{current} "
current.connected_vertices.each { |e|
if(!visited.include?(e) && !queue.include?(e))
queue.push(e)
end
}
# print queue
# puts
end
puts
end
def dfs(start)
get_vertex(start).dfs(Array.new, Array.new);
puts
end
def connect_vertices(from, to)
from.add_connection(to);
to.add_connection(from);
end
end
class Vertex
include Comparable
attr_accessor :connected_vertices,:index
def <=>(anOther)
@index <=> anOther.index
end
def initialize(index)
@connected_vertices = Array.new
@index = index;
end
def add_connection(vertex)
if !@connected_vertices.include?(vertex)
@connected_vertices.push(vertex)
end
end
def dfs(branch_stack, visited)
print "#{print self} ";
branch_stack.push(self);
@connected_vertices.each{|e|
if(!visited.include?(e) && !branch_stack.include?(e))
e.dfs(branch_stack, visited);
end
}
end
def to_s
return "#{@index}";
end
end
class Engine
attr_reader :reading_line,:lines
def initialize(lines)
@lines = lines;
@reading_line = 0;
@graphs = Array.new
end
def parse()
#parse
@number_of_graphs = read_line().to_i;
@number_of_graphs.times{ |i|
g = Graph.new(read_line().to_i);
#parse vertices and connections
g.number_of_vertices.times{|k|
from = nil;
from_read = false;
to_number_read = false;
read_line_array.each { |vertice_index|
vertice_index = vertice_index.to_i
if(!from_read)#first - to which we add conn
from = g.get_vertex(vertice_index);
from_read = true;
next;
end
if(!to_number_read)
to_number_read = true;
next;
end
if(vertice_index != 0)
g.connect_vertices(from, g.get_vertex(vertice_index))
end
}
}
puts "graph #{i + 1}"
#read config and output
config = read_line_array
while(config[0] != 0 || config[1] != 0)
if(config[1] == 1)
g.bfs(config[0])
else
if(config[1] == 0)
g.dfs(config[0])
else
throw "Undefined config #{config[1]}"
end
end
config = read_line_array
end
@graphs.push(g);
}
end
private
def read_line()
current_line = lines()[@reading_line];
@reading_line +=1;
return current_line
end
def read_line_array()
line = read_line
return line.split.collect!{|e|
e.to_i
}
end
end
f = File.open( "input.txt" , "r" )
lines = Array.new();
#change to array
f.each { |e|
lines.push(e);
}
engine = Engine.new(lines);
#parse
engine.parse()
f.close
| true |
8523e741d34535183dd3913c12ae9ce515b78262 | Ruby | sbetack/phase-0-tracks | /databases/simplify_radicals/sqlite3_file.rb | UTF-8 | 1,157 | 2.90625 | 3 | [] | no_license | ########################makes the database table
require_relative 'simplify_radicals'
require 'sqlite3'
db = SQLite3::Database.new("simplify_rads.db")
create_table_cmd = <<-SQL
CREATE TABLE IF NOT EXISTS simplifying_radical_problems(
id INTEGER PRIMARY KEY,
problem VARCHAR(255),
solution VARCHAR(255),
level_of_difficulty INT
)
SQL
db.execute(create_table_cmd)
list_of_problems = ['sqrt(64x^2y)', 'sqrt(40a^3b^7c)', 'sqrt(100)', 'sqrt(42a^2c^18)', 'sqrt(6408p^18q^123r^70)', 'sqrt(25xyz)', 'sqrt(68ab^7c)', 'sqrt(68ab^7c/(a^3b^7))','sqrt(225x^8y)', 'sqrt(20x^7y^8)', 'sqrt(30f^7g^10)', 'sqrt(500s^7t^19)', 'sqrt(60x^703y^90)', 'sqrt(12f^11g^14h^78j^22k^683)', 'sqrt(5608438x^4)', 'sqrt(56t^44)','sqrt(225x^8y+3x^2y)']
problems_nested_arr = db.execute("SELECT * FROM 'simplifying_radical_problems'")
list_of_problems.each do |radical_expression|
db.execute("INSERT INTO simplifying_radical_problems (problem, solution, level_of_difficulty) VALUES (?, ?, ?)", [radical_expression, simplify_radical_expression(radical_expression), rate_difficulty(radical_expression)])
end
# __________________________________________________________
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.