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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
baed6dd27a917749706687c2cc6bfe4d785e4ea8 | Ruby | benmicol/trading-web | /trading-web/spec/lib/common_spec.rb | UTF-8 | 2,010 | 3.40625 | 3 | [
"Apache-2.0"
] | permissive | require File.dirname(__FILE__) + '/../spec_helper'
class Holder
attr_accessor :nested
def initialize nested=nil
@nested = nested
end
end
describe "Common Util extenssion for string, dates, money and similar" do
it "should format Money into html representation with $ sign in front" do
money = Money.new 234
money.to_html.should == "<span class=\"\">2.34</span>"
money = Money.new(-234)
money.to_html.should == "<span class=\"red\">-2.34</span>"
end
it "should initialize Money from a string" do
Money.new('2.34').should == Money.new(234)
end
it "should initialize Money from a string when white spaces" do
Money.new('2 500 000').should == Money.new(250000000)
end
it "should initialize Money from a string when comma separators" do
Money.new('2,500,000').should == Money.new(250000000)
end
it "should format Date into html representation like month, date, year" do
date = Date.new 2005, 12, 31
date.to_html.should == "12/31/2005"
end
it "Ojbect respond_to? method should accept nested properties" do
holder3 = Holder.new
holder2 = Holder.new holder3
holder1 = Holder.new holder2
holder1.nested_respond_to?('nested.nested').should be_true
end
it "Ojbect respond_to? method should return false when no such method" do
holder1 = Holder.new Object.new
holder1.nested_respond_to?('nested.nested').should be_false
end
it "Ojbect respond_to? method should accept symbol" do
holder3 = Holder.new
holder2 = Holder.new holder3
holder1 = Holder.new holder2
holder1.nested_respond_to?(:nested).should be_true
end
it "Ojbect respond_to? method should return false when some of the nested properties is not a method" do
holder2 = Holder.new
holder1 = Holder.new holder2
holder3 = Holder.new
holder1.nested_send('nested.nested=', holder3).should == holder3
end
end | true |
75748a5c8520b63c8e9a716fb4faf5b5d51c03c2 | Ruby | hofmannedv/training-ruby | /calculations/min-max.rb | UTF-8 | 651 | 4.03125 | 4 | [] | no_license | # -----------------------------------------------------------
# calculate the minimum, and the maximum value for a list of integers
#o
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email frank.hofmann@efho.de
# -----------------------------------------------------------
# define a list of values
valueList = [1, 6, 3, 4, 5]
# list length
items = valueList.length
# check for empty lists, first
if items
minimumValue = valueList.min
maximumValue = valueList.max
# output minimum and maximum value
puts "The minimum value is: #{minimumValue}"
puts "The maximum value is: #{maximumValue}"
else
puts "The list is empty."
end
| true |
0530967f6a1bfc0e96b0a17395eb5949d41d2ab6 | Ruby | jshorns/bank-tech-test | /lib/account.rb | UTF-8 | 1,687 | 3.21875 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'transaction'
require_relative 'transaction_history'
require_relative 'statement'
require 'date'
# Account class, for recording balance and making deposits and withdrawals.
class Account
OPENING_BALANCE = 0
def initialize(transaction_history = TransactionHistory.new)
@transaction_history = transaction_history
end
def balance
if first_transaction?
OPENING_BALANCE
else
@transaction_history.most_recent.balance_after
end
end
def deposit(amount, transaction = Transaction.new(date = DateTime.now))
amount = check_format(amount)
validate_transaction(amount)
record_transaction(amount, transaction)
end
def withdraw(amount, transaction = Transaction.new(date = DateTime.now))
amount = check_format(amount)
validate_transaction(amount)
check_balance(amount)
record_transaction(-amount, transaction)
end
def statement(statement = Statement.new)
statement.print_statement(@transaction_history)
end
private
def first_transaction?
@transaction_history.empty?
end
def record_transaction(amount, transaction)
transaction.amount = amount
transaction.balance_after = balance + amount
@transaction_history.add_transaction(transaction)
end
def check_format(amount)
fail 'You must input a valid amount of money.' unless amount.match(/^[0-9]*.[0-9][0-9]$/)
amount.to_f
end
def validate_transaction(amount)
fail 'You must specify an amount more than zero.' if amount == 0
end
def check_balance(amount)
fail 'You do not have sufficient funds for that transaction' unless balance - amount >= 0
end
end
| true |
d809678d7e8dc82b3fb227ede26ac6e7943c86bb | Ruby | tewarbit/smslacquey | /lib/smslacquey/movietimes/movietimesfilter.rb | UTF-8 | 1,864 | 2.828125 | 3 | [] | no_license | require 'singleton'
require 'rubygems'
require 'orderedhash'
require 'lib/config'
module SmsLacquey
class MovieTimesFilter
include Singleton
private
def match_movie(title, msg_words)
title_words = title.downcase.scan(/[\w']+/)
(msg_words.select { |word| title_words.include?(word) }).size == msg_words.size
end
def remove_3d_imax_if_necessary(movie_list, is3D, isIMAX)
if (movie_list.size > 1)
filtered = movie_list.select do |movie|
title_words = movie.title.downcase.scan(/[\w']+/)
movie_is3D = title_words.include? '3d'
movie_isIMAX = title_words.include? 'imax'
is3D == movie_is3D && isIMAX == movie_isIMAX
end
if (filtered.size == 1)
movie_list = filtered
else
movie_list = [movie_list[0]]
end
end
movie_list
end
public
def filter_movies(movie_info, msg_body)
filtered = OrderedHash.new
msg_body_words = msg_body.downcase.scan(/[\w']+/)
is3D = msg_body_words.include? '3d'
isIMAX = msg_body_words.include? 'imax'
filtered_words = msg_body_words.delete_if{|word| word == "imax" || word == "3d"}
movie_info.each do | theater, movie_list |
filtered_movie_list = movie_list.select { |movie| match_movie(movie.title, filtered_words) }
filtered_movie_list = remove_3d_imax_if_necessary(filtered_movie_list, is3D, isIMAX)
# title_words = movie.title.downcase.scan(/[\w']+/)
# movie_is3D = title_words.include? '3d'
# movie_isIMAX = title_words.include? 'imax'
#
# end
if filtered_movie_list.size > 0
filtered[theater] = filtered_movie_list
end
end
filtered
end
end
end | true |
2503693f2393508105c93ed3fa47446710f19e1e | Ruby | SierraSchultz/advent-of-code | /2019/day1/day1Solver.rb | UTF-8 | 298 | 3.171875 | 3 | [] | no_license | puzzleFile = File.open("./day1InputSierra.txt")
puzzleData = puzzleFile.readlines.map(&:chomp)
puzzleFile.close
fuelCount = 0
def fuelDividedBy3(spaceModule)
(spaceModule.to_i / 3).floor
end
puzzleData.each do
|spaceModule| fuelCount += fuelDividedBy3(spaceModule) - 2
end
puts fuelCount
| true |
d3e377484d10caa749dac8e0c80e97ed5479e1c3 | Ruby | aparkening/orm-mapping-db-to-ruby-object-lab-online-web-pt-041519 | /lib/student.rb | UTF-8 | 2,641 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Student
attr_accessor :id, :name, :grade
# Create student instance from database row
def self.new_from_db(row)
new_student = self.new
new_student.id = row[0]
new_student.name = row[1]
new_student.grade = row[2]
new_student
end
# Get all students from database and create objects for each row
def self.all
sql = <<-SQL
SELECT *
FROM students
SQL
DB[:conn].execute(sql).map { |row| self.new_from_db(row) }
end
# Return array of all students in grade 9
def self.all_students_in_grade_9
sql = <<-SQL
SELECT *
FROM students
WHERE grade = 9
SQL
DB[:conn].execute(sql).map { |row| self.new_from_db(row) }
end
# Return array of all students below grade 12
def self.students_below_12th_grade
sql = <<-SQL
SELECT *
FROM students
WHERE grade < 12
SQL
DB[:conn].execute(sql).map { |row| self.new_from_db(row) }
end
# Return array of input number of students in grade 10
def self.first_X_students_in_grade_10(number)
number = number.to_i
sql = <<-SQL
SELECT *
FROM students
WHERE grade = 10
ORDER BY students.id
LIMIT ?
SQL
DB[:conn].execute(sql, number).map { |row| self.new_from_db(row) }
end
# Return first student in grade 10
def self.first_student_in_grade_10
number = number.to_i
sql = <<-SQL
SELECT *
FROM students
WHERE grade = 10
ORDER BY students.id
LIMIT 1
SQL
DB[:conn].execute(sql).map { |row| self.new_from_db(row) }.first
end
# Return array of students for input grade
def self.all_students_in_grade_X(grade)
number = number.to_i
sql = <<-SQL
SELECT *
FROM students
WHERE grade = ?
ORDER BY students.id
SQL
DB[:conn].execute(sql, grade).map { |row| self.new_from_db(row) }
end
# Find student in database and create new Student object from matching row
def self.find_by_name(name)
sql = <<-SQL
SELECT *
FROM students
WHERE name = ?
LIMIT 1
SQL
DB[:conn].execute(sql, name).map { |row| self.new_from_db(row) }.first
end
def save
sql = <<-SQL
INSERT INTO students (name, grade)
VALUES (?, ?)
SQL
DB[:conn].execute(sql, self.name, self.grade)
end
def self.create_table
sql = <<-SQL
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
grade TEXT
)
SQL
DB[:conn].execute(sql)
end
def self.drop_table
sql = "DROP TABLE IF EXISTS students"
DB[:conn].execute(sql)
end
end
| true |
e8bc7ae534443350378cac0925c7aebc1e2b620a | Ruby | GlynnisOC/dpl_1901 | /lib/library.rb | UTF-8 | 354 | 3.4375 | 3 | [] | no_license | class Library
attr_reader :books
def initialize
@books = [] #this doesn't seem like SRP (as books is included in the author class), please correct me if I'm wrong!
end
def add_to_collection(book_info)
@books << book_info
end
def include?(book_title)
@books.any? do |book_title|
book.title == book_title
end
end
end
| true |
f5bebe1eaf96be10493d51acca936a72372f45ce | Ruby | KarlGl/music_coder | /lib/wave.rb | UTF-8 | 2,260 | 2.8125 | 3 | [] | no_license | #a waveform. this is looped to create a Tone.
class Wave
# stores the detail amount in a #Fader.start. nil means use sin wave during generation.
# Fader.start is the main
# Fader.final is at the end. nil means same as wave start
attr_accessor :detail
#saturation effect (a random fluctuation on each data point to the cycle).
#the ammount of saturation is higher is more, 0 is none. range: 0 to 1.
attr_accessor :saturations
# hack to dramatically speed it up when on.
attr_accessor :cache_wave, :old_wave
def initialize(start=512,final=512,exp=0)
@detail = Fader.new(start, final, exp)
@saturations = Fader.new(0,0,0)
@cache_wave=Array.new(2)
@old_wave = nil#Wave.new # so false first time with is_eql
end
def saturation= val
saturations.start = val
saturations.final = val
end
#return WaveData of data for a single wave cycle
#len:: length in frames
#amp:: amplitude or volume (loudness), 0 to 1. 0 is silent
#wave_into:: how much of the final wave data is used this time. range: 0 to 1.
#
def out(freq, amp = 1, wave_into = 1)
final=WaveData.new
start=WaveData.new
if is_eql old_wave
# puts "using cahce"
start = cache_wave[0]
final = cache_wave[1]
else
# puts "not using cahce"
self.cache_wave=[nil,nil]
self.old_wave=self.dup
self.cache_wave[0] =WaveData.new(MathUtils.sinwave(detail.start, saturations.start))
self.cache_wave[1] =WaveData.new(MathUtils.sinwave(detail.final, saturations.final))
start = cache_wave[0]
final = cache_wave[1]
end
data = []
len = Composer.samplerate / freq
len.to_i.times do |i|
progress=i.to_f/len # from 0 to 1
if (detail.start > 0)
val = start.interpolate progress
# merging two waveforms
if (detail.final > 0)
val2 = final.interpolate progress
val_range = val2-val
val = val + val_range*wave_into
end
else # normal sign wave
raise "Error, wave detail isn't > 0"
# val = Math.sin(2.0*Math::PI*progress)
end
# puts "amp #{amp}, val #{val}"
val *= amp # reduce volume by this
data[i] = val
end
# puts "--> values: #{data.join(', ')}"
result=WaveData.new(data)
return result
end
def is_eql(other)
vars_eql?(other, ['@detail','@saturations'])
end
end | true |
78971437cb8348472eeda0d031e0a4644fc392e1 | Ruby | wasamasa/aoc | /2015/03.rb | UTF-8 | 3,085 | 4.34375 | 4 | [
"Unlicense"
] | permissive | require_relative 'util'
# --- Day 3: Perfectly Spherical Houses in a Vacuum ---
# Santa is delivering presents to an infinite two-dimensional grid of
# houses.
# He begins by delivering a present to the house at his starting
# location, and then an elf at the North Pole calls him via radio and
# tells him where to move next. Moves are always exactly one house to
# the north (`^`), south (`v`), east (`>`), or west (`<`). After each
# move, he delivers another present to the house at his new location.
# However, the elf back at the north pole has had a little too much
# eggnog, and so his directions are a little off, and Santa ends up
# visiting some houses more than once. How many houses receive at
# least one present?
# For example:
# - `>` delivers presents to 2 houses: one at the starting location,
# and one to the east.
# - `^>v<` delivers presents to 4 houses in a square, including twice
# to the house at his starting/ending location.
# - `^v^v^v^v^v` delivers a bunch of presents to some very lucky
# children at only 2 houses.
input = File.open('03.txt') { |f| f.read.chomp }
class SantaGrid
def initialize
@grid = Hash.new { |h, k| h[k] = 0 }
@x = 0
@y = 0
@grid[[@x, @y]] += 1
end
def walk(direction)
case direction
when '^' then @y += 1
when 'v' then @y -= 1
when '>' then @x += 1
when '<' then @x -= 1
end
@grid[[@x, @y]] += 1
end
def visited_houses
@grid.count # HACK
end
end
def easy(input)
grid = SantaGrid.new
input.each_char { |c| grid.walk(c) }
grid.visited_houses
end
assert(easy('>') == 2)
assert(easy('^>v<') == 4)
assert(easy('^v^v^v^v^v') == 2)
puts "easy(input): #{easy(input)}"
# --- Part Two ---
# The next year, to speed up the process, Santa creates a robot
# version of himself, Robo-Santa, to deliver presents with him.
# Santa and Robo-Santa start at the same location (delivering two
# presents to the same starting house), then take turns moving based
# on instructions from the elf, who is eggnoggedly reading from the
# same script as the previous year.
# This year, how many houses receive at least one present?
# For example:
# - `^v` delivers presents to 3 houses, because Santa goes north, and
# then Robo-Santa goes south.
# - `^>v<` now delivers presents to 3 houses, and Santa and Robo-Santa
# end up back where they started.
# - `^v^v^v^v^v` now delivers presents to 11 houses, with Santa going
# one direction and Robo-Santa going the other.
class SantasGrid < SantaGrid
def initialize
super
@x2 = 0
@y2 = 0
@grid[[@x2, @y2]] += 1
end
def robo_walk(direction)
case direction
when '^' then @y2 += 1
when 'v' then @y2 -= 1
when '>' then @x2 += 1
when '<' then @x2 -= 1
end
@grid[[@x2, @y2]] += 1
end
end
def hard(input)
grid = SantasGrid.new
input.each_char.each_slice(2) do |c1, c2|
grid.walk(c1)
grid.robo_walk(c2)
end
grid.visited_houses
end
assert(hard('^v') == 3)
assert(hard('^>v<') == 3)
assert(hard('^v^v^v^v^v') == 11)
puts "hard(input): #{hard(input)}"
| true |
62aff7b53d644540dfe4cad2f0b61822953042ce | Ruby | anle1337/RubyCodingProblemSolution | /RNAtoProteinSequence.rb | UTF-8 | 5,922 | 3.53125 | 4 | [] | no_license | # Description:
# The central dogma of molecular biology is that DNA is transcribed into RNA, which is then tranlsated into protein. RNA, like DNA, is a long strand of nucleic acids held together by a sugar backbone (ribose in this case). Each segment of three bases is called a codon. Molecular machines called ribosomes translate the RNA codons into amino acid chains, called polypeptides which are then folded into a protein.
# Protein sequences are easily visualized in much the same way that DNA and RNA are, as large strings of letters. An important thing to note is that the 'Stop' codons do not encode for a specific amino acid. Their only function is to stop translation of the protein, as such they are not incorporated into the polypeptide chain. 'Stop' codons should not be in the final protein sequence. To save a you a lot of unnecessary (and boring) typing the keys and values for your amino acid dictionary are provided.
# Given a string of RNA, create a funciton which translates the RNA into its protein sequence. Note: the test cases will always produce a valid string.
# protein('UGCGAUGAAUGGGCUCGCUCC') returns 'CDEWARS'
# Included as test cases is a real world example! The last example test case encodes for a protein called green fluorescent protein; once spliced into the genome of another organism, proteins like GFP allow biologists to visualize cellular processes!
# Amino Acid Dictionary
# Phenylalanine
'UUC'=>'F', 'UUU'=>'F',
# Leucine
'UUA'=>'L', 'UUG'=>'L', 'CUU'=>'L', 'CUC'=>'L','CUA'=>'L','CUG'=>'L',
# Isoleucine
'AUU'=>'I', 'AUC'=>'I', 'AUA'=>'I',
# Methionine
'AUG'=>'M',
# Valine
'GUU'=>'V', 'GUC'=>'V', 'GUA'=>'V', 'GUG'=>'V',
# Serine
'UCU'=>'S', 'UCC'=>'S', 'UCA'=>'S', 'UCG'=>'S', 'AGU'=>'S', 'AGC'=>'S',
# Proline
'CCU'=>'P', 'CCC'=>'P', 'CCA'=>'P', 'CCG'=>'P',
# Threonine
'ACU'=>'T', 'ACC'=>'T', 'ACA'=>'T', 'ACG'=>'T',
# Alanine
'GCU'=>'A', 'GCC'=>'A', 'GCA'=>'A', 'GCG'=>'A',
# Tyrosine
'UAU'=>'Y', 'UAC'=>'Y',
# Histidine
'CAU'=>'H', 'CAC'=>'H',
# Glutamine
'CAA'=>'Q', 'CAG'=>'Q',
# Asparagine
'AAU'=>'N', 'AAC'=>'N',
# Lysine
'AAA'=>'K', 'AAG'=>'K',
# Aspartic Acid
'GAU'=>'D', 'GAC'=>'D',
# Glutamic Acid
'GAA'=>'E', 'GAG'=>'E',
# Cystine
'UGU'=>'C', 'UGC'=>'C',
# Tryptophan
'UGG'=>'W',
# Arginine
'CGU'=>'R', 'CGC'=>'R', 'CGA'=>'R', 'CGG'=>'R', 'AGA'=>'R', 'AGG'=>'R',
# Glycine
'GGU'=>'G', 'GGC'=>'G', 'GGA'=>'G', 'GGG'=>'G',
# Stop codon
'UAA'=>'Stop', 'UGA'=>'Stop', 'UAG'=>'Stop'
# Test cases
Test.describe('Basic Tests') do
Test.it('Testing for Basic Functionality') do
Test.assert_equals(protein('AUGUGA'), 'M')
Test.assert_equals(protein('AUGUAUAAA'), 'MYK')
Test.assert_equals(protein('UGCGAUGAAUGGGCUCGCUCC'), 'CDEWARS')
end
Test.it('Testing for removal of "Stop"') do
Test.assert_equals(protein('AUGUGA'), 'M')
Test.assert_equals(protein('AUGUUAAUUUGA'), 'MLI')
end
end
Test.describe('Longer Sequence Tests') do
Test.it('Longer Sequences') do
Test.assert_equals(protein('AUGUCCUUCCAUCAAGGAAACCAUGCGCGUUCAGCUUUCUGA'), 'MSFHQGNHARSAF')
Test.assert_equals(protein('AUGCUUCAAGUGCACUGGAAAAGGAGAGGGAAAACCAGUUGA'), 'MLQVHWKRRGKTS')
Test.assert_equals(protein('AUGGCGUUCAGCUUUCUAUGGAGGGUAGUGUACCCAUGCUGA'), 'MAFSFLWRVVYPC')
Test.assert_equals(protein('AUGCAGCUUUCUAUGGAGGGUAGUGUUAACUACCACGCCUGA'), 'MQLSMEGSVNYHA')
Test.assert_equals(protein('AUGCUAUGGAGGGUAGUGUUAACUACCACGCCCAGUACUUGA'), 'MLWRVVLTTTPST')
Test.assert_equals(protein('AUGCUGAUUAUGGUUGUUGUAUCUUCCUAUCAAAAUAAAACUACCACAUGA'), 'MLIMVVVSSYQNKTTT')
Test.assert_equals(protein('AUGGAGCACAAUAAAAUACCAAUACCACUCACUCUCUACCCUACUCUACUCUCAUGA'), 'MEHNKIPIPLTLYPTLLS')
end
Test.it('This is the green fluorescent protein gene from the Snakelocks anemone!') do
Test.assert_equals(protein('AUGUAUCCUUCCAUCAAGGAAACCAUGCGCGUUCAGCUUUCUAUGGAGGGUAGUGUUAACUACCACGCCUUCAAGUGCACUGGAAAAGGAGAGGGAAAACCAUACGAAGGCACCCAAAGCCUGAAUAUUACAAUAACUGAAGGAGGUCCUCUGCCAUUUGCUUUUGACAUUCUGUCACACGCCUUUCAGUAUGGCAUCAAGGUCUUCGCCAAGUACCCCAAAGAAAUUCCUGACUUCUUUAAGCAGUCUCUACCUGGUGGUUUUUCUUGGGAAAGAGUAAGCACCUAUGAAGAUGGAGGAGUGCUUUCAGCUACCCAAGAAACAAGUUUGCAGGGUGAUUGCAUCAUCUGCAAAGUUAAAGUCCUUGGCACCAAUUUUCCCGCAAACGGUCCAGUGAUGCAAAAGAAGACCUGUGGAUGGGAGCCAUCAACUGAAACAGUCAUCCCACGAGAUGGUGGACUUCUGCUUCGCGAUACCCCCGCACUUAUGCUGGCUGACGGAGGUCAUCUUUCUUGCUUCAUGGAAACAACUUACAAGUCGAAGAAAGAGGUAAAGCUUCCAGAACUUCACUUUCAUCAUUUGCGUAUGGAAAAGCUGAACAUAAGUGACGAUUGGAAGACCGUUGAGCAGCACGAGUCUGUGGUGGCUAGCUACUCCCAAGUGCCUUCGAAAUUAGGACAUAACUGA'), 'MYPSIKETMRVQLSMEGSVNYHAFKCTGKGEGKPYEGTQSLNITITEGGPLPFAFDILSHAFQYGIKVFAKYPKEIPDFFKQSLPGGFSWERVSTYEDGGVLSATQETSLQGDCIICKVKVLGTNFPANGPVMQKKTCGWEPSTETVIPRDGGLLLRDTPALMLADGGHLSCFMETTYKSKKEVKLPELHFHHLRMEKLNISDDWKTVEQHESVVASYSQVPSKLGHN')
end
end
Test.describe("Random tests") do
base=$codons.keys
def randint(a,b) rand(b-a+1)+a end
def prosol(rna)
res=""
for _ in 0...rna.length/3
item=$codons[rna[_*3,3]]
if item=='Stop' then break end
res+=item
end
return res
end
40.times do
testrna=""
randint(1,25).times do
testrna+=base[randint(0,base.length-1)]
end
Test.it("Testing for "+testrna) do
Test.assert_equals(protein(testrna), prosol(testrna),"It should work for random inputs too")
end
end
end
# My answer:
def protein(rna)
codons = rna.split("").each_slice(3).to_a
codons = codons.map {|x| x.join}
seq = []
codons.each do |y|
if $codons[y] == "Stop"
break
end
seq.push($codons[y])
end
seq.join
#your code here
#you can copy and paste the codons from the description into a hash
#or use the preloaded $codons hash
end
# Best Answer:
def protein(rna)
rna.chars.each_slice(3).map do |codon|
codon = codon.join
$codons[codon]
end.join.sub(/Stop.*/,'')
end
# or
def protein(rna)
rna.scan(/.../).map{|i| $codons[i]}.take_while{|i| i != "Stop"}.join
end
| true |
db0c4630eab853741195d9336e8c6ab2ca070636 | Ruby | DannyBen/webcache | /spec/webcache/web_cache_spec.rb | UTF-8 | 7,052 | 2.53125 | 3 | [
"MIT"
] | permissive | describe WebCache do
let(:url) { 'http://example.com' }
before { subject.flush }
describe '#new' do
it 'sets default properties' do
expect(subject.life).to eq 3600
expect(subject.dir).to eq 'cache'
end
context 'with arguments' do
subject { described_class.new dir: 'store', life: 120, auth: auth }
let(:auth) { { user: 'user', pass: 's3cr3t' } }
it 'sets its properties' do
expect(subject.life).to eq 120
expect(subject.dir).to eq 'store'
expect(subject.user).to eq auth[:user]
expect(subject.pass).to eq auth[:pass]
end
end
end
describe '#get' do
it 'saves a file' do
subject.get url
expect(Dir['cache/*']).not_to be_empty
end
it 'downloads from the web' do
expect(subject).to receive(:http_get).with(url)
subject.get url
end
it 'loads from cache' do
subject.get url
expect(subject).to be_cached url
expect(subject).not_to receive(:http_get).with(url)
expect(subject).to receive(:load_file_content)
subject.get url
end
it 'returns content from cache' do
subject.get url
expect(subject).to be_cached url
response = subject.get url
expect(response.content.length).to be > 500
end
context 'with file permissions' do
before do
subject.permissions = 0o600
FileUtils.rm_f tmp_path
end
let(:tmp_path) { '/tmp/webcache-test-file' }
let(:file_mode) { File.stat(tmp_path).mode & 0o777 }
it 'chmods the cache file after saving' do
allow(subject).to receive(:get_path).with(url).and_return tmp_path
subject.get url
expect(file_mode).to eq 0o600
end
end
context 'with force: true' do
it 'always downloads a fresh copy' do
subject.get url
expect(subject).to be_cached url
expect(subject).to receive(:http_get).with(url)
subject.get url, force: true
end
end
context 'when cache is disabled' do
before { subject.disable }
it 'skips caching' do
subject.get url
expect(Dir['cache/*']).to be_empty
end
end
context 'when cache dir does not exist' do
before { expect(Dir).not_to exist 'cache' }
it 'creates it' do
subject.get url
expect(Dir).to exist 'cache'
end
end
context 'when the request is successful' do
let(:response) { subject.get url }
it 'sets response content' do
expect(response.content).to match 'Example Domain'
end
it 'sets response code' do
expect(response.code).to eq 200
end
it 'sets response base_uri' do
expect(response.base_uri).to be_a HTTP::URI
expect(response.base_uri.to_s).to eq 'http://example.com/'
end
it 'sets error to nil' do
expect(response.error).to be_nil
end
end
context 'with 404 url' do
let(:response) { subject.get 'http://example.com/not_found' }
it 'returns the error message' do
expect(response.content).to eq '404 Not Found'
end
it 'sets error to the error message' do
expect(response.error).to eq '404 Not Found'
end
it 'sets code to 404' do
expect(response.code).to eq 404
end
end
context 'with a bad url' do
let(:response) { subject.get 'http://not-a-uri' }
it 'returns the error message' do
expect(response.content).to match 'failed to connect'
end
it 'sets error to the error message' do
expect(response.error).to match 'failed to connect'
end
end
context 'with https' do
let(:response) { subject.get 'https://en.wikipedia.org/wiki/HTTPS' }
before { subject.disable }
it 'downloads from the web' do
expect(response.content.size).to be > 40_000
expect(response.error).to be_nil
end
end
context 'with basic authentication' do
let(:response) { subject.get "#{httpbin_host}/basic-auth/user/pass" }
context 'when the credentials are valid' do
before { subject.auth = { user: 'user', pass: 'pass' } }
it 'downloads from the web' do
expect(response).to be_success
content = JSON.parse response.content
expect(content['authenticated']).to be true
end
end
context 'when the credentials are invalid' do
before { subject.auth = { user: 'user', pass: 'wrong-pass' } }
it 'fails' do
expect(response).not_to be_success
expect(response.code).to eq 401
end
end
end
context 'with other authentication header' do
let(:response) { subject.get "#{httpbin_host}/bearer" }
before { subject.auth = 'Bearer t0k3n' }
it 'downloads from the web' do
expect(response).to be_success
content = JSON.parse response.content
expect(content['authenticated']).to be true
expect(content['token']).to eq 't0k3n'
end
end
end
describe '#cached?' do
it 'returns true when url is cached' do
subject.get url
expect(subject).to be_cached url
end
it 'returns false when url is not cached' do
expect(subject).not_to be_cached 'http://never.downloaded.com'
end
end
describe '#enable' do
it 'enables http calls' do
subject.enable
expect(subject).to be_enabled
expect(subject).to receive(:http_get)
subject.get url
end
end
describe '#disable' do
it 'disables cache handling' do
subject.disable
expect(subject).not_to be_enabled
expect(subject).to receive(:http_get).twice
expect(subject).not_to receive(:load_file_content)
subject.get url
subject.get url
end
end
describe '#clear' do
before do
subject.get url
expect(Dir).not_to be_empty subject.dir
end
it 'removes a url cache file' do
subject.clear url
expect(Dir).to be_empty subject.dir
end
end
describe '#flush' do
before do
subject.get url
expect(Dir).not_to be_empty subject.dir
end
it 'deletes the entire cache directory' do
subject.flush
expect(Dir).not_to exist subject.dir
end
end
describe '#life=' do
it 'handles plain numbers' do
subject.life = 11
expect(subject.life).to eq 11
end
it 'handles 11s as seconds' do
subject.life = '11s'
expect(subject.life).to eq 11
end
it 'handles 11m as minutes' do
subject.life = '11m'
expect(subject.life).to eq 11 * 60
end
it 'handles 11h as hours' do
subject.life = '11h'
expect(subject.life).to eq 11 * 60 * 60
end
it 'handles 11d as days' do
subject.life = '11d'
expect(subject.life).to eq 11 * 60 * 60 * 24
end
end
describe '#permissions=' do
it 'sets file permissions' do
subject.permissions = 0o600
expect(subject.permissions).to eq 0o600
end
end
end
| true |
e20bc512bfe891b3aaf9e3ec2948cc5636f7f4a4 | Ruby | BrianMehrman/EatMe | /app/models/nut_data.rb | UTF-8 | 730 | 2.515625 | 3 | [] | no_license | class NutData < ActiveRecord::Base
#set_primary_key :NDB_No
alias_attribute :n, :Nutr_Val
belongs_to :definition, :class_name => "NutrDef", :foreign_key => "Nutr_No", :primary_key => "Nutr_No"
belongs_to :source, :class_name => "SrcCd", :foreign_key => "Src_Cd", :primary_key => "Src_Cd"
belongs_to :derivation, :class_name => "DerivCd", :foreign_key => "Deriv_Cd", :primary_key => "Deriv_Cd"
has_many :factor, :as => :factoree
# the value of Nutr_Val is the number of grams in 100 grams total,
# which it makes it easy to calculate the amount in every 1 gram
def value(consumption)
v = (self.n * consumption.weight.Gm_Wgt * consumption.measurement ).to_f/100.0
puts "v:#{v}"
return v
end
end
| true |
caa3114683b9e2eb802282742d952b3afd6ea1eb | Ruby | kmanahan/programming-univbasics-3-build-a-calculator-lab-online-web-prework | /lib/math.rb | UTF-8 | 499 | 3.53125 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def addition(num1, num2)
puts num1 + num2
return num1 + num2
end
addition(1,2)
def subtraction(num1, num2)
puts num1 - num2
return num1 - num2
end
subtraction(2,1)
def division(num1, num2)
puts num1/num2
return num1/num2
end
division(2,1)
def multiplication(num1, num2)
puts num1 * num2
return num1 * num2
end
multiplication(2,1)
def modulo(num1, num2)
puts num1 % num2
return num1 % num2
end
modulo(2,1)
def square_root(num)
puts Math.sqrt(num)
return Math.sqrt(num)
end
square_root(4)
| true |
63a5bd0af90590398eb73f820502131b0b627ffb | Ruby | ushadow/tabletop_kinect | /ruby/eval_clicks.rb | UTF-8 | 3,154 | 3.328125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'optparse'
def eval_segment(segment)
avgx = segment.reduce(0) { |sum, e| sum + e[1] } / segment.size
avgy = segment.reduce(0) { |sum, e| sum + e[2] } / segment.size
{start_index: segment.first[0], end_index: segment.last[0], avgx: avgx,
avgy: avgy}
end
def eval_gt_clicks(groundtruth)
segment = [groundtruth.first]
clicks = []
groundtruth[1..-1].each do |e|
if e[0] > segment.last[0] + 1
clicks << eval_segment(segment)
segment = [e]
else
segment << e
end
end
clicks << eval_segment(segment)
end
# Evaluates the accuracy of the detected clicks.
# @param [Array] detected detected fingertips sorted according to frame IDs.
# @param [Array] groundtruth each element is an array of numbers as groundtruth
# true labels of fingertips sorted according to frame IDs.
def eval_detected_clicks(detected, groundtruth)
gt_clicks = eval_gt_clicks groundtruth
puts "Number of ground truth clicks: #{gt_clicks.size}"
cursor = 0
false_pos = true_pos = false_neg = 0
false_neg_duration = total_false_neg_duration = total_segment = 0
gt_clicks.each do |click|
start_index = click[:start_index]
end_index = click[:end_index]
prev = -1
while cursor < detected.size && detected[cursor][0] < start_index
false_pos += 1
if prev != -1
if detected[cursor][0] == prev + 1
false_neg_duration += 1
else
total_false_neg_duration += false_neg_duration + 1
total_segment +=1
prev = -1
false_neg_duration = 0
end
end
prev = detected[cursor][0]
puts "false positive: #{detected[cursor][0]}, " +
"start index = #{start_index}"
cursor += 1
end
total_false_neg_duration += false_neg_duration + 1
total_segment += 1
prev = -1
false_neg_duration = 0
if cursor < detected.size &&
(start_index..end_index) === detected[cursor][0]
true_pos += 1
cursor += 1
while cursor < detected.size &&
(start_index..end_index) === detected[cursor][0]
cursor += 1
end
else
false_neg += 1
puts "false negative: #{start_index} - #{end_index}"
end
end
{true_pos: true_pos, false_pos: false_pos, false_neg: false_neg,
false_neg_duration: Float(total_false_neg_duration) / total_segment}
end
option_parser = OptionParser.new do |opts|
executable_name = File.basename($0)
opts.banner = "Usage: #{executable_name} groundtruth_file detected_file"
end
if __FILE__ == $0
option_parser.parse!
groundtruth_file = ARGV[0]
groundtruth = File.read(groundtruth_file).split("\n")[1..-1]
groundtruth.map! { |l| l.split.map(&:to_i) }
detected_file = ARGV[1]
detected = File.read(detected_file).split("\n")[1..-1]
detected.map! { |l| l.split.map(&:to_i) }
result = eval_detected_clicks detected, groundtruth
puts <<EOS
true positives: #{result[:true_pos]}
false positivies: #{result[:false_pos]}
false negative : #{result[:false_neg]}
false negative duration: #{result[:false_neg_duration]}
EOS
end
| true |
7e952afda68f3f47b2ba2ee6736da3bde3696084 | Ruby | naranhoe/prime_number | /prime.rb | UTF-8 | 126 | 3 | 3 | [] | no_license | class PrimeFactors
def generate(number)
factors = []
if number > 1
factors << 2
end
factors
end
end
| true |
0fbb117ef79059081784876f9a02b035df211d27 | Ruby | Burrick2003/ruby-objects-has-many-lab-v-000 | /lib/song.rb | UTF-8 | 507 | 3.234375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
class Song
@@songs = 0
attr_accessor :name, :artist, :genre
def initialize(name)
@name = name
@@songs += 1
end
def artist_name
#@artist #why doesn't this work? (artist in artist class not song)
#if self.artist.name != nil #not does it have an artist name, but is it an existing artist (to be added later?)
output = "" #prob get rid of this, for test purposes
if self.artist
output << self.artist.name
else
output = nil
end
output
end
end
| true |
35a7454cadc772c977f1bd9e00e170dce915c05a | Ruby | floum/zwischenzug_cli | /lib/zwischenzug_cli/puzzle.rb | UTF-8 | 1,285 | 3 | 3 | [
"MIT"
] | permissive | class Puzzle
attr_reader :pgn
def initialize(attrs = {})
@initial_ply = attrs.fetch(:initial_ply) { 0 }
@fen = attrs.fetch(:fen)
@moves = attrs.fetch(:moves)
end
def pgn
%Q([SetUp "1"]\n[FEN "#{@fen}"]\n#{line}\n)
end
def yaml
%Q(- fen: #{@fen}\n moves: #{line}\n ply: 1\n)
end
def black_to_play?
@fen.split(' ')[1] == 'b'
end
def line
moves = @moves.map {|ply, san| san }
if black_to_play?
moves.unshift('..')
end
moves.each_slice(2).with_index.map do |move, index|
"#{index+1}.#{move.join(' ')}"
end.join(' ')
end
def self.parse(lichess_response_body)
positions = lichess_response_body.scan(/"ply":(\d+),"fen":"(\w+\/\w+\/\w+\/\w+\/\w+\/\w+\/\w+\/\w+ [wb] [-KQkq]+ [-\w]+ \d+ \d+)","id":"[^"]+","uci":"(\w+)","san":"([\w=#\+]+)"/).map {|ply, fen, uci, san| [ply.to_i, fen, uci, san]}
initial_ply = lichess_response_body[/"initialPly":\d+/][/\d+/].to_i
puzzle = positions.select {|position| position[0] >= initial_ply-1}
moves = puzzle.map do |ply, fen, uci, san, index|
[ply, san]
end[1..-1]
puzzle_fen = puzzle[0][1]
pgn = %Q([SetUp "1"]\n[FEN "#{puzzle_fen}"]\n#{moves})
Puzzle.new(fen: puzzle_fen, moves: moves, initial_ply: initial_ply)
end
end
| true |
56c03504e6af5f35e04f3d7e78ebe034da71a4ce | Ruby | jclemans/Point-of-Sale-System | /pos_ui.rb | UTF-8 | 3,578 | 3.34375 | 3 | [] | no_license | require 'active_record'
require 'pry'
require './lib/product'
require './lib/cashier'
require './lib/customer'
require './lib/checkout'
ActiveRecord::Base.establish_connection(YAML::load(File.open('./db/config.yml'))['development'])
def welcome
puts "Welcome to the POS system."
cashier_login
menu
end
def cashier_login
puts "You've successfully logged in as a cashier!"
end
def menu
choice = nil
until choice == 'x'
puts "Press 'a' to add a product, 'l' to list all, or 'd' to delete a product."
puts "Enter 's' to begin shopping, 'sl' to list all items in cart."
puts "Enter 'x' to logout."
puts "Press 'c' to create a new cashier, 'cl' to list all cashiers."
puts "Enter 'h' to check-out."
choice = gets.chomp
case choice
when 'a'
add_product
when 'l'
list_products
when 'd'
delete_product
when 's'
add_to_cart
when 'sl'
list_cart
when 'c'
add_cashier
when 'h'
checkout
when 'cl'
list_cashiers
when 'x'
puts "See ya!"
else
puts "Invalid entry. Please enter a new command."
end
end
end
def add_product
puts "Enter product name:"
product_name = gets.chomp
puts "What is the price for #{product_name}?"
product_price = gets.chomp
product = Product.create({name: product_name, price: product_price})
puts "#{product_name} has been added at #{product_price}."
end
def delete_product
puts "Enter name of product to delete:"
to_delete = gets.chomp
product = Product.where({name: to_delete})
Product.delete(product.first.id)
puts "#{product} has been deleted!"
end
def list_products
puts "List of all products in the system:\n\n"
products = Product.all
products.each { |product| puts product.name + " $" + product.price.to_s}
end
def add_cashier
puts "Please enter the name of the new cashier: "
name_c = gets.chomp
puts "Please enter a new password:"
password_c = gets.chomp
pass_valid(password_c)
new_cashier = Cashier.create({name: name_c, password: password_c})
"The new cashier has been made!"
end
def pass_valid(password)
return true
end
def list_cashiers
puts "Here is a list of all the current cashiers"
cashiers = Cashier.all
cashiers.each do |cashier|
puts cashier.name
end
end
def add_to_cart
list_products
puts "Enter the name of the product to add it to your cart:"
choice = gets.chomp
puts "Enter a quantity:"
quantity = gets.chomp.to_i
choice = Product.where({name: choice})
Customer.create({product_id: choice.first.id, quantity: quantity})
puts "#{quantity}: #{choice.first.name} has been added to your shopping cart!"
list_cart
end
def list_cart
total_price = []
cart_items = Customer.all
cart_items.each do |item|
item_name = Product.find(item.product_id).name
item_price = Product.find(item.product_id).price
item_number = item.quantity
puts "#{item_name}. . . \t# #{item_number}"
sub_price = item_price * item_number
total_price << sub_price
puts "Sub-Total: $#{sub_price}"
end
puts "Total: $ #{total_price.sum}"
end
def checkout
list_cart
puts "Enter cashier login:"
login = gets.chomp
puts "Enter cashier password (hint: money):"
password = gets.chomp
puts "Enter amount paid:"
payment = gets.chomp
current_cashier = Cashier.create(name: login, password: password)
Customer.all.each do |item|
new_checkout = Checkout.create({cashier_id: current_cashier.id, customer_id: item.id})
end
Customer.all.each { |item| item.destroy }
puts "You are done checking out!"
end
welcome
| true |
c11b694a3b04e8f1cf2059ed2f23b17ac2b7574e | Ruby | zeroboo/java-scripting-rhino-jdk8 | /engines/jruby/test/src/main/ruby/flowers.rb | UTF-8 | 474 | 4.0625 | 4 | [] | no_license | #
# flowers.rb
class Flowers
@@hash = {'red' => 'ruby', 'white' => 'pearl'}
def initialize(color, names)
@color = color
@names = names
end
def comment
$, = ", "
puts "#{@names}. Beautiful like a #{@@hash[@color]}!"
end
def others(index)
@names.delete_at(index)
puts "Others are #{@names}"
end
end
$red = Flowers.new('red', ["Hibiscus", "Poinsettia", "Camellia"])
$white = Flowers.new('white',["Gardenia", "Lily", "Narusissus"]) | true |
2ee5987dd16ca7130097546d41c4e3ba69215002 | Ruby | ajtran303/codeacademy-ruby | /5/basic-methods.rb | UTF-8 | 110 | 2.9375 | 3 | [] | no_license | # Review of writing methods
# define method
def welcome
puts "Welcome to Ruby!"
end
# call method
welcome
| true |
89cdb254e3b9f885ddedd51ac5e68f315231400d | Ruby | sa2taka/UnsecretPuzzle | /models/user.rb | UTF-8 | 926 | 2.796875 | 3 | [] | no_license | require 'digest'
require 'bcrypt'
require_relative '../models.rb'
class User < ActiveRecord::Base
validates :id, presence: true, uniqueness: true
validates :password, presence: true
has_many :styles
def self.create(name, new_password)
user = User.new
user.id = name
user.password = encrypt(new_password)
user.sessionid = generate_sessionid(name + new_password)
user.save
user
end
def authenticate(confirmed)
BCrypt::Password.new(self.password) == confirmed
end
private
def self.encrypt(new_password)
if new_password.present?
return BCrypt::Password.create(new_password)
else
raise ArgumentError
end
end
def self.generate_sessionid(string)
bin = Digest::SHA512.digest(string).split('').map { |c| c.ord > 127 ? '1' : '0'}.join
bin.scan(/.{1,8}/).map { |b| b.to_i(2).to_s(16) }.join('_')
end
end
| true |
b00dc43862c56d87016b41a66ebebc18cdbfbd0b | Ruby | tgrosch91/kitten-scraper | /lib/ages.rb | UTF-8 | 462 | 2.984375 | 3 | [] | no_license |
require 'pry'
require_relative '../lib/concerns/cattributes'
class Ages
include Cattribute::InstanceMethods
extend Cattribute::ClassMethods
attr_accessor :name, :cats
def initialize(name)
@name = name
@cats = []
end
def self.create(name)
self.new(name).tap{|age| age.save}
end
def self.find(name)
self.all.find{|age| age.name == name}
end
def save
@@all<<self
end
def self.all
@@all
end
@@all = []
end
| true |
4940e249c589cf24874a43a6a54355f29934a35a | Ruby | lucashungaro/scoring_rules | /lib/scoring_rules/rule.rb | UTF-8 | 205 | 3.140625 | 3 | [
"MIT"
] | permissive | class Rule
attr_accessor :points
def initialize(points, condition)
@points = points
@condition = condition
end
def evaluate(instance)
@condition.evaluate(instance) * @points
end
end | true |
581f7e022abd561eb15115c9e3c357bfb0679bd1 | Ruby | akandeel/CHOCO | /app/models/user.rb | UTF-8 | 5,883 | 2.75 | 3 | [] | no_license | class User < ApplicationRecord
enum role: [:customer, :business]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :customer
end
attr_accessor :remember_token, :activation_token # to create an accessible attribute to store cookies without saving to database
before_save :downcase_email
before_create :create_activation_digest #we only want the callback to fire when the user is created.
#to assign the token and corresponding digest
#***** FOR FIXTURES *****
before_save { self.email_address = email_address.downcase }
#ASSOCIATIONS
#has_many :sales
#VALIDATIONS
validates_presence_of :first_name,
:last_name,
:gender,
:date_of_birth,
:country,
:street_number,
:street_name,
:state,
:suit_number,
:mailing_address,
:email_address
validates_uniqueness_of :first_name,
:last_name,
:email_address
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email_address, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
#bcrypt does this implicitly but we just need to put a password length.
has_secure_password
#validates :password, presence: true, length: { minimum: 6 }
#don't need to validate :password,
#presence because has_secure_password
#already does it.
# Returns the hash digest of the given string.
# a method to create a password_digest attribute for our custom fixture user.
# *** the password digest is created using bcrypt (via has_secure_password)
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
#Because we’ll need to log the user in, we also
#have to include a valid password to compare
#with the password submitted to the Sessions
#controller’s create action. Referring to the
#model we see that this
#means creating a password_digest attribute
#for the user fixture, which we’ll accomplish
#by defining a digest method of our own.
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# PERFECT FOR REMEMBER TOKENS
#specifically designed to be safe in URLs
# ***** The urlsafe_base64 method from the SecureRandom module
#in the Ruby standard library returns a random string of length 22
# each of the 22 characters has 64 possibilities.
#we can create a valid token and associated digest
#by first making a new remember token using User.new_token,
#and then updating the remember digest with the result of
#applying User.digest. This procedure gives
#the remember method
# MAKE REMEMBER TOKEN METHOD.
# this is a class method.
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token #Using self ensures that assignment sets the user’s remember_token attribute and doesn't create a local variable.
update_attribute(:remember_digest, User.digest(remember_token))
end
# update_attribute bypasses the validations, which is necessary in this case because we don’t have access to the user’s password or confirmation.)
#USING BCRYPT CODE
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest") #removed self.send because its redundant.
return false if digest.nil?
#if remember_digest.nil? # using nil and returning false fixes error in test.
#false
#else
BCrypt::Password.new(digest).is_password?(token)
#end
# return false if remember_digest.nil? is required to set th digest
# to nil because BCrypt::Password.new(nil) raises an error, the test
#suite should be red. that line fixes it.
end
#ACITVATING AN ACCOUNT
def activate
update_attribute(:activated, true)
update_attribute(:activated_at, Time.zone.now)
end
def send_activation_email
User.Mailer.account_activation(self).deliver_now
end
#Note that the remember_token argument in the
#authenticated? method is not the same
#as the accessor in the class.attr_accessor :remember_token;
#instead, it is a variable local to the method.
#Because the argument refers to the remember token,
# it is not uncommon to use a method argument that
# has the same name.
#Also note the use of the
#remember_digest attribute, which is the
#same as self.remember_digest and,
#like name and email, is created automatically
#by Active Record based on the name of the
#corresponding database column (Listing 9.1).
#WHAT THE $#%&%$*^%$*
#forget a users permanent session by adding a forget helper and calling it from the log_out helper
def forget
#update_attribute (:remember_digest, nil) #this doesn't pass for some reason.
#end
if remember_digest.nil?
false
else
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
end
private
# Converts email to all lower-case.
def downcase_email
self.email_address = email_address.downcase
end
#Because the create_activation_digest
#method itself is only used internally
#by the User model, there’s no need to
#expose it to outside users
#will be used in before_create callback.
def create_activation_digest
# Creates and assigns the activation token and digest.
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
| true |
76b4b2eb029f9fb79785c90385a3336a62ad5758 | Ruby | addislw/appA-Foundations | /blocks_project/lib/part_1.rb | UTF-8 | 555 | 3.703125 | 4 | [] | no_license | def select_even_nums(array)
array.select do |nums|
nums % 2 == 0
end
end
def reject_puppies(hash_array)
hash_array.reject do |hash|
hash['age'] <= 2
end
end
def count_positive_subarrays(array)
array.count do |sub_array|
sub_array.sum > 0
end
end
def aba_translate(string)
vowels = 'aeiou'
string.split('').map do |char|
if vowels.include?(char)
char = "#{char}b#{char}"
else
char
end
end
.join
end
def aba_array(string_array)
string_array.map { |string| aba_translate(string) }
end | true |
cdbd7109472855d34b7850f406c1d36c79494fe1 | Ruby | mlowen/sequel_populator | /lib/sequel_populator/runner.rb | UTF-8 | 1,621 | 2.859375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Sequel
# Module is responsible for housing the functionality to populate a database
# with seed data, based on either a hash or file path provided.
module Populator
require 'sequel'
# This class is responsible for populating the database.
class Runner
def initialize(database)
Sequel.extension :inflector
@database = database
end
def run(data)
@database.transaction do
data.each { |table, entities| populate_table(table, entities) }
end
end
private
def populate_table(table, entity)
if entity.is_a? Hash
fetch_or_create(table, entity)
elsif entity.is_a? Array
entity.each { |item| populate_table(table, item) }
else
raise "Unexpected value for #{table}"
end
end
def populate_references(entity)
references = {}
key = :$refs if entity.key?(:$refs)
key = '$refs' if entity.key?('$refs')
unless key.nil?
entity[key].each do |ref, fields|
references[ref.foreign_key.to_sym] = fetch_or_create(ref, fields)
end
end
references
end
def fetch_or_create(table, entity)
fields = populate_references(entity)
table_name = table.tableize.to_sym
entity.each do |k, v|
fields[k.to_sym] = v unless k.to_s.start_with?('$')
end
existing = @database[table_name].first(fields)
existing.nil? ? @database[table_name].insert(fields) : existing[:id]
end
end
end
end
| true |
01669889027dfbe3827e3dbe6c490f2acd78244a | Ruby | DSIW/tictactie | /spec/tictactie/game_spec.rb | UTF-8 | 444 | 2.640625 | 3 | [
"MIT"
] | permissive | require "spec_helper"
RSpec.describe TicTacTie::Game do
let(:game) { described_class.new }
describe "status" do
context "correct player has won with message" do
before do
game.board.place_symbol(0, 'X')
game.board.place_symbol(4, 'X')
game.board.place_symbol(8, 'X')
end
it 'returns' do
expect(game.send(:status)).to eq "Congratulations, player X won!"
end
end
end
end
| true |
63a3222abe875f383cbcad83d8adcc9ea4695a50 | Ruby | megaya/tocaro_webhook | /lib/tocaro_webhook/sender.rb | UTF-8 | 1,000 | 2.78125 | 3 | [
"MIT"
] | permissive | require 'uri'
require 'net/http'
require 'openssl'
require 'tocaro_webhook/payload'
module TocaroWebhook
class Sender
attr_accessor :url
attr_writer :payload
def initialize(web_hook_key)
@url = web_hook_url(web_hook_key)
end
def set_text(text)
payload.text = text
end
# color is info, warning, danger, success
def set_color(color)
payload.color = color
end
def exec(options={})
payload.text ||= options[:text]
payload.color ||= options[:color]
request = Net::HTTP::Post.new(@url)
request.body = payload.to_body
uri = URI.parse(@url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
https.request(request)
end
def web_hook_url(web_hook_key)
"https://hooks.tocaro.im/integrations/inbound_webhook/#{web_hook_key}"
end
def payload
@payload ||= TocaroWebhook::Payload.new
end
end
end
| true |
6908fcc1541debe8df4a9fdb0696540a689a2196 | Ruby | peggycodus/poker_hand_ruby | /spec/poker_hand_spec.rb | UTF-8 | 216 | 2.71875 | 3 | [] | no_license | require('rspec')
require('poker_hand')
describe("poker_hand") do
it("returns the name of the poker hand, given a five card argument") do
poker_hand(['2S', '3C', '4D', '5C', '6H']).should(eq('straight'))
end
end
| true |
6e7f3253bf281ee9fa6fcca8fba32071ca3d22d1 | Ruby | tylerjharden/dbpedialite | /lib/freebase_api.rb | UTF-8 | 1,952 | 2.625 | 3 | [
"MIT"
] | permissive | require 'net/https'
require 'uri'
require 'cgi'
module FreebaseApi
USER_AGENT = 'DbpediaLite/1'
MQLREAD_URI = URI.parse('https://www.googleapis.com/freebase/v1/mqlread')
RDF_BASE_URI = URI.parse('http://rdf.freebase.com/rdf/')
GOOGLE_API_KEY = ENV['GOOGLE_API_KEY']
HTTP_TIMEOUT = 2
class Exception < Exception
end
class NotFound < FreebaseApi::Exception
end
def self.mqlread(query)
uri = MQLREAD_URI.clone
uri.query = 'query='+CGI::escape(JSON.dump(query))
unless GOOGLE_API_KEY.nil?
uri.query += "&key=#{GOOGLE_API_KEY}"
end
http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = HTTP_TIMEOUT
http.read_timeout = HTTP_TIMEOUT
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
res = http.get(uri.request_uri, {'User-Agent' => USER_AGENT})
# Throw an exception if HTTP request was unsuccessful
res.value
# Throw and exception if the JSON response was unsuccessful
data = JSON.parse(res.body)
if data.has_key?('error')
raise FreebaseApi::Exception.new("Freebase query failed: #{data['error']['message']}")
end
if data['result'].nil?
raise FreebaseApi::NotFound.new("Freebase query returned no results")
end
data['result']
end
def self.lookup_wikipedia_pageid(pageid, language='en')
mqlread({
'key' => {
'namespace' => "/wikipedia/#{language}_id",
'value' => pageid.to_s,
'limit' => 0
},
'id' => nil,
'name' => nil,
'mid' => nil,
'guid' => nil,
'limit' => 1
})
end
def self.lookup_by_id(identifier, language='en')
mqlread({
'id' => identifier,
'key' => {
'namespace' => "/wikipedia/#{language}_id",
'value' => nil,
'limit' => 1
},
'name' => nil,
'mid' => nil,
'guid' => nil,
'limit' => 1
})
end
end
| true |
e0ddcbcdced06f1cf3400c4b4c3fb028b61aa910 | Ruby | stereocat/training | /pbrlbswitch/pbrlb-table.rb | UTF-8 | 1,700 | 2.546875 | 3 | [] | no_license | #
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
class PbrLbTableEntry
attr_reader :ipaddr
attr_reader :tcp_port
def initialize(options)
@ipaddr = IPAddr.new(options[:ipaddr])
@tcp_port = options[:tcp_port]
end
end
class PbrLbTable
attr_reader :vserver
attr_reader :rservers
attr_reader :dsr
def initialize(options)
@vserver = PbrLbTableEntry.new(options[:vserver])
@rservers = []
options[:rservers].each do |each|
@rservers << PbrLbTableEntry.new(each)
end
@dsr = true if options[:dsr]
end
def balance_rserver(tcp_src_port)
puts "[PbrLbTable::balance_rserver #{tcp_src_port} -> Svr #{tcp_src_port %@rservers.length}]"
@rservers[tcp_src_port % @rservers.length]
end
def dsr?
@dsr
end
def dump
puts "[PbrLbTable::dump]"
puts "vserver: #{@vserver.ipaddr}, tcp/#{@vserver.tcp_port}"
@rservers.each do |each|
puts "rserver: #{each.ipaddr}, tcp/#{each.tcp_port}"
end
puts "dsr: #{@dsr}"
end
end
### Local variables:
### mode: Ruby
### coding: utf-8-unix
### indent-tabs-mode: nil
### End:
| true |
a5c0980a2fff7ff233715d880b5c596c5c48cbf9 | Ruby | JBlackN/budik | /lib/budik/devices.rb | UTF-8 | 4,427 | 2.765625 | 3 | [
"MIT"
] | permissive | # = devices.rb
# This file contains methods for managing devices (storage and TV).
#
# == Contact
#
# Author:: Petr Schmied (mailto:jblack@paworld.eu)
# Website:: http://www.paworld.eu
# Date:: September 20, 2015
module Budik
# 'Devices' class manages display and storage devices.
class Devices
include Singleton
# Loads TV and storage settings.
def initialize
options = Config.instance.options
@tv = {}
@storage = { mounted: nil, awake: nil, unmount: false }
tv_load(options['tv'])
storage_load(options['sources']['download'])
end
# Returns TV and storage settings.
attr_accessor :storage, :tv
# Loads storage settings.
#
# - *Args*:
# - +options+ -> Storage options (Hash).
#
def storage_load(options)
@storage[:device] = options['device']
@storage[:partition] = options['partition']
@storage[:dir] = options['dir']
part_sub = { '$partition': @storage[:partition] }
dev_sub = { '$device': @storage[:device] }
storage_parse_cmd('mount', options['mount'], part_sub, mounted: false)
storage_parse_cmd('unmount', options['unmount'], part_sub, unmount: true)
storage_parse_cmd('sleep', options['sleep'], dev_sub, awake: false)
end
# Substitutes device and partition in (un)mount and sleep commands.
#
# == Example
#
# cmd = 'sleep'
# template = 'sudo hdparm -y $device'
# subst = { '$device': '/dev/sda' }
# state_mods = { awake: false }
#
# Parsed command: 'sudo hdparm -y /dev/sda'
# State 'awake' set to false
#
# - *Args*:
# - +cmd+ -> Command ('mount', 'unmount' or 'sleep').
# - +template+ -> Command template (String).
# - +subst+ -> Variable to substitute (Hash, variable: value).
# - +state_mods+ -> State modifiers (Hash).
#
def storage_parse_cmd(cmd, template, subst, state_mods = {})
return if template.empty?
cmd = (cmd + '_command').to_sym
var, val = subst.first
@storage[cmd] = template.gsub(var.to_s, val)
state_mods.each { |state, setting| @storage[state] = setting }
end
# Mounts partition if needed and if not already mounted
# If applicable, sets 'mounted' and 'awake' states to true
def storage_mount
unless @storage[:mounted].nil? || @storage[:mounted] == true
system(@storage[:mount_command])
end
@storage[:mounted] = true unless @storage[:mounted].nil?
@storage[:awake] = true unless @storage[:awake].nil?
end
# Unmounts partition if needed and if mounted
# If applicable, sets 'mounted' state to false
def storage_unmount
unmount = !@storage[:unmount]
unless unmount || @storage[:mounted].nil? || @storage[:mounted] == false
system(@storage[:unmount_command])
end
@storage[:mounted] = false unless @storage[:mounted].nil?
end
# Spins device down if needed and if awake
# If applicable, sets 'awake' state to false
def storage_sleep
sleep_check = @storage[:awake].nil? || @storage[:awake] == false
unless sleep_check || @storage[:mounted] == true
system(@storage[:sleep_command])
end
@storage[:awake] = false unless @storage[:awake].nil?
end
# Loads TV settings if TV is available.
#
# - *Args*:
# - +options+ -> TV options (Hash).
#
def tv_load(options)
if options['available']
@tv[:use_if_no_video] = options['use_if_no_video']
@tv[:wait_secs_after_on] = options['wait_secs_after_on']
@tv[:on] = false
else
@tv[:on] = nil
end
end
# Turns on TV if needed and if not already on
# Gives TV time to turn on, then sets active HDMI as active source
# If applicable, sets 'on' state to true
def tv_on
unless @tv[:on].nil? || @tv[:on] == true
system('echo "on 0" | cec-client -s >/dev/null')
sleep(@tv[:wait_secs_after_on]) unless @tv[:wait_secs_after_on].nil?
system('echo "as" | cec-client -s >/dev/null')
end
@tv[:on] = true unless @tv[:on].nil?
end
# Turns off TV if needed and if on
# If applicable, sets 'on' state to false
# Doesn't work on my TV
def tv_off
unless @tv[:on].nil? || @tv[:on] == false
system('echo "standby 0" | cec-client -s >/dev/null')
end
@tv[:on] = false unless @tv[:on].nil?
end
end
end
| true |
1b01a845689e7f63ca592096d10b17e8dae9df9c | Ruby | mlarcher531/ruby-oo-relationships-practice-gym-membership-exercise-hou01-seng-ft-082420 | /tools/console.rb | UTF-8 | 374 | 3.140625 | 3 | [] | no_license | # You don't need to require any of the files in lib or pry.
# We've done it for you here.
require_relative '../config/environment.rb'
l1 = Lifter.new("Mike", 9000)
l2 = Lifter.new("J", 7000)
g1 = Gym.new("GloboGym")
g2 = Gym.new("Average Joe's")
m1 = Membership.new(20, g1, l1)
m2 = Membership.new(10, g2, l1)
m3 = Membership.new(500, g1, l2)
binding.pry
puts "Gains!"
| true |
74cad7b651c6c424c2fe878c38d40161f87763f8 | Ruby | rendon/algorithms_weekly_rally | /week05/SCHEDULE/gen.rb | UTF-8 | 134 | 2.875 | 3 | [] | no_license | #!/usr/bin/env ruby
puts 11 * 2 ** 10
0.upto(10) do |k|
0.upto(2**10 - 1) do |n|
puts "10 #{k}"
puts "%010b" % n
end
end
| true |
1ce860dfb44b5bbf2716c679f3e99e28f5011a22 | Ruby | orbanbotond/ruby_exercise | /spec/algorythms/alg_euclidean_02_common_prime_divisors_spec.rb | UTF-8 | 1,319 | 3.6875 | 4 | [] | no_license | require 'spec_helper'
describe 'Stone Wall' do
# you can use puts for debugging purposes, e.g.
# puts "this is a debug message"
def are_other_prime_divisors(x, common_prime_divisor)
while x > 1
gcd = x.gcd common_prime_divisor
break if gcd == 1
x /= gcd
end
x != 1
end
def has_same_prime_divisors(x,y)
gcd = x.gcd y
return false if are_other_prime_divisors(x,gcd)
return false if are_other_prime_divisors(y,gcd)
return true
end
def solution(a, b)
t = [a,b].transpose
t.count {|x| has_same_prime_divisors(x.first, x.last) }
end
specify 'empty' do
expect(solution([15, 10, 3], [75, 30, 5])).to eq(1)
end
specify 'just one' do
expect(solution([1], [1])).to eq(1)
end
specify 'wont pass' do
expect(solution([2], [8])).to eq(1)
end
specify 'empty' do
expect(solution([3, 9, 20, 11],[9, 81, 5, 13])).to eq(2)
end
specify 'empty' do
expect(solution([2, 1, 2], [1, 2, 2])).to eq(1)
end
specify 'simple test with small values' do
expect(solution([6059, 551],[442307, 303601])).to eq(2)
end
specify 'powers of prime' do
expect(solution([121, 8, 25, 81, 49],[11, 4, 125, 11, 7])).to eq(4)
end
specify 'small primes' do
expect(solution([7, 17, 5, 3],[7, 11, 5, 2])).to eq(2)
end
end
| true |
f9fb74befb81d0ce0aac92ba4c61a4960c357298 | Ruby | m1kal/exercism_ruby | /allergies/allergies.rb | UTF-8 | 415 | 3.390625 | 3 | [
"MIT"
] | permissive | class Allergies
ALLERGENS = %w(eggs peanuts shellfish strawberries
tomatoes chocolate pollen cats).freeze
def initialize(number)
@allergies = number.to_s(2).reverse
end
def allergic_to?(allergen)
@allergies[ALLERGENS.index(allergen)] == '1'
end
def list
@allergies.each_char.with_index.collect do |char, idx|
ALLERGENS[idx] if char == '1'
end.compact
end
end
| true |
779b563f9addc1fbc85dd35f12c19c2833c949c0 | Ruby | sherpanat/encrypt-246 | /encrypt.rb | UTF-8 | 593 | 3.46875 | 3 | [] | no_license | def encrypt(sentence)
alphabet = ("A".."Z").to_a
sentence.split("").map do |caracter|
caracter_upcased = caracter.upcase
old_index = alphabet.index(caracter_upcased)
old_index ? alphabet[old_index - 3] : caracter_upcased
end.join
end
# false
#on fait un tableau de lettres de l'alphabet
#on découpe la phrase en tableau de lettres
#pour chacune des lettres
#on recupère l'index de chacune des lettre
#si c'est un espace on ne fait rien
#on soustrait 3 à l'index
#on recupère dans l'alphabet la lettre du nouvel index
#on retourne cette nouvelle lettre
#on join tout ça
| true |
17d00d79195a7dabb708e1a10475120f2c9b5a87 | Ruby | fanjieqi/LeetCodeRuby | /101-200/130. Surrounded Regions.rb | UTF-8 | 1,311 | 3.828125 | 4 | [
"MIT"
] | permissive | AROUND = [
[-1, 0],
[+1, 0],
[0, -1],
[0, +1],
]
def solve_margin(board, points, x, y)
board[x][y] = "1"
points << [x, y]
AROUND.each do |i, j|
xx, yy = x + i, y + j
next if xx < 0 || yy < 0 || xx >= board.length || yy >= board[0].length
solve_margin(board, points, xx, yy) if board[xx][yy] == "O"
end
end
def solve_inner(board, x, y)
board[x][y] = "X"
AROUND.each do |i, j|
xx, yy = x + i, y + j
next if xx < 0 || yy < 0 || xx >= board.length || yy >= board[0].length
solve_inner(board, xx, yy) if board[xx][yy] == "O"
end
end
# @param {Character[][]} board
# @return {Void} Do not return anything, modify board in-place instead.
def solve(board)
m = board.length
return board if m <= 1
n = board[0].length
return board if n <= 1
points = []
(0..m-1).each do |i|
solve_margin(board, points, i, 0) if board[i][0] == "O"
solve_margin(board, points, i, n-1) if board[i][n-1] == "O"
end
(0..n-1).each do |i|
solve_margin(board, points, 0, i) if board[0][i] == "O"
solve_margin(board, points, m-1, i) if board[m-1][i] == "O"
end
(0..m-1).each do |i|
(0..n-1).each do |j|
solve_inner(board, i, j) if board[i][j] == "O"
end
end
points.each do |point|
board[point.first][point.last] = "O"
end
board
end
| true |
5def6a3e2f9c3bf96c475e2d51a79042ab6edb61 | Ruby | MtnBiker/Croatian-Restaurants-Rails-2 | /lib/tasks/import_addresses.rake | UTF-8 | 1,221 | 2.546875 | 3 | [] | no_license | #lib/tasks/import.rake
desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model] => [:environment] do |task,args|
lines = File.new(args[:filename]).readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
values = line.strip.split(',')
attributes = Hash[keys.zip values]
Module.const_get(args[:model]).create(attributes)
end
end
# From http://erikonrails.snowedin.net/?p=212
# rake csv_model_import[bunnies.csv,Bunny]
# File name and table name (BUT A RAILS NAME-SINGULAR)?
# rake csv_model_import[other/addresses1.csv,Address]
# NOTE CSV needs to have a header line with the attribute names, with commas and no spaces.
# No quotes needed in the csv data. Everything between the commas is imported.
# Works with default set for timestamp and city/state
# Note using Rails table name SINGULAR
# rake csv_model_import[other/addresses_import_using_rails_2015.10.11.csv,Address]
# So far the above isn't working
# unknown OID 25344: failed to recognize type of 'geom'. It will be treated as String.
# Used pgAdmin, but needed a created_at, so had to remove not NULL restriction, then had to paste date in so could continue to use Rails | true |
c3c43f603a2e7a186480dfc3e200a88d3dfac59a | Ruby | dudemcbacon/poop_dominos | /controller.rb | UTF-8 | 1,985 | 2.84375 | 3 | [] | no_license | require 'sinatra'
require 'rmagick'
require 'httparty'
AGENT_URL = "https://agent.electricimp.com/IxdMGFT6Ie3p/image"
WIDTH = 264
HEIGHT = 176
WHITE = 0
BLACK = 1
get '/start' do
image = start_page
prepare_image(image)
end
get '/pizza' do
filepath = File.dirname(__FILE__) + '/static/pizza.png'
logger.warn filepath
image = Magick::Image.read(filepath).first
prepare_image(image)
end
get '/poop' do
filepath = File.dirname(__FILE__) + '/static/poop.png'
logger.warn filepath
logger.warn Dir.entries File.dirname(__FILE__) + '/static'
image = Magick::Image.read(filepath).first
prepare_image(image)
end
def test(image)
image.rotate!(180)
pixels = image.export_pixels(0, 0, WIDTH, HEIGHT, 'I')
options = {
:body => interlace(pixels)
}
puts options
HTTParty.post(AGENT_URL, options)
end
def interlace(pixels)
image = ""
pixels.each_slice(WIDTH) do |row|
binned_pixels = row.map{|x| x > 0 ? WHITE : BLACK}
image << [binned_pixels.join].pack("B*")
end
return image
end
def start_page
canvas = Magick::Image.new(264, 176){self.background_color = 'white'}
gc = Magick::Draw.new
gc.font_weight = Magick::BoldWeight
gc.annotate(canvas, 0, 0, 0, -10, "Choose Wisely") {
self.gravity = Magick::CenterGravity
self.font = "Helvetica-Narrow-Bold"
self.pointsize = 40
}
gc.annotate(canvas, 0, 0, 2, 2, "Poop") {
self.gravity = Magick::SouthWestGravity
self.pointsize = 26
self.font = "Helvetica-Bold"
}
gc.annotate(canvas, 0, 0, 2, 2, "Dominos") {
self.gravity = Magick::SouthEastGravity
self.pointsize = 26
self.font = "Helvetica-Bold"
}
return canvas
end
def prepare_image(image)
image.rotate!(180)
pixels = image.export_pixels(0, 0, WIDTH, HEIGHT, 'I')
pixels = pixels.map{|x| x > 0 ? WHITE : BLACK}
return format_pixels(pixels)
end
def format_pixels(pixels)
line = ""
pixels.each_slice(WIDTH) do |row|
line << [row.join].pack("B*")
end
return line
end
| true |
77433289d835e5f89aafaf0d1e30d2033a937c41 | Ruby | Pamela454/cartoon-collections-v-000 | /cartoon_collections.rb | UTF-8 | 616 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def roll_call_dwarves(dwarves)
# code an argument here
# Your code here
dwarves.each_with_index do |dwarf, index|
puts "#{index + 1}, #{dwarf}."
end
end
def summon_captain_planet(planeteer)
planeteer.map do |planet|
"#{planet.capitalize + "!"}"
end
end
def long_planeteer_calls(calls)# code an argument here
# Your code here
calls.any? {|call| call.length > 4 }
end
def find_the_cheese(ingredients)# code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
ingredients.find do |ingredient|
cheese_types.include?(ingredient)
end
end
| true |
8754a4c83100223176d8916484166d597e019825 | Ruby | nklammer/zedg_multifamily | /analyses/osw_2_osa_multizedg.rb | UTF-8 | 27,544 | 2.546875 | 3 | [
"MIT"
] | permissive | # this will convert an OSW file to an OSA file
# additionally it can gather files for the analysis zip file
# It works by populating the workflow of a template OSA file with measure steps from the OSW
# ARGV[0] json file is generated unless false
# ARGV[1] zip file is generated unless false
# todo - add in arg for server name, nil if you don't want to send to server
# ARGV[2] analysis name
# ARGV[3] path relative path to source osw (can also be picked based on analysis name in ARGV[2])
# todo - break generic code used to do osw_2_osa to seprate file that is then called by this custom script
# todo - setup data file for variable sets instead of storing in the ruby script
# load dependencies
require 'fileutils'
require 'openstudio'
require 'json'
# setup arguments to control if json and zip files are made
if ARGV[0] == "false"
make_json = false
else
make_json = true
end
if ARGV[1] == "false"
make_zip = false
else
make_zip = true
end
if ARGV[2].nil?
# default to location sweep only
var_set = "location"
else
var_set = ARGV[2]
# supported var_set values
# location (default)
# constructions
# hvac
# swh (NA - is really about using different OSW for stratified tank)
# central_swh
# best
# all (add in the future)
# new runs added 11/22 for running on 2.9.0
# const2
# hvac2
# swh2
# new runs added 12/22 for high/low density as well as number of floors study
# density_low
# density_high
# don't need densitry_regular, that is the swh2 run
# floor_multi
# new added 12/27 for detailed results of small number of runs
# best2
# best2b
# new added 1/3 to look at lower appliance level
# appl
# new 1/9 to look at com vs res
# swh2_com
# swh2_res
# new 1/30 custom wall const, roof const, hrv and wwr for best
# best3a-e
# swh3 (like swh2 but just in unit swh as arg not variable)
end
# valid variable sets
valid_sets = ['location','constructions','hvac','swh','best','central_swh','const2','hvac2','swh2','density_low','density_high','floor_multi','best2','best2b','appl','swh2_com','swh2_res','best3a','best3b','best3c','best3d','best3e','swh3']
if !valid_sets.include?(var_set)
puts "this is an unexpected variable set, script is stopping"
return false
end
if ARGV[3].nil?
# add logic to use different default based on analysis chosen
if ['swh','best'].include?(var_set)
osw_path = OpenStudio::Path.new("../workflows/json_test_chicago_stratified_hpwh/floorplan.osw")
elsif ['central_swh','const2','hvac2','swh2','best2','best2b','appl','swh2_com','swh2_res','best3a','best3b','best3c','best3d','best3e','swh3'].include?(var_set)
osw_path = OpenStudio::Path.new("../workflows/json_chicago_central_swh/floorplan.osw")
elsif ['density_low'].include?(var_set)
osw_path = OpenStudio::Path.new("../workflows/low_dens_central_swh/floorplan.osw")
elsif ['density_high'].include?(var_set)
osw_path = OpenStudio::Path.new("../workflows/high_dens_central_swh/floorplan.osw")
elsif ['floor_multi'].include?(var_set)
osw_path = OpenStudio::Path.new("../workflows/story_mult_json_chi_ctr/floorplan.osw")
else
osw_path = OpenStudio::Path.new("../workflows/json_test_chicago/floorplan.osw")
end
puts "source OSW is #{osw_path}"
else
osw_path = ARGV[3]
end
# todo - add argument for template OSA
# load a copy of template OSA file
project_name = "osw_2_osa_zedg_multi_#{var_set}"
osa_template_path = "osa_template_doe.json"
analysis_files_path = "analysis_files"
run_directory = "run"
Dir.mkdir(run_directory) unless File.exists?(run_directory)
osa_target_path = "#{run_directory}/#{project_name}.json"
zip_path = "#{run_directory}/#{project_name}.zip"
json = File.read(osa_template_path)
hash = JSON.parse(json)
puts "loading template OSA"
# update name and display name
base_display_name = hash["analysis"]["display_name"]
base_name = hash["analysis"]["name"]
hash["analysis"]["display_name"] = "#{hash["analysis"]["display_name"]}_#{var_set}"
hash["analysis"]["name"] = "#{hash["analysis"]["name"]}_#{var_set}"
# load OSW file
osw = OpenStudio::WorkflowJSON.load(osw_path).get
runner = OpenStudio::Measure::OSRunner.new(osw)
workflow = runner.workflow
# hash to name measures with multiple instances
measures_used_hash = {} # key is measure value is an array of instances, will help me to index name when used multiple times
var_used_hash = {} # key variable name value is number of instances of similar name, will help me to index name when used multiple times
workflow_index = 0
# make zip file
if make_zip
zip_file = OpenStudio::ZipFile.new(zip_path,false)
puts "generating analysis zip file"
# bring in scripts (not from OSW)
puts "adding scripts to analysis zip"
zip_file.addDirectory("#{analysis_files_path}/scripts","scripts")
# bring in external files (hard coded for now vs. dynamic from OSW)
puts "adding external files to analysis zip"
zip_file.addDirectory("#{analysis_files_path}/files","lib/files")
# bring in all weather files
puts "adding weather files to analysis zip"
zip_file.addDirectory("../weather","weather")
end
# setup seed file
if workflow.seedFile.is_initialized
seed_file = workflow.seedFile.get
puts "setting seed file to #{seed_file}"
hash["analysis"]["seed"]= {"file_type" => "OSM","path" => "./seeds/#{seed_file}"}
if zip_file
source_path = workflow.findFile(seed_file).get
puts "adding seed model to analysis zip"
zip_file.addFile(source_path,OpenStudio::Path.new("seeds/#{seed_file}"))
end
end
# setup weather file
if workflow.weatherFile.is_initialized
weather_file = workflow.weatherFile.get
puts "setting weather_file to #{weather_file}"
hash["analysis"]["weather_file"]= {"file_type" => "EPW","path" => "./weather/#{weather_file}"}
# code below isn't necessary unless OSW weather file is not in the repo 'weather' directory
if zip_file
source_path = workflow.findFile(weather_file).get
puts "confirming weather file is in analysis zip"
zip_file.addFile(source_path,OpenStudio::Path.new("weather/#{weather_file}"))
end
end
# todo - I can't figure out how to setup an OSA to run with null seed or weather. While it is valid for an OSW, I don't know if it is valid for an OSA
# define discrete variables (nested hash of measure instance name and argument name)
desc_vars = {}
# weather_file
var_epw = []
# temp change in hvc2 and swh2 for test run
if ['best','location','hvac2','const2','swh2','density_low','density_high','floor_multi','floor_multi','best2','best2b','swh2_com','swh2_res','swh3'].include?(var_set)
var_epw << 'USA_AK_Fairbanks.Intl.AP.702610_TMY3.epw' #8
var_epw << 'USA_AZ_Davis-Monthan.AFB.722745_TMY3.epw' #2B
var_epw << 'USA_CA_Chula.Vista-Brown.Field.Muni.AP.722904_TMY3.epw' #3C
var_epw << 'USA_CO_Aurora-Buckley.Field.ANGB.724695_TMY3.epw' #5B
var_epw << 'USA_FL_MacDill.AFB.747880_TMY3.epw' #2A
var_epw << 'USA_GA_Atlanta-Hartsfield-Jackson.Intl.AP.722190_TMY3.epw' #3A
var_epw << 'USA_HI_Honolulu.Intl.AP.911820_TMY3.epw' #1A
var_epw << 'USA_MN_International.Falls.Intl.AP.727470_TMY3.epw' #7
var_epw << 'USA_MN_Rochester.Intl.AP.726440_TMY3.epw' #6A
var_epw << 'USA_MT_Great.Falls.Intl.AP.727750_TMY3.epw' #6B
var_epw << 'USA_NM_Albuquerque.Intl.AP.723650_TMY3.epw' #4B
var_epw << 'USA_NY_Buffalo-Greater.Buffalo.Intl.AP.725280_TMY3.epw' #5A
var_epw << 'USA_NY_New.York-J.F.Kennedy.Intl.AP.744860_TMY3.epw' #4A
var_epw << 'USA_TX_El.Paso.Intl.AP.722700_TMY3.epw' #3B
var_epw << 'USA_WA_Port.Angeles-William.R.Fairchild.Intl.AP.727885_TMY3.epw' #5C
var_epw << 'USA_WA_Seattle-Tacoma.Intl.AP.727930_TMY3.epw' #4c
var_epw << 'VNM_Hanoi.488200_IWEC.epw' #0A
var_epw << 'ARE_Abu.Dhabi.412170_IWEC.epw' #0B
var_epw << 'IND_New.Delhi.421820_ISHRAE.epw' #1B
elsif var_set == "best3a"
var_epw << 'VNM_Hanoi.488200_IWEC.epw' #0A
var_epw << 'USA_NY_New.York-J.F.Kennedy.Intl.AP.744860_TMY3.epw' #4A
var_epw << 'USA_NY_Buffalo-Greater.Buffalo.Intl.AP.725280_TMY3.epw' #5A
var_epw << 'USA_MN_Rochester.Intl.AP.726440_TMY3.epw' #6A
var_epw << 'USA_MN_International.Falls.Intl.AP.727470_TMY3.epw' #7
var_epw << 'USA_AK_Fairbanks.Intl.AP.702610_TMY3.epw' #8
elsif var_set == "best3b"
var_epw << 'ARE_Abu.Dhabi.412170_IWEC.epw' #0B
var_epw << 'USA_HI_Honolulu.Intl.AP.911820_TMY3.epw' #1A
var_epw << 'IND_New.Delhi.421820_ISHRAE.epw' #1B
elsif var_set == "best3c"
var_epw << 'USA_FL_MacDill.AFB.747880_TMY3.epw' #2A
var_epw << 'USA_AZ_Davis-Monthan.AFB.722745_TMY3.epw' #2B
var_epw << 'USA_GA_Atlanta-Hartsfield-Jackson.Intl.AP.722190_TMY3.epw' #3A
var_epw << 'USA_TX_El.Paso.Intl.AP.722700_TMY3.epw' #3B
var_epw << 'USA_NM_Albuquerque.Intl.AP.723650_TMY3.epw' #4B
var_epw << 'USA_WA_Seattle-Tacoma.Intl.AP.727930_TMY3.epw' #4c
var_epw << 'USA_CO_Aurora-Buckley.Field.ANGB.724695_TMY3.epw' #5B
var_epw << 'USA_MT_Great.Falls.Intl.AP.727750_TMY3.epw' #6B
elsif var_set == "best3d"
var_epw << 'USA_WA_Port.Angeles-William.R.Fairchild.Intl.AP.727885_TMY3.epw' #5C
var_epw << 'mean to fail.epw' # just added so results csv match other best3 analysis results
elsif var_set == "best3e"
var_epw << 'USA_CA_Chula.Vista-Brown.Field.Muni.AP.722904_TMY3.epw' #3C
var_epw << 'mean to fail.epw' # just added so results csv match other best3 analysis results
elsif 1 == 2 # temp code to run opposite of short set add to earlier run
var_epw << 'USA_AK_Fairbanks.Intl.AP.702610_TMY3.epw' #8
var_epw << 'USA_CO_Aurora-Buckley.Field.ANGB.724695_TMY3.epw' #5B
var_epw << 'USA_FL_MacDill.AFB.747880_TMY3.epw' #2A
var_epw << 'USA_HI_Honolulu.Intl.AP.911820_TMY3.epw' #1A
var_epw << 'USA_MN_Rochester.Intl.AP.726440_TMY3.epw' #6A
var_epw << 'USA_MT_Great.Falls.Intl.AP.727750_TMY3.epw' #6B
var_epw << 'USA_NM_Albuquerque.Intl.AP.723650_TMY3.epw' #4B
var_epw << 'USA_NY_New.York-J.F.Kennedy.Intl.AP.744860_TMY3.epw' #4A
var_epw << 'USA_TX_El.Paso.Intl.AP.722700_TMY3.epw' #3B
var_epw << 'USA_WA_Port.Angeles-William.R.Fairchild.Intl.AP.727885_TMY3.epw' #5C
var_epw << 'USA_WA_Seattle-Tacoma.Intl.AP.727930_TMY3.epw' #4c
var_epw << 'VNM_Hanoi.488200_IWEC.epw' #0A
var_epw << 'ARE_Abu.Dhabi.412170_IWEC.epw' #0B
var_epw << 'IND_New.Delhi.421820_ISHRAE.epw' #1B
else
#var_epw << 'USA_AK_Fairbanks.Intl.AP.702610_TMY3.epw' #8
var_epw << 'USA_AZ_Davis-Monthan.AFB.722745_TMY3.epw' #2B
var_epw << 'USA_CA_Chula.Vista-Brown.Field.Muni.AP.722904_TMY3.epw' #3C
#var_epw << 'USA_CO_Aurora-Buckley.Field.ANGB.724695_TMY3.epw' #5B
#var_epw << 'USA_FL_MacDill.AFB.747880_TMY3.epw' #2A
var_epw << 'USA_GA_Atlanta-Hartsfield-Jackson.Intl.AP.722190_TMY3.epw' #3A
#var_epw << 'USA_HI_Honolulu.Intl.AP.911820_TMY3.epw' #1A
var_epw << 'USA_MN_International.Falls.Intl.AP.727470_TMY3.epw' #7
#var_epw << 'USA_MN_Rochester.Intl.AP.726440_TMY3.epw' #6A
#var_epw << 'USA_MT_Great.Falls.Intl.AP.727750_TMY3.epw' #6B
#var_epw << 'USA_NM_Albuquerque.Intl.AP.723650_TMY3.epw' #4B
var_epw << 'USA_NY_Buffalo-Greater.Buffalo.Intl.AP.725280_TMY3.epw' #5A
#var_epw << 'USA_NY_New.York-J.F.Kennedy.Intl.AP.744860_TMY3.epw' #4A
#var_epw << 'USA_TX_El.Paso.Intl.AP.722700_TMY3.epw' #3B
#var_epw << 'USA_WA_Port.Angeles-William.R.Fairchild.Intl.AP.727885_TMY3.epw' #5C
#var_epw << 'USA_WA_Seattle-Tacoma.Intl.AP.727930_TMY3.epw' #4c
end
# chicago just in for testing, not part of climate zone set used for K12 and office ZEDG
#var_epw << 'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3.epw'
# setup weather file variable
desc_vars['ChangeBuildingLocation'] = {}
desc_vars['ChangeBuildingLocation']['weather_file_name'] = var_epw
# setup variable for zero_energy_multifamily
desc_vars['zero_energy_multifamily'] = {}
# hvac_system
# for constructions and swh use static value from OSW which should be set ot Fain Coils + DOAS
if ['hvac','hvac2'].include?(var_set)
var_hvac = []
var_hvac << 'Minisplit Heat Pumps with DOAS'
var_hvac << 'Minisplit Heat Pumps with ERVs'
var_hvac << 'Four-pipe Fan Coils with central air-source heat pump with DOAS'
var_hvac << 'Four-pipe Fan Coils with central air-source heat pump with ERVs'
var_hvac << 'PTHPs with DOAS'
var_hvac << 'PTHPs with ERVs'
var_hvac << 'Water Source Heat Pumps with Boiler and Fluid-cooler with DOAS'
var_hvac << 'Water Source Heat Pumps with Boiler and Fluid-cooler with ERVs'
desc_vars['zero_energy_multifamily']['hvac_system_type'] = var_hvac
elsif ["best","central_swh"].include?(var_set)
var_hvac = []
var_hvac << 'Minisplit Heat Pumps with DOAS'
var_hvac << 'Minisplit Heat Pumps with ERVs'
var_hvac << 'Four-pipe Fan Coils with central air-source heat pump with DOAS'
var_hvac << 'Four-pipe Fan Coils with central air-source heat pump with ERVs'
desc_vars['zero_energy_multifamily']['hvac_system_type'] = var_hvac
elsif ['swh2','density_low','density_high','floor_multi','swh2_com','swh2_res','best2'].include?(var_set)
var_hvac = []
var_hvac << 'Minisplit Heat Pumps with ERVs'
var_hvac << 'Four-pipe Fan Coils with central air-source heat pump with DOAS'
desc_vars['zero_energy_multifamily']['hvac_system_type'] = var_hvac
elsif ['best3a','best3b','best3c','best3d','best3e','swh3'].include?(var_set)
var_hvac = []
var_hvac << 'Minisplit Heat Pumps with ERVs'
var_hvac << 'Four-pipe Fan Coils with central air-source heat pump with DOAS'
var_hvac << 'Water Source Heat Pumps with Boiler and Fluid-cooler with ERVs'
desc_vars['zero_energy_multifamily']['hvac_system_type'] = var_hvac
end
# wall_roof_construction_template and window_construction_template
# for best use static value from OSW
if ['constructions','const2'].include?(var_set)
var_const_roof_wall = []
var_const_roof_wall << '90.1-2019'
var_const_roof_wall << 'Good'
var_const_roof_wall << 'Better'
var_const_roof_wall << 'ZE AEDG Multifamily Recommendations'
desc_vars['zero_energy_multifamily']['wall_roof_construction_template'] = var_const_roof_wall
var_const_window = []
var_const_window << '90.1-2019'
var_const_window << 'Good'
var_const_window << 'Better'
var_const_window << 'ZE AEDG Multifamily Recommendations'
desc_vars['zero_energy_multifamily']['window_construction_template'] = var_const_window
elsif ['hvac','swh','hvac2'].include?(var_set)
var_const_roof_wall = []
var_const_roof_wall << '90.1-2019'
var_const_roof_wall << 'ZE AEDG Multifamily Recommendations'
desc_vars['zero_energy_multifamily']['wall_roof_construction_template'] = var_const_roof_wall
var_const_window = []
var_const_window << '90.1-2019'
var_const_window << 'ZE AEDG Multifamily Recommendations'
desc_vars['zero_energy_multifamily']['window_construction_template'] = var_const_window
end
# todo - infiltration (unless we can setup this happens with construction)
# todo - construction type for wall
# window to wall ratio all facades
# when if wanted to use second instance of measure key would be SetWindowToWallRatioByFacade_2
# for hvac use static value from OSW
if ['constructions','const2'].include?(var_set)
var_wwr = [0.2,0.3,0.4]
desc_vars['SetWindowToWallRatioByFacade'] = {}
desc_vars['SetWindowToWallRatioByFacade']['wwr'] = var_wwr
=begin
elsif ['swh','best','best3a','best3b','best3c','best3d','best3e'].include?(var_set)
var_wwr = [0.2,0.3]
desc_vars['SetWindowToWallRatioByFacade'] = {}
desc_vars['SetWindowToWallRatioByFacade']['wwr'] = var_wwr
=end
end
# rotation
# for hvac and best use static value from osw
if ['constructions','const2'].include?(var_set)
var_rotation = [0.0,45.0,90.0]
desc_vars['RotateBuilding'] = {}
desc_vars['RotateBuilding']['relative_building_rotation'] = var_rotation
elsif var_set == "swh"
var_rotation = [0.0,90.0]
desc_vars['RotateBuilding'] = {}
desc_vars['RotateBuilding']['relative_building_rotation'] = var_rotation
end
# swh
if ['central_swh','swh2','density_low','density_high','floor_multi','swh2_com','swh2_res'].include?(var_set)
var_swh = []
var_swh << "Waste Water Heat Pump 140F Supply"
var_swh << "Waste Water Heat Pump 120F Supply and Electric Tank"
var_swh << "Waste Water Heat Pump 90F Supply and Electric Tank"
var_swh << "HPWH with Outdoor Condenser"
desc_vars['multifamily_central_wwhp'] = {}
desc_vars['multifamily_central_wwhp']['swh_type'] = var_swh
=begin
elsif ['best2','best2b'].include?(var_set)
desc_vars['multifamily_central_wwhp'] = {}
desc_vars['multifamily_central_wwhp']['__SKIP__'] = [true,false]
=end
end
# erv to hrv (1/9 moved swh2 here from nat vent)
if ['hvac2','swh2_com','swh2_res','best3a','best3b','best3c','best3d','best3e','swh3'].include?(var_set)
var_erv_hrv = []
var_erv_hrv << true
var_erv_hrv << false
desc_vars['set_ervs_to_hrvs'] = {}
desc_vars['set_ervs_to_hrvs']['__SKIP__'] = var_erv_hrv
end
# nat vent
if ['hvac2'].include?(var_set)
var_nat_vent = []
var_nat_vent << true
var_nat_vent << false
desc_vars['add_wind_and_stack_open_area'] = {}
desc_vars['add_wind_and_stack_open_area']['__SKIP__'] = var_nat_vent
end
# story multiplier
if ['floor_multi'].include?(var_set)
#var_multi = [1,2,3,4,5,5,6,7,12,17,37] # for doubles passing value not string is fine, but for integer it seems string is necessary
var_multi = ["1","2","3","4","5","6","7","12","17","37"]
desc_vars['change_zone_multiplier_by_building_story'] = {}
desc_vars['change_zone_multiplier_by_building_story']['multiplier_adj'] = var_multi
end
# older appliances
if ['appl'].include?(var_set)
var_frig = [348.0,434.0]
desc_vars['ResidentialApplianceRefrigerator'] = {}
desc_vars['ResidentialApplianceRefrigerator']['rated_annual_energy'] = var_frig
end
if ['appl'].include?(var_set)
var_frig = [5.2,4.5]
desc_vars['ResidentialApplianceClothesDryer'] = {}
desc_vars['ResidentialApplianceClothesDryer']['cef'] = var_frig
end
# populate workflow of OSA with steps from OSW
puts "processing source OSW"
workflow.workflowSteps.each do |step|
if step.to_MeasureStep.is_initialized
measure_step = step.to_MeasureStep.get
measure_dir_name = measure_step.measureDirName
puts " - gathering data for #{measure_dir_name}"
if zip_file
source_path = workflow.findMeasure(measure_dir_name.to_s).get
zip_file.addDirectory(source_path,OpenStudio::Path.new("measures/#{measure_dir_name}"))
end
# check if measure already exists
if measures_used_hash.has_key?(measure_dir_name)
measures_used_hash[measure_dir_name] += 1
inst_name = "#{measure_dir_name}_#{measures_used_hash[measure_dir_name]}"
else
inst_name = measure_dir_name
measures_used_hash[measure_dir_name] = 1
end
new_workflow_measure = {}
new_workflow_measure["name"] = inst_name.downcase # would be better to snake_case
new_workflow_measure["display"] = inst_name.downcase # would be better to snake_case
new_workflow_measure["measure_definition_directory"] = "./measures/#{measure_dir_name}"
if measure_step.arguments.size > 0
new_workflow_measure["arguments"] = []
end
measure_step.arguments.each do |k,v|
if v.to_s == "true" then v = true end
if v.to_s == "false" then v = false end
# remap argument that relies on external files in OSW that I have not figured out how to implement in OSA
if k == "floorplan_path"
arg_hash = {"name" => k,"value" => "../lib/files/#{v}"}
else
arg_hash = {"name" => k,"value" => v}
end
# add changes for best2
if ["best2"].include?(var_set)
if measure_dir_name == "openstudio_results" && k == "zone_condition_section"
arg_hash = {"name" => k,"value" => true}
elsif measure_dir_name == "envelope_and_internal_load_breakdown" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => false}
elsif measure_dir_name == "ResidentialHotWaterHeaterTank" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => true}
elsif measure_dir_name == "ResidentialHotWaterHeaterHeatPump" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => false}
elsif measure_dir_name == "multifamily_central_wwhp" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => true}
end
elsif ['swh3'].include?(var_set)
if measure_dir_name == "ResidentialHotWaterHeaterTank" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => true}
elsif measure_dir_name == "ResidentialHotWaterHeaterHeatPump" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => false}
elsif measure_dir_name == "multifamily_central_wwhp" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => true}
end
elsif ["best2b"].include?(var_set)
if measure_dir_name == "openstudio_results" && k == "zone_condition_section"
arg_hash = {"name" => k,"value" => true}
elsif measure_dir_name == "envelope_and_internal_load_breakdown" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => false}
end
elsif ["best3a"].include?(var_set)
if measure_dir_name == "zero_energy_multifamily" && k == "wall_roof_construction_template"
arg_hash = {"name" => k,"value" => 'ZE AEDG Multifamily Recommendations'}
elsif measure_dir_name == "zero_energy_multifamily" && k == "window_construction_template"
arg_hash = {"name" => k,"value" => 'ZE AEDG Multifamily Recommendations'}
elsif measure_dir_name == "multifamily_central_wwhp" && k == "swh_type"
arg_hash = {"name" => k,"value" => 'Waste Water Heat Pump 140F Supply'}
end
elsif ["best3b"].include?(var_set)
if measure_dir_name == "zero_energy_multifamily" && k == "wall_roof_construction_template"
arg_hash = {"name" => k,"value" => 'ZE AEDG Multifamily Recommendations'}
elsif measure_dir_name == "zero_energy_multifamily" && k == "window_construction_template"
arg_hash = {"name" => k,"value" => 'Good'}
elsif measure_dir_name == "multifamily_central_wwhp" && k == "swh_type"
arg_hash = {"name" => k,"value" => 'Waste Water Heat Pump 140F Supply'}
end
elsif ["best3c"].include?(var_set)
if measure_dir_name == "zero_energy_multifamily" && k == "wall_roof_construction_template"
arg_hash = {"name" => k,"value" => 'Better'}
elsif measure_dir_name == "zero_energy_multifamily" && k == "window_construction_template"
arg_hash = {"name" => k,"value" => 'Better'}
elsif measure_dir_name == "multifamily_central_wwhp" && k == "swh_type"
arg_hash = {"name" => k,"value" => 'Waste Water Heat Pump 140F Supply'}
end
elsif ["best3d"].include?(var_set)
if measure_dir_name == "zero_energy_multifamily" && k == "wall_roof_construction_template"
arg_hash = {"name" => k,"value" => '90.1-2019'}
elsif measure_dir_name == "zero_energy_multifamily" && k == "window_construction_template"
arg_hash = {"name" => k,"value" => 'Better'}
elsif measure_dir_name == "multifamily_central_wwhp" && k == "swh_type"
arg_hash = {"name" => k,"value" => 'Waste Water Heat Pump 140F Supply'}
end
elsif ["best3e"].include?(var_set)
if measure_dir_name == "zero_energy_multifamily" && k == "wall_roof_construction_template"
arg_hash = {"name" => k,"value" => '90.1-2019'}
elsif measure_dir_name == "zero_energy_multifamily" && k == "window_construction_template"
arg_hash = {"name" => k,"value" => '90.1-2019'}
elsif measure_dir_name == "multifamily_central_wwhp" && k == "swh_type"
arg_hash = {"name" => k,"value" => 'Waste Water Heat Pump 140F Supply'}
end
elsif ["swh2_com"].include?(var_set)
if measure_dir_name == "set_exterior_walls_and_floors_to_adiabatic" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => false}
elsif measure_dir_name == "set_exterior_walls_and_floors_to_adiabatic" && k == "ext_roofs"
arg_hash = {"name" => k,"value" => true}
elsif measure_dir_name == "ResidentialGeometryCreateFromFloorspaceJS" && k == "floorplan_path"
arg_hash = {"name" => k,"value" => "../lib/files/floorplan_com_only.json"}
elsif measure_dir_name == "ResidentialGeometryCreateFromFloorspaceJS" && k == "num_bedrooms"
arg_hash = {"name" => k,"value" => "0"} #not sure what to do when no units
end
elsif ["swh2_res"].include?(var_set)
if measure_dir_name == "set_exterior_walls_and_floors_to_adiabatic" && k == "__SKIP__"
arg_hash = {"name" => k,"value" => false}
elsif measure_dir_name == "set_exterior_walls_and_floors_to_adiabatic" && k == "ground_floors"
arg_hash = {"name" => k,"value" => true}
elsif measure_dir_name == "ResidentialGeometryCreateFromFloorspaceJS" && k == "floorplan_path"
arg_hash = {"name" => k,"value" => "../lib/files/floorplan_res_only.json"}
end
end
if desc_vars.has_key?(inst_name) && desc_vars[inst_name].has_key?(k)
# setup variable
if !new_workflow_measure.has_key?("variables")
new_workflow_measure["variables"] = []
end
new_var = {}
new_workflow_measure['variables'] << new_var
new_var['argument'] = arg_hash
if var_used_hash.has_key?(k)
var_used_hash[k] += 1
new_var['display_name'] = "#{k}_#{var_used_hash[k]}"
else
var_used_hash[k] = 1
new_var['display_name'] = k
end
new_var['variable_type'] = 'variable'
new_var['variable'] = true
new_var['static_value'] = v
new_var['uncertainty_description'] = {}
new_var['uncertainty_description']['type'] = 'discrete'
new_var['uncertainty_description']['attributes'] = []
attribute_hash = {}
attribute_hash['name'] = 'discrete'
values_and_weights = []
desc_vars[inst_name][k].each do |val|
# weight not important for DOE but may want to store with values for other use cases
values_and_weights << {'value' => val, 'weight' => 1.0/desc_vars[inst_name][k].size}
end
attribute_hash['values_and_weights'] = values_and_weights
new_var['uncertainty_description']['attributes'] << attribute_hash
else
# setup argument
new_workflow_measure["arguments"] << arg_hash
if !new_workflow_measure.has_key?("variables")
new_workflow_measure["variables"] = []
end
end
end
new_workflow_measure["workflow_index"] = workflow_index
workflow_index += 1
hash["analysis"]["problem"]["workflow"] << new_workflow_measure
else
#puts "This step is not a measure"
end
end
# save OSW file
if make_json
puts "saving modified OSA"
#puts JSON.pretty_generate(hash)
hash.to_json
File.open(osa_target_path, "w") do |f|
f.puts JSON.pretty_generate(hash)
end
end
# report number of variables
measures_with_vars = []
vars = []
var_vals = []
puts "-----"
desc_vars.each do |k,v|
measures_with_vars << k
v.each do |k2,v2|
puts "#{v2.size} variables for #{k2}: #{v2.inspect}"
vars << k2
var_vals << v2.size
end
end
puts "-----"
puts "#{measures_with_vars.size} measures have variables #{measures_with_vars.inspect}."
puts "The analysis has #{vars.size} variables #{vars.inspect}."
puts "With DOE algorithm the analysis will have #{var_vals.inject(:*)} datapoints."
# todo - put a break in the script to see if the user wants to send the analysis to the server (if arg for server address is not nil)
# todo - add in meta-cli call here as well,
| true |
67c57b4e4dbdddb474882259c577e5fa1acdb5a9 | Ruby | ryu2129/paiza | /Brank/3-3.rb | UTF-8 | 103 | 3.703125 | 4 | [] | no_license | #文字列が入力されるので、その長さを出力してください。
n = gets
puts n.length | true |
d43034905fad1e438bb51c4b8d753ae02e063b10 | Ruby | davidprea/freezing-shame | /monsters/orc.rb | UTF-8 | 4,813 | 2.796875 | 3 | [] | no_license | require './monster'
class Orc < Monster
def initialize
super
end
def self.armors
result = super
result[:orc_armor] = Armor.new("Orc armor", 3, 0)
return result
end
def self.weapons
result = super
result[:bent_sword] = Weapon.new( "Bent Sword", 4, 10, 12, 0, :one_handed, :disarm );
result[:bow_of_horn] = Weapon.new( "Bow of Horn", 4, 10, 12, 0, :ranged, :poison)
result[:broad_bladed_sword] = Weapon.new("Broad-bladed Sword", 5, 10, 14, 0, :one_handed, :poison)
result[:broad_headed_spear] = Weapon.new("Broad-headed Spear", 5, 10, 12, 0, :one_handed, :pierce)
result[:heavy_scimitar] = Weapon.new("Heavy Scimitar", 7, 10, 14, 0, :two_handed, :break_shield)
result[:orc_axe] = Weapon.new( "Orc-axe", 5, 12, 16, 0, :one_handed, :break_shield );
result[:spear] = Weapon.new("Spear", 4, 9, 12, 0, :versatile, :pierce)
result[:jagged_knife] = Weapon.new("Jagged Kinfe", 3, 12, 14, 0, :one_handed, :nil)
result[:stone_spear] = Weapon.new("Stone Spear", 4, 10, 12, 0, :one_handed, :pierce)
result
end
def self.types
result = {}
result[:goblin_archer] = { :name => "Goblin Archer", :size => 1, :attribute_level => 2, :endurance => 8, :hate => 1, :parry => 2, :shield => 0, :armor => 2, :weapons => [{ :type=>:bow_of_horn,:skill => 2, :favoured => true}, {:type=>:jagged_knife,:skill => 1 }], :abilities => [:hate_sunlight, :denizen_of_the_dark, :craven],
:optional_abilities => [:dwarf_hatred, :hobbit_hatred] }
result[:orc_guard] =
{
:name => "Orc Guard",
:size => 2,
:attribute_level => 4,
:endurance => 16,
:hate => 3,
:parry => 4,
:shield => 2,
:armor => 2,
:armor_favoured => true,
:weapons => [
{ :type=>:spear,:skill => 3},
{:type=>:bent_sword,:skill => 2 }],
:abilities => [:hate_sunlight, :hideous_toughness],
:optional_abilities => [:dwarf_hatred, :hobbit_hatred] }
result[:orc_soldier] =
{
:name => "Orc Soldier",
:size => 2,
:attribute_level => 3,
:endurance => 12,
:hate => 1,
:parry => 3,
:shield => 1,
:armor => 3,
:weapons => [
{ :type=>:spear,:skill => 2},
{:type=>:bent_sword,:skill => 2 }],
:abilities => [:hate_sunlight, :craven],
:optional_abilities => [:dwarf_hatred, :hobbit_hatred] }
result[:chieftan] = { :name => "Orc Chieftan", :attribute_level => 5, :endurance => 20, :size => 2, :hate => 5, :parry => 4, :armor => 3, :shield => 3, :weapons => [{:type => :orc_axe, :skill => 3}], :abilities => [:hate_sunlight, :snake_like_speed, :horrible_strength, :commanding_voice],
:optional_abilities => [:dwarf_hatred, :hobbit_hatred] }
result[:great] = { :name => "Great Orc", :attribute_level => 7, :endurance => 48, :size => 3, :hate => 8, :parry => 5, :armor => 4, :armor_favoured => true, :shield => 2, :weapons => [{:type => :heavy_scimitar, :skill => 3, :favoured => true }, {:type => :broad_headed_spear, :skill=>3}, {:type => :orc_axe, :skill=>2, :favoured => true }], :abilities => [:horrible_strength, :commanding_voice, :hideous_toughness, :great_size]}
result[:snaga_tracker] = { :name => "Snaga Tracker", :attribute_level => 2, :size => 1, :endurance => 8, :hate => 2, :parry => 3, :armor => 2, :shield => 0, :weapons => [{ :type => :bow_of_horn, :skill => 2}, {:type => :jagged_knife,:skill => 2 }], :abilities => [:hate_sunlight, :snake_like_speed]}
result[:black_uruk] = { :name => "Black Uruk", :attribute_level => 5, :size => 2, :endurance => 20, :hate => 4, :parry => 5, :armor => 2, :armor_favoured => true, :shield => 2, :weapons => [{ :type=>:broad_bladed_sword,:skill => 2, :favoured => true }, {:type=>:broad_headed_spear,:skill => 2 }], :abilities => [:horrible_strength] }
result[:messenger_of_lugburz] = { :name => "Messenger of Lugburz", :size => 2, :attribute_level => 4, :endurance => 18, :hate => 5, :parry => 4, :armor => 2, :weapons => [{:type=>:heavy_scimitar,:skill => 2}, {:type=>:jagged_knife,:skill => 3, :favoured => true}], :abilities => [:hate_sunlight, :snake_like_speed, :commanding_voice]}
result[:forest_goblin] = { :name => "Forest Goblin", :size => 1, :attribute_level => 2, :endurance => 10, :hate => 2, :parry => 2, :shield => 1, :armor => 2, :weapons => [{ :type=>:stone_spear,:skill => 2}, {:type=>:jagged_knife,:skill => 1 }], :abilities => [:hate_sunlight, :horrible_strength, :mirkwood_dweller, :craven] }
result
end
def self.chieftan
o = Orc.new
o.name = "Orc Chieftan"
o.attribute_level = 5
o.max_endurance = 20
o.max_hate = 5
o.parry = 4
o.shield = :shield
o.armor = :orc_armor
o.helm = :none
o.weapon = :orc_axe
o.weapon_skill = 3
return o
end
end
Monster.register Orc
| true |
3a440a040279199af4e362cefdbd25bd90396527 | Ruby | pocke/self-hosting-whitespace | /test/basic_features_test.rb | UTF-8 | 2,082 | 2.578125 | 3 | [] | no_license | require 'test_helper'
class BasicFeaturesTest < Minitest::Test
def test_calc_add
io = WhitespaceIO.new
io.push_num 3
io.push_num 8
io.add
io.write_num
io.exit
io.eof
assert_ws "11", io
end
def test_calc_sub
io = WhitespaceIO.new
io.push_num 3
io.push_num 8
io.sub
io.write_num
io.exit
io.eof
assert_ws "-5", io
end
def test_calc_multi
io = WhitespaceIO.new
io.push_num 3
io.push_num 8
io.multi
io.write_num
io.exit
io.eof
assert_ws "24", io
end
def test_calc_div
io = WhitespaceIO.new
io.push_num 10
io.push_num 2
io.div
io.write_num
io.exit
io.eof
assert_ws "5", io
end
def test_calc_mod
io = WhitespaceIO.new
io.push_num 11
io.push_num 3
io.mod
io.write_num
io.exit
io.eof
assert_ws "2", io
end
def test_dup
io = WhitespaceIO.new
io.push_num 42
io.dup
io.write_num
io.write_num
io.exit
io.eof
assert_ws "4242", io
end
def test_swap
io = WhitespaceIO.new
io.push_num 5
io.push_num 3
io.swap
io.write_num
io.write_num
io.exit
io.eof
assert_ws "53", io
end
def test_pop
io = WhitespaceIO.new
io.push_num 5
io.push_num 3
io.pop
io.write_num
io.exit
io.eof
assert_ws "5", io
end
def test_heap
io = WhitespaceIO.new
io.push_num 5 # addr
io.push_num 3 # val
io.heap_save
io.push_num 8 # addr
io.push_num -1 # val
io.heap_save
io.push_num 5
io.heap_load
io.write_num
io.push_num 8
io.heap_load
io.write_num
io.exit
io.eof
assert_ws "3-1", io
end
def test_io
io = WhitespaceIO.new
io.push_num 42
io.push_ch '!'
io.write_ch
io.write_num
io.exit
io.eof
assert_ws "!42", io
end
def test_def_call
io = WhitespaceIO.new
io.call "\t"
io.exit
io.def "\t"
io.push_num 42
io.write_num
io.end
io.eof
assert_ws "42", io
end
end
| true |
f54364b348236cc7ba8e6572b3c3147541e6a896 | Ruby | ishmetjahan/prime-ruby-dumbo-web-062419 | /prime.rb | UTF-8 | 207 | 2.65625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Add code here!
def prime?(num)
if num<=1
return false
elsif num==1 || num==2
return true
else
i=2
while i< num
if num% i ==0
return false
end
i+=1
end
end
return true
end | true |
07067df47ffa4c88ee4f2f22f62bc1a7b83946cd | Ruby | shelbycer/machine-translator-challenge | /lib/formatter.rb | UTF-8 | 166 | 2.90625 | 3 | [] | no_license | class Formatter
DELIMITER = "\n"
def self.split_string(text)
text.split(DELIMITER)
end
def self.join_pieces(text)
text.join(DELIMITER)
end
end
| true |
c6d27ebf01ce02b53358680c5a63f0956f53cdfe | Ruby | marcos-x86/AT04_API_test | /YuriOrtuno/Session_01/Practice_09/Practice01.rb | UTF-8 | 1,060 | 3.859375 | 4 | [] | no_license | class Father
attr_accessor :money
def initialize money
@@money = money
end
def howMoneyExist
@@money
end
end
class SonOne < Father
def initialize moneyTake
@moneyTake = moneyTake
@@money -= @moneyTake
end
def howtake
@moneyTake
end
end
class SonTwo < Father
def initialize moneyTake
@moneyTake = moneyTake
@@money -= @moneyTake
end
def howtake
@moneyTake
end
end
class SonThree < Father
def initialize moneyTake
@moneyTake = moneyTake
@@money -= @moneyTake
end
def howtake
@moneyTake
end
end
father = Father.new(100.0)
puts "Father have #{father.howMoneyExist}"
printf "SonOne take "
sonOne = SonOne.new(gets.chomp.to_f)
puts "his father"
printf "SonTwo take "
sonTwo = SonTwo.new(gets.chomp.to_f)
puts "his father"
printf "SonThree take "
sonThree = SonThree.new(gets.chomp.to_f)
puts "his father"
puts "sonOne take: #{sonOne.howtake}"
puts "sonOne take: #{sonTwo.howtake}"
puts "sonOne take: #{sonThree.howtake}"
puts "the end his father have: #{father.howMoneyExist}" | true |
b05b98026d17478305c32efccf2013ac0be4c394 | Ruby | herringtown/paper_trail | /lib/paper_trail/attribute_serializers/legacy_active_record_shim.rb | UTF-8 | 1,517 | 2.5625 | 3 | [
"MIT"
] | permissive | module PaperTrail
module AttributeSerializers
# Included into model if AR version is < 4.2. Backport Rails 4.2 and later's
# `type_for_attribute` so we can build on a common interface.
module LegacyActiveRecordShim
# An attribute which needs no processing. It is part of our backport (shim)
# of rails 4.2's attribute API. See `type_for_attribute` below.
class NoOpAttribute
def type_cast_for_database(value)
value
end
def type_cast_from_database(data)
data
end
end
NO_OP_ATTRIBUTE = NoOpAttribute.new
# An attribute which requires manual (de)serialization to/from what we get
# from the database. It is part of our backport (shim) of rails 4.2's
# attribute API. See `type_for_attribute` below.
class SerializedAttribute
def initialize(coder)
@coder = coder.respond_to?(:dump) ? coder : PaperTrail.serializer
end
def type_cast_for_database(value)
@coder.dump(value)
end
def type_cast_from_database(data)
@coder.load(data)
end
end
def type_for_attribute(attr_name)
serialized_attribute_types[attr_name.to_s] || NO_OP_ATTRIBUTE
end
def serialized_attribute_types
@attribute_types ||= Hash[serialized_attributes.map do |attr_name, coder|
[attr_name, SerializedAttribute.new(coder)]
end]
end
private :serialized_attribute_types
end
end
end
| true |
33c418cf41a2d35e27c975a34eb32fba76c5d795 | Ruby | MaksimPW/service_taxi | /app/models/inspection.rb | UTF-8 | 1,446 | 2.65625 | 3 | [] | no_license | class Inspection
# Принадлежит/лежит ли точка в/на окружности?
# x1, y1 - координаты точки
# x2, y2, r - координаты центра окружности и ее радиуса
def self.inside_the_circle?(x1,y1,x2,y2,r)
return true if (((x1 - x2)**2) + ((y1 - y2)**2)) <= r**2
false
end
def self.summary_build_route(locations)
# Mapzen Turn-by-Turn routing service API reference
# Limits and Documentation: https://mapzen.com/documentation/overview/
mapzen_key = Rails.application.secrets.mapzen_key
limit_locations = 20
if locations.count > limit_locations
drob = (locations.count/21) + 2
locations = locations.each_slice(drob).map(&:last)
end
@locations_json = Array.new
@locations = Array.new
locations.each do |id|
@locations << StatusCar.find(id)
end
@locations.each do |l|
@locations_json << {"lat": l.geo_lat, "lon": l.geo_lon}
end
respond_json = {locations: @locations_json,
costing:'auto',
costing_options:{auto:{country_crossing_penalty:2000.0}},
directions_options:{units:'km'},id:'build_route'}
response = RestClient.get 'http://valhalla.mapzen.com/route', {params: {json: respond_json.to_json, api_key: mapzen_key}}
# Out
parsed_body = JSON.parse(response.body)
parsed_body["trip"]["legs"][0]["summary"]
end
end
| true |
6ee7529e4fd917136d7d5487ed3d9c156fe7190c | Ruby | sreevenkat/destroy-all-software | /data-compressor/zip.rb | UTF-8 | 2,066 | 3.625 | 4 | [] | no_license | #!/usr/bin/env ruby
def compress(original)
tree = build_tree(original)
table = build_table(tree)
compressed = []
original.bytes.each do |byte|
bits = look_up_byte(table, byte)
compressed << bits
end.flatten
pack_table(table, compressed)
compressed
end
def decompress(compressed, data_length)
table = unpack_table(compressed)
data_length.times.map do
look_up_bits(table, bits)
end.map(&:chr).join
end
def build_tree(original)
bytes = original.bytes
unique_bytes = bytes.uniq
nodes = unique_bytes.map do |byte|
Leaf.new(byte, bytes.count(byte))
end
until nodes.length == 1
left_node = nodes.delete(nodes.min_by(&:count))
right_node = nodes.delete(nodes.min_by(&:count))
count = left_node.count + right_node.count
nodes << Node.new(left_node, right_node, count)
end
nodes.first
end
def build_table(node, path = [])
if node.is_a?(Node)
build_table(node.left, path + [0]) + build_table(node.right, path + [1])
else
[TableRow.new(node.byte, path)]
end
end
def look_up_byte(table, byte)
table.each do |row|
return row.bits if row.byte == byte
end
raise 'oops'
end
def look_up_bits(table, bits)
table.each do |row|
if row.bits == bits.take(row.bits.length)
bits.shift(row.bits.length)
return row.byte
end
end
raise 'oops'
end
def pack_table(table, compressed)
compressed.unshift(table.length)
table.each do |row|
compressed.unshift(row.byte)
compressed.unshift(row.bits.length)
compressed.unshift(row.bits)
end
end
def unpack_table(compressed)
table_length = compressed.shift.first
table = table_length.times.map do
byte = compressed.shift
bit_count = compressed.shift
bits = compressed.shift(bit_count)
TableRow.new(byte, bits)
end
end
Node = Struct.new(:left, :right, :count)
Leaf = Struct.new(:byte, :count)
TableRow = Struct.new(:byte, :bits)
original = 'abbcccc'
p original
compressed = compress(original)
p compressed
decompressed = decompress(compressed, original.length)
p decompressed
| true |
d0f7d7bbc61cd0c8f94d00a1712da432edd72293 | Ruby | mluts/mini-nrepl | /lib/mini_nrepl/nrepl/result_handler.rb | UTF-8 | 1,817 | 2.515625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'set'
require 'mini_nrepl/logging'
module MiniNrepl
class Nrepl
# Allows to setup flexible handling of nrepl output
class ResultHandler
include Logging
# @param args [Object] Any args accepted
def initialize(*args)
logger.debug(self.class) { "Initializing with #{args.inspect}" }
@on = {}
end
# @return [Proc] Proc to pass into Nrepl#op
def to_proc
proc { |msg| handle_message(msg) }
end
# Set block handler for key
#
# @param key [String] Message key to match
# @param val [nil,String,Array<String>]
# Value to match.
# If `nil` - then any value will match
# If single-value, then block will execute only on exact match
# If array, then block will execute if message value is in array
def on(key, val = nil, &block)
return unless block
val = val ? Set.new(Array(val)) : val
callbacks = @on.fetch(key, [])
callbacks << [val, block]
@on[key] = callbacks
end
# @param msg [Hash] Message received from nrepl
def handle_message(msg)
msg.each do |key, val|
msg_val_set = Set.new(Array(val))
@on.fetch(key, []).each do |(handle_val_set, block)|
block.call(msg) if !handle_val_set || (msg_val_set & handle_val_set).any?
end
end
msg
end
def with_opts(opts)
was = current_opts
Thead.current[opts_key] = opts
yield
ensure
Thread.current[opts_key] = was
end
def current_opts
Thread.current[opts_key] || {}
end
private
def opts_key
@opts_key ||= "ResultHandler->#{self.class}_opts"
end
end
end
end
| true |
18df2c55c817dc7818e3bf3a38040b5f3e9a7f93 | Ruby | eashmore/app_academy | /w2d4-master/piece.rb | UTF-8 | 2,770 | 3.34375 | 3 | [] | no_license | require 'colorize'
class Piece
MOVES_DIFFS = [[1,1], [1,-1], [-1,-1], [-1,1]]
PAWN_SYMBOL = '0'
KING_SYMBOL = 'K'
# JUMP_DIFFS = [[2,2], [2,-2], [-2,-2], [-2,2]]
attr_reader :color, :board
attr_accessor :pos, :king, :moves, :jumps, :neighbors
def initialize(pos, color, board)
@pos = pos
@color = color
@board = board
@king = false
end
def multiplier
color == :black ? -1 : 1
end
def symbol
symbol = (@king ? KING_SYMBOL : PAWN_SYMBOL)
symbol.colorize(:color => color)
end
def move_diffs
(color == :black) ? MOVES_DIFFS.take(2) : MOVES_DIFFS.drop(2)
end
def valid_slides
find_valid_slides(moves_diffs)
end
def find_valid_slides(moves_diffs)
moves = []
@neighbors = [] # TA: average @pos and destination pos... no more neighbors
cur_x, cur_y = pos
moves_diffs.each do |diff|
new_move = [cur_x + diff[0], cur_y + diff[1]]
neighbors << new_move
# p neighbors
next unless new_move.all?{ |pos| pos.between?(0,7)}
moves << new_move if board[new_move].nil?
end
moves
end
def perform_slide(new_pos)
if valid_slides.include?(new_pos)
board[pos] = nil
@pos = new_pos
board[new_pos] = self
else
raise "Not a valid input!"
end
end
def perform_jump(new_pos)
valid_slides
jump_list = valid_jumps
if valid_jumps.include?(new_pos)
board[pos] = nil
@pos = new_pos
board[new_pos] = self
p neighbors
jumped_piece = neighbors[jump_list.index(new_pos)]
board[jumped_piece] = nil
else
raise "Not a valid input"
end
end
def valid_jumps
@jumps = []
jump_moves = []
neighbors.each do |neighbor|
jump_moves << neighbor.dup
end
if board[jump_moves[0]].is_a?(Piece)
jump_moves[0][0] = jump_moves[0][0] - 1 * multiplier
jump_moves[0][1] = jump_moves[0][1] - 1 * multiplier
else
jump_moves[0] = nil
end
if board[jump_moves[1]].class == Piece
jump_moves[1][0] = jump_moves[1][0] - 1 * multiplier
jump_moves[1][1] = jump_moves[1][1] + 1 * multiplier
else
jump_moves[1] = nil
end
jump_moves.each_with_index do |pos, i|
next if pos.nil?
jump_moves[i] = nil unless pos.all?{ |val| val.between?(0,7) }
end
neighbors.each_with_index do |pos, i|
neighbors[i] = nil if jump_moves[i].nil?
end
@neighbors = clean_neighbors
jumps = jump_moves.reject{ |move| move.nil? }
end
def clean_neighbors
neighbors.compact unless neighbors.nil?
end
def valid_slide?(new_pos)
return true if valid_slides.include?(new_pos)
false
end
def valid_jump?(new_pos)
return true if valid_jumps.include?(new_pos)
false
end
end
| true |
243666ecf415d759e80d9835b368b868096f1c6b | Ruby | weyewe/zgazga | /app/models/roller_accessory_detail.rb | UTF-8 | 2,220 | 2.53125 | 3 | [] | no_license | class RollerAccessoryDetail < ActiveRecord::Base
belongs_to :roller_identification_form_detail
belongs_to :item
validates_presence_of :roller_identification_form_detail_id
validates_presence_of :item_id
validates_presence_of :amount
validate :valid_roller_identification_form_detail_id
validate :valid_item_id
validate :valid_amount
def valid_amount
if amount <= 0
self.errors.add(:amount, "Harus lebih besar dari 0")
return self
end
end
def valid_roller_identification_form_detail_id
return if roller_identification_form_detail_id.nil?
rifd = RollerIdentificationFormDetail.find_by_id roller_identification_form_detail_id
if rifd.nil?
self.errors.add(:sales_order_id, "Harus ada RollerIdentificationFormDetail Id")
return self
end
end
def valid_item_id
return if item_id.nil?
item = Item.find_by_id item_id
if item.nil?
self.errors.add(:item_id, "Harus ada Item_Id")
return self
end
if not item.item_type.name == ITEM_TYPE_CASE[:Accessory]
self.errors.add(:item_id, "Item bukan accesory")
return self
end
itemcount = RollerAccessoryDetail.where(
:item_id => item_id,
:roller_identification_form_detail_id => roller_identification_form_detail_id,
).count
if self.persisted?
if itemcount > 1
self.errors.add(:item_id, "Item sudah terpakai")
return self
end
else
if itemcount > 0
self.errors.add(:item_id, "Item sudah terpakai")
return self
end
end
end
def self.create_object(params)
new_object = self.new
new_object.item_id = params[:item_id]
new_object.roller_identification_form_detail_id = params[:roller_identification_form_detail_id]
new_object.amount = params[:amount]
if new_object.save
end
return new_object
end
def update_object(params)
self.item_id = params[:item_id]
self.roller_identification_form_detail_id = params[:roller_identification_form_detail_id]
self.amount = params[:amount]
if self.save
end
return self
end
def delete_object
self.destroy
return self
end
end
| true |
95ab4d4a62ef445d4649ed4c10159a8bbc50f172 | Ruby | thernull/star-wars-simulator | /Mission/Mission.rb | UTF-8 | 2,450 | 3.09375 | 3 | [] | no_license | class Mission
def initialize(goodSide, badSide)
@goodSide = goodSide
@badSide = badSide
@dead = []
@injured = []
@events = []
end
def play
(1..rand(10)+1).each do |idx|
break if @goodSide.size == 0
break if @badSide.size == 0
goodGuy = @goodSide[rand(@goodSide.size)]
badGuy = @badSide[rand(@badSide.size)]
lightSide, darkSide = power_of_force()
if (goodGuy.force+lightSide-badGuy.force-darkSide).abs > 1500
if goodGuy.force+lightSide < badGuy.force+darkSide
@events.push(Event.new(goodGuy, badGuy, "dead", nil, lightSide, darkSide))
goodGuy.dead = true
@dead.push(goodGuy)
@goodSide.delete(goodGuy)
add_exp(badGuy, goodGuy)
else
@events.push(Event.new(goodGuy, badGuy, nil, "dead", lightSide, darkSide))
badGuy.dead = true
@dead.push(badGuy)
@badSide.delete(badGuy)
add_exp(goodGuy, badGuy)
end
elsif (goodGuy.force+lightSide-badGuy.force-darkSide).abs > 1000
if goodGuy.force+lightSide > badGuy.force+darkSide
@events.push(Event.new(goodGuy, badGuy, nil, 'injured', lightSide, darkSide))
@injured.push(badGuy)
badGuy.force = new_force_after_injure(badGuy)
add_exp(goodGuy, badGuy)
else
@events.push(Event.new(goodGuy, badGuy, 'injured', nil, lightSide, darkSide))
@injured.push(goodGuy)
goodGuy.force = new_force_after_injure(goodGuy)
add_exp(badGuy, goodGuy)
end
else
@events.push(Event.new(goodGuy, badGuy, nil, nil, lightSide, darkSide))
end
end
end
def dead
@dead
end
def injured
@injured
end
def to_str
@events.map { |event| event.to_str }.join("\n")
end
def self.all_registered_mission_types
ObjectSpace.each_object(Class).select { |c| c < self }
end
def self.is_possible?(goodSide, badSide)
end
def self.existance_probability
end
protected
def new_force_after_injure(guy)
guy.force-rand(guy.force/2)
end
def add_exp(winner, looser)
if winner.force > looser.force
winner.force += (looser.force > 10000 ? rand(300) : rand(150))
else
winner.force += rand((looser.force-winner.force)/2)
end
end
def power_of_force
[rand(10000)-5000, rand(10000)-5000]
end
end | true |
1b06a129ee762cce08fd31537bdb40ccfce07418 | Ruby | davelively14/sep-assignments | /01-data-structures/01-introduction-to-data-structures/screen/screen_spec.rb | UTF-8 | 1,702 | 3.296875 | 3 | [] | no_license | require_relative 'screen'
RSpec.describe Screen, type: Class do
let(:screen) { Screen.new(10, 10) }
describe "#insert" do
it "inserts a pixel at the proper x, y coordinates" do
pixel = Pixel.new(255, 200, 175, 1, 1)
screen.insert(pixel)
expect(screen.at(1, 1)).to eq pixel
end
it "retains color information upon insertion" do
pixel = Pixel.new(255, 200, 175, 1, 1)
screen.insert(pixel)
p1 = screen.at(1, 1)
expect(p1.red).to eq pixel.red
expect(p1.green).to eq pixel.green
expect(p1.blue).to eq pixel.blue
end
end
describe "#at" do
it "returns the pixel at a specific location" do
pixel = Pixel.new(255, 200, 175, 1, 1)
screen.insert(pixel)
p1 = screen.at(1, 1)
expect(p1).to eq pixel
end
it "handles invalid x, y values gracefully" do
pixel = screen.at(-1, -1)
expect(pixel).to eq nil
end
end
describe "#matrix" do
it "returns the matrix" do
matrix = screen.matrix
expect(matrix.length).to eq 10
expect(matrix[0].length).to eq 10
end
it "cannot mutate" do
matrix = screen.matrix
expect(screen.at(0, 0)).to be_nil
matrix[0][0] = "asdf"
expect(matrix[0][0]).to eq "asdf"
expect(screen.at(0, 0)).to be_nil
end
end
describe "#show_matrix" do
it "displays the matrix" do
screen = Screen.new(2, 2)
screen.insert(Pixel.new(0, 0, 0, 0, 0))
screen.insert(Pixel.new(0, 0, 0, 0, 1))
screen.insert(Pixel.new(0, 0, 0, 1, 0))
screen.insert(Pixel.new(0, 0, 0, 1, 1))
expect(screen.show_matrix).to eq "[0, 0, 0][0, 0, 0]\n[0, 0, 0][0, 0, 0]\n"
end
end
end
| true |
e6f38e7b97ad40f35626ff4c0ceb6b8653841219 | Ruby | devnivek/Ruby | /Desafios Ruby/Word_Count.rb | UTF-8 | 524 | 3.21875 | 3 | [] | no_license | #DESAFIO CONTAR VOGAIS E CONSOANTES
class Word_Count
def vowels_count(phrase)
require "i18n" #aplicando internacionalização para remover acentos
puts I18n.transliterate(phrase).upcase.count "AEIOUY" #transformando em maiusculas e contando vogais
end
def consonants_count(phrase)
require "i18n" #aplicando internacionalização para remover acentos
puts I18n.transliterate(phrase).upcase.count "BCDFGHJKLMNPQRSTVWXZ" #transformando em maiusculas e contando consoantes
end
end | true |
93dc8974491341abd7aacadb2ebdaa500e3bad7b | Ruby | Solertis/splam | /lib/splam/rules/user.rb | UTF-8 | 452 | 2.53125 | 3 | [
"MIT"
] | permissive | class Splam::Rules::User < Splam::Rule
def run
bad_words = ["qq.com", "yahoo.cn", "126.com"]
bad_words |= %w( mortgage )
bad_words.each do |word|
add_score 50, "User's email address has suspicious parts: #{word}" if @user.email.include?(word)
end
add_score "20", "User has lots and lots of dots" if @user.email.split("@")[0].scan(/\./).size > 5
add_score 5, "User is untrusted" if !@user.trusted?
end
end | true |
3e2a0a167ec0ef78f3d392fe423b42b3b699496c | Ruby | TheMaxta/JobFinder | /jobs_sctructured.rb | UTF-8 | 5,266 | 2.796875 | 3 | [] | no_license | require 'HTTParty' #sends request to page
require 'Nokogiri' #places xml info into ruby object
require 'JSON'
require 'Pry' #debugging gem
require 'csv'
#AS OF NOW, ONLY CRAIGSLIST WORKS!!
class ProgramController
def initialize
@cities = %w[ denver sandiego sanantonio newyork seattle chicago orangecounty losangeles louisville ]
@websites = %w[Craigslist.org Indeed.com Monster.com ]
@searches = %w[ /search/jjj?excats=12-1-2-1-7-1-1-1-1-1-19-1-1-3-2-1-2-2-2-14-25-25-1-1-1-1-1-1 ]
#only contains one list currently. search sets to programming jobs... list[0]
end
def welcome
puts "\n\n\n\n============================================================\n\n"
puts "Welcome to the Job Finder!!"
puts "Coded by: Max Mahlke."
puts "\n============================================================\n\n\n"
puts "Press Enter To Commence Jobifying!!"
gets.chomp
puts "\n\n\n\n\n\n"
set_uri()
end
def set_uri
instance1 = Settings.new
@protocol = 'https://www.'
@host = instance1.set_host(@websites)
@city = instance1.set_city(@cities)
@search = instance1.set_search(@searches) ## what categories?
uriInstance = CreateUriObject.new(@protocol, @host, @city, @search)
@parsedPage = uriInstance.plugInVars
@keywords = set_keywords() #pass on controll to next method
end
def createCapitalizedWords(words)
words = words.map do |word|
word.capitalize
end
return words
end
def createUpcasedWords(words)
words = words.map do |word|
word.upcase
end
return words
end
def set_keywords
puts "\n\nWhat kind of keywords would you like the program to scan for?\n"
puts "Type 1 for preset keywords.\n\n"
response = gets.chomp
if response == '1'
@keywords = %w[php ruby rails c++ html xml css sql
javascript JavaScript java json c# Knockout.js node.js
Node.js jquery jQuery bootstrap Bootstrap python iOS ios IOS Ios swift
perl .net .Net .NET VisualBasic vb objective-c Objective-C ]
@keywordsCap = createCapitalizedWords(@keywords)
@keywordsUp = createUpcasedWords(@keywords)
@keywords << @keywordsCap
@keywords << @keywordsUp
puts @keywords
return(@keywords)
else
puts "Please Enter 5 Keywords.\n"
@keywords = []
5.times do |i|
puts "keyword#{i+1}: "
temp = gets.chomp
@keywords << temp
end
@keywordsCap = createCapitalizedWords(@keywords)
@keywordsUp = createUpcasedWords(@keywords)
#append together for simplicity
@keywords << @keywordsCap
@keywords << @keywordsUp
puts @keywords
return(@keywords)
end
end ## end set_keywords
def set_posts_to_load
puts "\n\nHow many Pages do you want parsed and scanned? (max: 100)\n\n"
response = gets.chomp
return (resonse)
end
class CreateUriObject
def initialize(protocol, host, city, search)
@protocol = protocol
@host = host
@city = city
@search = search
end
def plugInVars
puts @protocol
puts @city
@host = @host.downcase
puts @host
puts @search
@page = HTTParty.get("https://#{@city}.#{@host}#{@search}") #protocol causes crash...
#page = HTTParty.get("https://#{city}.craigslist.org/search/jjj?excats=12-1-2-1-1")
@parsed = Nokogiri::HTML(@page)
return(@parsed)
end
end
class Settings
def printList(array)
int = 1
array.each do |i|
puts "#{int}). #{i}"
int += 1
end
end
def set_host(list)
puts "These are websites we currently support. Please choose one by typing it in."
printList(list) ## doesn't return anything. just puts command.
puts "\n\n"
response = gets.chomp
validate = checkResponse(response, list)
if validate == true
puts "Correct selection!"
return (response) ## returns the user's choice of a host.
#return to caller
else
puts "Wrong! We do not support that website!"
set_host(list) ##recursively call, and pass list again.
end
end
#cities array contains list of all cities we can run
def set_city(list) #pass list of available cities
printList(list) #no return, just output
puts "\n\nVisit https://geo.craigslist.org/iso/us for more cities."
puts "\n\nPlease enter your city, as it appears on craigslist.."
response = gets.chomp
validate = checkResponse(response, list)
if validate == true
puts "Correct selection!"
return (response) ## returns the user's choice of city.
#return to caller
else
puts "Wrong! We do not support that website!"
set_city(list) ##recursively call, and pass list again.
end
end
def set_search(list)
printList(list)
puts "Please Select your choice of jobs to search for."
gets.chomp
response = list[0] ## Not Settup yet!!
validate = checkResponse(response, list)
if validate == true
puts "Okay, good selection!"
return (response)
else
puts "That option does not exist anywhere.. "
end
end
def city_list
end
def checkResponse(checkThis, againstThis)
againstThis.each do |against|
if checkThis == against
puts "Return True"
return true
else
end
end ## end checkResponse method
end ## end settings class
end
end
test = ProgramController.new
test.welcome | true |
f8072b303120088b4ce30ffff18ccb223a49e201 | Ruby | itsmumar/Hellobar | /app/services/calculate_bill.rb | UTF-8 | 2,202 | 2.890625 | 3 | [] | no_license | class CalculateBill
# @param [Bill::ActiveRecord_Relation] bills
# @param [Subscription] subscription
def initialize(subscription, bills:)
@subscription = subscription
@bills = bills
end
def call
if active_paid_bills.empty?
make_bill_to_full_amount
elsif upgrading?
make_bill_for_upgrading
else
make_bill_for_downgrading
end
end
private
attr_reader :bills, :subscription
def active_paid_bills
@active_paid_bills ||= bills.paid.active
end
def last_subscription
@last_subscription ||= active_paid_bills.last.subscription
end
def make_bill_to_full_amount
make_bill
end
def make_bill_for_upgrading
make_bill do |bill|
bill.amount = calculate_reduced_amount
end
end
# We are downgrading or staying the same,
# so just set the bill to start after this bill ends,
# but make it the full amount
def make_bill_for_downgrading
make_bill do |bill|
bill.amount = subscription.amount
bill.grace_period_allowed = true
bill.bill_at = active_paid_bills.last.end_date
bill.start_date = bill.bill_at
end
end
# Subtract the unused paid amount from the price and round it
def calculate_reduced_amount
num_days_used = (Time.current - active_paid_bills.last.start_date) / 1.day
last_paid_bill = active_paid_bills.last
total_days_of_last_subcription = (last_paid_bill.end_date - last_paid_bill.start_date) / 1.day
percentage_unused = 1.0 - (num_days_used.to_f / total_days_of_last_subcription)
unused_paid_amount = last_subscription.amount * percentage_unused
(subscription.amount - unused_paid_amount).to_i
end
def make_bill
Bill.new(subscription: subscription) do |bill|
bill.amount = subscription.amount
bill.grace_period_allowed = false
bill.bill_at = Time.current
bill.source = subscription.stripe? ? Bill::STRIPE_SOURCE : Bill::CYBERSOURCE
yield bill if block_given?
bill.start_date = bill.bill_at
bill.end_date = bill.start_date + subscription.period
end
end
def upgrading?
Subscription::Comparison.new(active_paid_bills.last.subscription, subscription).upgrade?
end
end
| true |
27812fa92df9b8d1bcb2b0bfbdfc0f7c0cdaa7e5 | Ruby | telsaiori/rbnd-toycity-part4 | /lib/udacidata.rb | UTF-8 | 2,970 | 3.109375 | 3 | [] | no_license | require_relative 'find_by'
require_relative 'errors'
require 'csv'
class Udacidata
create_finder_methods("brand", "name")
@@data_path = File.dirname(__FILE__) + "/../data/data.csv"
def self.create(attributes = {})
new_product = Product.new(attributes)
CSV.open(@@data_path, "a+") do |csv|
csv << [new_product.id, new_product.brand, new_product.name, new_product.price]
end
new_product
end
def self.all
products = []
CSV.read(@@data_path, headers: true).each do |product|
products << self.new(id: product["id"], brand: product["brand"], name: product["product"], price: product["price"])
end
products
#CSV.read(@@data_path).drop(1).map{ |product| @@products << self.new(id: product[0], brand: product[1], name: product[2], pricd: product[3])}
end
def self.first(n = 1)
if n == 1
all.first
else
all.first(n)
end
end
def self.last(n = 1)
if n == 1
all.last
else
all.last(n)
end
end
def self.find(n)
# raise ProductNotFoundError, "Can not found product id#{n}" if all[n-1].nil?
find_data = all.find{ |product| product.id == n }
if find_data.nil?
raise ProductNotFoundError, "Can not found product id#{n}"
else
find_data
end
end
def self.destroy(n)
products = []
database = CSV.table(@@data_path)
database.each do |data|
products << new(id: data[:id], brand: data[:brand], name: data[:product], price: data[:price])
end
if find(n)
del_product = find(n)
database.delete_if do |row|
row[:id] == n
end
end
File.open(@@data_path, "w") do |f|
f.write(database.to_csv)
end
del_product
end
def self.where(options = {})
if options[:brand]
all.select{|product| product.brand == options[:brand]}
else
all.select{|product| product.name == options[:name]}
end
end
def update(options = {})
products = []
data = CSV.table(@@data_path)
data.each do |product|
if product[:id] == self.id
product[:price] = options[:price] ? options[:price] : product[:price]
product[:brand] = options[:brand] ? options[:brand] : product[:brand]
product[:name] = options[:name] ? options[:name] : product[:name]
products = Product.new(id: product[:id], brand: product[:brand], name: product[:product], price: product[:price])
end
end
File.open(@@data_path, "w") do |f|
f.write(data.to_csv)
end
products
end
end
| true |
ade24971ccd552bc81e36ca1bc8a475346ea896c | Ruby | amt1/wkend-hmwrk | /wk2-wkend-hmwrk/specs/room_spec.rb | UTF-8 | 2,824 | 3.0625 | 3 | [] | no_license | require('minitest/autorun')
require('minitest/rg')
require_relative('../karaoke_bar')
require_relative('../guest')
require_relative('../room')
require_relative('../song')
class TestRoom < Minitest::Test
def setup
@room1 = Room.new("The Colorado Lounge", 2)
@guest1 = Guest.new("Delbert Grady", 100, "It's All Forgotten Now")
@guest2 = Guest.new("Danny Torrance", 1, "Angels")
@song1 = Song.new(0, "Angels", "Robbie Williams", "angels.jpg")
@song2 = Song.new(1, "It's All Forgotten Now", "Ray Noble and His Orchestra", "forgotten.jpg")
@song3 = Song.new(2, "Masquerade", "Jack Hylton and His Orchestra", "masquerade.jpg")
@song4 = Song.new(3, "The Ace of Spades", "Motorhead", "aceofspades.jpg")
@playlist = [@song1, @song2, @song4]
@room1.load_playlist(@playlist)
end # end setup
# def test_room_name
# assert_equal("The Colorado Lounge", @room1.name)
# end
#
# def test_room_capacity
# assert_equal(2, @room1.capacity)
# end
#
# def test_add_guest_to_room
# @room1.add_guest(@guest1)
# assert_equal(@guest1, @room1.get_guest_list[0])
# end
#
# def test_is_guest_in_room
# @room1.add_guest(@guest1)
# assert_equal(true, @room1.is_guest_in_room(@guest1.name))
# assert_equal(false, @room1.is_guest_in_room(@guest2.name))
# end
#
# def test_remove_guest_from_room
# @room1.add_guest(@guest2)
# @room1.remove_guest(@guest2.name)
# assert_equal(false, @room1.is_guest_in_room(@guest2.name))
#
# end
#
# def test_add_song_to_room
# @room1.add_song_to_playlist(@song1)
# assert_equal(@song1, @room1.get_song_list[0])
# end
#
# def test_is_room_full
# assert_equal(false, @room1.is_full)
# @room1.add_guest(@guest1)
# @room1.add_guest(@guest2)
# assert_equal(true, @room1.is_full)
# end
#
# def test_load_playlist
# # @room1.load_playlist(@playlist)
# assert_equal(@playlist, @room1.get_song_list)
# end
#
#
# def test_is_song_in_room_playlist
# assert_equal(true, @room1.is_song_in_playlist(@song1.title, @song1.artist))
# assert_equal(false, @room1.is_song_in_playlist(@song3.title, @song3.artist))
# end
# def test_check_guest_tab
# @room1.add_guest(@guest1)
# p "Tab: "
# p @room1.check_tab(@guest1)
# end
# def test_add_to_guest_tab
# @room1.add_guest(@guest1)
# @room1.add_to_tab(@guest1.name,50)
# assert_equal(50, @room1.check_tab(@guest1.name))
# end
def test_sell_to_guest_with_tab__enough_money
@room1.add_guest(@guest1)
@room1.sell_to_guest_tab(@guest1,50)
assert_equal(50, @room1.check_tab(@guest1.name))
end
def test_sell_to_guest_with_tab__not_enough_money
@room1.add_guest(@guest1)
@room1.sell_to_guest_tab(@guest1,500)
assert_equal(0, @room1.check_tab(@guest1.name))
end
def test_delete_tab
@room1.add_guest(@guest1)
@room1.delete_tab(@guest1)
assert_nil(@room1.check_tab(@guest1.name))
# p @room1.check_tab(@guest1.name)
end
end # end class
| true |
2fa7cfa5027614cf051c28409cdb054664c4b3ea | Ruby | hnsaavedraa/Mock-Nequi | /Goal.rb | UTF-8 | 2,360 | 3.234375 | 3 | [] | no_license | require_relative "DBconect.rb"
class Goal
def initialize(id,sql)
@mysql_obj = sql
@id = id
@list_goals = Array.new()
@max_goals = Array.new()
@balance_goals = Array.new()
end
def createGoal(name_goal, value_goal, date_goal)
@mysql_obj.query("INSERT INTO accounts (`type_account`, `name_account`, `goal_date`, `goal_balance`, `iduser`)
VALUES ('metas', '#{name_goal}', '#{date_goal}', '#{value_goal}', '#{@id}');")
end
def depositGoal(id_goal,value,source,max,balance)
if(balance > max)
puts "Felicidades,ha completado su meta"
puts "Ya no podra ingresar mas dinero a esta meta"
puts "Proceda a borrarla para hacer disponible su dinero"
elsif (value.to_i > 0 && source.to_i >= value.to_i && balance < max)
@mysql_obj.query("CALL movement_accounts(#{@id}, #{id_goal},-#{value});")
elsif(source.to_i < value.to_i)
puts "Lo sentimos, no posee esa cantidad en su cuenta. "
puts "Actualmente en cuenta de ahorros: #{source}"
else
puts "Formato de entrada incorrecto"
puts "Recuerda: El valor debe ser un numero sin comas o puntos "
puts "y el valor minimo a retirar es de $1"
end
end
def deleteGoal(id_goal)
@mysql_obj.query("CALL disable_account(#{id_goal});")
end
def returnGoal(value)
return @list_goals[value.to_i].to_i
end
def returnmaxGoal(value)
return @max_goals[value.to_i].to_i
end
def returnbalanceGoal(value)
return @balance_goals[value.to_i].to_i
end
def listGoal()
count = 1
message = ""
@mysql_obj.query("SELECT a.idaccount, a.name_account, a.balance, a.goal_balance, a.goal_date
FROM accounts a WHERE a.type_account = 'metas' AND a.iduser = #{@id} AND a.status_account = 1;").each do |e|
message = message + " #{count.to_s.rjust(3)} | #{e["name_account"].ljust(25)} | #{e["balance"].to_s.rjust(12)} | #{e["goal_balance"].to_s.rjust(12)} | #{e["goal_date"]} |\n"
@list_goals[count] = e["idaccount"].to_i
@max_goals[count]= e["goal_balance"].to_i
@balance_goals[count]= e["balance"].to_i
count = count + 1
end
puts " id | Nombre Meta | abonado | Valor meta | Limite |",
"-----┼---------------------------┼----------------┼--------------┼------------┼",
message
end
end
| true |
20086a5b81cd52e9f5dab6d0029c0ac1fd6e7b8b | Ruby | jfeng702/JS-Exercises | /cracking/linkedlist/kth_to_last.rb | UTF-8 | 874 | 4.03125 | 4 | [] | no_license | # find kth to last element of singly linked list
class Node
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
def kth_to_last(head, k)
counter = 1
@head = head
while head
head = head.next
counter += 1
end
counter_2 = 1
head = @head
while head
if counter_2 == counter - k
return head
end
head = head.next
counter_2 += 1
end
end
# recursive
def kth_to_last2(head,k)
if head.nil?
return 0
end
index = kth_to_last2(head.next, k) + 1
if index == k
p "#{k}rd to last node is #{head.val}"
end
index
end
head = Node.new(1)
head.next = Node.new(2)
head.next.next = Node.new(3)
head.next.next.next = Node.new(4)
head.next.next.next.next = Node.new(5)
head.next.next.next.next.next = Node.new(6)
head.next.next.next.next.next.next = Node.new(7)
p kth_to_last2(head, 3)
| true |
57815c904e1b5cef1ff8a86639502e2a2467c826 | Ruby | sf-squirrels-2017/hipsteroverflow | /app/helpers/session_helpers.rb | UTF-8 | 308 | 2.71875 | 3 | [] | no_license | helpers do
def login(user)
session[:user_id] = user.id
end
def logout
session.clear
end
def current_user
if session[:user_id]
User.find(session[:user_id])
else
nil
end
end
def user?
if current_user != nil
true
else
false
end
end
end
| true |
5f681c5e5859f74d55d3becb9063fb8d5ba08e11 | Ruby | coinbase/salus | /lib/salus/path_validator.rb | UTF-8 | 567 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | module Salus
class PathValidator
def initialize(base_path)
@base_path = base_path
end
def local_to_base?(path)
return true if @base_path.nil?
path = Pathname.new(File.expand_path(path)).cleanpath.to_s
rpath = File.expand_path(@base_path)
return true if path == rpath
if !path.start_with?(rpath + "/") || path.include?("/.")
# the 2nd condition covers like abcd/.hidden_file or abcd/..filename
# which cleanpath does not do anything about
return false
end
true
end
end
end
| true |
b482fd185ee4ff8aaddefcd70e2d4c6a1c2c16db | Ruby | pabloleonalcaide/webChat | /webChat-back/lib/errors/roomsNotFound.rb | UTF-8 | 359 | 2.75 | 3 | [
"MIT"
] | permissive | module Errors
class RoomsNotFound < StandardError
def initialize
@message = 'No se han encontrado salas'
@status = 400
end
def to_h
{
status: status,
message: message
}
end
def serializable_hash
to_h
end
def to_s
to_h.to_s
end
attr_reader :message, :status
end
end | true |
d3940116f085e6625fb0d886200c4ec277125231 | Ruby | Jayin/practice-on-Ruby | /getting-start/iterators.rb | UTF-8 | 292 | 3.984375 | 4 | [] | no_license | #iterators 迭代
# C style
s = 'abc'
i = 0
while i<s.length
printf "<%c>", s[i]
i+=1
end
print "\n"
#Ruby
s.each_byte{
|item|
printf "<%c>", item
}
print "\n"
# yield
def repeat(num)
while num > 0
yield
num -= 1
end
end
repeat(3) {
puts "foo"
} | true |
61b37b8594bd35eb3017757e6d09bf1e80ffaa3d | Ruby | necrojan/exercises | /opposite.rb | UTF-8 | 305 | 3.640625 | 4 | [] | no_license | def opposite_sum(nums)
count = 0
nums.each_with_index do |ele1, idx1|
nums.each_with_index do |ele2, idx2|
if ele1 + ele2 == 0 && idx2 > idx1
count += 1
end
end
end
return count
end
puts opposite_sum([2, 5, 11, -5, -2, 7])
puts opposite_sum([21, -23, 24, -12, 23])
| true |
5bd377cb550ab8423ba13219a1666cd917970a98 | Ruby | glen/algorithms | /ruby/linear_search/app.rb | UTF-8 | 1,137 | 2.78125 | 3 | [] | no_license | require File.expand_path('../boot', __FILE__)
["linear_search.rb"].each do |lib_file|
require_relative(File.join(App.root, 'lib', lib_file))
end
require_relative(File.join(App.root, 'helpers', 'formatted_output.rb'))
include FormattedOutput
print_value(value: "#{'#'*25} Linear Search Implementation #{'#'*25}", color: :black, background: :white)
begin
if LinearSearch.valid_number?(ARGV[0])
ls = LinearSearch.new(ARGV[0])
print_label(label: "Input", color: :blue, column_width: 20)
print_value(value: "[#{ls.input.join(', ')}]", color: :yellow)
print_label(label: "Number to Search", color: :blue, column_width: 20)
print_value(value: ARGV[0], color: :yellow)
print_label(label: "Located", color: :blue)
if ls.search == -1
print_value(value: "No", color: :red)
else
print_value(value: "Yes", color: :green)
end
print_label(label: "Iterations", color: :blue)
print_value(value: ls.iterations, color: :yellow)
else
print_value(value: "Invalid input #{ARGV[0]}. Searching only on numbers.", color: :red)
puts
exit 1
end
rescue Exception => e
raise e
end
puts | true |
a8ab63b89dbb9760595b1627e2fa4fd2fa228ff3 | Ruby | lenn4rd/chores_kit | /lib/chores_kit/chore/notification.rb | UTF-8 | 223 | 2.59375 | 3 | [
"MIT"
] | permissive | class Notification
def initialize(condition)
@condition = condition
@commands = []
end
# rubocop:disable Style/MethodMissing
def method_missing(name, *args)
end
# rubocop:enable Style/MethodMissing
end
| true |
63df779f5ac1c4d78434b075262430db87ca96bb | Ruby | dfucci/StarWars-Gosu | /bobba.rb | UTF-8 | 1,726 | 3.046875 | 3 | [] | no_license | load 'bullet.rb'
class Bobba
attr_reader :x, :y, :direction, :shoots, :height, :bullet
attr_accessor :shooting
SPEED = 6
def initialize window, x, y
@height, @x, @window, @direction, @shooting, @shoots = height, x,
window, direction, false, 3
@width = 32
@height = 41
@frame = 0
@sample = Gosu::Sample.new @window, "audio/gun.mp3"
@image = Gosu::Image.load_tiles @window, "images/bobba.png",
@width, @height, true
@direction = :right
@y = y - @height - 1 # 1px padding
@shooting = false
@bullet = nil
@shooting_direction = :right
@shooting_position = @x
end
def update(droid=nil)
@bullet.update if @shooting && @bullet
self.kill droid if droid
end
def draw
@bullet.draw if @bullet
f = @frame % @image.size
tile = @image[f]
if @direction == :right
tile.draw @x, @y, 1
else
tile.draw @x + tile.width, @y, 1, -1
end
end
def can_shoot?
@shoots>0
end
def facing? other
@x < other.x && @direction == :right || @x > other.x && @direction == :left
end
def next_tile
@frame+=1
end
def move direction
@direction = direction
@x += SPEED if @direction == :right
@x -= SPEED if @direction == :left
@x = 0 if self.x > @window.width
@x = @window.width if self.x < 0
next_tile
end
def shoot droid
@shooting_direction = @direction
@shooting_position = @x
@sample.play
@shooting = true
@bullet = Bullet.new @window, self
end
def remove
@y = -100
end
def kill droid
if @bullet && @bullet.hits?(droid, @shooting_direction, @shooting_position)
droid.kill
droid = nil
@bullet = nil
end
end
end
| true |
efd2b888bef49df538e42ee96ae5e3c7265a774b | Ruby | wengkhing/flashcards | /db/seeds.rb | UTF-8 | 618 | 2.640625 | 3 | [] | no_license | require 'faker'
if Card.all.count == 0
deck = Deck.create(name: "Geography", instruction: "Guess if place name is a country, a state or a city?")
50.times do
randnum = rand(3)
case randnum
when 0
Card.create(question: Faker::Address.country, answer: "country", deck: deck)
when 1
Card.create(question: Faker::Address.state, answer: "state", deck: deck)
when 2
Card.create(question: Faker::Address.city, answer: "city", deck: deck)
end
end
end
if User.all.count == 0
20.times do
User.create(username: Faker::Internet.user_name, password: SecureRandom.hex(4))
end
end
| true |
148a45abac90b8c4dedf381a4333129ae481d5b3 | Ruby | jede/crafty | /lib/crafty/toolset.rb | UTF-8 | 1,774 | 2.75 | 3 | [
"MIT"
] | permissive | module Crafty
module Toolset
class << self
# Define the given elements and self-closing elements in the given
# module. The module will be modified to never overwrite existing
# methods, even if they have been defined in superclasses or other
# previously-included modules.
def define(mod, elements = [], empty_elements = [])
define_elements(mod, elements)
define_empty_elements(mod, empty_elements)
mod.module_eval do
include Tools
def self.append_features(mod)
redefined = mod.instance_methods & self.instance_methods(false)
if redefined.any?
dup.tap do |safe|
redefined.each do |method|
safe.send :remove_method, method
end
end.append_features(mod)
else
super
end
end
end
end
# Define regular elements in the given module.
def define_elements(mod, elements)
elements.each do |element|
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{element}(*arguments, &block)
attributes = arguments.pop if arguments.last.kind_of? Hash
content = arguments.first || ""
element!("#{element}", content, attributes, &block)
end
RUBY
end
end
# Define empty, self-closing elements in the given module.
def define_empty_elements(mod, elements)
elements.each do |element|
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{element}(attributes = nil)
element!("#{element}", nil, attributes)
end
RUBY
end
end
end
end
end
| true |
708186024980a2b9f3f0a93a0135a2d8d59a71c8 | Ruby | yuhangwu2009/eulerPrjs | /ruby/project_6.rb | UTF-8 | 223 | 3.765625 | 4 | [] | no_license | print "Please input your number: "
number = gets.chomp.to_i
x = 1
y = 0
sum = 0
while x <= number
y += x
sum += x*x
x += 1
end
y = y*y
z = y-sum
puts "The difference is #{z} which is the difference of #{y} & #{sum}."
| true |
e56a4b1e3e09632fd3d0834c36d837d879c78235 | Ruby | harrisj/nytimes-movies | /lib/nytimes/movies/link.rb | UTF-8 | 737 | 2.734375 | 3 | [
"MIT"
] | permissive | module Nytimes
module Movies
##
# Represents a link returned from the Reviews API. Each link has a URL, suggested text, and a link_type which gives you some idea of what the remote
# target of the link is. Possible link types include:
# FIXME
class Link
attr_reader :link_type, :url, :suggested_text
def initialize(hash={})
@url = hash[:url]
@link_type = hash[:link_type]
@suggested_text = hash[:suggested_text]
end
##
# Create a Link object from a hash snippet returned from the API. You should never need to call this.
def self.create_from_api(hash={})
Link.new :url => hash['url'], :link_type => hash['type'], :suggested_text => hash['suggested_link_text']
end
end
end
end | true |
a17c4d197f4afec58df82c64a427e7dcaf97e8d8 | Ruby | Bhanditz/gem-aws-instmd | /lib/aws/instmd.rb | UTF-8 | 1,986 | 2.90625 | 3 | [
"MIT"
] | permissive | require 'net/http'
module AWS
class InstMD
def self.method_missing name, *args, &block
@@root ||= InstMD.new
@@root.method(name).call(*args, &block)
end
# Can't be the first one to make that pun.
# Still proud.
class Hashish < Hash
def method_missing name
self[name.to_s.gsub('_', '-')]
end
end
class Treeish < Hashish
private
def initialize http, prefix
entries = InstMD.query http, prefix
entries.lines.each do |l|
l.chomp!
if l.end_with? '/'
self[l[0..-2]] = Treeish.new http, "#{prefix}#{l}"
# meta-data/public-keys/ entries have a '0=foo' format
elsif l =~ /(\d+)=(.*)/
number, name = $1, $2
self[name] = Treeish.new http, "#{prefix}#{number}/"
else
self[l] = InstMD.query http, "#{prefix}#{l}"
end
end
end
end
attr_accessor :user_data, :meta_data, :dynamic
# Amazon, Y U NO trailing slash entries
# in /, /$version and /$version/dynamic/??
# There is waaay too much code here.
def initialize version='latest', host='169.254.169.254', port='80'
http = Net::HTTP.new host, port
@meta_data = Treeish.new http, "/#{version}/meta-data/"
@user_data = InstMD.query http, "/#{version}/user-data"
@dynamic = Hashish.new
begin
dynamic_stuff = InstMD.query(http, "/#{version}/dynamic/").lines
rescue
dynamic_stuff = []
end
dynamic_stuff.each do |e|
e = e.chomp.chomp '/'
@dynamic[e] = Treeish.new http, "/#{version}/dynamic/#{e}/"
end
end
def self.query http, path
rep = http.request Net::HTTP::Get.new path
unless Net::HTTPOK === rep
raise Net::HTTPBadResponse, "#{rep.code} #{path}"
end
rep.body
end
def to_hash
{:meta_data => @meta_data, :user_data => @user_data, :dynamic => @dynamic}
end
end
end
| true |
3536fb3ee4766cbc79fddcdf785e90d0698b7896 | Ruby | WildCat27/Ruby | /Project/SingleControllers/DBController.rb | UTF-8 | 1,329 | 2.6875 | 3 | [] | no_license | require "mysql2"
require_relative "Singleton"
class DBController
private_class_method :new
def self.controller
@@controller ||= new
end
def try_connect
begin
@client = Mysql2::Client.new(
:host => "localhost",
:username => "test_user",
:password => "test_user",
:database => "Staff"
) if !@client
true
rescue Mysql2::Error::ConnectionError
false
end
end
def initialize
@requests = []
try_connect
end
def execute(request, *args)
@requests.append([request, args])
begin
if (@client || try_connect)
while !@requests.empty?
req = @requests[0]
statement = @client.prepare(req[0])
if result = statement.execute(*(req[1]))
result = result.entries
end
@requests.delete_at(0)
end
result
else
raise Mysql2::Error::ConnectionError.new("Ошибка подключения")
end
rescue Mysql2::Error::ConnectionError
@client = false
return false
end
end
end | true |
a4f358f33f90bf491a98841b272b2309eb0ac4da | Ruby | sdevine90/little_pets | /controllers/pets_controller.rb | UTF-8 | 941 | 2.578125 | 3 | [] | no_license | require( 'sinatra' )
require( 'sinatra/contrib/all' )
require( 'pry-byebug' )
require_relative( '../models/pet.rb' )
require_relative( '../models/owner.rb' )
get '/pets' do
@pets = Pet.all
@owners = Owner.all
erb(:"pets/index")
end
get '/pets/new' do
erb :"pets/new"
end
post '/pets' do
pet = Pet.new(params)
pet.save
redirect to('/pets')
end
post '/pets/adopt/:pet_id' do
pet_id = params[:pet_id].to_i
owner_id = params[:owner_id].to_i
pet = Pet.find(pet_id)
pet.adopt(owner_id)
redirect to('/pets')
end
#all this is new
get '/pets/:id' do
@pet = Pet.find( params[:id] )
erb(:"pets/show")
end
post '/pets/update/:id' do
Pet.update( params)
redirect to ("/owners")
end
# post '/pets/:id/show' do
# @pet = Pet.find( params[:id] )
# redirect to ("/show")
# end
# post '/pets/unadopt/:pet_id' do
# owner_id = params[:owner_id].to_i
# Pet.unadopt(owner_id)
# redirect to('/pets')
# end
| true |
4555eff83b8cc80aa2ded35b434cbf93831e91ed | Ruby | dawa/codeprep | /interview_1_wk_2.rb | UTF-8 | 1,543 | 4.125 | 4 | [] | no_license |
class CustomHash
def initialize()
@length = 16
@hash_array = []
@size = 0
end
def get(key)
index = hash_func(key)
@hash_array[index][1] unless @hash_array[index].nil?
end
def put(key, value)
index = hash_func(key)
@hash_array[index] = [key, value]
@size += 1
@length += 16 if @size > @length
end
def remove(key)
index = hash_func(key)
@hash_array.delete_at(index)
@size -= 1
#@length = @length/2 if @size < @length/2
end
def size
@size
end
def clear
@hash_array = []
@size = 0
end
def isEmpty?
@size == 0
end
def containsKey?(key)
@hash_array.each do |item|
next if item.nil?
return true if item.first == key
end
false
end
# [[5,"orange"], [], [], [25, "pear"], [] []]
def containsValue?(value)
puts @hash_array.inspect
@hash_array.each do |item|
next if item.nil?
puts item
return true if item[1] == value
end
false
end
private
def hash_func(key)
key % @length
end
end
my_hash = CustomHash.new
puts my_hash.size
my_hash.put(5, "apple")
puts my_hash.get(5)
my_hash.put(5, "orange")
puts my_hash.get(5)
my_hash.put(25, "pear")
puts my_hash.get(25)
puts my_hash.size
my_hash.remove(5)
puts my_hash.get(5)
puts my_hash.size
#my_hash.clear
puts my_hash.isEmpty?
#puts my_hash.size
puts my_hash.containsKey?(25)
puts my_hash.containsKey?(12)
puts my_hash.containsValue?("orange")
puts my_hash.containsValue?("people")
| true |
2281982b6a9163fa1f5ef509a65cca87c8bce565 | Ruby | shiveshdewangan/LaunchSchool | /smallproblems/Easy2/teddy.rb | UTF-8 | 63 | 3.09375 | 3 | [] | no_license | def teddy()
puts "Teddy is #{rand(20..200)} years old!"
end | true |
b53f4b385fd14169bb8667061134288845d91429 | Ruby | dbesserman/LS_exercises | /small_problems/medium_2/6.rb | UTF-8 | 485 | 3.828125 | 4 | [] | no_license | def triangle(angle_1, angle_2, angle_3)
angles_array = [angle_1, angle_2, angle_3]
if (angles_array.inject(:+) != 180) || angles_array.include?(0)
:invalid
elsif angles_array.include?(90)
:right
elsif angles_array.any? { |angle| angle > 90 }
:obtuse
else
:acute
end
end
puts triangle(60, 70, 50) == :acute
puts triangle(30, 90, 60) == :right
puts triangle(120, 50, 10) == :obtuse
puts triangle(0, 90, 90) == :invalid
puts triangle(50, 50, 50) == :invalid
| true |
1ee2883c5a8c84d679cee38f0558d106274c9fe2 | Ruby | mikekauffman/reddit_warmup | /image_fetcher.rb | UTF-8 | 386 | 2.953125 | 3 | [] | no_license | class ImageFetcher
def initialize(data)
@data = data
end
def count_children
@data["data"]["children"].count
end
def first_child
@data["data"]["children"].first["data"]
end
def all_images
@data["data"]["children"].map { |child| child["data"]["url"]}
end
def only_imgur_images
all_images.select { |image| image.include?"i.imgur.com"}
end
end | true |
aab9defd1e0ac35ae33cfb006cfb23042fe27961 | Ruby | triplecanopy/alongslide | /lib/alongslide.rb | UTF-8 | 2,238 | 2.8125 | 3 | [
"MIT"
] | permissive | #
# alongslide-redcarpet.rb: top-level bindings and entrypoint for Redcarpet
# and Treetop.
#
# Copyright 2013 Canopy Canopy Canopy, Inc.
# Author Adam Florin
#
require 'yaml'
require 'haml'
require "alongslide/engine"
require "alongslide/templates"
require "alongslide/redcarpet/render"
require "alongslide/treetop/parser"
require "alongslide/syntax_error"
module Alongslide
@@parser = nil
class << self
# Accept configuration from initializer.
#
def configure(&block)
Templates.configure &block
end
# Render HTML from Markdown.
#
# @option locals - if present, stash locals in class config static variable.
# NOTE! This is not threadsafe. but fine for general usage.
# @option plain - use secondary plain renderer
#
def render(markdown, options={})
unless options[:locals].nil?
Templates.configure do |config|
config.locals = options[:locals]
end
end
(options[:plain] ? plain_renderer : renderer).render markdown
end
# Get Redcarpet renderer, init'ing if necessary.
#
def renderer
Redcarpet::Markdown.new(Redcarpet::Render::Alongslide, :footnotes => true)
end
# Plain vanilla renderer for the Markdown blocks extracted by the first
# renderer. (Can't call render() on a renderer in the middle of rendering,
# or you'll get Abort Traps.)
#
def plain_renderer
Redcarpet::Markdown.new Redcarpet::Render::HTML
end
# Get Treetop parser, init'ing if necessary.
#
def parser
@@parser ||= Grammar::RootParser.new
end
# Given an indented block of Alongslide-flavored Markdown, parse and return
# rendered HTML including appropriate templates.
#
# @param markdown raw Markdown containing directives and raw text.
#
# @return HTML for display
#
def render_block(markdown)
rootNode = parser.parse(markdown)
if rootNode
return rootNode.render
else
error_line = markdown.split("\n")[parser.failure_line-1]
raise SyntaxError.new "Alongslide syntax error around: \"#{error_line}\""
end
rescue
raise SyntaxError.new "Unknown Alongslide syntax error"
end
end
end
| true |
357b1055f9eebdd8fd1255440ac977ebc95df0b7 | Ruby | amolborcar/Project-Euler | /problem_007.rb | UTF-8 | 212 | 3.484375 | 3 | [
"MIT"
] | permissive | def nth_prime(n)
primes = []
i = 2
while primes.length < n do
primes << i if (2..i-1).all? { |num| i % num != 0 }
i += 1
end
return primes
end
p nth_prime(10001)
# This is slow...
# As hell... | true |
a5556536ea25e6f4772281ffe6e2c43f060d6384 | Ruby | MeowNya/Ruby_socket_based_simple_server_client | /common.rb | UTF-8 | 518 | 3.046875 | 3 | [] | no_license | def recv_all(s)
begin
raw_msg_len = s.read(8).unpack('Q').first # Unpack is 8 byte to number
return s.read(raw_msg_len)
rescue
return ''
end
end
def send_all(s, msg)
begin
msg = msg.to_s
s.write [msg.length].pack('Q') + msg # Q is 8 byte (long long int)
rescue
return
end
end
def parse_command(msg)
command = msg[0..9].rstrip
args = msg[10..]
return command, args
end
def merge_command(command, args)
if args.nil?
args = ''
end
return command.ljust(10) + args
end | true |
940d0e71278d42bcbac6edb9027b07ecddcf0a27 | Ruby | Keerthu8999/WEB-TECH-LAB | /pg3.rb | UTF-8 | 338 | 3.609375 | 4 | [] | no_license | puts "String Operations"
string = "keerthana"
p string.upcase
p string.downcase
p string.capitalize
p string.swapcase
p string.center(100)
p string.ljust(20)
p string.rjust(50)
p string.chomp("na")
p string.include?("t")
p string.index("h")
p string.start_with?("s")
p string.end_with?("na")
p string.sub("thana","thu")
| true |
66b37a6a85b93f0c3d291e0bcf3deaf7761f0d3a | Ruby | matao0214/Demo | /1946.rb | UTF-8 | 40 | 2.703125 | 3 | [] | no_license | m,n = gets.split.map(&:to_i)
puts m - n
| true |
fb1b4d1056735bb7a31160fc401957e5e149f55d | Ruby | redding/whysoslow | /lib/whysoslow/measurement.rb | UTF-8 | 950 | 3.046875 | 3 | [
"MIT"
] | permissive | require 'benchmark'
module Whysoslow
class Measurement
MEASUREMENTS = [:user, :system, :total, :real]
attr_reader :units, :multiplier
attr_reader *MEASUREMENTS
def initialize(units='ms')
@user, @system, @total, @real = 0
@units, @multiplier = if units == 's'
['s', 1]
else # MB
['ms', 1000]
end
end
def benchmark(&block)
Benchmark.measure(&block).tap do |values|
measurments = values.to_s.strip.gsub(/[^\s|0-9|\.]/, '').split(/\s+/)
self.user, self.system, self.total, self.real = measurments
end
end
protected
def user=(value_in_secs); @user = value_in_secs.to_f * @multiplier; end
def system=(value_in_secs); @system = value_in_secs.to_f * @multiplier; end
def total=(value_in_secs); @total = value_in_secs.to_f * @multiplier; end
def real=(value_in_secs); @real = value_in_secs.to_f * @multiplier; end
end
end
| true |
583d5916ca6bab4c6f0c6b6bda4769df9fa682dd | Ruby | krile136/atcoder | /138/A-Red_or_Not.rb | UTF-8 | 99 | 2.765625 | 3 | [] | no_license | a = gets.strip.to_i
s = gets.strip.split('')
if a >= 3200
puts s.join('')
else
puts 'red'
end | true |
d0a489568988b3fb6390a83c2b44fbfcd4fbd142 | Ruby | jpabico/reference_stuff | /euler_project/ep_problem_20.rb | UTF-8 | 175 | 3.1875 | 3 | [] | no_license |
product = 1
for i in 1..100
product *= i
end
a = product.to_s.split("")
b= a.map do |elem|
elem.to_i
end
sum = 0
b.each do |element|
sum += element
end
sum
| true |
3ef5c5fb75e5525a67880f3fd0d685fe6193b5f9 | Ruby | enowmbi/algorithms | /add_to_array_form_of_integer.rb | UTF-8 | 262 | 3.15625 | 3 | [] | no_license | # @param {Integer[]} a
# @param {Integer} k
# @return {Integer[]}
def add_to_array_form(a, k)
return a if k == 0
sum = (a.join.to_i) + k
result = []
sum.to_s.each_char do |char|
result << char.to_i
end
return result
end
| true |
24abe69353bbe2b363f591cee0fe9f7b8e901827 | Ruby | CynthiaBin/Programacion-Paralela | /proyecto/daemon.rb | UTF-8 | 1,737 | 2.765625 | 3 | [] | no_license | require 'httparty'
require_relative './models/server'
require_relative './models/file'
# Client
class Daemon
include HTTParty
base_uri 'localhost:9292'
def delete_(server_name, current_file)
url = '/files/' + server_name + '/' + current_file
self.class.delete(url)
end
def copy_(server_name, current_file, target)
url = '/files/' + current_file
body = { command: 'cp', target: '../' + server_name + target }
self.class.patch(url, body: body)
end
def run
for_ever = true
Thread.new do
while for_ever
servers = []
ServerM.servers.each { |server| servers.push(server.uri) }
p_deletes = FileM.by_status('PENDING_DELETE')
p_deletes.each do |file|
start_deletes(file.path, servers)
file.update_status('DELETED')
end
p_copies = FileM.by_status('PENDING_COPY')
p_copies.each do |file|
start_copies_(file.path, servers)
file.update_status('ACTIVE')
end
sleep 100
end
end
end
def start_copies_(current_file, servers)
t_file = current_file
from_server = ''
servers.each do |server_name|
if current_file.index(server_name) == 1
t_file = current_file.gsub '/' + server_name, ''
from_server = server_name
end
end
servers.each do |server_name|
copy_(server_name, current_file, t_file) unless from_server == server_name
end
end
def start_deletes(current_file, servers)
servers.each do |server_name|
if current_file.index(server_name) == 1
current_file = current_file.gsub '/' + server_name, ''
end
end
servers.each { |server_name| delete_(server_name, current_file) }
end
end
| true |
9e4a027cc91f93ad7a6c9fbb72dfdcb0476e1dd2 | Ruby | mthorry/ruby-collaborating-objects-lab-web-071717 | /lib/song.rb | UTF-8 | 525 | 4.03125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # The Song class will be responsible for creating songs given each filename and sending the artist's name (a string) to the Artist class
class Song
attr_accessor :name, :artist
def initialize(name)
@name = name
end
def self.new_by_filename(filename)
song_name = filename.split(" - ")[1]
song = self.new(song_name)
artist_name = filename.split(" - ")[0]
artist = Artist.new(artist_name)
song.artist = artist
song
end
def artist_name(artist_name)
@artist = artist_name
end
end | true |
9ace6b60423d7a3abdb81b985d5c0a35c2831546 | Ruby | kaanbursa/kaan.bursa.kaanbursa | /exercises/hashonhash.rb | UTF-8 | 238 | 2.78125 | 3 | [] | no_license | hash1 = {
:description => "rice",
:ingrendients => ["salt", "pepper", "water"],
:steps => ["soak the rice in water", "boil and cook", "add salt"]
}
cookbook = {
"Hash browns" => ["description", "ingrendients", "steps"]
}
puts hash1 | true |
118cf2a5aef62c4f06fe3ce166540b25c22e0ee9 | Ruby | Asoyan/exo_rb | /pyramide.rb | UTF-8 | 636 | 3.265625 | 3 | [] | no_license | i = 0
puts ("- Salut BG, bienvenue dans ma super pyramide ! Combien d'étages veux-tu ? ")
print "> "
nombre = gets.chomp.to_i
puts ("- On essaye!! : ")
while (i < nombre)
i += 1
htag = "#" * i
puts htag
end
puts "- OHHH!! Bravooo BGGG!! t'es trop fort là !!! t'arrives bien à descendre toi hein!!??? et bah tu peux remonter maintenant? "
j = 0
puts ("- Ben ouais, combien d'étages veux-tu ? ")
print "> "
nombre2 = gets.chomp.to_i
espace2 = ""
puts ("- Regarde bien!! : ")
while (j < nombre2)
j += 1
htag2 = ("#" * (j)).rjust(nombre2, ' ')
puts (espace2+htag2)
end
puts "- T'es vraiment un wild BGGG!!!"
| true |
7a65da9f2ed08560b1db6f90c1a0e550e4f89597 | Ruby | TaylorHuston/Ruby_RestaurantFinder | /lib/restaurant.rb | UTF-8 | 1,649 | 3.296875 | 3 | [] | no_license | class Restaurant
@@filepath=nil
def self.filepath=(path=nil)
@@filepath = File.join(APP_ROOT, path)
end
attr_accessor :name, :cuisine, :price
#Class should know if restaurant file exists
def self.file_usable?
if (@@filepath!=nil && File.exists?(@@filepath) && File.readable?(@@filepath) && File.writable?(@@filepath))
return true
else
return false
end
end
#Create restaurant file
def self.create_file
File.open(@@filepath, 'w')
return file_usable?()
end
def self.build
args = {}
print "Restaurant name: "
args[:name]= gets.chomp.strip
print "Restaurant cuisine: "
args[:cuisine] = gets.chomp.strip
print "Restaurant price: "
args[:price] = gets.chomp.strip
self.new(args)
end
def self.saved_restaurants()
restaurants = []
if file_usable?
File.open(@@filepath, 'r') do |file|
file.each_line do |line|
line_array = line.chomp.split("\t")
temp = Restaurant.new
temp.name = line_array[0]
temp.cuisine = line_array[1]
temp.price = line_array[2]
restaurants << temp
end
end
end
return restaurants
end
def initialize(args={})
@name = args[:name] ||""
@cuisine = args[:cuisine] || ""
@price = args [:price] || ""
end
#Saves a new restaurant to the textfile
def save
if (!Restaurant.file_usable?)
return false
end
File.open(@@filepath, 'a') do |file|
file.puts "#{[@name, @cuisine, @price].join("\t")}\n"
end
return true
end
end
| true |
eec31cc165165225ffb118e5be24f06d48cf0aa1 | Ruby | idkjay/Launch | /week1-advoop/bounding-box/spec/02_bounding_area_spec.rb | UTF-8 | 1,717 | 3.0625 | 3 | [] | no_license | require_relative '../lib/bounding_area'
require_relative '../lib/bounding_box'
RSpec.describe BoundingArea do
describe '#boxes_contain_point?' do
it 'is always false for an empty bounding area' do
empty_area = BoundingArea.new([])
expect(empty_area.boxes_contain_point?(0.0, 0.0)).to eq(false)
end
it 'is true if the point is contained within one of the rects' do
bottom_box = BoundingBox.new(-3.0, -3.0, 2.0, 2.0)
middle_box = BoundingBox.new(0.0, 0.0, 2.0, 1.0)
top_box = BoundingBox.new(2.0, 1.0, 3.0, 4.0)
area = BoundingArea.new([middle_box, top_box])
expect(area.boxes_contain_point?(0, 0.5)).to eq(true)
expect(area.boxes_contain_point?(3.0, 4.0)).to eq(true)
another_area = BoundingArea.new([bottom_box, top_box])
expect(another_area.boxes_contain_point?(-2.5, -2.0)).to eq(true)
expect(another_area.boxes_contain_point?(3.0, 3.0)).to eq(true)
end
it 'is false if the point is outside of all of the rects' do
bottom_box = BoundingBox.new(-3.0, -3.0, 2.0, 2.0)
middle_box = BoundingBox.new(0.0, 0.0, 2.0, 1.0)
top_box = BoundingBox.new(2.0, 1.0, 3.0, 4.0)
area = BoundingArea.new([middle_box, top_box])
expect(area.boxes_contain_point?(0.0, 3.0)).to eq(false)
expect(area.boxes_contain_point?(6.0, 4.0)).to eq(false)
expect(area.boxes_contain_point?(-2.0, -2.5)).to eq(false)
another_area = BoundingArea.new([bottom_box, top_box])
expect(another_area.boxes_contain_point?(-9.0, 3.0)).to eq(false)
expect(another_area.boxes_contain_point?(-9.0, -9.0)).to eq(false)
expect(another_area.boxes_contain_point?(0, 0.5)).to eq(false)
end
end
end
| true |
d941b39da073b8eafae9342df8a4e189974c4f68 | Ruby | oscos/launch_school | /rb101/lesson2/calculator_refactored.rb | UTF-8 | 2,171 | 4.15625 | 4 | [] | no_license | =begin
Launch School: RB101 - Lesson 2 - Refactoring Calculator
ExerciseName: [Refactoring Calculator](https://launchschool.com/lessons/a0f3cd44/assignments/fcd8a299)
FileName: calculator.rb
Answered On: 09/18/2020
=end
=begin
- ask the user to input two numbers
- ask user to input type of operation to use in calculation
- output result of calculation
- user Kernel.gets()
- use keernel.chomp()
=end
require 'pry'
num1 = nil
num2 = nil
op_type = nil
def user_prompt(message)
Kernel.puts("=> #{message}")
end
def valid_number?(number)
return 0 if number == "0"
number.to_f != 0
# binding.pry
end
user_prompt("What is your first name?")
fname = Kernel.gets().chomp()
user_prompt("Welcome #{fname}. Let's calculate some numbers!")
loop do while
loop do
user_prompt("Enter a number")
num1 = Kernel.gets().chomp()
break if valid_number?(num1)
user_prompt("Invalid entry for the first number. Try again.")
end
loop do
user_prompt("Enter a second number")
num2 = Kernel.gets().chomp()
break if valid_number?(num2)
user_prompt("Invalid entry for the second number. Try again.")
end
operator_prompt = <<-MSG
What operation would you like to perform
1 - Add
2 - Subtract
3 - Multiply
4 - Divide
MSG
user_prompt(operator_prompt)
loop do
op_type = Kernel.gets().chomp()
num = ["1", "2", "3", "4"].include?(op_type) # returns True or False
break if num
user_prompt("Invalid operator, Entry must be either 1, 2, 3, or 4")
# binding.pry
end
op_type_selected =
case op_type
when "1" then "Adding"
when "2" then "Subtracting"
when "3" then "Multiplying"
else "Dividing"
end
result =
case op_type
when "1" then num1.to_f() + num2.to_f()
when "2" then num1.to_f() - num2.to_f()
when "3" then num1.to_f() * num2.to_f()
else num1.to_f() / num2.to_f()
end
Kernel.puts("#{op_type_selected} #{num1} and #{num2} is #{result}")
user_prompt("Play again? Y for Yes or any key for No")
play = Kernel.gets().chomp()
if play.downcase == "y"
next
else
user_prompt("Thanks for playing! Good-bye!")
break
end
end
| true |
fea8ff8756691a3e4c2a56345bb5834f6068325c | Ruby | cherifb16/ruby_sample_codes | /code.rb | UTF-8 | 1,545 | 3.984375 | 4 | [] | no_license | # concaténation
# car = "Ferrari"
# puts "my favorite car is" + car
# puts "One of the luxury cars is the" + car
# Expansion de l'expression
# car = "Ferrari"
# puts "my favorite car is #{car}"
# puts "One of the luxury cars is the #{car}"
# compter les caractères dans un mot d'un utilisateur
# puts "enter any word"
# word = gets.chomp
# word.length
# puts " the length of the entered word/sentence is: #{word.length}"
# Application blog
# puts "Veuillez sélectionner l'action ci-dessous\n"
# puts "1: Créer un blog"
# puts "2: Quitter l'application"
# number = gets.to_i
# if number == 1
# puts "1 : Créer un blog\n\n"
# puts "Entrez le titre du blog"
# blog_title = gets
# puts "Entrez le contenu du blog"
# blog_content = gets
# puts "Titre et corps du texte saisis\n\n"
# puts "Title:#{blog_title}"
# puts "Contenu:#{blog_content}"
# elsif number == 2
# puts "2: Quitter l'application"
# else
# puts "Veuillez entrer un nombre de 1 à 2"
# end
# Déclaration "Unless".
# age = 22
# unless age < 20
# puts "I'm not a minor"
# end
# Déclaration case
# age = 20
# case age
# when 10
# puts "I'm still a kid"
# when 20
# puts "Became an adult"
# when 60
# puts "Retirement age"
# else
# puts ""
# end
#variable
name1 = "John"
name2 = "James"
name3 = "Jack"
#Maintenir dans le tableau
names = ["John", "James","Jack"]
puts names
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.