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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
faebe5d84edb7cbf44add2a824165c7da3d055a6 | Ruby | pilarcormo/SNP_distribution_method | /Test/unit_tests_VCF.rb | UTF-8 | 1,885 | 2.671875 | 3 | [] | no_license | #encoding: utf-8
require_relative '../lib/vcf'
require_relative '../lib/write_it'
require 'test/unit'
class TestVCF < Test::Unit::TestCase
def setup
@vcf_ngs = "test/ngs.vcf"
@chromosome = 1
@vcfs_info = {"ADP"=>"17", "WT"=>"0", "HET"=>"1", "HOM"=>"0", "NC"=>"0"}, {"ADP"=>"25", "WT"=>"0", "HET"=>"1", "HOM"=>"0", "NC"=>"0"}
@vcfs_pos = [5, 123]
@snps = {5 => "HET", 123 => "HET"}
@vcf = ["1\t5\t.\tC\tA\t.\tPASS\tADP=17;WT=0;HET=1;HOM=0;NC=0\tGT:GQ:SDP:DP:RD:AD:FREQ:PVAL:RBQ:ABQ:RDF:RDR:ADF:ADR\t0/1:24:17:17:9:7:41.18%:3.3988E-3:65:52:9:0:1:6\n",
"1\t123\t.\tG\tA\t.\tPASS\tADP=25;WT=0;HET=1;HOM=0;NC=0\tGT:GQ:SDP:DP:RD:AD:FREQ:PVAL:RBQ:ABQ:RDF:RDR:ADF:ADR\t0/1:39:25:25:14:11:44%:1.1933E-4:69:66:6:8:6:5\n"]
end
def test_open_vcf
vcf, chrom, pos, info = Vcf.open_vcf(@vcf_ngs, @chromosome)
assert_equal( ["1\t5\t.\tC\tA\t.\tPASS\tADP=17;WT=0;HET=1;HOM=0;NC=0\tGT:GQ:SDP:DP:RD:AD:FREQ:PVAL:RBQ:ABQ:RDF:RDR:ADF:ADR\t0/1:24:17:17:9:7:41.18%:3.3988E-3:65:52:9:0:1:6\n",
"1\t123\t.\tG\tA\t.\tPASS\tADP=25;WT=0;HET=1;HOM=0;NC=0\tGT:GQ:SDP:DP:RD:AD:FREQ:PVAL:RBQ:ABQ:RDF:RDR:ADF:ADR\t0/1:39:25:25:14:11:44%:1.1933E-4:69:66:6:8:6:5\n"], vcf)
assert_equal(["1", "1"], chrom)
assert_equal([5, 123], pos)
assert_equal( [{"ADP"=>"17", "WT"=>"0", "HET"=>"1", "HOM"=>"0", "NC"=>"0"}, {"ADP"=>"25", "WT"=>"0", "HET"=>"1", "HOM"=>"0", "NC"=>"0"}], info)
end
def test_type_per_pos
snps, hm, ht = Vcf.type_per_pos(@vcfs_info, @vcfs_pos)
assert_equal({5 => "HET", 123 => "HET"}, snps)
assert_equal([], hm)
assert_equal([5, 123], ht)
end
def test_filtering
snps_p = {5 => "HET", 365 => "HOM"}
short_vcf = Vcf.filtering(@vcfs_pos, snps_p, @snps, @vcf)
assert_equal(["1\t123\t.\tG\tA\t.\tPASS\tADP=25;WT=0;HET=1;HOM=0;NC=0\tGT:GQ:SDP:DP:RD:AD:FREQ:PVAL:RBQ:ABQ:RDF:RDR:ADF:ADR\t0/1:39:25:25:14:11:44%:1.1933E-4:69:66:6:8:6:5\n"], short_vcf)
end
end | true |
84cbaebfe75c8b2dbd452e0f04c104902544aa56 | Ruby | deminew/remarkable | /lib/remarkable/active_record/macros/validations/validate_acceptance_of_matcher.rb | UTF-8 | 2,301 | 2.84375 | 3 | [
"MIT"
] | permissive | module Remarkable # :nodoc:
module ActiveRecord # :nodoc:
module Matchers # :nodoc:
class ValidateAcceptanceOfMatcher < Remarkable::Matcher::Base
include Remarkable::ActiveRecord::Helpers
undef_method :allow_blank, :allow_blank?
arguments :attributes
optional :accept
assertions :allow_nil?, :require_accepted?, :accept_is_valid?
def description
message = "require #{@attributes.to_sentence} to be accepted"
message << " or nil" if @options[:nil]
message
end
private
def require_accepted?
return true if bad?(false)
@missing = "not require #{@attribute} to be accepted"
return false
end
def accept_is_valid?
return true unless @options.key? :accept
return true if good?(@options[:accept])
@missing = "is not accepted when #{@attribute} is #{@options[:accept].inspect}"
false
end
# Receives a Hash
def default_options
{ :message => :accepted }
end
def expectation
message = "that the #{subject_name} can be saved if #{@attribute} is accepted"
message << " or nil" if @options[:allow_nil]
message
end
end
# Ensures that the model cannot be saved if one of the attributes listed is not accepted.
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:accept</tt> - the expected value to be accepted.
# * <tt>:allow_nil</tt> - when supplied, validates if it allows nil or not.
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp, string or symbol. Default = <tt>I18n.translate('activerecord.errors.messages.accepted')</tt>
#
# Example:
# it { should validate_acceptance_of(:eula, :terms) }
# it { should validate_acceptance_of(:eula, :terms, :accept => true) }
#
def validate_acceptance_of(*attributes)
ValidateAcceptanceOfMatcher.new(*attributes)
end
end
end
end
| true |
0194c4d8c1d72c6de23348fed4273a6b5ba49d18 | Ruby | bikio/dpl-challenges | /ruby/person.rb | UTF-8 | 1,223 | 4.03125 | 4 | [] | no_license | require_relative 'helper'
class Person
include Helper
attr_accessor :attributes, :energy
def initialize(attributes = {})
@attributes = attributes
@energy = 10
end
# This returns a string of the person's name
def name
attributes[:name]
end
# This returns a string of the person's first name
def first_name
name.split(' ')[0]
end
# This returns a string of the person's last name
def last_name
name.split(' ')[1]
end
# This returns a string of the person's age
def age
attributes[:age]
end
# This returns a fixnum of the person's birthyear
def birthyear
(age.to_i - Time.now.year.to_i).abs
end
# This prints to the console
def say(words)
puts "#{words}"
end
# This returns @energy minus a random subtracted from it
def run
@energy -= rand(5)
end
# This returns a string describing the Person instance's energy level
def energy_level
case @energy
when -100..-1
"OMG ABOUT TO DIE!"
when 0..3
"tired"
when 4..6
"doing ok"
when 7..10
"ready to go"
end
end
# This is a setter to change the instance's energy level
def energy_level=(amount)
@energy += amount
end
end | true |
beb37cd4d2c0e91302ee346548c4a410ef5a9afc | Ruby | mv/aws-cf-builder | /lib/rake/for-all.rb | UTF-8 | 1,447 | 2.5625 | 3 | [] | no_license | # vim:ft=ruby
require 'json'
###
### Hack(?)
###
namespace :'for-all' do
desc "Usage: rake for-all:regions task='task-name'"
task :regions do |task|
if ! ENV.has_key?('task')
printf "\n Error: you must define a task name.\n\n"
exit
end
output = %x{
aws ec2 describe-regions \
--output json \
--query 'Regions[*].RegionName' # return in a simple array list
}
JSON.parse(output).sort.each do |region|
printf "Region: %s\n", region
ENV['AWS_DEFAULT_REGION'] = region
Rake::Task[ ENV['task'] ].execute
printf "\n"
end # JSON array
end # regions
# desc "Usage: rake for-all:azs task='task-name'"
task :azs do
if ! ENV.has_key?('task')
printf "\n Error: you must define a task name.\n\n"
exit
end
output = %x{
aws ec2 describe-availability-zones \
--output json \
--query 'AvailabilityZones[*].ZoneName'
}
JSON.parse(output).sort.each do |az|
printf "AZ: %s\n", az
ENV['az'] = az
Rake::Task[ ENV['task'] ].execute
printf "\n"
end # JSON array
end # azs
end # namespace
desc "ec2: describe-availability-zones"
task :'list-azs' do
sh "aws ec2 describe-availability-zones --output text | sort | column -t"
end
desc "ec2: describe-regions"
task :'list-regions' do
sh "aws ec2 describe-regions --output text | sort | column -t"
end
| true |
43cae66c9e8162deac22f694e67bd6bea5960ab5 | Ruby | krunaljhaveri/RubyPost | /app/models/ability.rb | UTF-8 | 3,193 | 2.890625 | 3 | [] | no_license | class Ability
include CanCan::Ability
def initialize(user)
# Defines abilities for the passed in user here. For example:
#
# user ||= User.new # guest user (not logged in)
# if user.admin?
# can :manage, :all
# else
# can :read, :all
# end
#
# The first argument to `can` is the action you are giving the user
# permission to do.
# If you pass :manage it will apply to every action. Other common actions
# here are :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on.
# If you pass :all it will apply to every resource. Otherwise pass a Ruby
# class of the resource.
#
# The third argument is an optional hash of conditions to further filter the
# objects.
# For example, here the user can only update published articles.
#
# can :update, Article, :published => true
#
# See the wiki for details:
# https://github.com/ryanb/cancan/wiki/Defining-Abilities
unless user.nil?
# Can manage his post
can :manage, Post do |p|
p.user == user
end
can :create, Post
# Can manage his comments
can :manage, Comment do |c|
c.user == user
end
can :create, Comment
# Can vote if allowed
can :create, Vote do |v|
voting_for_self = true
already_voted = true
if v.voteable_type == 'Post'
voting_for_self = (Post.find(v.voteable_id).user == user)
already_voted = !(Vote.where('voteable_type = "Post" AND voteable_id = ? AND user_id = ?', v.voteable_id, user).empty?)
elsif v.voteable_type == 'Comment'
voting_for_self = (Comment.find(v.voteable_id).user == user)
already_voted = !(Vote.where('voteable_type = "Comment" AND voteable_id = ? AND user_id = ?', v.voteable_id, user).empty?)
end
!voting_for_self and !already_voted
end
if user.admin?
# Admin can delete any post or comment
can :destroy, [Post, Comment]
# Admin can create Categories
can :manage, Category
# Admin can manage other users
can :manage, User
# Admin cannot manage other Admins and Super Admin
cannot :manage, User do |u|
u.admin? or u.super_admin?
end
# Admin can manage himself
can :manage, User do |u|
u == user
end
can :administer, User do |u|
u.admin == true
end
end
# Super admin can manage everything
if user.super_admin?
# Super admin can delete any post or comment
can :destroy, [Post, Comment]
# Super admin can create Categories
can :manage, Category
# Super admin can manage other users
can :manage, User
# Super admin cannot manage himself
cannot :manage, User do |u|
u == user
end
can :administer, User do |u|
u.super_admin == true
end
end
end
# Any user can read everything
can :read, :all
# Guest can register
can :create, User
end
end
| true |
741fda529b9bb9233aef689565e30658782fe391 | Ruby | dimasumskoy/ruby | /part_1/task_4.rb | UTF-8 | 752 | 3.859375 | 4 | [] | no_license | # Квадратное уравнение
puts "Коэффициент a"
a = gets.chomp.to_f
puts "Коэффициент b"
b = gets.chomp.to_f
puts "Коэффициент c"
c = gets.chomp.to_f
d = b ** 2 - (4 * a * c) # Вычисляем дискриминант
# Вычисляем корни, если они есть
if d < 0
puts "Корней нет. Дискриминант равен #{d}"
elsif d > 0
d_sqrt = Math.sqrt(d)
x1 = (-b + d_sqrt) / 2 * a
x2 = (-b - d_sqrt) / 2 * a
puts "Дискриминант равен #{d}, корни уравнения равны: X1 = #{x1}, X2 = #{x2}"
elsif d == 0
x = (-b) / 2 * a
puts "Дискриминант равен #{d}, корень уравнения X = #{x}"
end | true |
8553c4ad63b0b9fe2c8bf9cbe9dcd2e751129cfc | Ruby | marlitas/war_or_peace | /lib/deck.rb | UTF-8 | 520 | 3.59375 | 4 | [] | no_license | require 'pry'
class Deck
attr_reader :cards
def initialize (cards)
@cards = cards
@high_cards = []
end
def rank_of_card_at (index)
@cards[index].rank
end
def high_ranking_cards
@high_cards = @cards.select do |x|
x.rank >= 11
end
end
def percent_high_ranking
((@high_cards.length.to_f / @cards.length.to_f) * 100).round(2)
end
def remove_card
@cards.shift
end
def add_card(card)
@cards << card
end
def shuffle
@cards = @cards.shuffle
end
end
| true |
f9eaea9f1ba34751a03f15e6c16e7bcd9ee8d780 | Ruby | darkzeroman/ruby-experiments | /FacebookHackerCupTry2.rb | UTF-8 | 701 | 3.21875 | 3 | [] | no_license |
cases = gets.chomp!.to_i
def nCr(n,k)
nfact = (1..n).inject(:*)
kfact = (1..k).inject(:*)
nminuskfact = (1..(n-k)).inject(:*)
return nfact / (kfact * nminuskfact)
end
cases.times do |t|
n_k = gets.split(' ').map{|i| i.to_i}
n = n_k[0]
k = n_k[1]
arr = gets.split(' ').map{|i| i.to_i}
next if ((n == 0) || (k == 0))
arr.sort!.reverse!
sum = 0
num_iter = nCr(n,k)
arr.each do |a|
for i in (1..k)
sum = sum + a
num_iter = num_iter - 1
p "here"
break if num_iter == 0
end
break if num_iter == 0
end
# all = arr.combination(k).to_a
# maxSum = all.inject(0) {|r,e| r+e.max}
# puts "Case #" + (t+1).to_s + ": " + maxSum.to_s
# p arr.length
p ""
end
| true |
420e14e05e1a44ca325fae0633db0b6dac12603e | Ruby | venkataramana/Jquery-examples | /Ruby only/Triangles/descend.rb | UTF-8 | 249 | 3.078125 | 3 | [] | no_license | arr=[4,7,1,6,5,9,3,8,0,2]
#temp=[]
for i in 0..arr.length-1
for j in (i+1)..arr.length-1
if(arr[i] < arr[j])
x=arr[i]
arr[i]=arr[j]
arr[j]=x
end
end
# for i in 1..arr.length-1
# puts arr[i]
end
puts arr
| true |
0f364d4d460542797bb89f8f0b27bfb1aa8d6f68 | Ruby | salamidrus/ruby_101 | /files_io/writing_files.rb | UTF-8 | 412 | 3.21875 | 3 | [
"MIT"
] | permissive | # Append data to a file
# File.open("./files_io/data.txt", "a") do |file|
# file.write("\nPutri, Developer")
# end
# Create new file
# File.open("./files_io/index.html", "w") do |file|
# file.write("<h1>hello world</h1>")
# end
# Read and write file
File.open("./files_io/data.txt", "r+") do |file|
file.readline() # go to the next line
file.write("Overridden") # override the specific line
end | true |
eb9b8a18ad43b67b98274d79437473ad81504b17 | Ruby | Etsap/my-advent | /adventofcode2015/problem14.rb | UTF-8 | 981 | 3.234375 | 3 | [] | no_license | input = ""
File.open("input14.txt", 'r') {|f| input = f.read}
inputdata, bestdistance, maxpoints = [], 0, 0
input.split(/\n/).each do |line|
deer, speed, flyduration, restduration = line.match(/(\w+) can fly (\d+) km\/s for (\d+) seconds, but then must rest for (\d+)/).captures
inputdata << {"speed" => speed.to_i, "fly" => flyduration.to_i, "rest" => restduration.to_i, "distance" => 0, "points" => 0}
end
for i in 0..2502
maxdistance = 0
inputdata.each do |deer|
tick = i % (deer["fly"] + deer["rest"])
deer["distance"] += deer["speed"] if tick < deer["fly"]
maxdistance = deer["distance"] if deer["distance"] > maxdistance
end
inputdata.each {|deer| deer["points"] += 1 if deer["distance"] == maxdistance}
end
inputdata.each {|deer| bestdistance = deer["distance"] if deer["distance"] > bestdistance}
inputdata.each {|deer| maxpoints = deer["points"] if deer["points"] > maxpoints}
puts "Part 1: #{bestdistance}"
puts "Part 2: #{maxpoints}"
| true |
a29cc0f41089b122714aa6102affad22e7da91e4 | Ruby | RhysStansfield/ruby_prac | /ex5.rb | UTF-8 | 683 | 3.921875 | 4 | [] | no_license | #! /usr/bin/env ruby
name = 'Rhys Stansfield'
age = 25 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'Brown'
teeth = 'White...ish'
hair = 'Brown'
height_cm = height.to_f * 2.54
weight_k = weight.to_f * 0.453592
puts "Lets talk about %s." % name
puts "He's %d inches tall, or %d in centimeters." % [height, height_cm]
puts "He's %d pounds heavy, or %d in kilos." % [weight, weight_k]
puts "Actually that's not too heavy."
puts "He's got %s eyes and %s hair." % [eyes, hair]
puts "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
puts "If I add %d, %d and %d I get %d." % [age, height, weight, age + height + weight]
| true |
ebad6c459c5d35285899638237c34fe691a98cd9 | Ruby | amhursh/battleship | /lib/computer_player.rb | UTF-8 | 2,868 | 3.296875 | 3 | [] | no_license | require './lib/player'
require './lib/validation'
require './lib/board'
require './lib/ship'
require 'pry'
class ComputerPlayer < Player
include Validation
attr_accessor :computer_board
attr_reader :shells_fired,
:computer_ships,
:board_size
def initialize(board_size)
@board_size = board_size
@computer_board = Board.new(board_size)
@shells_fired = 0
@computer_ships = []
end
def random_starting_coordinate_for_ship
output_coordinates = []
coordinates = computer_board.game_board.keys
output_coordinates << coordinates.delete_at(rand(coordinates.length))
end
def random_coordinates_for_two_unit_ship(ship_length)
starting_coord = random_starting_coordinate_for_ship[0]
output_coordinates = [starting_coord]
coordinates = get_all_possible_col_and_row_values(starting_coord, @computer_board, ship_length)
output_coordinates << coordinates.delete_at(rand(coordinates.length))
output_coordinates
end
def random_coordinates_for_three_unit_ship(ship_length)
starting_coords = random_coordinates_for_two_unit_ship(2).sort
flag = find_liner_upper(starting_coords)
index = flag_index(starting_coords, flag)
possible_coords = starting_coords.map do |coord|
get_all_possible_col_and_row_values(coord, @computer_board, ship_length)
end
final_coords = possible_coords.flatten.uniq.delete_if do |coord|
coord[index] != flag
end
final_coords = final_coords.sort
if rand.round == 0
final_coords = final_coords - [final_coords.last]
return final_coords
else
final_coords = final_coords - [final_coords.first]
return final_coords
end
end
def random_coordinates_for_four_unit_ship(ship_length)
starting_coords = random_coordinates_for_three_unit_ship(3).sort
flag = find_liner_upper(starting_coords)
index = flag_index(starting_coords, flag)
possible_coords = starting_coords.map do |coord|
get_all_possible_col_and_row_values(coord, @computer_board, ship_length)
end
final_coords = possible_coords.flatten.uniq.delete_if do |coord|
coord[index] != flag
end
final_coords = final_coords.sort
until final_coords.count == 4
if rand.round == 0
final_coords = final_coords - [final_coords.last]
else
final_coords = final_coords - [final_coords.first]
end
end
final_coords
end
def find_liner_upper(starting_coords)
starting_coords = starting_coords.map { |coord| coord.split("", 2) }
starting_coords = starting_coords.flatten.sort
freq = starting_coords.inject(Hash.new(0)) { |h, v| h[v] += 1; h }
starting_coords.max_by { |v| freq[v] }
end
def flag_index(starting_coords, flag)
return 0 if (starting_coords[0][0] == flag)
return 1 if (starting_coords[0][1..2] == flag)
end
end
| true |
6189dc86a788fb5f966c4898ecfaa742560a8cce | Ruby | rocking42/Ruby-fun | /class_test/class.rb | UTF-8 | 416 | 3.8125 | 4 | [] | no_license | require_relative 'student'
class Class
def initialize(name, teacher)
@name = name.upcase
@teacher = teacher.capitalize
@class = []
end
def add_student(student)
@class << student
end
def year_up
@class.each { |t| t.grade_up}
end
def all_students
puts "There is #{@class.length} students in #{@teacher}'s class #{@name}"
puts "students:".upcase
puts @class
end
end
| true |
1b8684b1d4b2a84234e7f502301d7a039d7ee362 | Ruby | geoffyoungs/rack-magic-incoming-url | /lib/rack/magic-incoming-url.rb | UTF-8 | 1,589 | 2.90625 | 3 | [
"MIT"
] | permissive | =begin
Magic Incoming URL is a piece of rack middleware that redirects a URL to another one - but only when it's not from a local link.
It's designed for sites that respond to multiple domains, where different domains should lead to different landing pages.
e.g. You run Simon's Shoes and have two domains: simons-shoes.net and simons-boots.net.
They both point to the same site, but you want customers who go to simons-boots.net to end up
start on the boots page.
http://www.simons-shoes.net -> http://www.simons-shoes.net/
http://www.simons-boots.net -> http://www.simons-boots.net/boots
You can achieve this with the following config:
map '/' do
use Rack::MagicIncomingUrl, { 'www.simons-boots.net' => { '/' => '/boots' } }
run MyWebApp
end
=end
module Rack
class MagicIncomingUrl
def initialize(app, map)
@app, @map = app, map
end
def redirect_for_env(env)
return nil unless @map
host, path, server = env['HTTP_HOST'], env['PATH_INFO'], env['SERVER_NAME']
settings = @map[host] || @map[server]
return unless settings
settings[path]
end
def call env
redirect = redirect_for_env(env)
if redirect
# Only continue if no referer or non-local refererer
if env['HTTP_REFERER'].nil? or env['HTTP_REFERER'].index(env['HTTP_HOST']).nil?
if redirect[0..0] == '/'
redirect = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}#{redirect}"
end
res = Rack::Response.new
res.redirect(redirect)
return res.finish
end
end
@app.call(env)
end
end
end
| true |
f06049dd1cdc0131edd0007bae4c179d15149ed2 | Ruby | jakedjohnson/DBC-highlights | /week-2/orange-trees-1/runner.rb | UTF-8 | 1,035 | 3.84375 | 4 | [
"MIT"
] | permissive | require_relative 'orange'
require_relative 'orange_tree'
tree = OrangeTree.new
# Let seasons pass until the tree is ready to bear fruit.
tree.pass_growing_season until tree.mature?
# Report yearly harvest information for the lifetime of the tree.
until tree.dead?
harvested_oranges = []
while tree.has_oranges?
harvested_oranges << tree.pick_an_orange
end
orange_diameters = []
harvested_oranges.each { |orange| orange_diameters << orange.diameter }
average_orange_diameter = orange_diameters.reduce(:+) / orange_diameters.length
# This is a heredoc, a way to create a formatted multiline string.
# http://makandracards.com/makandra/1675-using-heredoc-for-prettier-ruby-code
puts <<-HARVEST_REPORT.gsub(/^ {4}/, '')
YEAR #{tree.age} REPORT
-----------------------
Height: #{tree.height} feet.
Harvest: #{harvested_oranges.size} oranges with an average diameter of #{average_orange_diameter} inches.
HARVEST_REPORT
tree.pass_growing_season
end
puts "Alas, the tree, she is dead!"
| true |
506c33bccec7c4dcc722cf157e19d2e4e6af4228 | Ruby | vecerek/css_compare | /lib/css_compare/css/value/url.rb | UTF-8 | 502 | 2.625 | 3 | [
"MIT"
] | permissive | module CssCompare
module CSS
module Value
# Wraps the SassScript `url` Funcall.
class Url < Base
# Checks, whether two url calls are equal.
#
# @param [Url] other the other url call
# @return [Boolean]
def ==(other)
return false unless super
value1 = sanitize_url(@value.args[0].value.value)
value2 = sanitize_url(other.value.args[0].value.value)
value1 == value2
end
end
end
end
end | true |
18bc599afff8b7e0a6f450d1d0ca2f282a1d4195 | Ruby | PatreevIgor/NewCyberBot | /app/models/order.rb | UTF-8 | 2,698 | 2.53125 | 3 | [] | no_license | class Order < ApplicationRecord
def create_buy_orders(profitable_orders)
profitable_orders.each do |order|
Connection.send_request(format(Constant::CREATE_ORDER_URL, class_id: order_info_hash(order)[Constant::ITEM_HASH_CLASS_ID_KEY],
instance_id: order_info_hash(order)[Constant::ITEM_HASH_INSTANCE_ID_KEY],
price: price.price_of_buy_for_order(order),
your_secret_key: Rails.application.secrets.your_secret_key))
# telegram_chat_bot.send_message_create_buy_order
end
# users_informator.inform_user_about_created_order
end
# def delete_orders
# Connection.send_request(format (Constant::DELETE_ORDERS_URL, your_secret_key: Rails.application.secrets.your_secret_key))
# end
def create_order_in_db(item_hash)
Order.create(class_id: item_hash[Constant::ITEM_HASH_CLASS_ID_KEY],
instance_id: item_hash[Constant::ITEM_HASH_INSTANCE_ID_KEY],
hash_name: item_hash[Constant::ITEM_HASH_HASH_NAME_KEY],
link: link_generator.generate_link(item_hash),
status: Constant::NOT_ACTUALIZED_ORDER_STATUS)
end
def actualize_new_orders
non_actualized_orders = Order.where(status: Constant::NOT_ACTUALIZED_ORDER_STATUS)
non_actualized_orders.each do |order|
if item_validator.item_profitable?(order_info_hash(order))
order.status = Constant::PROFITABLE_ORDER_STATUS
order.save
else
order.status = Constant::UNPROFITABLE_ORDER_STATUS
order.save
end
end
end
def actualize_old_orders
Order.where(status: [Constant::UNPROFITABLE_ORDER_STATUS, Constant::PROFITABLE_ORDER_STATUS]).each do |order|
if item_validator.item_profitable?(order_info_hash(order))
order.status = Constant::PROFITABLE_ORDER_STATUS
order.save
else
order.status = Constant::UNPROFITABLE_ORDER_STATUS
order.save
end
end
end
def order_not_exists?(item_hash)
Order.exists?(link: link_generator.generate_link(item_hash)) ? false : true
end
private
def item_validator
@item_validator ||= ItemValidator.new
end
def telegram_chat_bot
@telegram_chat_bot ||= TelegramChatBot.new
end
def price
@price ||= Price.new
end
def link_generator
@link_generator ||= LinkGenerator.new
end
def order_info_hash(order)
{ Constant::ITEM_HASH_CLASS_ID_KEY => order.class_id, Constant::ITEM_HASH_INSTANCE_ID_KEY => order.instance_id }
end
end
| true |
aa4dd06179dfcaa7893f6ff87df0ff95feb037be | Ruby | cbow27/lsrubybk | /Exercises/14.rb | UTF-8 | 181 | 2.796875 | 3 | [] | no_license | a = ['white snow', 'winter wonderland', 'melting ice',
'slippery sidewalk', 'salted roads', 'white trees']
arr = []
a.each{|word| arr.push(word.split)}
arr.flatten!
print arr
| true |
e491f5b4fa0f29b6e3963ff417aa4d664b83acc5 | Ruby | hmalueg/Cipher | /cipher.rb | UTF-8 | 1,571 | 3.90625 | 4 | [] | no_license | require 'pry'
#
# cipher ==> regular function f(x) = (x+5) mod 26
# decipher ==> inverse f-(x) = (x-5) mod 26
#
# one-to-one relationship between the key and value of a hash data structure
# a gets mapped to 0, b gets mapped to 1, c gets mapped to 3 and so on
# since we have a one to one relationship, we can do an inverse function
# and therefore create a cipher and decipher function
@alphabet = {'a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4, 'f' => 5, 'g' => 6,
'h' => 7, 'i' => 8, 'j' => 9, 'k' => 10, 'l' => 11, 'm' => 12, 'n' =>13,
'o' => 14,'p' => 15,'q' => 16,'r' => 17,'s' => 18, 't' => 19, 'u' => 20,
'v' => 21,'w' => 22,'x' => 23,'y' => 24,'z' => 25}
@fake_message = ""
@real_message = ""
def cipher(char)
return (char+ 5) % 26
end
def decipher(char)
return (char - 5) % 26
end
def scramble(message)
@fake_message = ""
message.each_byte do |i|
real_letter = i.chr.downcase
if real_letter == ' '
@fake_message += real_letter
elsif real_letter != ' '
real_index = @alphabet[real_letter]
fake_index = cipher(real_index)
fake_letter = @alphabet.key(fake_index)
@fake_message += fake_letter
end
end
return @fake_message
end
def descramble(message)
@real_message = ""
message.each_byte do |i|
fake_letter = i.chr.downcase
if fake_letter == ' '
@real_message += fake_letter
elsif fake_letter != ' '
fake_index = @alphabet[fake_letter]
real_index = decipher(fake_index)
real_letter = @alphabet.key(real_index)
@real_message += real_letter
end
end
return @real_message
end
binding.pry | true |
3d21cbcd5b8af79196c9e350511d48a57e725ebd | Ruby | jdliss/robot_world | /generate-world/generate.rb | UTF-8 | 702 | 2.671875 | 3 | [] | no_license | require 'faker'
require 'time'
require_relative '../app/models/robot_world'
class RobotWorldApp
def robot_world
world = Sequel.sqlite("db/robot_world.sqlite")
@robot_world ||= RobotWorld.new(world)
end
end
robot_world = RobotWorldApp.new.robot_world
def generate_robot
robot = {
:name => Faker::Name.name,
:city => Faker::Address.city,
:state => Faker::Address.state,
:avatar => Faker::Avatar.image,
:birthdate => Faker::Date.birthday.strftime("%F"),
:date_hired => Faker::Time.between(Faker::Date.birthday,Time.now).to_s[0..9],
:department => Faker::Company.profession
}
end
1000.times do
robot_world.create(generate_robot)
end
| true |
4a67114bac41eea30cb53d67115f48360bba4820 | Ruby | MatteBru/prime-ruby-prework | /prime.rb | UTF-8 | 208 | 2.546875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Add code here!
#require "pry"
def prime? (num)
return false if num <= 1
divisor = (2..Math.sqrt(num).to_i).to_a
divisor.each do |div|
return false if num % div == 0
end
true
end
#binding.pry
| true |
b04688f1e8a015869f4bd1c1b9f0bc0e843e5ce4 | Ruby | gitter-badger/admiral_stats | /app/controllers/ship_list_controller.rb | UTF-8 | 2,990 | 2.53125 | 3 | [
"MIT"
] | permissive | class ShipListController < ApplicationController
before_action :authenticate
def index
set_meta_tags title: '艦娘一覧'
# URL パラメータ 'all' が true の場合は、未配備の艦娘も表示
if ActiveRecord::Type::Boolean.new.deserialize(params[:all])
@ships = ShipMaster.all.to_a
else
@ships = ShipMaster.where('implemented_at <= ?', Time.now).to_a
end
# 1枚目のカードから「**改」という名前になっている図鑑No. の配列を作成
kai_book_numbers = @ships.select{|s| s.ship_name =~ /改$/ }.map{|s| s.book_no }
# ship_cards および ship_statuses の両方が空の場合は true
@is_blank = true
# 取得済みのカードを調べた結果
@cards = {}
# カードの枚数の配列
# 取得済みは :acquired、未取得は :not_acquired、存在しない項目は nil を設定
# ただし、表示名が「**改」のカードについては、index に 3 加算して配列に入れる(「改」の列に表示されるようにする)
@ships.each do |ship|
if kai_book_numbers.include?(ship.book_no)
@cards[ship.book_no] = [nil, nil, nil, :not_acquired, :not_acquired, :not_acquired]
else
@cards[ship.book_no] = Array.new(ship.variation_num, :not_acquired)
end
end
# 所持カードのフラグを立てる
# ただし、表示名が「**改」のカードについては、index に 3 加算して配列に入れる(「改」の列に表示されるようにする)
ShipCard.where(admiral_id: current_admiral.id).each do |card|
if kai_book_numbers.include?(card.book_no)
@cards[card.book_no][card.card_index + 3] = :acquired
else
@cards[card.book_no][card.card_index] = :acquired
end
@is_blank = false
end
# 各艦娘の現在のレベルを調べるために、最後にエクスポートされたデータ(レベルも最大値のはず)を取得
@statuses = {}
ShipStatus.find_by_sql(
[ 'SELECT * FROM ship_statuses AS s1 WHERE s1.admiral_id = ? AND NOT EXISTS ' +
'(SELECT 1 FROM ship_statuses AS s2 ' +
'WHERE s1.admiral_id = s2.admiral_id AND s1.book_no = s2.book_no ' +
'AND s1.remodel_level = s2.remodel_level AND s1.exported_at < s2.exported_at)',
current_admiral.id ]
).each do |status|
# レベル
# レベルはノーマルも改も同じなので、両者を区別する必要はない
@statuses[status.book_no] ||= {}
@statuses[status.book_no][:level] = status.level
# 星の数
# 星の数はノーマルと改で別管理なので、remodel_level で区別する
@statuses[status.book_no][:star_num] ||= []
@statuses[status.book_no][:star_num][status.remodel_level] = status.star_num
# 艦娘一覧が空ではないことを表すフラグを立てる
@is_blank = false
end
end
end
| true |
931b230e88c0cd06180c0d51267506eff6b08708 | Ruby | gmazelier/mongo-meta-driver | /ruby/lib/bson/int64.rb | UTF-8 | 611 | 2.671875 | 3 | [] | no_license | # encoding: utf-8
module BSON
# Represents a $maxKey type, which compares less than any other value in the
# specification.
#
# @see http://bsonspec.org/#/specification
#
# @since 2.0.0
class Int64
# A boolean is type 0x08 in the BSON spec.
#
# @since 2.0.0
BSON_TYPE = 18.chr.force_encoding(BINARY).freeze
# Raised if an integer value is out of range to be serialized as 8 bytes.
#
# @since 2.0.0
class OutOfRange < RuntimeError; end
# Register this type when the module is loaded.
#
# @since 2.0.0
Registry.register(BSON_TYPE, self)
end
end
| true |
5f4c70b58bba95f559aeee04b0583ffb79340cd0 | Ruby | ttscott2/launch_school_book | /capitalize.rb | UTF-8 | 145 | 3.078125 | 3 | [] | no_license | def capitalize(string)
if string.length > 10
string.upcase
else
string
end
end
p capitalize('tim')
p capitalize('fastfoodnation')
| true |
5263377b7c688e43a190ca5ab67fb8088806772c | Ruby | TechLit/interview-kiosk | /data/catalog/setup.rb | UTF-8 | 476 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'csv'
require 'pg'
DB = PG.connect
puts 'setup: creating books table'
DB.exec <<~SQL
create table books (
id serial primary key,
uid varchar,
title varchar,
author varchar,
category varchar)
SQL
puts 'setup: seeding books'
sql = 'insert into books (uid, title, author, category) values ($1, $2, $3, $4)'
CSV.open(File.join(__dir__, 'seeds', 'books.csv')).each do |book|
DB.exec_params(sql, book)
end
puts 'setup: done'
| true |
2b5dded7d5967d1002ef722ac039bc0393bb86c5 | Ruby | msabrina/countdown-to-midnight-001-prework-web | /countdown.rb | UTF-8 | 317 | 3.546875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def countdown(number)
number = 10
10. times do
puts "#{number} SECOND(S)!"
number = number - 1
end
"HAPPY NEW YEAR!"
end
countdown(10)
def countdown_with_sleep (num_secs)
number = 10
10. times do
puts "#{number} SECOND(S)!"
number = number - 1
sleep 1
end
end
countdown(4) | true |
ff5ee19bbe42938c7ec627e593790d187dc99e17 | Ruby | tompng/mathfont | /mathfont.rb | UTF-8 | 9,657 | 2.65625 | 3 | [] | no_license | module Font
def self.register c, &block
@faces ||= {}
@faces[c.to_s] = Face.new &block
end
def self.face c
@faces[c.to_s[0]] || @faces[c.to_s[0].downcase] || none
end
def self.none
@none ||= Face.new{-1}
end
def self.aa_table
[
'MM#TT',
'Qd0V*',
'par<?',
'gu!:^',
'g,,. '
]
end
class Face
def initialize &defs
@defs = defs
end
def value x, y
n = 128
ix, iy = [x,y].map { |v| i = (n*(v+1)/2.0).round; i < 0 ? 0 : i >= n ? n-1 : i }
@values ||= (0...n).to_a.repeated_permutation(2).map do |ix, iy|
__value 2.0*ix/n-1, 2.0*iy/n-1
end
@values[n*ix+iy]
end
def __value x, y
scale = 1.2
@defs.call(scale*x, scale*y, scale*Math.sqrt(x*x+y*y), Math.atan2(y, x))
end
def include? x, y
value(x, y) > 0
end
end
module Definitions
def self.register *args, &block
Font.register *args, &block
end
include Math
register('!'){|x,y|(1/32.0-x**2-(y+3/4.0)**2)*(4*x**2+(y-1/3.0)**6-1/8.0)}
register('"'){|x,y|1-(16*x**4+1/64.0/x**2-1/4.0)*16**(1-y)-(4*y-3)**2}
register('#'){|x,y|1/4.0-(((3*x-y/2)**2+4*y**2)/5)**8-(Math.cos(6*x-y)*Math.cos(4*y))**2}
register('$'){|x,y,r,th|1/4.0-(32*(r*Math.cos(th+8*r-4*r**2-7/2.0))**2+(r*Math.sin(th+8*r-4*r**2-7/2.0))**4-1/2.0)*(32*x**2+4*y**2*(y**2-1/2.0)**4-1/32.0)}
register('%'){|x,y|(((6*x+2)**2+(6*y-3)**2-2)**2-2)*(((6*x-2)**2+(6*y+3)**2-2)**2-2)*(3-(12*x-8*y)**2-(y+3*x/4)**8)}
register('&'){|x,y|1-13/(16+100*y**2)-1/80.0/((x+1/16.0)**2+(y-7/16.0)**2)-1/(30*(x-(5*y+1)/15)**2+50*(y+2/5.0)**2)-3*(x+(1-y)/8)**2*Math.exp(y/2)-2*y**4+2/(1+10*(x-y-1)**4+80*(x+y)**2)+2/(1+80*(x-y-3/4.0)**2+10*(y+x-3/4.0)**4)}
register("'"){|x,y|1-24*x**2*8**(1-y)-(4*y-3)**2}
register('('){|x,y|1-(8*x-4*y**2+2)**2-y**16}
register(')'){|x,y|1-(8*x+4*y**2-2)**2-y**16}
register('*'){|x,y,r,th|3-Math.cos(6*th)-6*r}
register('+'){|x,y,r,th|2+Math.cos(4*th)+Math.cos(8*th)/6-5*r}
register(','){|x,y|1/32.0-x**2-(y+3/4.0)**2-128*x*y/(1+(128*x)**2+(64*y+72)**2)}
register('-'){|x,y|1-6*x**4-40*y**2}
register('.'){|x,y|1/32.0-x**2-(y+3/4.0)**2}
register('/'){|x,y|8-64*(y-2*x)**2-(y+x/2)**8}
register(':'){|x,y|-(1/32.0-x**2-(y+3/4.0)**2)*(1/32.0-x**2-(y-1/2.0)**2)}
register(';'){|x,y|-(1/32.0-x**2-(y+3/4.0)**2-128*x*y/(1+(128*x)**2+(64*y+72)**2))*(1/32.0-x**2-(y-1/2.0)**2)}
register('<'){|x,y|1-(4*x+3-3*Math.sqrt(1+32*y**2)/2)**2-64*y**8}
register('='){|x,y|1-3*x**4-10*y**4-1/20.0/y**2}
register('>'){|x,y|1-(4*x-3+3*Math.sqrt(1+32*y**2)/2)**2-64*y**8}
register('?'){|x,y|20-1/(2*(x-y/2+1/3.0)**2+y**2)**2+1/(x**2+(y+3/4.0)**2)**2+1/8.0/(4*x**2+(y+1/4.0)**2)**2-(24*x**2+48*(y-1/3.0)**2-6)**2}
register('@'){|x,y|2/(1+2*(8*x**2+8*y**4-2)**4)+1/(1+(12*(x-1/5.0)**2+(2*y+1/4.0)**4-1)**4)+4/((4*x-1)**4+(24*y+16)**2)-1}
register('['){|x,y|1-128/(1+16*(2*x-1)**8+(2*y)**16)-32*x**4-2*y**8}
register('\\'){|x,y|8-64*(y+2*x)**2-(y-x/2)**8}
register(']'){|x,y|1-128/(1+16*(2*x+1)**8+(2*y)**16)-32*x**4-2*y**8}
register('^'){|x,y|1-(6*y-5+Math.sqrt(1+32*x**2))**2-64*x**8}
register('_'){|x,y|1-6*x**4-40*(y+4/5.0)**2}
register('`'){|x,y|1/4.0-(2*x-y+5/6.0)**4-4*(2*y-5/3.0+x)**2}
register('{'){|x,y|1-(8*x+2*y**2-3*y**4+3/(2+64*y**2))**2-y**16}
register('|'){|x,y|4-256*x**2-y**16}
register('}'){|x,y|1-(8*x-2*y**2+3*y**4-3/(2+64*y**2))**2-y**16}
register('~'){|x,y|1/32.0-x**8-(y+Math.sin(6*x)/8)**2}
register(0){|x,y|1-(8*(x-y/8)**2+4*y**2-8/3.0)**2}
register(1){|x,y|1-32*(x-y/8)**2-2*y**8}
register(2){|x,y|1/32.0-Math.exp(-4*x-2*y-4)+1/(2*(x-1/8)**8+4*(4*y+3)**2)-((x+(1-y)/2)**2+y**2-1/2.0)**2}
register(3){|x,y|1-8*x**2/(1+64*y**2)-1/(20*(x+(1-y)/8)**2+32*(y-2/5.0)**2)-1/(20*(x+(1-y)/8)**2+20*(y+2/5.0)**2)-(Math.exp(y/2-4*x)-y**2)/8-2*(x+(1-y)/8)**2-y**4}
register(4){|x,y|1-1/((x-1/8.0)**2+((4*y-3)/2)**2)-(12*(x-y/3)**2+2*y-2/3.0+(2*y-2/3.0)**4-1/2.0)*(12*(x-y/3)**2+3*y-1+16*(y-1/3.0)**4-2)*((8*x-3-y/2)**2+(2*y+1)**4-1)}
register(5){|x,y|1+1/((2*x-1)**4+(5*y-4)**2)-(x/4+y)**4-(8*x-2*y+2+4*Math.sin((x+4*y)*5/6)/(1+Math.exp(4*x+16*y)))**2}
register(6){|x,y|4/(1+32*(x**2+(y+1/2.0)**2-1/5.0)**2)+4/(1+32*(x+(1-y)/3-y**2/2)**2+4*(y-1/2.0)**4)-3}
register(7){|x,y|2-(4*x+4*y-1+8*(x-y)/3-3*Math.cos((12*x-12*y+3)/5))**2-(x-y+1/4.0)**4}
register(8){|x,y|1-1/(4+64*y**2)-1/(20*(x-y/8)**2+32*(y-2/5.0)**2)-1/(16*(x-y/8)**2+24*(y+2/5.0)**2)-2*(x-y/8)**2*Math.exp(y/4)-y**4}
register(9){|x,y|4/(1+32*(x**2+(y-1/2.0)**2-1/5.0)**2)+4/(1+32*(x-(1+y)/3+y**2/2)**2+4*(y+1/2.0)**4)-3}
register(:a){|x,y|1/2.0+32/(1+512*(x**4+(y+1/4.0)**2))-x**6-(3/2.0-2*y-8*x**2+5*x**4)**2}
register(:b){|x,y|2-1/(Math.cos(4*y)**2+16*x**4)-8*(x-(Math.sqrt(16/16-Math.cos(7*y))-1)/5/(1+Math.exp(-8*x)))**4-y**4}
register(:c){|x,y,r,th|1/2.0-((1+Math.cos(th))/2)**16-(4*x**2+3*y**2-2)**2}
register(:d){|x,y|1/12.0-(y**2+(3*x/2+y**2/2+y**4/16)**2-3/4.0)**2}
register(:e){|x,y|2-6*x**4-y**4-4*(1-Math.cos(4*y)**4)/(1+Math.exp(-16*x-8))}
register(:f){|x,y|2-8*x**4-2*y**4+y**2-2*(1-Math.cos(y**2+3*y)**6)*(2-y)/(1+Math.exp(-16*x-6))}
register(:g){|x,y,r,th|1/2.0-((1+Math.cos(th))/2)**16+2/(1+4*(4*x-1)**8+2*(8*y+2)**4)-((2*x+1/(4+4*(2*x-1)**4+(4*y+1)**4))**2+3*y**2-2)**2}
register(:h){|x,y|-5*(16*x**8+y**8-1)-9/((5*x/2)**16+2*(y**2-1)**4)}
register(:i){|x,y|2-(8*x)**4-y**8}
register(:j){|x,y|1/6.0-Math.exp(8*y-10/(1+Math.exp(-16*x)))-(3*x**2+6*(y/2-1/4.0)**4-1)**2}
register(:k){|x,y|1/8.0-64*x**8-((x+1/8.0-Math.sqrt(1/64.0+y**2))**2-1/32.0)*((8*x+3)**2+y**8-1)}
register(:l){|x,y|1-16*x**8-y**8-64.0/((2*x-1)**8+(y-1)**8)}
register(:m){|x,y|1-12/(4+4*(2*x)**8+(y-2+(4+6*x**4)/(1+2*x**2))**8)-8*x**8-(y+(4+6*x**4)/(1+2*x**2)-11/4.0)**8}
register(:n){|x,y|1/(4+64*(2*x+y)**2)-64*x**8+8*x**4-(y-x/8)**8-1/8.0}
register(:o){|x,y|1/4.0-(3*x**2+2*y**4-1)**2}
register(:p){|x,y|1-((8*x**2+2*(2*y-1)**2-2)**2-1)*((8*x+4)**4+y**8-1)}
register(:q){|x,y|1/4.0+(2+4*x)/(1+(8*y-2*Math.cos(3*x)+5)**8)/(1+Math.exp(-32*x-10))-(3*x**2+2*y**4-1)**2}
register(:r){|x,y|-(Math.atan(3*x**2+3*(y-1/2.0)**2)*Math.atan((8*x+4)**4+y**8)*Math.atan((8*x-1+2*y)**4+4*(y+1/4.0)**4)-2)*(8*x**2+2*(2*y-1)**2-1)}
register(:s){|x,y|1/6.0-x**4-((x-y/2)**3+2*(x+y)*(1-(y+x/4)**2))**2}
register(:t){|x,y|1-(4*x**8+3*(4*y-3)**2-1)*(32*x**2+3*(y+1/4.0)**8-1)}
register(:u){|x,y|1/6.0-Math.exp(16*y-16)-(3*x**2+5*(y/2-1/4.0)**4-1)**2}
register(:v){|x,y|1/2.0-x**6-(2*y+3/2.0-8*x**2+5*x**4)**2}
register(:w){|x,y|1-x**8-(3*y-2*Math.cos(6*x)-3*x**2+2*x**4)**2}
register(:x){|x,y,r,th|3*Math.atan((2+Math.tan(2*th-Math.sin(2*th)/4)**2)/6)-4*r}
register(:y){|x,y,r,th|3*Math.atan((2+Math.tan(3*th/2+Math::PI/4-Math.cos(th)/2-Math.sin(2*th)/4)**2)/8)-4*r}
register(:z){|x,y|1/(4+128*(x-y)**2)-2*y**8+5*y**4/4-(x+y/8)**8-1/8.0}
end
def self.chars char, size
font = face char
to_aa(size){|x,y|font.include? x,y}
end
def self.mix_char c1, c2, val, size
f1, f2 = face(c1), face(c2)
to_aa(size){|x,y|
d1, d2 = val, val-1
v1 = f1.value(x+d1/2,y-d1/4)
v2 = f2.value(x+d2/2,y-d2/4)
Math.atan(v1)*(1-val) + val*Math.atan(v2) > 0
}
end
def self.to_aa size, &block
(size/2).times.map{|iy|
s=size.times.map{|ix|
u, d = 2.times.map{|ud|
2.times.to_a.repeated_permutation(2).count{|jx, jy|
x, y = (ix+jx.fdiv(2))/size*2-1, 1-(2*iy+(ud+jy.fdiv(2)))/size*2
block.call x, y
}
}
aa_table[4-u][4-d]
}.join
}
end
end
require 'io/console'
def banner msg, size: nil
h, w = $>.winsize rescue nil
cw = size || (!w ? 12 : [(w-1)/4, 12].max)
if w
cw = size || [(w-1)/4, 12].max
lsize = [(w-1)/cw, 1].max
lines = msg.lines.map{|l|l.chomp.chars.each_slice(lsize).map(&:join)}.flatten
else
cw = size || 12
lines = msg.lines
end
@cache = {}
lines.each do |l|
clines = l.chars.map{|c|(@cache[c]||=Font.chars(c, cw+cw/6)).map{|l|l[cw/12,cw]}}.transpose.map(&:join)
puts clines.map{|l|"|#{l}"}
end
end
def animate msg, size: nil
msg = "#{msg} "
move = ->{$> << "\e[1;1H"}
clear = ->{$> << "\e[J"}
clear.call
move.call
loop.with_index{|_,i|
h, w = ($>.winsize rescue [24, 80])
t = i/20.0%msg.size
x = ->x{3*x*x-2*x*x*x}
lines = Font.mix_char msg[t.to_i], msg[(t.to_i+1)%msg.size], x[t%1], (size||h*2)
clear.call
move.call
print lines.map{|s|s[0,w]}[0,h].join("\n")
move.call
sleep 0.05
}
end
options = {}
commands = {
h: {name: :help, run: ->{help commands}},
a: {name: :animate, run: ->{options[:animate] = true}},
s: {name: :size, run: ->(s){options[:size] = s.to_i}}
}
def help commands
puts "\e[1mruby #{__FILE__} [options] message\m"
commands.each do |type, cmd|
puts "\t\e[1m-#{[type, *cmd[:run].arity.times.map{'*'}].join ' '}\t\e[m #{cmd[:name]}"
end
exit
end
args = ARGV.dup
loop do
a = args.first
break unless /^--?(?<cmd>[a-z]*)$/ =~ a
args.shift
break if cmd == ''
command = commands[cmd.to_sym] || commands.find{|k,v|v[:name].to_s==cmd}&.last
raise "unknown option #{a}" unless command
block = command[:run]
block.call *block.arity.times.map{args.shift}
end
msg = args.join ' ' unless args.empty?
if options[:animate]
unless msg
$> << "message> "
msg = STDIN.gets
end
animate msg, size: options[:size]
else
if msg
banner msg, size: options[:size]
else
loop do
msg = STDIN.gets
break if msg.nil?
banner msg, size: options[:size]
end
end
end
| true |
f6f134e7af84febbf2d46da6207562fcc0a3e9ff | Ruby | netarc/structured_object | /test/structured_object/serialize_test.rb | UTF-8 | 2,851 | 2.953125 | 3 | [
"MIT"
] | permissive | require "test_helper"
class SerializeTest < Test::Unit::TestCase
class Foo < StructuredObject
struct do
uint16 :l1
uint16 :l2
int16 :l3
byte :a1, :array => {:fixed_size => 3}
char :a2, :array => true
struct :s1 do
byte :x
char :y
end
struct :s2, :array => {:fixed_size => 2} do
char :x
end
struct :s3, :array => true do
char :x
end
byte :blocks, :array => {:storage => :uint32}
byte :stack_count, :value => Proc.new { stacks.length }
byte :stacks, :array => {:initial_size => Proc.new { stack_count }, :storage => false}
end
end
context "should serialize object" do
should "serialize" do
goal = ""
foo = Foo.new
goal += "\x22\x22"
foo.l1 = 8738
goal += "\x33\x33"
foo.l2 = 13107
goal += "\x44\x44"
foo.l3 = 17476
goal += "\x00\x00\x01"
foo.a1 = [0,0,1]
goal += "\x02" + "\x99\x11"
foo.a2 << -103
foo.a2 << 17
goal += "\x7B\xEC"
foo.s1.x = 123
foo.s1.y = -20
goal += "\xF6\xEC"
foo.s2[0].x = -10
foo.s2[1].x = -20
goal += "\x03" + "\xF6\xEC\xE2"
foo.s3 = [foo.s3.new, foo.s3.new, foo.s3.new]
foo.s3[0].x = -10
foo.s3[1].x = -20
foo.s3[2].x = -30
goal += "\x04\x00\x00\x00" + "\x05\x06\x07\x08"
foo.blocks = [5,6,7,8]
goal += "\x03" + "\x01\x02\x03"
foo.stacks = [1,2,3]
assert_equal goal.unpack('H*')[0], foo.serialize_struct.unpack('H*')[0]
end
end
context "should unserialize object" do
should "unserialize" do
goal = "\x22\x22\x33\x33\x44\x44\x00\x00\x01\x02\x99\x11\x7B\xEC\xF6\xEC\x03\xF6\xEC\xE2\x04\x00\x00\x00\x05\x06\x07\x08\x03\x01\x02\x03"
foo = Foo.new
foo.unserialize_struct(goal)
assert_equal 8738, foo.l1
assert_equal 13107, foo.l2
assert_equal 17476, foo.l3
assert_equal 3, foo.a1.size
assert_equal 0, foo.a1[0]
assert_equal 0, foo.a1[1]
assert_equal 1, foo.a1[2]
assert_equal 2, foo.a2.size
assert_equal -103, foo.a2[0]
assert_equal 17, foo.a2[1]
assert_equal 123, foo.s1.x
assert_equal -20, foo.s1.y
assert_equal 2, foo.s2.size
assert_equal -10, foo.s2[0].x
assert_equal -20, foo.s2[1].x
assert_equal 3, foo.s3.size
assert_equal -10, foo.s3[0].x
assert_equal -20, foo.s3[1].x
assert_equal -30, foo.s3[2].x
assert_equal 4, foo.blocks.size
assert_equal 5, foo.blocks[0]
assert_equal 6, foo.blocks[1]
assert_equal 7, foo.blocks[2]
assert_equal 8, foo.blocks[3]
assert_equal 3, foo.stack_count
assert_equal 1, foo.stacks[0]
assert_equal 2, foo.stacks[1]
assert_equal 3, foo.stacks[2]
end
end
end
| true |
a15915514b6901227a5ae9af71b68f520f6b204b | Ruby | stazman/ruby-collaborating-objects-lab-v-000 | /lib/song.rb | UTF-8 | 472 | 3.171875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Song
attr_accessor :name, :artist, :songs, :song
def initialize(name)
@name = name
end
def self.new_by_filename(filename)
split_file_name_song = filename.split(" - ")[1]
name = filename.split(" - ")[0]
song = self.new(split_file_name_song)
new_artist = Artist.find_or_create_by_name(name)
song.artist = new_artist
new_artist.add_song(song)
song
end
end
| true |
9df55fd38b93d4ef68b571c057d766982f41d1fb | Ruby | AJFaraday/re-rpg | /scripts/declarative_battle.rb | UTF-8 | 2,899 | 3.75 | 4 | [
"MIT"
] | permissive | # Combatants: alice, bob and charlie
# their health is 10
# their damage is 2
# Each turn, a character chooses a target and attacks them.
# attacking
# They have a 90% chance to hit (nullify)
# They have a 20% chance of a critical (x 2, multiply)
# defending
# They have a 50% chance to block (half damage, multiply)
# They have a 10% change to dodge (nullify)
require_relative '../lib/environment'
class Character < GameEntity
has_actions
changing_attribute :health, initial: 10, maximum: 10
attr_reader :name
alias_method :to_s, :name
action_template :attack, :health, :decrease, 2,
type: 'physical',
message: "SELF attacks TARGET",
modifiers: [
{
type: 'Nullify',
percent: 10,
message: 'but it missed.'
},
{
type: 'Multiply',
percent: 10,
multiplier: 2,
message: 'Critical hit! Double damage!'
}
]
action_template :drain, :health, :from, 1,
type: 'magic',
message: 'SELF drains health from TARGET',
modifiers: [
{
type: 'Nullify',
percent: 30,
message: 'but it fails.'
}
]
def initialize(name, attrs={})
super()
@name = name
end
def dead?
!alive?
end
def alive?
get(:health) > 0
end
end
def report_health(characters)
GameLogger.info("")
GameLogger.info(characters.collect { |c| "#{c}: #{c.get(:health)}" })
GameLogger.info("")
end
characters = ['Alice', 'Bob', 'Charlie'].collect do |name|
Character.new(name)
end
characters[1].add_action(
:"big attack", :health, :decrease, 4, type: 'physical',
message: 'SELF launches a huge attack on TARGET',
modifiers: [
{
type: 'Nullify', percent: 50, message: "but he can't be bothered"
}
]
)
characters[1].modify_action(:attack, {
type: 'Nullify', percent: 10, message: "but he can't be bothered"
})
characters[2].add_action(
:heal, :health, :increase, 2, type: 'magic',
message: 'SELF heals TARGET',
modifiers: [
{
type: 'Nullify', percent: 30, message: "but it didn't work"
}
]
)
turn = 1
until characters.count(&:alive?) <= 1
character = characters[0]
GameLogger.info("Turn: #{turn += 1} - #{Character.name}")
target = characters[1]
action = character.actions[rand(character.actions.length)]
if action == :heal
character.action(action, character)
else
character.action(action, target)
end
characters.delete(target) if target.dead?
report_health(characters)
characters.rotate!
end
GameLogger.info("#{characters[0].name} won") | true |
5dd447e2b815c4b5d22fff5c30fe5ae5c95186ab | Ruby | sahilbathla/tv_guide | /app/helpers/home_helper.rb | UTF-8 | 260 | 2.671875 | 3 | [] | no_license | module HomeHelper
# @param [TvShow] tv_show: Tv Show for which you need repeating days
def repeating_days(tv_show)
tv_show.repeats_on.split(',').uniq.map do |wday|
::Constants::DAYS_MAP[wday.to_i]
end.join(', ')
end
end
| true |
4983bb2545b378ef5cee30aa790b660b247a2113 | Ruby | oddruud/art-crawl | /image.rb | UTF-8 | 903 | 3.078125 | 3 | [] | no_license | require 'RMagick'
include Magick
module ArtCrawl
class Image
attr_reader :img
attr_reader :mean_color
def initialize filename
puts "analyzing image #{filename}..."
begin
@img = Magick::Image.read( filename )[0]
rescue
end
unless @img.nil?
puts @img.to_s
@img = @img.quantize( 16 )
histogram = @img.color_histogram()
@mean_color = get_mean_color( histogram )
end
end
def get_mean_color( histogram )
red = 0
blue = 0
green = 0
count = 0
histogram.each do |pixel, occurances|
count += occurances
red += pixel.red * occurances
green += pixel.green * occurances
blue += pixel.blue * occurances
end
red /= count
green /= count
blue /= count
return {"red"=>red, "green"=>green, "blue"=>blue}
end
end
end
| true |
8bc371b9c05c93927d1c24302f6d5e6896f8c9ee | Ruby | yukijina/nyc-pigeon-organizer-online-web-prework | /nyc_pigeon_organizer.rb | UTF-8 | 450 | 3.09375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer(data)
# write your code here!
obj = Hash.new{|h,k| h[k] = {color: [], gender: [],lives: []}}
data.each_with_object(obj) do |(key, value), obj|
value.each do |item,array|
array.each do |string|
obj[string][:color] << item.to_s if key == :color
obj[string][:gender] << item.to_s if key == :gender
obj[string][:lives] << item.to_s if key == :lives
end
end
end
end | true |
c2f529c62737c50f4117e36664efcb2c80eaa522 | Ruby | yaqizhao/projet_THP | /Ruby/exo_09.rb | UTF-8 | 204 | 3.15625 | 3 | [] | no_license | puts "Bonjour, c'est quoi votre prénom ?"
user_first_name = gets.chomp
puts "Après, c'est quoi votre nom de famille ?"
user_last_name = gets.chomp
puts "Bonjour, #{user_first_name} #{user_last_name} !"
| true |
1ce94de185c5b56ce4fbda61de8304ba64c31547 | Ruby | sroop/Takeaway | /lib/takeaway.rb | UTF-8 | 715 | 3.28125 | 3 | [] | no_license | require_relative './text.rb'
class Takeaway
include Text
attr_reader :menu
def initialize(menu = [])
@menu = menu
end
def add_menu(menu)
@menu << menu
@menu
end
def view(menu)
menu.view_menu
end
def user_input
puts "Type the name of the dish:"
@user_input_dish = gets.chomp
puts "Type the quantity:"
@quantity = gets.chomp.to_i
end
# def place(order)
# user_input
# @dish = @menu.map { |dish| dish.name == @user_input_dish }
# order.add(@dish, @quantity)
# end
# def total_price(order)
# order.price
# end
def confirm_order
puts "Thank you for your order! We've sent you a text message to confirm the delivery."
send_text
end
end
| true |
07a10e7d9c519a9ee42e0657f4e74dd2a9e30891 | Ruby | ufo2mstar/cuker | /lib/cuker/helpers/writers/summary_x_l_writer.rb | UTF-8 | 2,831 | 2.859375 | 3 | [
"MIT"
] | permissive | require_relative 'abstract_writer'
require 'rubyXL'
require 'rubyXL/convenience_methods'
module Cuker
class SummaryXLWriter < RubyXLWriter
def initialize
# @ext = '.xlsm'
super
@template_file_name = "template_excel_summary.xlsm"
@log.debug "initing #{self.class}"
end
def make_new_book name
@log.debug "summary rxl make new sheet"
#todo: dangit! handling this path naming properly
file_name = "#{name.nil? ? super(name) : name}#{ext}"
@book[file_name] = SummaryRubyXLFile.new file_name, @template_file_name
@active_file = @book[file_name]
file_name
end
def write model, output_file_path
file_name = make_new_file output_file_path
write_title model.title
model.data.each {|row| write_new_row row}
finishup
file_name
end
end
class SummaryRubyXLFile < RubyXLFile
attr_accessor :workbook, :worksheets, :worksheet
def initialize file_name, template_file_name
premade = File.basename(file_name) =~ /xlsm/
template_file_path = File.join File.dirname(__FILE__), template_file_name
@file_name = premade ? template_file_path : file_name
# super @file_name #replaced below
init_logger
@name = file_name
@rows = []
@log.debug "Making new #{self.class} => #{@file_name}"
@workbook = premade ? RubyXL::Parser.parse(@file_name) : RubyXL::Workbook.new
@worksheets = @workbook.worksheets
@worksheet = @workbook['Feature Summary raw']
@rows = sheet_rows.dup # starting Row
@offset = 0 # starting Col
@file_name = file_name
end
def locate_sheet sheet_name
sheet_index = @workbook.worksheets.index {|x| x.sheet_name == sheet_name}
@link_sheet = @workbook.worksheets[sheet_index]
if sheet_index
@log.debug "located sheet #{sheet_name} @location #{sheet_index}"
# @workbook.worksheets.delete_at(sheet_index)
sheet_index
else
@log.error "no sheet named '#{sheet_name}' found.. available sheets []"
nil
end
end
def current_row
rows.size - 1
end
def current_col
@offset
end
def add_row ary
# super ary
@rows << ary
row, col = current_row, current_col
worksheet.insert_row(row)
ary.each do |val|
case val.class.to_s
when "String", "Integer", /Nil/, /Fixnum/
worksheet.insert_cell(row, col, val)
else
@log.error "SummaryRubyXLFile auto stringification of unknown format: #{val.class} => '#{val}'"
worksheet.insert_cell(row, col, val)
# worksheet.insert_cell(row, col, val.to_s)
end
col += 1
end
@log.trace workbook.worksheets.map(&:sheet_name)
end
alias :add_line :add_row
end
end | true |
d731d81196ee35802fcf8edae0285d5af9450568 | Ruby | HeyCampbell/GoParkYourself | /app/models/street_section.rb | UTF-8 | 1,478 | 2.765625 | 3 | [] | no_license | class StreetSection < ActiveRecord::Base
SYMBOLS_TO_BOROUGHS = {"M" => "Manhattan", "B" => "Bronx", "K" => "Brooklyn", "Q" => "Queens"}
has_many :signs, :foreign_key => 'status_order', :primary_key => 'status_order'
before_save :set_encoder_class, :set_encoder, :encode_cross_streets
def borough_name
SYMBOLS_TO_BOROUGHS(borough)
end
def set_encoder_class(args = {})
@encoder_class = args[:encoder_class] || StreetSectionEncoder
end
def set_encoder
@encoder = @encoder_class.new(self)
end
def encode_cross_streets
@encoder.encode!
end
def point_from
[latitude_from, longitude_from]
end
def point_to
[latitude_to, longitude_to]
end
def length
GeographicEncoder.get_distance_in_feet(point_from, point_to)
end
def buffer
(self.length - self.signs.last.distance) / 2
end
def signs_near(distance_from)
signs = self.signs
results = []
signs.each_with_index do |sign, index|
if sign.distance >= distance_from
upper_result = sign
lower_result = signs[index-1]
results << signs.find_all{|s| s.distance == lower_result.distance}
results << signs.find_all{|s| s.distance == upper_result.distance}
return results.flatten!
end
end
return results
end
def self.refresh_gps
StreetSection.all.each do |sect|
sect.get_point_from
sect.save
sect.get_point_to
sect.save
end
end
end
| true |
1ee73aa7f43689b3496eaf4a0595912d1db89935 | Ruby | randhirray/dell-cisconexus5k | /lib/puppet_x/cisconexus5k/ssh.rb | UTF-8 | 678 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #This class is responsible for SSH specific transport to the switch
require 'puppet/util/network_device/transport/ssh'
module PuppetX
module Cisconexus5k
class Ssh < Puppet::Util::NetworkDevice::Transport::Ssh
#These switches require a carriage return as well, instead of just new line. So we override Puppet's method to add \r
def send(line, noop=false)
Puppet.debug "SSH send: #{line}" if Puppet[:Debug]
@channel.send_data(line + "\r") unless noop
end
def sendwithoutnewline(line, noop = false)
Puppet.debug "SSH send: #{line}" if Puppet[:debug]
@channel.send_data(line) unless noop
end
end
end
end | true |
6f7c795644fbd3b67583338a3e52f5e732988b58 | Ruby | uranussg/aA_classwork | /W1D4/rspec_exercise_3/lib/part_2.rb | UTF-8 | 352 | 3.484375 | 3 | [] | no_license | def element_count(arr)
count = Hash.new(0)
arr.each do |el|
count[el] += 1
end
count
end
def char_replace!(str, hash)
str.each_char.with_index do |char, idx|
if hash.has_key?(char)
str[idx] = hash[char]
end
end
str
end
def product_inject(arr)
arr.inject { |acc, num| acc * num }
end | true |
3063744907a30396333b586e524bbbf60fb8071f | Ruby | SarahBunker/rb101_programming_foundations | /ruby_written_assessment_practice/practice_spot_8_11.rb | UTF-8 | 2,522 | 4.46875 | 4 | [] | no_license | =begin
Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is not good
in maths. Can you help him to find out, how many cakes he could bake considering his recipes?
Write a function cakes(), which takes the recipe (object) and the available ingredients
(also an object) and returns the maximum number of cakes Pete can bake (integer). For simplicity
there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200).
Ingredients that are not present in the objects, can be considered as 0.
In: 2 objects
1st object is a recipe
2nd object is amount of eact ingrediant he has, can have extra ingrediants
objects are hashes
out: integer representing the maximum number of cakes
Problem: for a given recipe and given amounts of ingrediants find the number of cakes you can make
Examples:
// must return 2
cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: 200});
// must return 0
cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: 2000, milk: 2000});
Data:
two hashes come in
intermediary, store number of times recipe goes into ingrediants as array
integer goes out
keys are stored as strings
values are stored as integers
Algorythim:
create cakes method
initizize empty array to store amount of times you could make the recipe for each ingrediant
iterate through recipe hash
access amount of matching ingrediant avaible
return zero if ingrediant is not avaible
find amount of times you could make the recipe for that ingrediant
store in array
return minimum of array storing # of times you could make the recipe for each ingrediant
=end
def cakes(recipe, pantry)
max_cake_per_ingrediant = []
num_cakes
end
p cakes({"flour"=>500, "sugar"=>200, "eggs"=>1},{"flour"=>1200, "sugar"=>1200, "eggs"=>5, "milk"=>200}) == 2
p cakes({"cream"=>200, "flour"=>300, "sugar"=>150, "milk"=>100, "oil"=>100},{"sugar"=>1700, "flour"=>20000, "milk"=>20000, "oil"=>30000, "cream"=>5000}) == 11
p cakes({"apples"=>3, "flour"=>300, "sugar"=>150, "milk"=>100, "oil"=>100},{"sugar"=>500, "flour"=>2000, "milk"=>2000}) == 0
p cakes({"apples"=>3, "flour"=>300, "sugar"=>150, "milk"=>100, "oil"=>100},{"sugar"=>500, "flour"=>2000, "milk"=>2000, "apples"=>15, "oil"=>20}) == 0
p cakes({"eggs"=>4, "flour"=>400},{}) == 0
p cakes({"cream"=>1, "flour"=>3, "sugar"=>1, "milk"=>1, "oil"=>1, "eggs"=>1},{"sugar"=>1, "eggs"=>1, "flour"=>3, "cream"=>1, "oil"=>1, "milk"=>1}) == 1 | true |
880988f8506e7b8ffbb866a21aea7b5937cfd31c | Ruby | rafaelzuim/preflight-0.3.0 | /lib/preflight/profile.rb | UTF-8 | 3,397 | 2.78125 | 3 | [] | no_license | # coding: utf-8
module Preflight
# base functionality for all profiles.
#
module Profile
def self.included(base) # :nodoc:
base.class_eval do
extend Preflight::Profile::ClassMethods
include InstanceMethods
end
end
module ClassMethods
def profile_name(str)
@profile_name = str
end
def import(profile)
profile.rules.each do |array|
rules << array
end
end
def rule(*args)
rules << args
end
def rules
@rules ||= []
end
end
module InstanceMethods
def check(input)
valid_rules?
if File.file?(input)
check_filename(input)
elsif input.is_a?(IO)
check_io(input)
else
raise ArgumentError, "input must be a string with a filename or an IO object"
end
end
def rule(*args)
instance_rules << args
end
private
def check_filename(filename)
File.open(filename, "rb") do |file|
return check_io(file)
end
end
def check_io(io)
PDF::Reader.open(io) do |reader|
raise PDF::Reader::EncryptedPDFError if reader.objects.encrypted?
check_pages(reader) + check_hash(reader)
end
rescue PDF::Reader::EncryptedPDFError
["Can't preflight an encrypted PDF"]
end
def instance_rules
@instance_rules ||= []
end
def all_rules
self.class.rules + instance_rules
end
def check_hash(reader)
hash_rules.map { |chk|
chk.check_hash(reader.objects)
}.flatten.compact
rescue PDF::Reader::UnsupportedFeatureError
[]
end
def check_pages(reader)
rules_array = page_rules
issues = []
begin
reader.pages.each do |page|
page.walk(*rules_array)
issues += rules_array.map(&:issues).flatten.compact
end
rescue PDF::Reader::UnsupportedFeatureError
nil
end
issues
end
# ensure all rules follow the prescribed API
#
def valid_rules?
invalid_rules = all_rules.reject { |arr|
arr.first.instance_methods.map(&:to_sym).include?(:check_hash) ||
arr.first.instance_methods.map(&:to_sym).include?(:issues)
}
if invalid_rules.size > 0
raise "The following rules are invalid: #{invalid_rules.join(", ")}. Preflight rules MUST respond to either check_hash() or issues()."
end
end
def hash_rules
all_rules.select { |arr|
arr.first.instance_methods.map(&:to_sym).include?(:check_hash)
}.map { |arr|
klass = arr[0]
klass.new(*deep_clone(arr[1,10]))
}
end
def page_rules
all_rules.select { |arr|
arr.first.instance_methods.map(&:to_sym).include?(:issues)
}.map { |arr|
klass = arr[0]
klass.new(*deep_clone(arr[1,10]))
}
end
# round trip and object through marshall as a hacky but effective
# way to deep clone the object. Used to ensure rules that mutate
# their arguments don't impact later profile checks.
def deep_clone(obj)
Marshal.load Marshal.dump(obj)
end
end
end
end
| true |
6b35b9bd4d787a8c3c8e3f9fcf1358ce9a72611a | Ruby | jekyll/jekyll | /lib/jekyll/utils/win_tz.rb | UTF-8 | 1,625 | 2.796875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Jekyll
module Utils
module WinTZ
extend self
# Public: Calculate the Timezone for Windows when the config file has a defined
# 'timezone' key.
#
# timezone - the IANA Time Zone specified in "_config.yml"
#
# Returns a string that ultimately re-defines ENV["TZ"] in Windows
def calculate(timezone, now = Time.now)
External.require_with_graceful_fail("tzinfo") unless defined?(TZInfo)
tz = TZInfo::Timezone.get(timezone)
#
# Use period_for_utc and utc_total_offset instead of
# period_for and observed_utc_offset for compatibility with tzinfo v1.
offset = tz.period_for_utc(now.getutc).utc_total_offset
#
# POSIX style definition reverses the offset sign.
# e.g. Eastern Standard Time (EST) that is 5Hrs. to the 'west' of Prime Meridian
# is denoted as:
# EST+5 (or) EST+05:00
# Reference: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
sign = offset.positive? ? "-" : "+"
rational_hours = offset.abs.to_r / 3600
hours = rational_hours.to_i
minutes = ((rational_hours - hours) * 60).to_i
#
# Format the hours and minutes as two-digit numbers.
time = format("%<hours>02d:%<minutes>02d", :hours => hours, :minutes => minutes)
Jekyll.logger.debug "Timezone:", "#{timezone} #{sign}#{time}"
#
# Note: The 3-letter-word below doesn't have a particular significance.
"WTZ#{sign}#{time}"
end
end
end
end
| true |
ef0fd0d1251d7e8a2828bc68a00f17a48571495d | Ruby | aigecko/Kemonomimi | /src/StatusWindow/Button.rb | UTF-8 | 496 | 2.5625 | 3 | [] | no_license | #coding: utf-8
class StatusWindow::Button
def initialize(str,name,x,y)
@str=str
@name=name
@x=x
@y=y
@str_pic=Font.render_texture(str,20,*Color[:attrib_font])
@w,@h=@str_pic.w,@str_pic.h
@button=Rectangle.new(@x,@y,@w,@h,Color[:attrib_val])
end
def update_coord(x,y)
@button.x=@x=x
@button.y=@y=y
end
def detect_click(x,y)
return x.between?(@x,@x+@w)&&y.between?(@y,@y+@h)
end
def draw
@button.draw
@str_pic.draw(@x,@y)
end
end | true |
85395bb7a5791f6b2896d1b99e0902de5e16249e | Ruby | dcvezzani/zzt-parser | /zzt_parser.rb | UTF-8 | 1,702 | 2.796875 | 3 | [] | no_license | require "rubygems"
require "bundler/setup"
require File.dirname(__FILE__) + "/models/zzt_game_header"
require File.dirname(__FILE__) + "/lib/zzt_parser_utils"
# require your gems as usual
require "ruby-debug"
class ZZTParser
include ZZTParserUtils
attr_accessor :game_file, :hex_array, :game_header, :game_boards
def initialize(arg)
@game_header = nil
@content = nil
@game_boards = []
if(arg.is_a?(Array))
@original_hex_array = arg
else
@game_file = arg
load_file
end
reset
self
end
def bytes_read
(@original_hex_array.length - @hex_array.length)
end
def bytes_original_len
@original_hex_array.length
end
def load_file
File.open(game_file,"rb") do |f|
buffer = nil
while((buffer = f.read(2048)))
(@content ||= '') << buffer
end
end
# now parse @header to hex array
@original_hex_array = @content.each_byte.collect {|val| "%02X" % val}
end
def reset
@hex_array = @original_hex_array.clone()
end
def self.parse
p = ZZTParser.new("/Users/davidvezzani/projects/zzt/zzt/tour.zzt")
zzt_game_identifier = p.read_hex_array(2, true, "zzt_file")
game_header = p.game_header = ZZTGameHeader.parse(p)
# p.game_boards = (0...p.game_header.board_cnt).map{|x|
# ZZTGameBoard.parse(p)
# }
padding_buffer_len = "200".hex - p.bytes_read
p.read_hex_array(padding_buffer_len, true, "padding")
#(0...padding_buffer_len).each{|x| p.hex_array.shift()}
#p.hex_array.slice!(padding_buffer_len, p.bytes_original_len)
(0...game_header.board_cnt).each{|index|
p.game_boards << ZZTGameBoard.parse(p, (index+1))
}
p
end
end
| true |
2bdbc565d4bab89a12c8995e51b9a7318afb206b | Ruby | vvainio/ratebeer | /spec/models/brewery_spec.rb | UTF-8 | 1,702 | 2.75 | 3 | [] | no_license | require 'rails_helper'
describe Brewery do
it 'has the name and year set correctly and is saved to database' do
brewery = Brewery.create name: 'Schlenkerla', year: 1674
expect(brewery.name).to eq('Schlenkerla')
expect(brewery.year).to eq(1674)
expect(brewery).to be_valid
end
it 'without a name is not valid' do
brewery = Brewery.create year: 1674
expect(brewery).not_to be_valid
end
describe 'with ratings' do
let!(:user) { FactoryGirl.create :user }
let!(:brewery) { FactoryGirl.create :brewery, name: 'Brewery' }
it 'has the correct average' do
create_beer_to_brewery_with_rating(brewery, 5, user)
create_beer_to_brewery_with_rating(brewery, 10, user)
create_beer_to_brewery_with_rating(brewery, 15, user)
expect(brewery.average_rating).to eq(10)
end
end
describe 'multiple breweries' do
let!(:user) { FactoryGirl.create :user }
let!(:brewery1) { FactoryGirl.create :brewery, name: 'Brewery 1' }
let!(:brewery2) { FactoryGirl.create :brewery, name: 'Brewery 2' }
it 'top list has correct results' do
create_beer_to_brewery_with_rating(brewery1, 5, user)
create_beer_to_brewery_with_rating(brewery1, 10, user)
create_beer_to_brewery_with_rating(brewery1, 15, user) # avg 10
create_beer_to_brewery_with_rating(brewery2, 30, user)
create_beer_to_brewery_with_rating(brewery2, 30, user) # avg 30
top_breweries = Brewery.top(2)
expect(top_breweries.first).to eq(brewery2)
expect(top_breweries.first.average_rating).to eq(30)
expect(top_breweries.last).to eq(brewery1)
expect(top_breweries.last.average_rating).to eq(10)
end
end
end
| true |
92bd892b0fa954ec5deb721d236323f9eb961abb | Ruby | b-n/obs-control | /lib/obs_control/store.rb | UTF-8 | 1,038 | 2.90625 | 3 | [
"WTFPL"
] | permissive | module OBSControl
class Store
def devices=(devices)
@devices = devices
@devices.each do |device|
device.register -> (event, payload) { receive(event, payload) }
end
end
# Called when an event is fired either by a device
#
# @param event [Symbol] The event being fired
# @param payload [Hash] Information from the events
#
# @return nil
def receive(event, payload)
raise 'Implement a receive method in your store'
end
# Send a particular event. Will return with the value from the first device that
# responds to this event
#
# @param event [Symbol] the event to fire
# @param payload [Hash] additional parameters that may be required
#
# @returns Dependent on implementation
def put(event, payload = {})
result = @devices.lazy.map do |device|
device.handles?(event) && device.send(event, payload)
end.find(&:itself)
raise "Event: #{event} not implemented" if result.nil?
result
end
end
end
| true |
5c1cc45182b635b3db62ed5af8705af0a323cdeb | Ruby | riverswb/event_reporter | /lib/event_manager.rb | UTF-8 | 879 | 2.875 | 3 | [] | no_license | require 'csv'
require 'sunlight/congress'
require 'erb'
Sunlight::Congress.api_key = "8ed8af10edf6473583d8878e183284f5"
def legislators_by_zipcode(zipcode)
Sunlight::Congress::Legislator.by_zipcode(zipcode)
end
# def save_thank_you_letters(id,form_letter)
#
# Dir.mkdir("output") unless Dir.exists? "output"
#
# filename = "output/thanks_#{id}.html"
#
# File.open(filename, 'w') do |file|
# file.puts form_letter
# end
# end
contents = CSV.open "event_attendees_small.csv", headers: true, header_converters: :symbol
template_letter = File.read "form_letter.erb"
erb_template = ERB.new template_letter
contents.each do |row|
id = row[0]
name = row[:first_name]
zipcode = clean_zipcode(row[:zipcode])
@legislators = legislators_by_zipcode(@zipcode)
#form_letter = erb_template.result(binding)
# save_thank_you_letters(id,form_letter)
end
| true |
3b9878d05ebf90c2c85afb7c78a745bc5afdae95 | Ruby | JulianCedric/programming-univbasics-nds-nds-to-insight-with-methods-nyc-web-030920 | /test.rb | UTF-8 | 2,018 | 3.0625 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | $LOAD_PATH.unshift(File.dirname(__FILE__))
require 'directors_database'
require 'pp'
# Find a way to accumulate the :worldwide_grosses and return that Integer
# using director_data as input
# first_director_name = directors_database.first.values.first
# first_director_hash = directors_database.find{ |x| x[:name] == first_director_name }
# p directors_database.find{ |x| x[:name] == first_director_name }
# def gross_for_director(director_name)
# row_index = 0
# while row_index < directors_database.length do
# if directors_database[row_index][:name] = director_name do
# indiv_gross = 0
# inner_row_index = 0
# while inner_row_index < directors_database[row_index][:movies].length do
# indiv_gross += directors_database[row_index][:movies][inner_row_index][:worldwide_gross]
# inner_row_index += 1
# end
# end
# row_index += 1
# end
# p indiv_gross
# end
def directors_totals(nds)
array = []
row_index = 0
while row_index < directors_database.length do
array << directors_database[row_index][:name]
grosses_per_director = 0
inner_array = []
inner_row_index = 0
while inner_row_index < directors_database[row_index][:movies].length do
grosses_per_director += directors_database[row_index][:movies][inner_row_index][:worldwide_gross]
inner_array << grosses_per_director
inner_row_index += 1
end
array << inner_array.max
row_index += 1
end
new_array = []
string_array = []
integer_array = []
index = 0
while index < array.length do
if array[index].class == String
string_array << array[index]
elsif array[index].class == Integer
integer_array << array[index]
end
new_array << string_array || integer_array
index += 1
end
hash = {
"Stephen Spielberg" => 1357566430
}
hash_index = 0
while hash_index < string_array.length do
hash[string_array[hash_index]] = integer_array[hash_index]
hash_index += 1
end
hash
end | true |
5a0cb04fe705843f9e70bcefc3d505104da6a54f | Ruby | jamaleh1111/launch_school | /introduction_to_programming/more_stuff/exception_handling.rb | UTF-8 | 889 | 4.21875 | 4 | [] | no_license | # exception handling is a specific process that deals with errors in a manageable and predictable way.
# Ruby has an Exception class that makes handling these errors much easier.
# reserved words "begin", "rescue", "end"
# exception_example.rb
names = ['bob', 'joe', 'steve', nil, 'frank']
names.each do |name|
begin
# perform some dangerous operation
puts "#{name}'s name has #{name.length} letters in it."
rescue
# do this if operation fails
# for example, log the error
puts "Something went wrong!"
end
end
#inline_exception_example.rb
zero = 0
puts "Before each call"
zero.each { |element| } rescue puts "Can't do that!"
puts "After each call"
#divide.rb
def divide(number, divisor)
begin
answer = number / divisor
rescue ZeroDivisionError => e
puts e.message
end
end
puts divide(16,4)
puts divide(4, 0)
puts divide(14, 7)
| true |
9391ed9363efb980a4151f6f337a7a907c71375b | Ruby | digideskio/momogs | /getCSVPercentageComplete.rb | UTF-8 | 4,350 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'rubygems'
require 'json'
require 'pp'
require 'time'
require 'date'
require 'mongo'
require 'date'
require 'parseconfig'
MONGO_HOST = ENV["MONGO_HOST"]
raise(StandardError,"Set Mongo hostname in ENV: 'MONGO_HOST'") if !MONGO_HOST
MONGO_PORT = ENV["MONGO_PORT"]
raise(StandardError,"Set Mongo port in ENV: 'MONGO_PORT'") if !MONGO_PORT
MONGO_USER = ENV["MONGO_USER"]
raise(StandardError,"Set Mongo user in ENV: 'MONGO_USER'") if !MONGO_USER
MONGO_PASSWORD = ENV["MONGO_PASSWORD"]
raise(StandardError,"Set Mongo user in ENV: 'MONGO_PASSWORD'") if !MONGO_PASSWORD
db = Mongo::Connection.new(MONGO_HOST, MONGO_PORT.to_i).db("gs")
auth = db.authenticate(MONGO_USER, MONGO_PASSWORD)
if !auth
raise(StandardError, "Couldn't authenticate, exiting")
exit
end
topicsColl = db.collection("topics")
if ARGV.length < 2
puts "usage: #{$0} yyyy mm"
exit
end
yyyy = ARGV[0].to_i
mm = ARGV[1].to_i
# compute start and stop times and 3 letter month name e.g. Feb for each of the last 12 months and store in array
# each array element has: metrics_start, metrics_stop, month name, number of topics created, number of topics marked complete in that time period
kpi_percentage_complete_last_twelve_months = []
12.times do
next_yyyy = yyyy
next_mm = mm + 1
previous_yyyy = yyyy
previous_mm = mm - 1
if mm == 12
next_mm = 1
next_yyyy += 1
end
if mm == 1
previous_mm = 12
previous_yyyy = yyyy - 1
end
kpi_percentage_complete_last_twelve_months.push(
{
"metrics_start" => Time.utc(yyyy, mm, 1, 0, 0),
"metrics_stop" => Time.utc(next_yyyy, next_mm, 1, 0, 0),
"three_letter_month_name" => Time.utc(yyyy, mm, 1, 0, 0).strftime("%b"),
"num_topics_created" => 0,
"num_topics_completed" => 0,
"percentage_completed" => 0.0
})
mm = previous_mm
yyyy = previous_yyyy
end
# loop through array and then compute number of topics created_at versus status_journal status "complete" to get % Solved
# and then output CSV File of the form: Month, % e.g. Feb,24.3 or Jan,21.6
csv_percentage_complete = []
# Compute Num Topics Created in the Last 12 months
kpi_percentage_complete_last_twelve_months.each do |k_complete|
k_complete["num_topics_created"] = topicsColl.find({"created_at" =>
{"$gte" => k_complete["metrics_start"], "$lt" => k_complete["metrics_stop"]}}).count()
end
# Compute Num Topics Completed in the Last 12 months and Percentage Completed
kpi_percentage_complete_last_twelve_months.each do |k_complete|
metrics_start = k_complete["metrics_start"]
metrics_stop = k_complete["metrics_stop"]
topicsColl.find({"last_active_at" => {"$gte" => metrics_start, "$lt" => metrics_stop},
"status" => "complete"},
:fields => ["last_active_at", "at_sfn", "id", "subject", "synthetic_status_journal","author"]).each do |t|
$stderr.printf("***START of topic\n")
PP::pp(t,$stderr)
$stderr.printf("***END of topic\n")
# A topic is answered in the time period if and only if:
# the first status_update_time to be "complete" is within in the time period
# SMALL BUG: this fails if MongoDB was updated more than a day AFTER the topic was marked solved in Get Satisfaction
# LUCKILY this only happens with very old solved topics and is therefore rare
sj = t["synthetic_status_journal"].detect {|status_journal|status_journal["status"] == "complete" }
if sj && (sj["status_update_time"] <=> metrics_start) >= 0 &&
(sj["status_update_time"] <=> metrics_stop) == -1
$stderr.printf("SOLVED topic in time period title:%s url:%s\n",t["subject"].gsub(","," - ")[0..79],t["at_sfn"])
k_complete["num_topics_completed"] += 1
end
end
k_complete["percentage_completed"] = 100.0 * k_complete["num_topics_completed"] / k_complete["num_topics_created"]
$stderr.printf("PERCENTAGE:%f, completed:%d, complete:%d\n", k_complete["percentage_completed"],
k_complete["num_topics_completed"], k_complete["num_topics_created"])
csv_percentage_complete.push({"three_letter_month_name"=>k_complete["three_letter_month_name"],
"percentage_completed" => k_complete["percentage_completed"]})
end
csv_percentage_complete.reverse.each do |c|
printf "%s,%f\n", c["three_letter_month_name"], c["percentage_completed"]
end
| true |
93c642fa13141253f949e22df456661420094f9b | Ruby | kbs5280/http | /lib/game.rb | UTF-8 | 702 | 3.671875 | 4 | [] | no_license | class Game
attr_accessor :answer, :guesses
def initialize
@answer = rand(1..100)
@guesses = []
end
def guess(number)
guesses << number
end
def check_guess
guess = guesses.last.to_i
case
when guess > 100 || guess < 1
"Please enter a number between 1 and 100."
when guess < answer
"Your guess was #{guess}, and it was too low."
when guess == answer
"Your guess was #{guess}, and it was correct!"
when guess > answer
"Your guess was #{guess}, and it was too high."
end
end
def game_info
return "No guesses have been made." if guesses.empty?
"#{guesses.count} guess(es) have been taken. #{check_guess}"
end
end
| true |
3efa3b16deeeb9b2d8ef5645aba77699daff70a7 | Ruby | okayjeffrey/mongthu-sf | /Rakefile | UTF-8 | 2,481 | 3.328125 | 3 | [] | no_license | require './environment'
require 'csv'
desc 'Import data from csv files into the database'
task :import do
soup_file = "soups-updates.csv"
puts "Removing #{Soup.count} existing soups and importing new ones from #{soup_file}"
# A transaction keeps us from really fucking things up. If any part of the code
# fails inside this block the database will "rollback" to where it was before
# we started!
Soup.transaction do
Soup.destroy # delete all the soups!
# reads the csv one row at a time.
CSV.foreach(soup_file){|row|
puts row.inspect
number = row[1]
title = row[2]
price = row[3]
desc = row[4]
image = row[5]
image = nil if image == "Image here"
soup = Soup.create(:number => number, :title => title, :price => price, :description => desc, :image => image)
puts soup.inspect
}
puts "Created #{Soup.count} soups!"
end
sandwich_file = "sandwiches-updates.csv"
puts "Removing #{Sandwich.count} existing sandwiches and importing new ones from #{sandwich_file}"
# A transaction keeps us from really fucking things up. If any part of the code
# fails inside this block the database will "rollback" to where it was before
# we started!
Sandwich.transaction do
Sandwich.destroy
CSV.foreach(sandwich_file){|row|
puts row.inspect
number = row[1]
title = row[2]
price = row[3]
desc = row[4]
image = row[5]
image = nil if image == "Image here"
sandwich = Sandwich.create(:number => number, :title => title, :price => price, :description => desc, :image => image)
puts sandwich.inspect
}
puts "Created #{Sandwich.count} sandwiches!"
end
dessert_file = "desserts-updates.csv"
puts "Removing #{Dessert.count} existing desserts and importing new ones from #{dessert_file}"
# A transaction keeps us from really fucking things up. If any part of the code
# fails inside this block the database will "rollback" to where it was before
# we started!
Dessert.transaction do
Dessert.destroy
CSV.foreach(dessert_file){|row|
puts row.inspect
number = row[1]
title = row[2]
price = row[3]
desc = row[4]
image = row[5]
image = nil if image == "Image here"
dessert = Dessert.create(:number => number, :title => title, :price => price, :description => desc, :image => image)
puts dessert.inspect
}
puts "Created #{Dessert.count} desserts!"
end
end
| true |
0a9d1a04184ac50cee687aa686cfd6045dd7ea1c | Ruby | ACBullen/algorithms_pratice | /cracking_the_coding_interview/is_uniq.rb | UTF-8 | 510 | 3.9375 | 4 | [] | no_license | #Given a string, determine if it has all unqique characters.
#what do you do if you can't use other data structures?
#using additional data structure, n space
def is_unique? string
alph_hash = {}
string.each_char do |char|
return false if alph_hash[char]
alph_hash[char] = true
end
true
end
#without additional data structures, O(1) space, n^2 time comp
def is_unique_O1? string
i = 0
while i < string.length
return false if string.index(string[i]) != i
i += 1
end
true
end
| true |
806ca3cea0ac2b0949698d6cb08be05febf87cf5 | Ruby | kriom/ray | /lib/ray/text_helper.rb | UTF-8 | 873 | 2.84375 | 3 | [
"Zlib"
] | permissive | module Ray
module TextHelper
module_function
if defined? ::Encoding
# @param [String] string Any string
# @param [String] enc Name of the encoding of String. Gueseed in 1.9.
#
# @return [String] String in Ray's internal encoding
def internal_string(string, enc = "UTF-8")
string.encode(InternalEncoding)
end
# @param [String] string A string encoded using Ray's internal encoding
# @param [String] enc Output encoding
#
# @return [String] string converted to the asked encoding
def convert(string, enc = "UTF-8")
string.encode enc
end
else
def internal_string(string, enc = "UTF-8")
Iconv.conv(InternalEncoding, enc, string)
end
def convert(string, enc = "UTF-8")
Iconv.conv(enc, InternalEncoding, string)
end
end
end
end
| true |
feab624d25c711bbe7a688b99924002884453a97 | Ruby | treinalinux/Logica_de_Programacao_com_Ruby | /dc/ruby_avancado/namespace_reverse_word.rb | UTF-8 | 248 | 2.96875 | 3 | [] | no_license | # frozen_string_literal: true
# module ReserveWorld
module ReserveWorld
def self.puts(text)
# Kernel::puts text.reverse.to_s
Kernel.puts text.reverse.to_s
end
end
# ReserveWorld::puts 'The result is'
ReserveWorld.puts 'The result is'
| true |
2fa1e0d98832bc355e60013ab02b384696d9f565 | Ruby | 844196/komono | /doseisan | UTF-8 | 1,005 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env ruby
class Dosei
def self.convert_doseisan_lang(string)
before_dosei_char = ['い', 'き', 'く', 'さ', 'し', 'せ', 'そ', 'ち', 'つ', 'て', 'の', 'ひ', 'へ', 'み', 'も', 'や', 'ら', 'り', 'る', 'ん', 'ぎ', 'ぐ', 'ざ', 'じ', 'ぜ', 'ぞ', 'ぢ', 'づ', 'で', 'ば', 'び', 'べ']
after_dosei_char = ['Ɩı', '₹', 'ㄑ', 'ㄜ', 'ι', 'ㄝ', 'ƺ', 'ㄘ', '⊃ ', 'Շ', '๑', 'Ʊ', 'ㄟ', 'Ⴋ', 'Ⱡ', '兯', 'ʖˋ', 'レ)', 'ʓ', 'ƕ ', '₹˝', 'ㄑ˝', 'ㄜ˝', 'ι˝', 'ㄝ˝', 'ƺ˝', 'ㄘ˝', '⊃ ˝', 'Շ˝', '∣ժ̅˝', 'Ʊ˝', 'ㄟ˝']
string.each_char.map {|c|
r = c.gsub(/./, Hash[*before_dosei_char.zip(after_dosei_char).flatten])
r.empty? ? c : r
}.join
end
end
if __FILE__ == $PROGRAM_NAME
require 'optparse'
opt = ARGV.getopts('', 'help')
if opt['help']
puts "Usage: #{File.basename(__FILE__)} [File]..."
exit
end
ARGF.read.split("\n").each {|line| puts Dosei.convert_doseisan_lang(line) }
end
| true |
1ea2856c0295953b8190e7f7681962c88c33539c | Ruby | amirrajan/mana-duel | /lib/sokushi.rb | UTF-8 | 307 | 2.75 | 3 | [] | no_license | =begin
F = violet
P = red
S = green
W = indigo
D = yellow
C = [blue, blue]
(stab) = orange
nothing () = Wait
=end
class Sokushi < Spell
def initialize
@type = :attack
end
def sequence
[:red, :indigo, :red, :violet,
:green, :green, :green, :yellow]
end
def damage
100
end
end
| true |
99011d73758d0aedf8b074a8d87016fe30968f86 | Ruby | xis19/leetcode | /1065.rb | UTF-8 | 198 | 3.0625 | 3 | [] | no_license | def index_pairs(text, words)
words.map { |word|
0.upto(text.length - 1)
.select { |i| text[i..-1].start_with?(word) }
.map { |i| [i, i + word.length - 1] }
}.flatten(1).sort
end
| true |
22edffdcdde0020999bb548d4b96cd100fc5653c | Ruby | costagavras/ruby-fundamentals-arrays-iterations | /ex10.rb | UTF-8 | 2,207 | 4.25 | 4 | [] | no_license | # 1. Start out by creating the following hash representing the number of students in past Bitmaker cohorts:
hh_bitmaker_students = { :cohort1 => 34, :cohort2 => 42, :cohort3 => 22 }
# 2. Create a method that displays the name and number of students for each cohort.
def show_vertical(my_hash)
my_hash.each do |cohort, students|
puts "#{cohort}: #{students} people \n"
end
end
show_vertical(hh_bitmaker_students)
# 3. Add cohort 4, which had 43 students, to the hash.
hh_bitmaker_students[ :cohort4 ] = 43
show_vertical(hh_bitmaker_students)
# 4. Use the keys method to output all of the cohort names.
def show_names(my_hash)
my_hash.each do |keys, values|
puts "#{keys} \n"
end
end
show_names(hh_bitmaker_students)
# 5. The classrooms have been expanded! Increase each cohort size by 5% and display the new results.
puts "---------------------------"
puts hh_bitmaker_students.class
#map on hash gives back an array, not a hash
#attempting to keep the hash a hash avoiding "map"
hh_bitmaker_students_plus5pc = hh_bitmaker_students.transform_values { |students| students * 1.05 }
#no map alternative
hh_bitmaker_students_plus5pc = hh_bitmaker_students.each do |cohorts, students|
hh_bitmaker_students[cohorts] = students * 1.05
end
puts hh_bitmaker_students_plus5pc.class
puts hh_bitmaker_students_plus5pc
puts "---------------------------"
# 6. Delete the 2nd cohort and redisplay the hash.
hh_bitmaker_students_plus5pc.delete(:cohort2)
puts "---------------------------"
puts hh_bitmaker_students_plus5pc
# 7. BONUS: Calculate the total number of students across all cohorts using each and a variable to keep track of the total. Output the result.
hh_bitmaker_students = { :cohort1 => 34, :cohort2 => 42, :cohort3 => 22 }
i_student_count = 0 #to initialise variable as integer type
hh_bitmaker_students.each do |cohort, student|
i_student_count += student
end
puts i_student_count
# 8. BONUS: Create another similar hash called staff and display it using the display method from above.
hh_bitmaker_staff = { :instructors => 20, :admin => 12, :faris => 1 }
show_vertical(hh_bitmaker_staff)
| true |
fec315d6291fe9a4888eb84e85a495eb5800b4e3 | Ruby | Zhann/pr_bot | /app.rb | UTF-8 | 3,112 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'bundler'
require 'json'
Bundler.require
Dotenv.load
require_relative "lib/strategies/list_strategy.rb"
require_relative "lib/strategies/teams_strategy.rb"
require_relative "lib/strategies/tiered_strategy.rb"
set :bind, ENV['BIND'] || 'localhost'
# Let the library traverse all pages, most querries won't fetch large lists anyway
Octokit.auto_paginate = true
# Required ENV vars:
#
# GITHUB_USER: botsname
# GITHUB_PASSWORD: YourPwd
# REVIEWER_POOL (simple strategy): ["user1", "user2", "user3"]
# REVIEWER_POOL (tiered strategy): [{"count": 2, "name": ["andruby","jeff","ron"]},{"count": 1, "names": ["defunkt","pjhyett"]}]
# REVIEWER_POOL (teams strategy): [{"captain": "user1", "members": ["user2", "user3"]},{"captain": "user4", "members": ["user4", "user5"]}]
# PR_LABEL: for-review
#
# Optional ENV vars:
#
# STRATEGY: list OR tiered OR teams (defaults to simple)
class PullRequest
attr_reader :strategy
def initialize(payload, reviewer_pool:, label:, strategy: )
@payload = payload
@label = label
@strategy = Object.const_get("#{(strategy || "list").capitalize}Strategy").new(reviewer_pool: reviewer_pool)
end
def needs_assigning?
# When adding label "for-review" and no reviewers yet
@payload["action"] == "labeled" && @payload.dig("label", "name") == @label && gh_client.pull_request_review_requests(repo_id, pr_number)[:users] == []
end
def set_reviewers!
gh_client.request_pull_request_review(repo_id, pr_number, reviewers)
rescue Octokit::UnprocessableEntity => e
puts "Unable to add set reviewers: #{e.message}"
end
def add_comment!
gh_client.add_comment(repo_id, pr_number, message)
end
def reviewers
@reviewers ||= strategy.pick_reviewers(pr_creator: creator)
end
def creator
@payload.dig("pull_request", "user", "login")
end
private
def message
reviewers_s = reviewers.map { |a| "@#{a}" }.join(" and ")
"Thank you @#{creator} for your contribution! I have determined that #{reviewers_s} shall review your code"
end
def pr_number
@payload.dig("number")
end
def repo_id
@payload.dig("repository", "id")
end
def gh_client
@@gh_client ||= Octokit::Client.new(gh_authentication)
end
def gh_authentication
if ENV['GITHUB_TOKEN']
{access_token: ENV['GITHUB_TOKEN']}
else
{login: ENV['GITHUB_USER'], password: ENV['GITHUB_PASSWORD']}
end
end
end
get '/status' do
"ok"
end
post '/' do
payload = JSON.parse(request.body.read)
# Write to STDOUT for debugging perpose
puts "Incoming payload with action: #{payload["action"].inspect}, label: #{payload.dig("label", "name").inspect}, current reviewers: #{payload.dig("pull_request", "reviewers").inspect}"
pull_request = PullRequest.new(payload, reviewer_pool: JSON.parse(ENV['REVIEWER_POOL']), label: ENV['PR_LABEL'], strategy: ENV['STRATEGY'])
if pull_request.needs_assigning?
puts "Assigning #{pull_request.reviewers.inspect} to PR from #{pull_request.creator}"
pull_request.add_comment!
pull_request.set_reviewers!
else
puts "No need to assign reviewers"
end
end
| true |
7297f817253de2f92562b928260f5751b9c376b2 | Ruby | CSheesley/cross_check | /lib/season_module.rb | UTF-8 | 1,384 | 2.84375 | 3 | [] | no_license | module Season
def teams_in_season(season)
season = hash_games_by_season[season]
teams = []
season.each do |game|
teams << game.away_team_id
teams << game.home_team_id
end
teams.uniq!
end
def create_reg_pre_hash(game_hash,team)
h = Hash.new {|hash,key| hash[key] = 0}
reg_games = all_games_for_team(team) & game_hash["R"]
pre_games = all_games_for_team(team) & game_hash["P"]
total_reg = reg_games.count
total_pre = pre_games.count
won_reg = (game_hash["R"] & won_games(team)).count.to_f
won_pre = (game_hash["P"] & won_games(team)).count.to_f
if total_pre > 0
h[:reg_win_pct] = won_reg / total_reg
h[:pre_win_pct] = won_pre / total_pre
end
h
end
def reg_pre_diff_hash(season)
reg_v_pre = hash_games_by_season[season].group_by do |game|
game.type
end
teams = teams_in_season(season)
hash = {}
teams.each do |team|
hash[team] = create_reg_pre_hash(reg_v_pre,team)
end
hash
end
def game_id_to_season(game_id)
game_team = @games.repo.find do |game|
game.game_id == game_id
end
game_team.season
end
def all_game_teams_for_season(season)
hash = @game_teams.repo.group_by do |game_team|
game_team.game_id[0...4]
end
hash.keep_if do |game_id,game_teams|
game_id[0...4] == season[0...4]
end
end
end
| true |
33824daccdc309838292f7b12545408e38c50dfe | Ruby | tenderlove/remotehash | /lib/remotearray.rb | UTF-8 | 2,411 | 2.765625 | 3 | [
"MIT"
] | permissive | require 'uri'
require 'xmlrpc/client'
require 'digest/sha1'
require 'logger'
class RemoteArray
OPENDHT_URI = "http://openlookup.appspot.com/"
def initialize key = Time.now.to_i, secret = key, uri = OPENDHT_URI
uri = URI.parse(uri)
@rpc = XMLRPC::Client.new3(
:host => uri.host,
:port => uri.port,
:path => uri.path
)
@secret = secret.to_s
@key = key
self.debug_output = nil
self.debug_output = Logger.new($stdout) if $DEBUG
end
###
# Set a debugger to see the server interaction.
def debug_output= logger
@debug_output = logger
@rpc.instance_eval("@http").set_debug_output logger
end
def push value
retries = 0
begin
result = @rpc.call('put_removable',
XMLRPC::Base64.new(Marshal.dump(@key)),
XMLRPC::Base64.new(Marshal.dump(value)),
'SHA',
XMLRPC::Base64.new(Digest::SHA1.digest(@secret)),
3600,
'remotehash'
)
raise "Capacity" if result == 1
rescue Timeout::Error => e
raise(e) if retries == 4
retries += 1
retry
end
end
alias :<< :push
def pop
rm(to_a.last)
end
def length
to_a.length
end
def last
to_a.last
end
def to_a
values = []
placemark = ''
loop do
retries = 0
begin
result = @rpc.call('get_details',
XMLRPC::Base64.new(Marshal.dump(@key)),
10,
XMLRPC::Base64.new(placemark),
'remotehash'
)
values += result.first
placemark = result.last
break if placemark == ''
rescue Timeout::Error => e
raise e if retries == 4
retries += 1
retry
end
end
# Get the newest value with a matching sha1
values.find_all { |entry|
entry.last == Digest::SHA1.digest(@secret)
}.sort_by { |entry| entry[1] }.map { |x| Marshal.load(x.first) }
end
def clear
to_a.each { |v| rm(v) }
end
private
def rm obj
retries = 0
begin
result = @rpc.call('rm',
XMLRPC::Base64.new(Marshal.dump(@key)),
XMLRPC::Base64.new(Digest::SHA1.digest(Marshal.dump(obj))),
'SHA',
XMLRPC::Base64.new(@secret),
3610,
'remotehash'
)
raise if result == 1
rescue Timeout::Error => e
raise(e) if retries == 4
retries += 1
retry
end
obj
end
end
| true |
e4b703eb01cd4e6750bfd4a499067d5950150a27 | Ruby | TCraig7/binary_translator | /test/binary_translator_test.rb | UTF-8 | 1,610 | 3.0625 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/binary_translator'
class BinaryTranslatorTest < Minitest::Test
def test_it_exists
bt = BinaryTranslator.new
assert_instance_of BinaryTranslator, bt
end
def test_it_can_translate
bt = BinaryTranslator.new
assert_equal "000001", bt.translate("a")
assert_equal "011010", bt.translate("z")
assert_equal "010100010101010010001001001110000111", bt.translate("turing")
end
def test_it_can_translate_capital_letters
bt = BinaryTranslator.new
assert_equal "000001", bt.translate("A")
assert_equal "010100010101010010001001001110000111", bt.translate("turing")
assert_equal "010100010101010010001001001110000111", bt.translate("TURING")
end
def test_it_can_translate_spaces
bt = BinaryTranslator.new
assert_equal "000000", bt.translate(" ")
end
def test_it_does_not_translate_symbols
bt = BinaryTranslator.new
expected = "001000000101001100001100001111000000010111001111010010001100000100"
assert_equal "", bt.translate("!")
assert_equal "", bt.translate("!@{$#%^&*()}")
assert_equal expected, bt.translate("Hello World!")
end
def test_it_can_translate_from_binary_to_alpha
bt = BinaryTranslator.new
message_1 = "001000000101001100001100001111000000010111001111010010001100000100"
message_2= "000000000000001000000101001100001100001111000000000000010111001111010010001100000100000000000000"
assert_equal "hello world", bt.translate_to_text(message_1)
assert_equal " hello world ", bt.translate_to_text(message_2)
end
end
| true |
4414fba3b5cc49936609bbebbd4d6358bd841850 | Ruby | jhogan2072/cwscentral | /app/helpers/contacts_helper.rb | UTF-8 | 1,500 | 2.65625 | 3 | [] | no_license | module ContactsHelper
def find_last_date(new_assignment_param)
current_date = DateTime.strptime(new_assignment_param["effective_start_date(1i)"] + "-" +
new_assignment_param["effective_start_date(2i)"] + "-" +
new_assignment_param["effective_start_date(3i)"], "%Y-%m-%d")
return current_date.yesterday.strftime("%Y-%m-%d")
end
def update_parameters(contact_params)
new_assignment_index = -1
original_assignment_index = -1
contact_params[:contact_assignments_attributes].each_with_index do |assignment, index|
if assignment[1]["effective_end_date"] == ""
new_assignment_index = index
else
if assignment[1]["effective_end_date"].to_s.split("-")[0] == "9999"
original_assignment_index = index
end
end
end
cp = contact_params
if new_assignment_index > -1 and original_assignment_index > -1
cp[:contact_assignments_attributes].values[new_assignment_index]["effective_end_date"] = "9999-12-31"
original_end_date = find_last_date(cp[:contact_assignments_attributes].values[new_assignment_index])
cp[:contact_assignments_attributes].values[original_assignment_index]["effective_end_date"] =
original_end_date
else
if new_assignment_index > -1
cp[:contact_assignments_attributes].values[new_assignment_index]["effective_end_date"] = "9999-12-31"
end
end
return cp
end
end
| true |
84863c58c3c3ff9f2fa9699f7b3f8f9293fc7537 | Ruby | toddt67878/udemy-learn-to-code-with-ruby | /STRINGS/overwrite_characters_in_string.rb | UTF-8 | 712 | 4.15625 | 4 | [] | no_license | thing = "rocket ship"
p thing[0]
p thing
thing[0] = "P" # 0 index position gets overwritten and "r" turns into "P"
p thing
thing[1] = "a"
p thing
thing[9] = "o"
p thing
fact = "I love blueberry pie"
fact[7, 4] = "rasp"
p fact
fact[7..10] = "blue"
p fact
fact[2..5] = "absolutely adore"
p fact
#case method deals with capitalization and lowecasing of the letters
puts "hello".capitalize #capitalizes only the first letter of a string
puts "heLLo".capitalize
puts "Hello".capitalize
puts "hello world".capitalize
puts "boris123".upcase
puts "blah blah blah".upcase
lowercase = "I'm patient"
uppercase = lowercase.upcase
p uppercase
puts "BORIS".downcase
puts "boRIS".swapcase #reverses the cases in a string
| true |
f42b132bb2f0cea06e348b699a5d464c5dc87442 | Ruby | mlongerich/url_shortener | /app/models/link.rb | UTF-8 | 1,087 | 3.046875 | 3 | [] | no_license | # frozen_string_literal: true
class Link < ApplicationRecord
require 'uri'
validates_presence_of :url, :short_url
validates_uniqueness_of :url
validates :short_url, uniqueness: { case_sensitive: false }
validates :short_url, format: { with: /\w{6}/ }
validates :short_url, length: { is: 6 }
validate :valid_url
# prepends 0's, turns id into base36 digit, returns 6 digit string
def self.generate_short_url
return '000001' if Link.last.nil?
('00000' + (Link.last.id + 1).to_s(36))[-6, 6]
end
def self.clean_url(url)
URI.escape(no_whitespace(url)) unless url.nil?
end
private
def valid_url
return if url.nil?
errors.add(:url, "is invalid. Did you include 'http://'?") if URI.parse(url).host.nil? && url.present?
end
# replaces all %20 with spaces, removes all leading and trailing spaces
# this allows for 'http://random_blog.com/this%20is%20my%20blog'
# while correcting for 'http://random_site.com %20 %20 %20' to 'http://random_site.com'
def self.no_whitespace(url)
url.html_safe.gsub('%20', ' ').strip
end
end
| true |
b73d1517dd290519a137801b26a989ca65c9b782 | Ruby | oishi123/project | /app/models/student.rb | UTF-8 | 1,562 | 2.71875 | 3 | [] | no_license | class Student < ApplicationRecord
belongs_to :family
has_many :registrations
has_many :camps, through: :registrations
validates :first_name , presence: true
validates :last_name , presence: true
validates :family_id , presence: true , numericality: { only_integer: true, greater_than: 0 }
validates_date :date_of_birth, :before => lambda { Date.today }, allow_blank: true, on: :create
validates :rating, numericality: { only_integer: true, allow_blank: true , less_than_or_equal_to: 3000 , greater_than_or_equal_to: 0}
scope :alphabetical, -> { order('last_name, first_name') }
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
scope :below_rating, ->(ceiling) { where('rating < ?', ceiling) }
scope :at_or_above_rating, ->(floor) { where('rating >= ?', floor) }
#methods
before_save :set_to_zero
def set_to_zero
self.rating ||= 0
end
before_destroy :check
def check
flag = 1
self.camps.map do |camp|
if camp.end_date < Date.today
flag = 0
end
end
if (flag == 0)
errors.add(:student, "unable to destroy camp")
throw(:abort)
end
end
def age
return nil if date_of_birth.blank?
rn = Time.now.to_s(:number).to_i
dob = date_of_birth.to_time.to_s(:number).to_i
(rn- dob)/10e9.to_i
end
def name
"#{self.last_name}, #{self.first_name}"
end
def proper_name
"#{self.first_name} #{self.last_name}"
end
end
| true |
12b7dcc60dce752bae2f1eb3c599cedc54331b8a | Ruby | samip-sharma/Mod1-project | /parsing_API/lyrics_API.rb | UTF-8 | 587 | 2.59375 | 3 | [] | no_license | require "rest-client"
require "pry"
require "json"
def lyricsAPI(artist, song)
artist = artist.split(" ").join("_")
song=song.split(" ").join("_")
url = "https://private-anon-fa9f05909e-lyricsovh.apiary-proxy.com/v1/#{artist}/#{song}"
lyrics_data = RestClient.get(url)
hash = JSON.parse(lyrics_data.body)
hash["lyrics"].to_s.gsub(/\n/, ' ')
end
# "lyricssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss".each_char { |letter| print(letter); sleep(0.2) }
# Like.where('user_id = ? AND post_id = ?', params[:user_id], params[:post_id])
| true |
672ce79dc02a690fe0f0dd42589d6ecb4099e158 | Ruby | tristanharris/spikes | /typed_arrays/Arrays3.rb | UTF-8 | 2,605 | 3.265625 | 3 | [] | no_license | class TypedArrayException < Exception
end
class Array
def to_typed
return if size == 0
type = self.first.class
raise TypedArrayException.new('Cannot make typed array, cant do multi-dimension arrays') if type.kind_of? Array
if self.any? { |obj| obj.class != type}
raise TypedArrayException.new('Cannot make typed array, types of contents dont match')
else
modname = (type.to_s+'Array')
mod = Object.const_get modname
mod.new self
end
end
end
class Object
class << self
alias_method :const_missing_orig, :const_missing
def const_missing(name)
if (m=name.to_s.match(/^(.*)Array$/)) && Object.const_defined?(m[1])
Object.class_eval "class #{name} < TypedArray; end"
c=const_get name
c.send :include, const_get(name.to_s+'Functions') if const_defined?(name.to_s+'Functions')
c
else
begin
const_missing_orig(name)
rescue Exception => e
e.backtrace.shift
raise e
end
end
end
end
end
class TypedArray < Array
def self.new(*params)
s = super
in_type *s
s
end
def self.[](*params)
in_type *params
super
end
(self.public_instance_methods - Object.public_instance_methods).each do |m|
class_eval(%{
def #{m}(*params)
s = super
if s.kind_of? Array
in_type *s
if s.instance_of? Array
s = self.class.new(s)
end
end
s
rescue TypedArrayException => e
e.backtrace.shift
e.backtrace.shift
msg = e.backtrace[1].split(':')
msg[2] = e.backtrace[0].split(':')[2]
e.backtrace[0] = msg.join(':')
raise e
end
})
end
protected
def self.in_type(*params)
raise 'Cant create TypedArray object' if self == TypedArray
type = Object.const_get self.to_s.sub(/Array$/,'')
if params.all? { |obj| obj.kind_of? type}
true
else
raise TypedArrayException.new('Invalid content for '+self.to_s)
end
end
def in_type(*params)
self.class.in_type(*params)
end
end
module FixnumArrayFunctions
def total
inject(0) do |sum,i|
sum+i
end
end
end
a=FixnumArray[1,2,3]
puts a.inspect
puts a.class
b=FixnumArray.new([1,4])
puts b.inspect
puts b.class
FixnumArray.new(5,6).inspect
c = b + [8,6]
puts c.inspect
puts c.class.inspect
puts c.include?(8)
puts c.delete_if{|o| o == 8}.inspect
puts [1,2,3].to_typed.inspect
puts c.total
s = ['a','b'].to_typed
puts s.class
puts s.inspect
#s << 5
# def hhh
# puts Bob
# s = ['a','b'].to_typed
# s << 5
# #3+'bob'
# end
# hhh
puts [1,2,3].to_typed.to_typed.class
| true |
0adaf12919c70fbeb71d55a012dc30412cab36be | Ruby | whtouche/wdi_2_ruby_sql_lab_hogwarts | /Ruby/houses.rb | UTF-8 | 171 | 2.625 | 3 | [] | no_license | class Houses
# attr
def initialize(name:, animal:, points:)
end
end
# Houses have a list of their students, and students hold a reference to the house they belong to
| true |
dfbb8994f0d812c4ee895345de2ae19a90e25f64 | Ruby | codingcat1/to-do-ruby-again | /spec/toado_spec.rb | UTF-8 | 694 | 2.90625 | 3 | [
"MIT"
] | permissive | require 'rspec'
require 'task'
require 'list'
describe List do
it "starts out with an empty list of tasks" do
test_list = List.new "School stuff"
test_list.tasks.should eq []
end
it "can add tasks" do
test_list = List.new "School stuff"
test_task = Task.new "Learn Ruby", 1
test_list.add_task(test_task)
test_list.tasks.should eq [test_task]
end
it "start name the current list" do
test_list = List.new "Grocery List"
test_list.save
List.all.should eq [test_list]
end
end
describe Task do
it "lets you read the task name" do
test_task = Task.new("study for school", 5)
test_task.task_descrip.should eq "study for school"
end
end
| true |
a5e3ee6e0fbba440140b0baaad95578835b33a5f | Ruby | SmartBear/gem-licenses | /lib/gem/licenses.rb | UTF-8 | 1,118 | 2.578125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | permissive | module Gem
def self.licenses
licenses = {}
config_path = File.expand_path('../../licenses/config.yml', __FILE__)
config = YAML.safe_load(File.read(config_path))
Gem.loaded_specs.each_value do |spec|
spec.licenses.map(&:downcase).each do |license|
license_name = config[license] || license
licenses[license_name] ||= []
licenses[license_name] << spec
end
end
licenses
end
def self.licenses_and_copyright
licenses = {}
copyrights = {}
config_path = File.expand_path('../../licenses/config.yml', __FILE__)
config = YAML.safe_load(File.read(config_path))
Gem.loaded_specs.each_value do |spec|
licenses_received, copyrights_received = spec.licenses_and_copyright
licenses_received.each do |license|
license_name = config[license] || license
licenses[spec.name] ||= []
licenses[spec.name] << license_name
end
copyrights_received.each do |copyright|
copyrights[spec.name] ||= []
copyrights[spec.name] << copyright
end
end
return licenses, copyrights
end
end
| true |
6db7d6ab90750a595d1e60de0a7f8e55f7999776 | Ruby | wwslau/Manage_brown_field_VMS_B2M | /crxml.rb | UTF-8 | 2,269 | 2.8125 | 3 | [] | no_license | require 'csv'
def capture_managed_vm
my_managed = 'csa_vm_details.txt'
$managed_vm_array = Array.new
# Load my_managed_vm into an array
puts ("***********************")
managed_vm = CSV.read(my_managed)
managed_vm.shift
managed_vm.shift
managed_vm.each do |line|
vm_name = line[0]
vm_name = vm_name.strip
#puts(vm_name)
$managed_vm_array.push(vm_name)
end
puts ("Managed_vm = " + managed_vm_array.length.to_s)
end
class Vm_details
def initialize(line)
item_count=0
@vc = line[item_count]
item_count+=1
@owner = line[item_count]
item_count+=1
@managed_by_csa = line[item_count]
item_count+=1
@env_name = line[item_count]
item_count+=1
@server_group_name = line[item_count]
item_count+=1
@vm_id = line[item_count]
item_count+=1
@uuid = line[item_count]
item_count+=1
@name = line[item_count]
item_count+=1
@overall_status = line[item_count]
item_count+=1
@ip_address = line[item_count]
item_count+=1
@mac_address = line[item_count]
item_count+=1
@datacenter = line[item_count]
item_count+=1
@cluster_compute_resource = line[item_count]
item_count+=1
@resource_pool = line[item_count]
end
attr_reader :ip_address, :vc, :owner
def to_s
return ('<Server ip_address="'+@ip_address.to_s+'" mac_address="'+@mac_address.to_s + '" uuid="' + @uuid.to_s + '" />')
end
end
my_vm_details = 'new_vm_details.csv'
puts ("User name=")
my_user_name = gets.chomp
puts ("VC=")
my_vc = gets.chomp
puts (my_user_name)
puts (my_vc)
my_env_file = my_user_name.to_s + '_env_file_' + my_vc.to_s + '.csv'
vm_array = []
vm_detail = CSV.read(my_vm_details)
vm_detail.shift
my_file_hander = File.open(my_env_file, 'w')
my_file_hander.puts('<Env name="Wilson-app">')
my_file_hander.puts('<ServerGroup name="Wilson-app-group" providerType="VMWARE_VCENTER">')
vm_num = 1
vm_detail.each do |line|
my_vm = Vm_details.new(line)
if !(my_vm.ip_address.to_s == 'n/a') && my_vm.vc==my_vc && my_vm.owner==my_user_name
my_file_hander.puts(my_vm.to_s)
end
end
my_file_hander.puts('</ServerGroup>')
my_file_hander.puts('</Env>')
my_file_hander.close
puts ("***********************")
| true |
7d18d4aa2f4cd1f807ceb512939bfe6622fa57f2 | Ruby | Melodija/learn_to_program | /ch13-creating-new-classes/extend_built_in_classes.rb | UTF-8 | 485 | 3.96875 | 4 | [] | no_license | class Integer
def factorial
if self <= 1
1
else
self * (self-1).factorial
end
end
def to_roman
romans = {
1000 => "M",
500 => "D",
100 => "C",
50 => "L",
10 => "X",
5 => "V",
1 => "I",
}
numerals = []
num = self
romans.each do |number, letter|
numerals << letter * (num / number)
num = num % number
end
return numerals.join("")
end
end | true |
0180945e42861b48c5bddf5ee00528afe66a9fbe | Ruby | kangdiyu/ics-bootcamp | /ch07/leapYearCounter.rb | UTF-8 | 325 | 3.671875 | 4 | [] | no_license | puts 'Enter starting year: '
year_start = gets.chomp.to_i
puts 'Enter ending year: '
year_end = gets.chomp.to_i
puts 'Leap Year(s): '
year_test = year_start
while year_test <= year_end
if ( (year_test % 4 == 0) && (year_test % 100 != 0) ) || year_test % 400 == 0
puts year_test
end
year_test = year_test + 1
end
| true |
dc91774da02ebe293daae66d5268c77d96d3695e | Ruby | HerrNeu/hw-sinatra-saas-hangperson | /lib/hangperson_game.rb | UTF-8 | 1,007 | 3.296875 | 3 | [] | no_license | class HangpersonGame
attr_accessor :word
attr_accessor :wrong_guesses
attr_accessor :guesses
def initialize(word)
@word = word
@guesses = ''
@wrong_guesses = ''
end
def guess(letter)
raise ArgumentError unless letter =~ /^[a-z]$/i
letter.downcase!
if @word.include? letter
return false if @guesses.include? letter
@guesses += letter
else
return false if @wrong_guesses.include? letter
@wrong_guesses += letter
end
end
def word_with_guesses
@word.chars.map { |a| @guesses.include?(a) ? a : "-"}.join
end
def check_win_or_lose
return :lose if @wrong_guesses.length >= 7
return :win if @word.chars.map {|a| guesses.include? a}.all?
return :play
end
def self.get_random_word
require 'uri'
require 'net/http'
uri = URI('http://watchout4snakes.com/wo4snakes/Random/RandomWord')
Net::HTTP.new('watchout4snakes.com').start { |http|
return http.post(uri, "").body
}
end
end
| true |
3b9d768f521673c685f8e2bddb13f103fd0d2e05 | Ruby | samanthasanford/cartoon-collections-onl01-seng-ft-032320 | /cartoon_collections.rb | UTF-8 | 624 | 3.34375 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves(dwarf_names)# code an argument here
# Your code here
dwarf_names.each_with_index{|dwarf, index| p "#{index+1}. #{dwarf}"}
end
def summon_captain_planet(planeteer_calls)# code an argument here
# Your code here
planeteer_calls.map{|string| string.capitalize + '!'}
end
def long_planeteer_calls(short_words)# code an argument here
# Your code here
short_words.any?{|string| string.size > 4}
end
def find_the_cheese(array)# code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
array.find {|cheese| cheese_types.include?(cheese)}
end
| true |
25c5e0f65db9a01e346cfb0fe1b6b41bd4d97df0 | Ruby | shibatasuguru0311/fleamarket_sample_79bb | /spec/models/item_spec.rb | UTF-8 | 2,924 | 2.71875 | 3 | [] | no_license | require 'rails_helper'
#空だと登録できないこと
describe Item do
it "is invalid without a name" do
item = Item.new(name: nil)
item.valid?
expect(item.errors[:name]).to include("can't be blank")
end
it "is invalid without a price" do
item = Item.new(price: nil)
item.valid?
expect(item.errors[:price]).to include("can't be blank")
end
it "is invalid without an introduction" do
item = Item.new(introduction: nil)
item.valid?
expect(item.errors[:introduction]).to include("can't be blank")
end
it "is invalid without an condition" do
item = Item.new(condition: nil)
item.valid?
expect(item.errors[:condition]).to include("can't be blank")
end
it "is invalid without an postage_user" do
item = Item.new(introduction: nil)
item.valid?
expect(item.errors[:postage_user]).to include("can't be blank")
end
it "is invalid without an prefecture_id" do
item = Item.new(prefecture_id: nil)
item.valid?
expect(item.errors[:prefecture_id]).to include("can't be blank")
end
it "is invalid without an preparation" do
item = Item.new(preparation: nil)
item.valid?
expect(item.errors[:preparation]).to include("can't be blank")
end
it "is invalid without an category" do
item = Item.new(category: nil)
item.valid?
expect(item.errors[:category]).to include("must exist")
end
#名前が41文字以上だと登録されない
it "is invalid with a name that has more than 40 characters " do
item = Item.new(name: "a"*41)
item.valid?
expect(item.errors[:name]).to include("is too long (maximum is 40 characters)")
end
#説明文が1001文字以上だと登録されない
it "is invalid with a introduction that has more than 1000 characters " do
item = Item.new(introduction: "a"*1001)
item.valid?
expect(item.errors[:introduction]).to include("is too long (maximum is 1000 characters)")
end
#金額が10000000円以上だと登録されない
it "is invalid with a price that has more than 9999999 integer " do
item = Item.new(price: 100000000)
item.valid?
expect(item.errors[:price]).to include("must be less than or equal to 9999999")
end
#金額が299円以下だと登録されない
it "is invalid with a price that has less than 300 integer " do
item = Item.new(price: 299)
item.valid?
expect(item.errors[:price]).to include("must be greater than or equal to 300")
end
end
#必須項目全て入力されていれば登録ができること
describe Item do
describe '#create' do
it "is valid with a name, introduction, price, condition,postage_user,prefecture_id,preparation" do
item = Item.new(brand:nil)
expect(item).to be_invalid
end
end
end | true |
192d705b771d661fc1f47aa6aad0b8f162bad3e2 | Ruby | lightmotive/ls-book-ruby-intro | /loops_and_iterators/perform_again.rb | UTF-8 | 155 | 3.125 | 3 | [] | no_license | # frozen_string_literal: true
loop do
puts 'Do you want to do that again?'
answer = gets.chomp
break unless %w[y yes].include?(answer.downcase)
end
| true |
cf45a72f2f269ec053605c94f39d8ce9f51287aa | Ruby | piotrmurach/tty-runner | /lib/tty/runner/inflection.rb | UTF-8 | 349 | 2.59375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | # frozen_string_literal: true
module TTY
class Runner
module Inflection
# Convert snakecase string into camelcase
#
# @param [String] string
#
# @api public
def camelcase(string)
string.split("_").each(&:capitalize!).join
end
module_function :camelcase
end
end # Runner
end # TTY
| true |
28fd053f40bceac601a7a8160de43f4fd54edb45 | Ruby | dieu-detruit/lecture-algorithm | /Week4/power.rb | UTF-8 | 355 | 3.203125 | 3 | [] | no_license | # yは整数とし、0^0は未定義とする
def power(x, y)
begin
raise RangeError if y.floor != y
if y==0 then
raise RangeError if x==0
return 1
elsif y>0 then
prod = 1.0
y.times do
prod *= x
end
return prod
else
prod = 1.0
(-y).times do
prod /= x
end
end
rescue RangeError => error
p error
end
end
| true |
d50b94ee0c15d95881b6485819e3cdc3f845d877 | Ruby | sophomorica/dpl_week1 | /Homework/contact_list.rb | UTF-8 | 2,293 | 3.5625 | 4 | [] | no_license | require "pry"
@contacts = ["jack", "jill", "bob", "shirly", "fran"]
def modify_contact
puts "\n-------------------\nWhich Peep needs Changed?\n-------------------\n"
@contacts.each_with_index do |f,i|
puts "#{i +1 }) #{f}"
end
input = gets.strip.to_i
puts "\n --------------------\n enter a new name \n \n ---------------------"
new_name = gets.strip
@contacts[input -1] = new_name
puts "you have changed to '#{new_name}'"
viewing_contacts
end
def main_menu
puts "\n-------------------\nYo Choices\n-------------------\n"
puts "1) Create Contact"
puts "2) View Contacts"
puts "3) Modify"
puts "4) Delete Contact"
puts "5) Exit"
input = gets.strip.to_i
case input
when 1
puts "You want to create a new guy"
create_contact
when 2
viewing_contacts
when 3
modify_contact
when 4
delete_option
when 5
exit_application
else
puts "enter a valid number you dunce"
main_menu
end
end
def delete_option
puts "\n-------------------\nWhich Peep To Delete?\n-------------------\n"
#------------viewing the array-----------------
@contacts.each_with_index do |f,i|
puts "#{i +1 }) #{f}"
end
input = gets.strip.to_i
puts "\n You have Deleted #{@contacts[input - 1]} \n "
@contacts.delete_at(input - 1)
main_menu
end
def viewing_contacts
puts "\n-------------------\nHere yo Peeps\n-------------------\n"
@contacts.each_with_index do |f,i|
puts "#{i +1 }) #{f}"
end
puts "\n--------------------------------------\n"
puts "#{@contacts.length + 1}) to modify"
puts "#{@contacts.length + 2}) to delete peeps"
puts "#{@contacts.length + 3}) to main menu"
input = gets.strip.to_i
case input
when input = @contacts.length + 1
modify_contact
when input = @contacts.length + 2
delete_option
when input = @contacts.length + 3
main_menu
else
puts "invalid option ya dingus"
puts "\n"
main_menu
end
end
def create_contact
puts "\n-------------------\nYo Peeps Name\n-------------------\n"
name_input = gets.strip
# puts "Enter the Last Name"
# last_input = gets.strip
@contacts << name_input
main_menu
end
main_menu
| true |
f9a4b36c0cd69ce51b20cfacc31ecae3a62df6db | Ruby | krismacfarlane/godot | /w02/d06/instructor/enumerables.rb | UTF-8 | 360 | 2.96875 | 3 | [] | no_license | require 'pry'
arr = [
"patricio",
"dflip"
]
upcased_names = arr.map do |y|
y.upcase
end
short_names = arr.select do |x|
x.length < 6
end
binding.pry
class Celebrity < Human
def initialize
@solved = false
end
def setup
solved
end
def take_out_trash
super
@tired = true
end
def self.parse
end
end
| true |
2c160e00267361f54327f25ebaeeab457ff826e1 | Ruby | maoueh/buildozer | /lib/buildozer/cli/core/base.rb | UTF-8 | 3,398 | 3.03125 | 3 | [
"MIT"
] | permissive | require 'optparse'
require 'buildozer/helper/string'
module Buildozer
module Cli
module Core
class Base
@@MAX_WIDTH = 70
def initialize(arguments = ARGV, options = {})
@arguments = arguments
end
##
# Specify the name of the command. Used as the default
# name when usage is not defined. So with this, it is
# possible to just specify a command name and then
# let base class handles the rest.
def name()
self.class.name.split("::").last().downcase()
end
##
# Specify the description of this command.
# Overriding classes just need to return a
# string that will be output to terminal
# as-is. No formatting occurs.
def usage()
"Usage: #{name()} (options)"
end
##
# Specify the description of this command.
# Overriding classes just need to return a
# string that will be formatted correctly
# for the terminal.
#
# Return nil if you dont want a description,
# this is the default.
def description()
nil
end
##
# Specify the tail of this command.
# Overriding classes just need to return a
# string that will be formatted correctly
# for the terminal.
def tail()
"Available options:"
end
##
# Specify additional arguments parse options
# Use OptoinParser syntax
def options(parser)
parser.on_tail("-h", "--help", "Show help") do
help()
end
end
##
# This is the method that will be invoked to
# execute the cli command task.
def execute()
end
##
# Show command help for this instance and exit
# with code 0.
def help()
puts @parser
exit(0)
end
##
# Print an error message followed by the parser
# help.
def error(message)
puts "ERROR: #{message}"
puts ""
help()
end
def run()
@parser = parser()
@arguments = parser.parse(@arguments)
execute()
end
def parser()
return @parser if @parser
parser = OptionParser.new()
set_usage(parser)
set_description(parser)
options(parser)
set_tail(parser)
parser
end
def set_usage(parser)
parser.banner = usage()
end
def set_description(parser)
set_text(description(), parser,
:prepend_newline => true,
:max_width => @@MAX_WIDTH
)
end
def set_tail(parser)
set_text(tail(), parser,
:prepend_newline => true,
:max_width => @@MAX_WIDTH
)
end
def set_text(text, parser, options = {})
return if not text
parser.separator("") if options[:prepend_newline]
lines = text
lines = Helper::format_text(text, :max_width => options[:max_width]) if not lines.kind_of?(Array)
lines.each do |line|
parser.separator(line)
end
parser.separator("") if options[:append_newline]
end
end
end
end
end
| true |
74cf039a04a3beb44a293c871338be547a5f583f | Ruby | rcorre/dotfiles-old | /other/commit-msg | UTF-8 | 1,370 | 2.859375 | 3 | [] | no_license | #!/usr/bin/ruby
# This commit message hook will prefix commit messages with a tag indicating
# their configuration area.
# For example, commits that modify vim-related files will prefix the commit with
# the tag [vim].
# This script will also reject a commit if changes are made to separate areas.
# Use `git commit --no-verify` if such a commit is intentional.
$tags = %w{
nvim awesome bash git mail pianobar qutebrowser vim task zathura aseprite setup windows ssh
}
def get_commit_tag filename
$tags.find{|tag| filename.match tag}
end
to_commit = `git diff --cached --name-only`.split "\n"
commit_tags = to_commit.map {|filename| get_commit_tag filename}
unless commit_tags.all? {|s| s == nil || s == commit_tags.first}
puts "Not all commit tags match!"
to_commit.zip(commit_tags).each {|s| puts "#{s.first} --> #{s.last}"}
puts "Are you sure you want to commit files for different categories?"
puts "Use git commit --no-verify to override"
exit 1
end
commit_tag = commit_tags.first
unless commit_tag.nil? || commit_tag.empty? #append message based on class
message_file = ARGV[0]
commit_msg = File.read(message_file)
commit_msg.sub! /^\[.*\]/, '' #remove previous tag (for amend)
File.open message_file, "w" do |file|
file.puts "[#{commit_tag}] #{commit_msg}"
end
end
exit 0
| true |
2ef858cb10e6d6976abf545dc9fca70e354f10fd | Ruby | blolol/rpg | /app/models/battle.rb | UTF-8 | 1,600 | 2.75 | 3 | [
"MIT"
] | permissive | class Battle
include ActiveModel::Validations
# Attributes
attr_reader :challenger, :challenger_roll, :loser, :opponent, :opponent_roll,
:pre_battle_challenger, :pre_battle_opponent, :winner
# Delegates
delegate :balance, :fairness, to: :fairness_calculator
# Validations
validates :challenger, active: true, presence: true
validates :opponent, active: true, presence: true
def initialize(challenger: nil, opponent: nil)
@challenger = challenger || find_challenger
@opponent = opponent || find_opponent
cache_pre_battle_character_state
end
def challenger_won?
challenger == winner
end
def fight!
if valid? && !fought?
@challenger_roll = BattleRoll.new(challenger)
@opponent_roll = BattleRoll.new(opponent)
@loser, @winner = *[@challenger_roll, @opponent_roll].sort.map(&:character)
apply_rewards!
end
end
def fought?
!!challenger_roll && !!opponent_roll
end
def rewards
@rewards ||= BattleRewards.new(self).rewards
end
def tie?
challenger_roll == opponent_roll
end
private
def apply_rewards!
rewards.each &:apply!
end
def cache_pre_battle_character_state
@pre_battle_challenger = CachedCharacter.new(challenger)
@pre_battle_opponent = CachedCharacter.new(opponent)
end
def fairness_calculator
@fairness_calculator ||= BattleFairnessCalculator.new(challenger, opponent)
end
def find_challenger
Character.active.order('RANDOM()').first
end
def find_opponent
Character.active.where.not(id: challenger.id).order('RANDOM()').first
end
end
| true |
e4f772478d22996380d37c16d98c965cdb5261cc | Ruby | chestercun/projeuler | /12.rb | UTF-8 | 385 | 3.5 | 4 | [] | no_license |
def divisors(n)
ct = 2
mid = n/2
for i in 2..mid
if n%i==0
ct+=1
end
end
return ct
end
triangle = {}
triangle[:last] = 1
triangle[:num] = 1
desired = ARGV[0].to_i
while (divisors(triangle[:num]) < desired)
for i in 0..25
triangle[:last] += 1
triangle[:num] += triangle[:last]
end
end
puts triangle[:num]
| true |
7ecc6dff89aab3a0858df41ef1cb02930bd88fc1 | Ruby | mecampbellsoup/codewars | /snail.rb | UTF-8 | 2,680 | 3.65625 | 4 | [] | no_license | require 'pry'
require 'minitest/autorun'
class Element
attr_reader :val
attr_accessor :visited
def initialize(val)
@val = val
@visited = false
end
end
class Map
attr_reader :data, :size, :result
def initialize(array)
@result = []
@size = array.size
@data = []
array.each do |arr|
arr.each do |val|
@data << Element.new(val)
end
end
end
def snail
position = 0
until result.size >= data.size do
position = go_right(position)
position = go_down(position)
position = go_left(position)
position = go_up(position)
end
result.uniq
end
private
def go_right(position)
data[position, size].each do |elem|
result << elem.val unless elem.visited
elem.visited = true if data[position]
end
data[result.last - 1].val - 1
end
def go_left(position)
data[position - size, size].reverse.each do |elem|
result << elem.val unless elem.visited
elem.visited = true if data[position]
end
data[result.last - 1].val - 1
end
def go_down(position)
while position < data.size - 1
position += size
unless data[position].nil?
result << data[position].val unless data[position].visited
data[position].visited = true if data[position]
end
end
data[result.last - 1].val - 1
end
def go_up(position)
position -= size
while position > 0
result << data[position].val unless data[position].visited
data[position].visited = true if data[position]
position -= size
end
data[result.last - 1].val - 1
end
end
describe Map do
small = [[1,2], [3,4]]
big = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
bigger = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]
map = Map.new(small)
describe "#initialize" do
it "casts each data value into an Element" do
map.data.must_be_instance_of Array
map.data.first.must_be_instance_of Element
map.data.last.must_be_instance_of Element
end
it "assigns positions correctly to each Element" do
map.data[0].val.must_equal 1
map.data[1].val.must_equal 2
map.data[2].val.must_equal 3
end
it "initializes each Element with false visited value" do
map.data.first.visited.must_equal false
end
end
describe "#snail" do
it "returns a snail-snorted flattened array" do
map.snail.must_equal [1,2,4,3]
Map.new(big).snail.must_equal [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
Map.new(bigger).snail.must_equal [1,2,3,4,5,10,15,20,25,24,23,22,21,16,11,6,7,8,9,14,19,18,17,12,13]
end
end
end
| true |
c6cb0242e536d361832bdee847ac23afdd11032d | Ruby | ALPHACamp/testing-demo-air-conditioner | /air_conditioner.rb | UTF-8 | 2,458 | 3.03125 | 3 | [] | no_license | # 冷氣
class AirConditioner
attr_accessor :ispower, :isopen, :timer
def initialize
@isopen = false
@ispower = false
@timer = 0
end
def open!
@isopen = true
end
# 出風口
def outlet_status
if @isopen
'wind~~~'
else
'nothing'
end
end
# 檢查定時,改變冷氣狀態
def check_timer
@isopen = false if (@timer_start_time + @timer.hours) < Time.now
end
# 指令接收器
def receiver order
case order
when 'check_is_opened'
return @isopen
when 'open'
if @ispower
self.open!
else
raise 'Try again after connecting with power'
end
true
when 'set_timer'
@timer_start_time = Time.now
if @timer < 12
@timer += 1
else
@timer = 0
end
return @timer
else
return 'unknown order'
end
end
end
# 冷氣遙控器
class AirConditionerController
def initialize ac
@ac = ac
@dashboard = {
status: 'off',
timer: '0 hour'
}
end
def print_dashboard
@dashboard
end
def open
# 紅外線發射器 = 紅外線模組載入
require './ir'
ir = IR.new
isopen = check_if_ac_open?(ir)
# if 開啟狀態 == 沒開
if isopen == false
# 設定開機為要執行的指令
@order = 'open'
# 選擇透過紅外線發送
@launcher = ir
# 結果 = 發送開機指令
result = self.class.send(@ac, @order)
# if 結果 == 成功
if result
# 於冷氣遙控器儀表板上顯示 on
@dashboard[:status] = 'on'
else
# 於設定冷氣遙控器儀表板上顯示 off
@dashboard[:status] = 'off'
end
end
end
def set_timer
@order = 'set_timer'
result = self.class.send(@ac, @order)
@dashboard[:timer] = "#{result} hour"
result
end
def self.send ac, order
ac.receiver(order)
end
def check_if_ac_open? ir
# 設定指令 -> 確認冷氣是否開啟
@order = 'check_is_opened'
# 設定發射器 -> 紅外線發射器
@launcher = ir
# 開啟狀態 = 發送問題給冷氣
self.class.send(@ac, @order)
end
end
class Fixnum
SECONDS_IN_MINUTES = 60
SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTES
SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR
def days
self * SECONDS_IN_DAY
end
def hours
self * SECONDS_IN_HOUR
end
def minutes
self * SECONDS_IN_MINUTES
end
end
| true |
9142f2e9ee9082dfb681d85d9e52c023047cc38e | Ruby | SwankForeigner5/331-Project- | /problem5.rb | UTF-8 | 1,016 | 4.03125 | 4 | [] | no_license | # Statistics about a Matrix #
require 'matrix'
def matrix_stats(matrix)
# Row and column sizes
row_size = matrix.row_size.to_f
col_size = matrix.column_size.to_f
sum = 0.to_f
print "Row Averages: "
# Iterates over matrix rows
0.upto(row_size - 1) do |i|
# Iterates over each element in row
matrix.row(i).each do |element|
# Elements are added to sum
sum += element.to_f
end
print (sum/col_size).to_s + " "
# Resets sum to 0 after every row
sum = 0
end
print "\n"
# Iterates over matrix columns
print "Column Averages: "
# Iterates over each element in column
0.upto(col_size - 1) do |i|
matrix.column(i).each do |element|
# Elements are added to sum
sum += element.to_f
end
print (sum/row_size).to_s + " "
# Resets sum to 0 after every column
sum = 0
end
print "\n"
end
# Default matrix
matrix = Matrix[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
matrix_stats(matrix)
| true |
f5fce0d9a4aecf449f3980e98de320ac91c2073b | Ruby | tyedye105/rfish | /lib/game.rb | UTF-8 | 517 | 3.390625 | 3 | [] | no_license | class Game
define_method(:initialize) do
@deck = []
end
define_method(:deck) do
@deck
end
define_method(:create_deck) do
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks.each() do |rank|
suits.each() do |suit|
card = ''
card += rank + ' of ' + suit
@deck.push(card)
end
end
@deck
end
define_method(:shuffle) do
@deck.shuffle()
end
end
| true |
e318027d3fd18df02be6dbcc806845a0c745da99 | Ruby | jjdinho/fuel-economy-calculator | /app/controllers/cars_controller.rb | UTF-8 | 1,727 | 2.8125 | 3 | [] | no_license | require 'pg'
class CarsController < ApplicationController
def year
# Not necessary for single page app with full database...
# cars = Car.select('year')
# @years = cars.map do |car|
# car.year
# end
# @years = @years.uniq.sort
# render json: @years, callback: 'yearsQuery'
end
def make
year = params[:year].to_i
cars = Car.select('make').where(year: year)
@makes = cars.map do |car|
car.make
end
@makes = @makes.uniq.sort
render json: @makes
end
def model
year = params[:year].to_i
make = params[:make]
cars = Car.where("year = ? AND make LIKE ?", year, make)
@models = cars.map do |car|
car.model
end
@models = @models.uniq.sort
render json: @models
end
def get_info
if params[:year].nil? || params[:make].nil? || params[:model].nil?
@result = { error: 'Incorrect parameters. Please complete the form above.' }
else
year = params[:year].to_i
make = params[:make]
model = params[:model]
miles = params[:miles].to_i
@car = Car.find_by('year = ? AND make LIKE ? AND model LIKE ?', year, make, model)
if @car.nil?
@result = { error: 'Incorrect parameters. Please complete the form above.' }
else
@miles_info = calculate_mileage_info(@car, miles)
@result = { car: @car, fuel: @miles_info }
end
end
render json: @result
end
def home
# 'year' method is not necessary for single page app with full database...
# year
end
private
def calculate_mileage_info(car, miles)
world_trips = miles / 24901
gallons_consumed = miles / car.mileage
{trips: world_trips, gallons: gallons_consumed}
end
end
| true |
344fd2921ecc5d58540b54e3dd11f813834e24a1 | Ruby | bizchina/tocmd.gem | /lib/tocmd/markdown_render.rb | UTF-8 | 1,401 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'redcarpet'
require 'pygments'
require 'redcarpet'
require 'rexml/document'
module Redcarpet::Render
class Custom < Base
def header(title, level)
@headers ||= []
title_elements = REXML::Document.new(title)
flattened_title = title_elements.inject('') do |flattened, element|
flattened += if element.respond_to?(:text)
element.text
else
element.to_s
end
end
permalink = flattened_title.downcase.gsub(/[^a-z\s]/, '').gsub(/\W+/, "-")
# for extra credit: implement this as its own method
if @headers.include?(permalink)
permalink += "_1"
# my brain hurts
loop do
break if !@headers.include?(permalink)
# generate titles like foo-bar_1, foo-bar_2
permalink.gsub!(/\_(\d+)$/, "_#{$1.to_i + 1}")
end
end
@headers << permalink
%(\n<h#{level}><a name="#{permalink}" class="anchor" href="##{permalink}"><span class="anchor-icon"></span></a>#{title}</h#{level}>\n)
end
end
end
class HTMLwithPygments < Redcarpet::Render::HTML
def doc_header()
'<style>' + Pygments.css('.highlight',:style => 'friendly') + '</style>'
end
def block_code(code, language)
Pygments.highlight(code, :lexer => language, :options => {:encoding => 'utf-8'})
end
end
| true |
7f11dd652a5040ce9ff0aebfe49c37bf1973f676 | Ruby | irmscher7353/yoyaku2011 | /app/models/cart.rb | UTF-8 | 462 | 3.3125 | 3 | [
"MIT"
] | permissive | # vim:ts=2:sw=2
class Cart
attr_reader :name, :phone, :address, :items
def initialize
@name = ""
@phone = ""
@address = ""
@items = []
end
def add_product(product, quantity)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity(quantity)
else
@items << CartItem.new(product, quantity)
end
end
def total_price
@items.sum {|item| item.price}
end
end
| true |
64f6b0e9ccf7a8d815874f11a32b77b7d135bedf | Ruby | vjoel/easy-serve | /examples/remote-run-script.rb | UTF-8 | 433 | 2.84375 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | class RemoteRunScript
attr_reader :conns, :host, :log, :args
def initialize conns, host, log, *args
@conns = conns
@host = host
@log = log
@args = args
end
def run
conn = conns[0]
log.progname = "run remote on #{host} with args #{args}"
log.info "trying to read from #{conn.inspect}"
log.info "received: #{conn.read}"
conn.write "hello from #{log.progname}"
conn.close
end
end
| true |
5d4ce4c366e3d531c43cc60dd915e54f80df5bc2 | Ruby | SukritiSingal/login-count | /test/models/users_test.rb | UTF-8 | 4,249 | 2.859375 | 3 | [] | no_license | require 'test_helper'
class UsersTest < ActiveSupport::TestCase
$SUCCESS = 1
$ERR_BAD_CREDENTIALS = -1
$ERR_USER_EXISTS = -2
$ERR_BAD_USERNAME = -3
$ERR_BAD_PASSWORD = -4
test "1 Sign up blank username" do
code = User.add(username:"", password:"")
assert (code[0] == $ERR_BAD_USERNAME), "Expected sign up failure with blank username,
but sign up was successful with code: #{code}"
end
test "2 Sign up with a redundant user" do
code = User.add(username:"testredundancy",password:"")
assert code[0] == $SUCCESS, "Expected to succesfully add new username to database, but failed and got code #{code}"
code_redundant = User.add(username:"testredundancy",password:"")
assert code_redundant[0] == $ERR_USER_EXISTS, "Expected signing up with user with a username already in database
to fail ('user1') , but was able to save successfully"
end
test "3 Password too long" do
longPassword = "It was about the deepest sort of beauty,
the product of the human mind being stamped onto a piece of silicon that you might one day cart
around in your briefcase. A poem in a rock. A theorem in a slice of stone.
The programmers were the artisans of the future"
code = User.add(username: "testUsernameLen", password: longPassword)
assert code[0] == $ERR_BAD_PASSWORD, "Expected signup failure due to password legnth constraint (Password length >> 128),
but was able to sign up successfully"
end
test "4 Username exactly 128 characters" do
exactUsername = "The machines would revolutionize the world.
It was not machines that were evil,
but minds of the top brass behind them"
code = User.add(username: exactUsername, password: "")
assert code[0] == $SUCCESS, "Expected successful sign up with username exactly 128 characters, the allowed
maximum, but got the error code #{exactUsername.length}"
end
test "5 Login with username not in database" do
bad_username = "badUsername"
bad_pass = "badPass"
User.TESTAPI_resetFixture
code = User.login(username: bad_username, password: bad_pass)
assert code[0] == $ERR_BAD_CREDENTIALS, "Expected unsucessful login with bad username, but
sign in successful, and got code #{code}"
end
test "6 Login with incorrect pass" do
User.TESTAPI_resetFixture
code = User.login(username: "user1", password: "pass3")
assert code[0] == $ERR_BAD_CREDENTIALS, "Expected code -1, bad credentials -
login fail with wrong password, but got code #{code}"
end
test "7 Login with correct username and pass" do
User.TESTAPI_resetFixture
User.add(username:"user1", password: "pass1")
code = User.login(username:"user1", password: "pass1")
assert code[0] == $SUCCESS, "Expected success code 1; logged in with correct
password and username, but got code: #{code}"
end
test "8 Adding user should set count to 1" do
User.TESTAPI_resetFixture
code =User.add(username:"testCount", password: "pass1")
assert code[0] == $SUCCESS, "Expected success code 1; logged in with correct
password and username, but got code: #{code}"
assert code[1] == 1, "Expected count to = 1 when user is added successfully but
got count = #{code[1]}"
end
test "9 Add new user and login" do
User.TESTAPI_resetFixture
add_code = User.add(username:"testAddandLogin", password: "")
assert add_code[0] == $SUCCESS, "Adding user failed, got code #{add_code[0]}"
login_code = User.login(username:"testAddandLogin", password: "")
assert login_code[0] == $SUCCESS, "Expected succesful login after succssful sign up, but got code #{login_code}"
end
test "10 Case sensitive sign up" do
User.TESTAPI_resetFixture
add_code = User.add(username:"jessica", password: "")
assert add_code[0] == $SUCCESS, "Adding user 'jessica' failed with code #{add_code}"
add_sensitive = User.add(username:"Jessica", password: "")
assert add_sensitive[0] == $SUCCESS, "Expecting successful sign up with username
same as one in database, but with a capital letter in the beginning. Usernames should be
case sensitive, but got the error code: #{add_sensitive}"
end
end | true |
55ffd2706b04d538380d76217d5da6fb870be203 | Ruby | developwithpassion/fakes | /lib/fakes/class_swaps.rb | UTF-8 | 602 | 3.140625 | 3 | [
"MIT"
] | permissive | require 'singleton'
module Fakes
class ClassSwaps
include Singleton
attr_reader :swaps
def initialize
@swaps = {}
end
def add_fake_for(klass, the_fake)
symbol = klass.name.to_sym
ensure_swap_does_not_already_exist_for(symbol)
swap = ClassSwap.new(klass, the_fake)
@swaps[symbol] = swap
swap.initiate
end
def ensure_swap_does_not_already_exist_for(symbol)
raise "A swap already exists for the class #{symbol}" if @swaps.key?(symbol)
end
def reset
@swaps.values.each(&:reset)
@swaps.clear
end
end
end
| true |
bd4c196f7205bec11eb6ede07615826aa6000189 | Ruby | rhday/deli-counter-onl01-seng-pt-030220 | /deli_counter.rb | UTF-8 | 1,369 | 3.671875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here.
def line(customers)
if customers.length >= 1
new_array = []
index = 1
customers.each do |name|
new_array << "#{index}. #{name}"
index += 1
end
puts "The line is currently: #{new_array.join(" ")}"
else
puts "The line is currently empty."
end
end
def take_a_number(katz_deli, new_customer)
katz_deli << new_customer
puts "Welcome, #{new_customer}. You are number #{katz_deli.length} in line."
end
def now_serving(katz_deli)
if katz_deli.length == 0
puts "There is nobody waiting to be served!"
else
puts "Currently serving #{katz_deli[0]}."
katz_deli.shift
end
end
#below are previous attempts which failed
=begin
def line(customers)
current_line = "The line is currently:"
customers.each.with_index(1) do |name, number|
current_line << " #{number}. #{name}"
end
puts current_line
end
=end
=begin def line(katz_deli)
deli_line = []
if katz_deli.length > i do
katz_deli.each.with_index(1) do |name, position|
position = "The line is currently: #{position}. #{name}."
end
else puts "The line is currently empty."
end
end
=end
=begin def assign_rooms(attendees)
rooms =[]
attendees.each.with_index(1) do |name, room_number|
rooms << room_number = "Hello, #{name}! You'll be assigned to room #{room_number}!"
end
rooms
end
=end | true |
858643d29a9b117983e060a22e6b6d69ec99e63e | Ruby | Ermelo1983/pizzeria | /storage.rb | UTF-8 | 497 | 2.953125 | 3 | [] | no_license | require './ingredient'
class Storage
def initialize
@items = [
ingredient.new(ingredient::TOMATO, 8),
ingredient.new(ingredient::DOUGH, 2),
ingredient.new(ingredient::TOMATO, 8),
ingredient.new(ingredient::TOMATO, 8)
]
end
def fetch(ingredients)
ingredients.each do |ingredient|
item = @items.detect{|item| item.name == ingredient.name}
if item
item.use ingredient.amount
else
return false
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.