# frozen_string_literal: true
module Verto
module DSL
class File
def initialize(filename, path: Verto.config.project.path)
@filename = filename
@path = Pathname.new(path)
end
def replace(to_match, to_replace)
content = file.read
file.open('w') do |f|
f << content.sub(to_match, to_replace)
end
end
def replace_all(to_match, to_replace)
content = file.read
file.open('w') do |f|
f << content.gsub(to_match, to_replace)
end
end
def append(content)
file.open('a') do |f|
f << content
end
end
def prepend(content)
file_content = file.read
file.open('w') do |f|
f << (content + file_content)
end
end
alias gsub replace_all
alias sub replace
private
def file
@path.join(@filename)
end
end
end
end
# Encoding: utf-8
require "spec_helper"
require "longest_word"
describe "#generate_grid" do
let(:grid) { generate_grid(9) }
it "should generate grid of required size" do
grid.size.must_equal 9
end
it "should generate random grid" do
grid.wont_equal generate_grid(9)
end
it "should allow for repetitive letters" do
long_grid = generate_grid(26)
long_grid.uniq.length.wont_equal long_grid.length # hoping not to compute a perfect permutation :)
end
end
TEST = [["wagon", %w(W G G Z O N A L)], ["law", %w(W G G Z O N A L)], ["law", %w(W G G Z O N A L)]]
describe "#run_game" do
let(:perfect) { run_game("wagon", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
let(:quick) { run_game("law", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
let(:slow) { run_game("law", %w(W G G Z O N A L), Time.now, Time.now + 10.0) }
context "the given word is not an english one" do
let(:not_english) { run_game("zon", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
it "should compute score of zero for non-english word" do
not_english[:score].must_equal 0
end
it "should return nil translation for invalid word" do
not_english[:translation].must_equal nil
end
it "should build custom messages for invalid word" do
not_english[:message].must_equal "not an english word"
end
end
context "the given word is not in the grid" do
let(:not_in_the_grid) { run_game("train", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
it "should compute score of zero for word not in the grid" do
not_in_the_grid[:score].must_equal 0
end
it "should build custom messages for word not in the grid" do
not_in_the_grid[:message].must_equal "not in the grid"
end
end
it "should compute higher score for longer word" do
perfect[:score].must_be :>, quick[:score]
end
it "should compute higher score for quicker answer" do
quick[:score].must_be :>, slow[:score]
end
it "should consider the first translation returned by the API" do
perfect[:translation].must_equal "chariot"
end
it "should build custom messages for good catch" do
perfect[:message].must_equal "well done"
end
end
true
92e1eb6e7c65ba702bb30695f57fb2520423a7a8
Ruby
marina-h/LaunchSchool
/course_120/lesson_2/03_lecture_inheritance.rb
UTF-8
2,406
4.40625
4
[]
no_license
# 1. Given this class:
# class Dog
# def speak
# 'bark!'
# end
#
# def swim
# 'swimming!'
# end
# end
#
# teddy = Dog.new
# puts teddy.speak # => "bark!"
# puts teddy.swim # => "swimming!"
# One problem is that we need to keep track of different breeds of dogs, since
# they have slightly different behaviors. For example, bulldogs can't swim, but
# all other dogs can.
# Create a sub-class from Dog called Bulldog overriding the swim method to
# return "can't swim!"
# class Bulldog < Dog
# def swim
# "can't swim!"
# end
# end
#
# karl = Bulldog.new
# puts karl.speak # => "bark!"
# puts karl.swim # => "can't swim!"
# 2. Let's create a few more methods for our Dog class.
# class Dog
# def speak
# 'bark!'
# end
#
# def swim
# 'swimming!'
# end
#
# def run
# 'running!'
# end
#
# def jump
# 'jumping!'
# end
#
# def fetch
# 'fetching!'
# end
# end
# Create a new class called Cat, which can do everything a dog can, except swim
# or fetch. Assume the methods do the exact same thing. Hint: don't just copy
# and paste all methods in Dog into Cat; try to come up with some class
# hierarchy.
class Pet
def run
'running!'
end
def jump
'jumping!'
end
end
class Dog < Pet
def speak
'bark!'
end
def swim
'swimming!'
end
def fetch
'fetching!'
end
end
class Bulldog < Dog
def swim
"can't swim!"
end
end
class Cat < Pet
def speak
'meow!'
end
end
pete = Pet.new
kitty = Cat.new
dave = Dog.new
bud = Bulldog.new
puts pete.run # => "running!"
# puts pete.speak # => NoMethodError
puts kitty.run # => "running!"
puts kitty.speak # => "meow!"
# puts kitty.fetch # => NoMethodError
puts dave.speak # => "bark!"
puts bud.run # => "running!"
puts bud.swim # => "can't swim!"
# 3. Draw a class hierarchy diagram of the classes from step #2
# Pet (run, jump) -> Dog (speak, fetch, swim) -> Bulldog (swim)
# -> Cat (speak)
# 4. What is the method lookup path and how is it important?
# The method loopup path is the class hierarchy in which Ruby will look for
# method names to invoke. You can use the .ancestors method to check the path:
p Bulldog.ancestors
# => [Bulldog, Dog, Pet, Object, Kernel, BasicObject]
true
2bf65e00920f5f130eb8ae07dea357c4ea2a3487
Ruby
jkgit/sample-ror-application
/app/models/catalog.rb
UTF-8
3,072
2.828125
3
[]
no_license
class Catalog < ActiveRecord::Base
attr_accessible :name
has_many :items
# return an array of item objects corresponding to a batch of items related to this catalog
def get_batch_of_items (page = nil, size=nil)
# set reasonable defaults for page and convert to an int
page=page.nil? ? 1 : page.to_i
# set reasonable defaults for size and convert to an int
size=size.nil? ? 12 : size.to_i
# calculate the start item based on the page and the size of the batch
start_item = (page - 1) * size + 1
# grab the next set of items based on start item and size for this catalog. this is not ideal
# because it grabs all items first and then processes them. would be better to only select a
# page at a time when executing the query
all_items_for_catalog = Item.where("catalog_id = ?", id).order(:sort_order);
item_groups = all_items_for_catalog.in_groups_of(size, false)
if (item_groups.length>=page)
return item_groups[page-1]
end
end
# switch the sort order of each pair of id -> sort orders in the array
def self.do_update_order_of_items (sort_orders)
result = "success";
sort_orders.each do |k,v|
item=Item.find(k);
item.sort_order=v;
if !item.save then
result = "failed"
end
end
result
end
# insert the moved items before the dropped on item, and then recalculate the sort order for the new list
# only updating items that have a new sort order. do not update all items if the sort order has not changed
def do_update_order_of_items_bulk (moved_item_ids, before_item_id)
all_items = Item.where("catalog_id = ?", id).order(:sort_order)
# will hold item objects based on ids in moved_items
new_items = Array.new
# loop through all items related to this catalog and insert the moved items before the item
all_items.each do |item|
# insert the moved items before this item if its id matches the before_item_id
if (item.id==before_item_id.to_i) then
moved_item_ids.each do |moved_item_id|
new_items.push Item.find(moved_item_id)
end
end
# don't add the moved items back into the array at their regular position but add everything else
if moved_item_ids.index(item.id.to_s).nil? then
new_items.push item
end
end
# a hash to hold the item id and item sort order of any items that were affected by the move
changed_items = Hash.new
# now loop through all items and reset the sort order. save the item if changed and populate an array
# which we will return
current_sort_order=1
new_items.each do | item |
if (item.sort_order != current_sort_order )
item.sort_order=current_sort_order
if item.save then
changed_items[item.id]=item.sort_order
end
end
current_sort_order=current_sort_order+1
end
Rails.logger.debug("Changed sort orders: #{changed_items.inspect}")
return changed_items
end
end
true
4275c3256f4338b4ffba2c53c45d5bff182b1301
Ruby
SProjects/ruby-friday
/symbols.rb
UTF-8
946
4.4375
4
[]
no_license
=begin
Symbols are like literal constants only that they don't hold a value or object
BUT their name is important.
They are written with a preceding full colon.
USES:
1.used commonly in ruby as parameters to functions e.g
attr_accessor :firstname :lastname or attr_accessor(:firstname :lastname)
2.used as keys in hashes e.g
student1 = {:firstname => "Oliver", :lastname => "Twist"}
student2 = {:firstname => "John", :lastname => "Doe", :age => 26, :hobbies => ["swimming,soccer"]}
3.More efficient.
If program one is run in memory we shall have :good,:bad
If program two is run in memory we shall have good,good,bad
=end
# PROGRAM 1 USES SYMBOLS:
current_situation = :good
puts "Everything is fine" if current_situation == :good
puts "PANIC!" if current_situation == :bad
# PROGRAM 2 USES VARIABLES:
current_situation = "good"
puts "Everything is fine" if current_situation == "good"
puts "PANIC!" if current_situation == "bad"
true
1cb06ca54c3da1aafcd637961030947bf3dc7509
Ruby
samg/timetrap
/lib/timetrap/formatters/csv.rb
UTF-8
514
2.96875
3
[
"MIT"
]
permissive
module Timetrap
module Formatters
class Csv
attr_reader :output
def initialize entries
@output = entries.inject("start,end,note,sheet\n") do |out, e|
next(out) unless e.end
out << %|"#{e.start.strftime(time_format)}","#{e.end.strftime(time_format)}","#{escape(e.note)}","#{e.sheet}"\n|
end
end
private
def time_format
"%Y-%m-%d %H:%M:%S"
end
def escape(note)
note.gsub %q{"}, %q{""}
end
end
end
end
true
7c49dcc1200716be3302667072b934d44a2927e1
Ruby
jiripospisil/rock_config
/lib/rock_config/config.rb
UTF-8
508
2.875
3
[
"MIT"
]
permissive
module RockConfig
class Config
def initialize(hash)
@hash = hash
end
def [](key)
fetch(key)
end
def method_missing(name, *args, &block)
fetch(name.to_s)
end
def raw
@hash.dup
end
private
def fetch(key, default = nil)
value = @hash[key.to_s]
value_or_config(value) unless value.nil?
end
def value_or_config(value)
if Hash === value
Config.new(value)
else
value
end
end
end
end
true
d2a61b2adfd9c304ee3ab73759866afc7f9aea9d
Ruby
Machi427/ruby_scripting
/sample_scripts/lecture06/randseek.rb
UTF-8
480
3.3125
3
[]
no_license
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
thisfile = "randseek.rb" # このファイルの名前
sz = File.size(thisfile)
open(thisfile, "r") do |file|
while true
while line = file.gets
print line
end
puts "読み終わりました。[Enter]でもう一度。やめたい場合は C-c"
gets
file.seek(rand(sz)) # 乱数でファイルポインタを移動
printf("%dバイト目から読み直します。\n", file.pos)
end
end
true
fbd469533131a84e6e73c395ea8ffc996d308627
Ruby
almendragr/introduccion_ruby
/ventas_faker/pedido.rb
UTF-8
1,410
3.625
4
[]
no_license
require 'faker'
class Pedido
attr_reader :codigo #
attr_reader :total # la suma total del pedido
attr_accessor :productos # almacenar una lista/array de productos
attr_reader :fecha_creacion # fecha de hoy
attr_accessor :fecha_entrega # sumar a la fecha de hoy 2 días
attr_reader :estado # preparando / enviando / entregado
def initialize
@codigo = Faker::Barcode.ean
@total = 0
@productos = []
@fecha_creacion = Time.now.strftime("%d/%m/%Y")
@fecha_entrega = Faker::Date.forward(days: 2)
@estado = "preparando"
end
def mostrar_resumen_pedido
puts " ===== RESUMEN PEDIDO ===="
puts "Codigo: #{self.codigo}"
puts "Fecha creacion: #{self.fecha_creacion}"
puts "Fecha entrega: #{self.fecha_entrega}"
puts "Estado: #{self.estado}"
self.productos.each do |producto|
puts "\t\t#{producto.nombre} \t\t #{producto.precio}"
end
puts "_____________________"
puts "Total a pagar es \t\t #{suma_total}"
end
def suma_total
#map genera una nueva lista con el ultimo elemento del bloque
precios = self.productos.map do |producto|
producto.precio
end
return precios.sum
end
end
require_relative 'tic_tac_toe'
class TicTacToeNode
def initialize(board, next_mover_mark, prev_move_pos = nil)
@board = board
@next_mover_mark = next_mover_mark
@prev_move_pos = prev_move_pos
@parent = nil
end
def losing_node?(evaluator)
if @board.won?
@board.winner != evaluator
else
false
end
end
def winning_node?(evaluator)
if @board.won?
@board.winner == evaluator
else
false
end
end
# This method generates an array of all moves that can be made after
# the current move.
def children
possible_moves = [ ]
@board.each do |row|
@col.each do |col|
move = [row, col]
possible_moves << move if @board.empty?(move)
end
end
children_array = possible_moves.map do |move|
child_board = board.dup
child_board[move] = next_mover_mark
child = TicTacToeNode.new(child_board, @next_mover_mark, move)
child.parent = self
child.switch_mark
end
children_array
end
def switch_mark
@next_mover_mark = (@next_mover_mark == :x) ? :o : :x
end
protected
def parent=(tictacnode)
@parent = tictacnode
end
end
true
38d76b4cbfb71c56ebe3374f1fe461fcd31f5d6a
Ruby
BenDunjay/FizzBuzz
/spec/fizzbuzz_spec.rb
UTF-8
1,138
3.375
3
[]
no_license
require "./lib/fizzbuzz.rb"
RSpec.describe FizzBuzz do
let(:numbers) { described_class.new(15) }
context "initializing" do
it "creates a new instance" do
expect(numbers).to be_instance_of(FizzBuzz)
end
it " works with no argument" do
expect(FizzBuzz).to respond_to(:new).with(1).arguments
end
end
describe "#fizzbuzz_action method" do
context "is divisible by 3" do
let(:divisible_by_3) { FizzBuzz.new }
it "will return `Fizz` if the number is divisible by 3 " do
expect(divisible_by_3.fizzbuzz_output(3)).to eq("Fizz")
end
end
context "is divisible by 5" do
let(:divisible_by_5) { FizzBuzz.new }
it "will return `Fizz` if the number is divisible by 5 " do
expect(divisible_by_5.fizzbuzz_output(5)).to eq("Buzz")
end
end
context "is divisible by 3 and 5" do
let(:divisible_by_3_and_5) { FizzBuzz.new }
it "will return `Fizz` if the number is divisible by 3 and 5 " do
expect(divisible_by_3_and_5.fizzbuzz_output(15)).to eq("FizzBuzz")
end
end
end # fizzbuzz method describe end
end #class end
true
2b6d8436e2123fe6bfa71b1bc677d6d0ac3e40c8
Ruby
godfat/struct_trans
/lib/struct_trans/hash.rb
UTF-8
306
2.515625
3
[
"Apache-2.0"
]
permissive
module StructTrans
module_function
def trans_hash struct, *schemas
transform(:hash, struct, schemas)
end
def construct_hash
{}
end
def write_hash hash, key, value
raise KeyTaken.new("Key already taken: #{key.inspect}") if
hash.key?(key)
hash[key] = value
end
end
# coding: utf-8
%w{httpi multi_json multi_xml rainbow}.map { |lib| require lib }
module Oversetter
class Hablaa
# Fetches supported languages from Hablaa.
class Getlangs
# @param search [String] The word or phrase to search for.
# @param params [Hash] The search parameters to use.
def get_lang(search, params)
func, result = 'languages', nil
lang = Oversetter::Hablaa.new
result = lang.get_word(search, func, params, result)
result = MultiJson.load(result) #array of hashes
label = 'Languages'
Oversetter.label(label)
puts ''
x, y = 0, result.length - 1
while x <= y
item = result[x]
print Rainbow('Name|').bright
print "#{item['name']}|"
print Rainbow('Code|').bright
print "#{item['lang_code']}|"
print Rainbow('Site Language?|').bright
if item['site_language'] == '1' then print 'yes' else print 'no'; end
puts ''
x += 1
end
end
end
end
end
true
960a11b357b26916a9b3d2030dbcececb01d5df7
Ruby
prongstudios/tutorial
/lib/drm.rb
UTF-8
348
2.53125
3
[
"MIT"
]
permissive
require 'rest-client'
require 'json'
class Drm
def check
begin
@response = RestClient.get 'http://tutorialthegame.com/pages/drm.json', {:accept => :json}
return JSON.parse(@response)["status"]
rescue Exception => e
return 'error checking drm: ' + e.message
end
end
def success
return JSON.parse(@response)["success"]
end
end
true
847db69337ababc8c6ee91f46a4b26473b4a7cb0
Ruby
cherylsiew/ownpairbnb
/app/models/booking.rb
UTF-8
423
2.515625
3
[]
no_license
class Booking < ApplicationRecord
belongs_to :user
belongs_to :listing
validate :overlap?
def overlap?
if self.listing.bookings.where("(start_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?)", self.start_date, self.end_date, self.start_date, self.end_date).count > 0
errors.add(:start_date, "is not available")
end
end
# def overlap?(x,y)
# (x.first - y.end) * (y.first - x.end) > 0
# end
end
true
e250ba33fbbddd2a2fcc78b339ded33297bb8bef
Ruby
activeadmin/arbre
/lib/arbre/element/builder_methods.rb
UTF-8
2,227
2.96875
3
[
"MIT"
]
permissive
# frozen_string_literal: true
module Arbre
class Element
module BuilderMethods
def self.included(klass)
klass.extend ClassMethods
end
module ClassMethods
def builder_method(method_name)
BuilderMethods.class_eval <<-EOF, __FILE__, __LINE__
def #{method_name}(*args, &block)
insert_tag ::#{self.name}, *args, &block
end
EOF
end
end
def build_tag(klass, *args, &block)
tag = klass.new(arbre_context)
tag.parent = current_arbre_element
with_current_arbre_element tag do
if block_given? && block.arity > 0
tag.build(*args, &block)
else
tag.build(*args)
append_return_block(yield) if block_given?
end
end
tag
end
def insert_tag(klass, *args, &block)
tag = build_tag(klass, *args, &block)
current_arbre_element.add_child(tag)
tag
end
def current_arbre_element
arbre_context.current_arbre_element
end
def with_current_arbre_element(tag, &block)
arbre_context.with_current_arbre_element(tag, &block)
end
alias_method :within, :with_current_arbre_element
private
# Appends the value to the current DOM element if there are no
# existing DOM Children and it responds to #to_s
def append_return_block(tag)
return nil if current_arbre_element.children?
if appendable_tag?(tag)
current_arbre_element << Arbre::HTML::TextNode.from_string(tag.to_s)
end
end
# Returns true if the object should be converted into a text node
# and appended into the DOM.
def appendable_tag?(tag)
# Array.new.to_s prints out an empty array ("[]"). In
# Arbre, we append the return value of blocks to the output, which
# can cause empty arrays to show up within the output. To get
# around this, we check if the object responds to #empty?
if tag.respond_to?(:empty?) && tag.empty?
false
else
!tag.is_a?(Arbre::Element) && tag.respond_to?(:to_s)
end
end
end
end
end
true
2db5d07dc8a1411acefe43844f373c3e5ae12fdb
Ruby
ivanjankovic/e-appacademy
/Ruby/*05_sudoku_game/board.rb
UTF-8
1,879
3.53125
4
[]
no_license
require_relative 'tile'
# require 'colorize'
class Board
attr_reader :grid
def initialize
@grid = Array.new(9) { Array.new(9) }
end
def from_file
File.readlines('./puzzles/sudoku1.txt')
# File.readlines('./puzzles/sudoku1_almost.txt')
end
def populate
(0...9).each do |row|
(0...9).each do |col|
value = self.from_file[row][col].to_i
if value == 0
@grid[row][col] = Tile.new(nil, false)
else
@grid[row][col] = Tile.new(value, true)
end
end
end
end
def set_value(pos, value)
row, col = pos
if @grid[row][col].from_file
return false
else
@grid[row][col].value = value
return true
end
end
def render
system 'clear'
puts
puts " 0 1 2 3 4 5 6 7 8".light_black
puts " #{'-' * 19}".light_cyan
(0...9).each do |row|
print row.to_s.light_black + ' '
(0...9).each do |col|
print " #{@grid[row][col]}"
end
puts
end
puts " #{'-' * 19}".light_cyan
end
def solved?
if grid.flatten.none?(nil)
rows = grid.map { |row| row.map(&:value) }
columns = rows.transpose
blocks = to_blocks(rows)
all_numbers?(rows) && all_numbers?(columns) && all_numbers?(blocks)
end
end
def to_blocks(rows)
r_st, r_end, c_st, c_end = 0, 2, 0, 2
blocks, block = [], []
3.times do
rows.each_with_index do |row, idx|
(c_st..c_end).each do |col|
block << row[col]
end
if idx == 2 || idx == 5 || idx == 8
blocks << block
block = []
end
end
c_st += 3
c_end += 3
end
blocks
end
def all_numbers?(array_2d)
array_2d.all? { |array| uniq_nums?(array) }
end
def uniq_nums?(numbers)
(1..9).all? { |num| numbers.include?(num) }
end
end
true
4d4bedea2e91ab93970f0c080e263571e64b527d
Ruby
cyrilpestel/searchzt
/src/ZTSearchProvider.rb
UTF-8
1,214
2.6875
3
[]
no_license
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require "cgi"
require_relative 'Util'
class ZTSearchProvider
def search(term, neededQuality)
termEncoded = CGI::escape(term)
url = "http://www.zone-telechargement.com/films-gratuit.html?q=#{termEncoded}&minrating=0&tab=all&orderby_by=popular&orderby_order=desc"
puts "============================================"
puts "Looking for : #{term}"
puts "Getting url : #{url}"
puts "============================================"
begin
page = Nokogiri::HTML(open(url))
results = page.css("div[class='cover_infos_title'] a")
util = Util.new()
results.each { |result|
found = false
#details = result.css("span[class='detail_release size_11'] span")
#quality = details[0]
#lang = details.css("span")[1]
#puts quality
if !neededQuality
found = true
else
found = util.matchQuality(result,neededQuality)
end
if found
puts " + #{result.text} - #{result['href']}"
#puts quality.text
# puts result["href"]
# puts "============================================"
end
}
rescue OpenURI::HTTPError => error
response = error.io
response.status
end
end
end
module FunWithJsonApi
module Attributes
# Ensures a value is either Boolean.TRUE, Boolean.FALSE or nil
# Raises an argument error otherwise
class BooleanAttribute < Attribute
def decode(value)
return nil if value.nil?
return value if value.is_a?(TrueClass) || value.is_a?(FalseClass)
raise build_invalid_attribute_error(value)
end
private
def build_invalid_attribute_error(value)
exception_message = I18n.t('fun_with_json_api.exceptions.invalid_boolean_attribute')
payload = ExceptionPayload.new
payload.detail = exception_message
payload.pointer = "/data/attributes/#{name}"
Exceptions::InvalidAttribute.new(exception_message + ": #{value.inspect}", payload)
end
end
end
end
true
e72d6580814c994904bdffe612de4f90943598a8
Ruby
bolshakov/fear
/lib/fear/partial_function/guard/and.rb
UTF-8
889
2.921875
3
[
"MIT"
]
permissive
# frozen_string_literal: true
module Fear
module PartialFunction
class Guard
# @api private
class And < Guard
# @param c1 [Fear::PartialFunction::Guard]
# @param c2 [Fear::PartialFunction::Guard]
def initialize(c1, c2)
@c1 = c1
@c2 = c2
end
attr_reader :c1, :c2
private :c1
private :c2
# @param other [Fear::PartialFunction::Guard]
# @return [Fear::PartialFunction::Guard]
def and(other)
Guard::And.new(self, other)
end
# @param other [Fear::PartialFunction::Guard]
# @return [Fear::PartialFunction::Guard]
def or(other)
Guard::Or.new(self, other)
end
# @param arg [any]
# @return [Boolean]
def ===(arg)
(c1 === arg) && (c2 === arg)
end
end
end
end
end
true
36e8c84cf0960dfc44d428be308f2312a1d5a036
Ruby
kaledoux/ruby_small_problems
/Medium2/matching_parentheses.rb
UTF-8
3,019
4.75
5
[]
no_license
# Write a method that takes a string as argument, and returns true if all
# parentheses in the string are properly balanced, false otherwise.
# To be properly balanced, parentheses must occur in matching '(' and ')' pairs.
#
# Examples:
#
# balanced?('What (is) this?') == true
# balanced?('What is) this?') == false
# balanced?('What (is this?') == false
# balanced?('((What) (is this))?') == true
# balanced?('((What)) (is this))?') == false
# balanced?('Hey!') == true
# balanced?(')Hey!(') == false
# balanced?('What ((is))) up(') == false
#
# PEDAC:
# Understand the Problem:
# > Input:
# - string
# > Output:
# - boolean
# > Requirements:
# - must take a non empty string argument
# > string may or may not contain '(' or ')' or multiple instance of each
# - analyzes whether each parentheses is paired correctly
# > correct pairing must start with '(' and be followed by a ')'
# > each '(' must be accounted for with a ')' and vice verca
#
# > Rules:
# - must return a boolean value
# > true if each parentheses pair is valid
# > false otherwise
#
# Examples:
# p balanced?('What (is) this?') == true
# p balanced?('What is) this?') == false
# p balanced?('What (is this?') == false
# p balanced?('((What) (is this))?') == true
# p balanced?('((What)) (is this))?') == false
# p balanced?('Hey!') == true
# p balanced?(')Hey!(') == false
# p balanced?('What ((is))) up(') == false
#
# Data Structures:
# start with the string
# set value for a counter variable
# iterate through each character
# if the character is '('
# add 1 to the counter
# if the character is ')'
# subtract 1 from the counter
# break loop if counter value is less than 0
# test if the counter variable is == 0
# this will make sure the loop ended with each parentheses being paired
#
# Algorithm:
# > Pseudo:
# START
# DEFINE balanced?(string)
# SET counter = 0
# ITERATE through string (each_char)
# IF char == '(' ADD 1 to counter
# IF char == ')' SUBTRACT 1 from counter
# BREAK LOOP if counter < 0
# END
# CHECK if counter == 0
# END
#
# Code with Intent:
# def balanced?(string)
# counter = 0
# string.each_char do |char|
# counter += 1 if char == '('
# counter -= 1 if char == ')'
# break if counter < 0
# end
# counter.zero?
# end
# refactored to include capability for other paired characters
def balanced?(string, first, second)
counter = 0
string.each_char do |char|
counter += 1 if char == first
counter -= 1 if char == second
break if counter < 0
end
counter.zero?
end
p balanced?('Hey!', '(', ')') == true
p balanced?(')Hey!(', '(', ')') == false
p balanced?('What ((is))) up(', '(', ')') == false
# p balanced?('What (is) this?') == true
# p balanced?('What is) this?') == false
# p balanced?('What (is this?') == false
# p balanced?('((What) (is this))?') == true
# p balanced?('((What)) (is this))?') == false
# p balanced?('Hey!') == true
# p balanced?(')Hey!(') == false
# p balanced?('What ((is))) up(') == false
true
86c7fcea10ec1042ac30d9e0b5826883252e55be
Ruby
outstand/shipitron
/lib/shipitron/docker_image.rb
UTF-8
541
2.53125
3
[
"Apache-2.0"
]
permissive
require 'shipitron'
module Shipitron
class DockerImage < Hashie::Dash
property :registry
property :name
property :tag
def name_with_tag(tag_override = nil)
tag_str = [tag_override, tag, ''].find {|str| !str.nil? }
tag_str = tag_str.to_s
if !tag_str.empty? && !tag_str.start_with?(':')
tag_str = tag_str.dup.prepend(':')
end
name_with_registry = [registry, name].compact.join('/')
"#{name_with_registry}#{tag_str}"
end
def to_s
name_with_tag
end
end
end
true
ac596f3758af8f24b605945d0242f3dfba5687e1
Ruby
Sarvotam/some_solution
/Problem1.rb
UTF-8
329
4.5625
5
[]
no_license
# Problem 1:
# Given three numbers X, Y & Z. write a function/method that finds the greatest among the numbers.
def greatest
puts "Enter value of X"
x = gets.chomp
puts "Enter value of y"
y = gets.chomp
puts "Enter value of z"
z = gets.chomp
max_num = [x,y,z].max
puts "The greates number is #{max_num}"
end
greatest
class Bob
def hey message
empty = ->(message) { message == '' }
shouting = ->(message) { message == message.upcase }
question = ->(message) { message.end_with?('?') }
case message.to_s
when empty
'Fine. Be that way!'
when shouting
'Woah, chill out!'
when question
'Sure.'
else
"Whatever."
end
end
end
true
d0a77892563dd8b6bd6d06ae223058479c364844
Ruby
anastasiiatulentseva/tulenmenu
/test/models/dish_day_test.rb
UTF-8
1,022
2.71875
3
[]
no_license
require 'test_helper'
class DishDayTest < ActiveSupport::TestCase
def setup
@dish = dishes(:borsch)
@dish_day = dish_days(:one)
@dish_day_past = dish_days(:two)
end
test "should be valid" do
assert @dish_day.valid?
end
test "dish id should be present" do
@dish_day.dish_id = nil
assert_not @dish_day.valid?
end
test "day should be present" do
@dish_day.day = nil
assert_not @dish_day.valid?
end
test "dish should not go twice or more a day" do
dish_day = DishDay.new(dish_id: 3, day: Date.today)
dish_day.save
assert_not dish_day.persisted?
end
test "day should be today or later when create" do
dish_day = DishDay.new(day: Date.yesterday)
dish_day.save
assert_not dish_day.persisted?
assert_not dish_day.valid?
end
test "day can be in the past when save" do
@dish_day_past.day = 2.days.ago
@dish_day_past.save
assert @dish_day_past.persisted?
assert @dish_day_past.valid?
end
end
true
ea0f1245291f40113e6fdf70c46c42eedb583eb5
Ruby
motaHack/project100knock
/projectEuler/025.rb
UTF-8
158
2.859375
3
[]
no_license
start_time = Time.now
f1 = 0
f2 = 1
n = 0
while (f1.to_s).length < 1000 do
f3 = f1 + f2
f1 = f2
f2 = f3
n += 1
end
p n
puts(Time.now - start_time)
true
1989762b8d639ef4546dfe7ec3d0116499c9ddde
Ruby
okamiarata/okamiarata
/lib/api_url_generator.rb
UTF-8
1,493
2.59375
3
[
"MIT"
]
permissive
require "api_url_generator/version"
module APIURLGenerator
@@url
def self.url(x)
@@url = x
end
def self.get_url
@@url
end
def self.dectect_polymorphic(object)
object.instance_variables.each do |variable|
if variable.to_s[-9..-1] == "able_type"
return {
name: {variable.to_s[1..-1].to_sym => object.instance_eval(variable.to_s)},
id: {(variable.to_s[1..-5] + "id").to_sym => object.instance_eval(variable.to_s[1..-5] + "id")}
}
end
end
return false
end
def self.generate_url(object, nest = nil)
polymorphous = dectect_polymorphic(object)
if polymorphous && nest
nested_id = "/#{object.instance_eval(polymorphous[:name].keys[0].to_s).tableize.downcase}/#{object.instance_eval("#{polymorphous[:id].keys[0]}")}"
object_id = "/#{object.class.to_s.tableize.downcase}/#{object.id}"
if object.instance_eval(polymorphous[:name].keys[0].to_s).downcase != nest
raise ArgumentError, "Invalid nest param"
end
return "#{@@url}#{nested_id}#{object_id}"
elsif nest
begin
nested_id = "/#{nest.pluralize}/#{object.instance_eval("#{nest}_id")}"
object_id = "/#{object.class.to_s.tableize.downcase}/#{object.id}"
return "#{@@url}#{nested_id}#{object_id}"
rescue NameError
raise ArgumentError, "Invalid nest param"
end
else
return "#{@@url}/#{object.class.to_s.tableize.downcase}/#{object.id}"
end
end
end
true
a929dc24330d52deff6303913e81cbb821c54c43
Ruby
honorwoolong/launch_school
/RB100/Ruby_Basics_User_Input.rb
UTF-8
6,921
4.15625
4
[]
no_license
#Repeat after me
puts ">> Type anything you want:"
answer = gets.chomp
puts answer
#Your Age in Months
puts ">> What is your age in years?"
answer = gets.chomp
months = answer.to_i * 12
puts "You are #{months} months old."
#Print Something (Part 1)
puts ">> Do you want me to print something? (y/n)"
answer = gets.chomp
puts "something" if answer == "y"
#Print Something (Part 2)
loop do
puts ">> Do you want me to print something? (y/n)"
answer = gets.chomp.downcase
if answer == "y"
puts "something"
break
elsif answer == "n"
nil
break
else
puts "Invalid input! Please enter y or n"
end
end
#Launch school solution
choice = nil
loop do
puts '>> Do you want me to print something? (y/n)'
choice = gets.chomp.downcase
break if %w(y n).include?(choice) #%w(y n) = ['y', 'n'], shortcut syntax to represent the Array
puts '>> Invalid input! Please enter y or n'
end
puts 'something' if choice == 'y'
#Launch School Printer (Part 1)
loop do
puts ">> How many output lines do you want? Enter a number >= 3:"
answer = gets.chomp.to_i
if answer >= 3
answer.times { puts "Launch School is the best!" }
break
else
puts "That's not enough lines."
end
end
#Launch School Solution
number_of_lines = nil
loop do
puts '>> How many output lines do you want? Enter a number >= 3:'
number_of_lines = gets.to_i
break if number_of_lines >= 3
puts ">> That's not enough lines."
end
while number_of_lines > 0
puts 'Launch School is the best!'
number_of_lines -= 1
end
#Passwords
PASSWORD = "SecreT" #define password as a constant which is a string
loop do
puts ">> Please enter your password:"
answer = gets.chomp
break if answer == PASSWORD
puts ">> Invalid password!"
end
puts "Welcome!"
#User Name and Password
USER = "admin"
PASSWORD = "SecreT"
loop do
puts ">> Please enter user name:"
answer_1 = gets.chomp
puts ">> Please enter your password:"
answer_2 = gets.chomp
break if answer_1 == USER && answer_2 == PASSWORD
puts ">> Authorization failed!"
end
puts "Welcome!"
#Dividing Numbers
def valid_number?(number_string)
number_string.to_i.to_s == number_string
end
numerator = nil
loop do
puts ">> Please enter the numerator:"
numerator = gets.chomp
if valid_number?(numerator)
break
else
puts ">> Invalid input. Only integers are allowed."
end
end
denominator = nil
loop do
puts ">> Please enter the denominator:"
denominator = gets.chomp
if valid_number?(denominator) && denominator != "0"
break
elsif denominator == "0"
puts ">> Invalid input. A denominator of 0 is not allowed."
else
puts ">> Invalid input. Only integers are allowed."
end
end
puts "#{numerator}/#{denominator} is #{numerator.to_i/denominator.to_i}"
#Launch School Solution
def valid_number?(number_string)
number_string.to_i.to_s == number_string
end
numerator = nil
loop do
puts '>> Please enter the numerator:'
numerator = gets.chomp
break if valid_number?(numerator)
puts '>> Invalid input. Only integers are allowed.'
end
denominator = nil
loop do
puts '>> Please enter the denominator:'
denominator = gets.chomp
if denominator == '0'
puts '>> Invalid input. A denominator of 0 is not allowed.'
else
break if valid_number?(denominator)
puts '>> Invalid input. Only integers are allowed.'
end
end
result = numerator.to_i / denominator.to_i
puts "#{numerator} / #{denominator} is #{result}"
#Launch School Printer (Part 2)
loop do
puts '>> How many output lines do you want? Enter a number >= 3 (Q to Quit):'
number_of_lines = gets.chomp.downcase
if number_of_lines.to_i >= 3
number_of_lines.to_i.times { puts ">> Launch School is the best!" }
elsif number_of_lines == 'q'
break
else
puts ">> That's not enough lines."
end
end
#Launch School Solution
loop do
input_string = nil
number_of_lines = nil
loop do
puts '>> How many output lines do you want? ' \
'Enter a number >= 3 (Q to Quit):'
input_string = gets.chomp.downcase
break if input_string == 'q'
number_of_lines = input_string.to_i
break if number_of_lines >= 3
puts ">> That's not enough lines."
end
break if input_string == 'q'
while number_of_lines > 0
puts 'Launch School is the best!'
number_of_lines -= 1
end
end
#Opposites Attract
def valid_number?(number_string)
number_string.to_i.to_s == number_string && number_string.to_i != 0
end
loop do
input_number_1 = nil
loop do
puts ">> Please enter a positive or negative integer: "
input_number_1 = gets.chomp
break if valid_number?(input_number_1)
puts ">> Invalid input. Only non-zero integers are allowed"
end
input_number_2 = nil
loop do
puts ">> Please enter a positive or negative integer: "
input_number_2 = gets.chomp
break if valid_number?(input_number_2)
puts ">> Invalid input. Only non-zero integers are allowed"
end
if input_number_1.to_i * input_number_2.to_i < 0
puts "#{input_number_1} + #{input_number_2} = #{input_number_1.to_i + input_number_2.to_i}"
break
else
puts ">> Sorry. One integer must be positive, one must be negative."
puts ">> Please start over."
end
end
# Launch School Solution
def valid_number?(number_string)
number_string.to_i.to_s == number_string && number_string.to_i != 0
end
def read_number
loop do #if loop in def method, no need to use break to stop looping. After returning, it will stop
puts '>> Please enter a positive or negative integer:'
number = gets.chomp
return number.to_i if valid_number?(number) #Need to return value if true
puts '>> Invalid input. Only non-zero integers are allowed.'
end
end
first_number = nil
second_number = nil
loop do
first_number = read_number
second_number = read_number
break if first_number * second_number < 0
puts '>> Sorry. One integer must be positive, one must be negative.'
puts '>> Please start over.'
end
sum = first_number + second_number
puts "#{first_number} + #{second_number} = #{sum}"
# Or
def valid_number?(number_string)
number_string.to_i.to_s == number_string && number_string.to_i != 0
end
input_number_1 = nil
input_number_2 = nil
loop do
loop do
puts ">> Please enter a positive or negative integer: "
input_number_1 = gets.chomp
break if valid_number?(input_number_1)
puts ">> Invalid input. Only non-zero integers are allowed"
end
loop do
puts ">> Please enter a positive or negative integer: "
input_number_2 = gets.chomp
break if valid_number?(input_number_2)
puts ">> Invalid input. Only non-zero integers are allowed"
end
break if input_number_1.to_i * input_number_2.to_i < 0
puts ">> Sorry. One integer must be positive, one must be negative."
puts ">> Please start over."
end
puts "#{input_number_1} + #{input_number_2} = #{input_number_1.to_i + input_number_2.to_i}"
true
823969792672075b911ce27069c7ac8589514b56
Ruby
lmilekic/bluejadetwitter
/seeds.rb
UTF-8
1,137
3.0625
3
[]
no_license
require 'sinatra'
require 'sinatra/activerecord'
require './config/environments'
require 'faker'
require './app'
#100 users
# 10 tweets each
# each follows 10 people
puts "This is the seed file!!!"
test_users = Array.new
(0..99).each do
#create user
user = User.create(:username => Faker::Internet.user_name,
:password => Faker::Internet.password)
if user.save
"#{user.username} is now a test user!"
else
"unable to save user"
end
test_users << user
#make each test user tweet 10 times
(0..9).each do |i|
tweet = Tweet.create(:text => Faker::Hacker.say_something_smart,
:user_id => user.id,
:created_at => Time.now)
if tweet.save
"tweet attempt: #{i} for #{user.username} is a success!!!"
else
"unable to make #{user.username} tweet on attempt: #{i}"
end
end
end
# Make each user follow 10 other random users
test_users.each do |user|
to_follow = test_users.sample.id
stalk = FollowConnection.create(:user_id => user.id,
:followed_user_id => to_follow)
if stalk.save
"user #{user.id} is now following #{to_follow}"
else
"user #{user.id}unable to follow #{to_follow}"
end
end
true
3e719d032eda4341db98ade39c46826bacfeb39f
Ruby
GreenTer/My-knowledge
/L [11-20]/L15.1.0.rb
WINDOWS-1251
1,631
3.546875
4
[]
no_license
# encoding: cp866
# 3 ( )
class Albom
attr_accessor :name, :songs
def initialize name
@name = name
@songs = []
end
def add_song song
@songs << song
end
end
class Song
attr_accessor :name, :durations
def initialize name
@name = name
@durations = [] # @duration = duration song1 = Song.new 'Podryga Piter', 6 !!
end
def add_duration duration
@durations << duration
end
end
#
albom1 = Albom.new 'KPSS'
#
song1 = Song.new 'Podryga Piter'
song2 = Song.new 'Zaberi'
song3 = Song.new 'Ya ne lublu'
#
albom1.add_song song1
albom1.add_song song2
albom1.add_song song3
#
song1.add_duration '6 min'
song2.add_duration '4 min'
song3.add_duration '5 min'
#
all_alboms = []
all_alboms << albom1
# -> ->
all_alboms.each do |albom_name|
puts "Albom: #{albom_name.name}"
albom_name.songs.each do |song_name|
puts "Song: #{song_name.name}"
song_name.durations.each do |song_durations|
puts "Duration: #{song_durations}"
end
end
end
require_relative "../../../spec_helper"
module EnemyCharacters
class Dragon
module Actions
RSpec.describe BasicAttack do
let(:dummy) { DummyCharacter.new.generate_attributes }
describe ".run_against" do
it "will deal a range of damage to target" do
prev_hp = dummy.hp
BasicAttack.run_against(target: dummy, me: dummy)
damage_dealt = prev_hp - dummy.hp
expect(BasicAttack::DAMAGE_RANGE).to cover(damage_dealt)
end
end
end
end
end
end
true
c8148544a61f30b292fbca8bb36dab7918524277
Ruby
moveson/set-card-game
/lib/card.rb
UTF-8
972
3.78125
4
[
"MIT"
]
permissive
class Card
COLORS = %w[R G B]
NUMBERS = %w[1 2 3]
SHADINGS = %w[E H F]
SHAPES = %w[S O D]
def initialize(color, number, shading, shape)
@color = color # R, G, B
@number = number # 1, 2, 3
@shading = shading # E, H, F
@shape = shape # S, O, D
validate_setup
end
def to_s
"#{color}#{number}#{shading}#{shape}"
end
def ==(other)
color == other.color &&
number == other.number &&
shading == other.shading &&
shape == other.shape
end
attr_reader :color, :number, :shading, :shape
private
def validate_setup
raise ArgumentError, "Color #{color} is not recognized." unless COLORS.include?(color)
raise ArgumentError, "Number #{number} is not recognized." unless NUMBERS.include?(number)
raise ArgumentError, "Shading #{shading} is not recognized." unless SHADINGS.include?(shading)
raise ArgumentError, "Shape #{shape} is not recognized." unless SHAPES.include?(shape)
end
end
true
6cee52a9fdc892fc5bbf34fdc74968a045ddc8d4
Ruby
liaa2/wdi30-homework
/sarita_nair/Week4/Thursday/main.rb
UTF-8
1,485
2.671875
3
[]
no_license
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
require 'pry'
get '/' do
erb:home
end
get '/animals' do
sql_stmt = "select * from animal"
@results = query_db sql_stmt
# binding.pry
erb:animal_list
end
get '/animals/new' do
erb :animal_new
end
get '/animals/:id' do
@results = query_db "SELECT * FROM animal WHERE id=#{ params[:id] }"
@results = @results.first # Pluck the single butterfly from the results array.
erb :animal_show
end
get '/animals/:id/edit' do
@results = query_db "SELECT * FROM animal WHERE id=#{ params[:id] }"
@results = @results.first # Pluck the single butterfly from the results array.
erb :animal_edit
end
post '/animals' do
query = "INSERT INTO animal(name,class,image) values ('#{params[:name]}', '#{params[:class]}', '#{params[:image]}')"
query_db query
redirect to('/animals') # Redirect will make a GET request
end
post '/animals/:id' do
query = "UPDATE animal SET name='#{params[:name]}', class='#{params[:class]}', image='#{params[:image]}' WHERE id=#{ params[:id] }"
query_db query
redirect to("/animals/#{ params[:id] }")
end
get '/animals/:id/delete' do
query_db "DELETE FROM animal WHERE id=#{ params[:id] }"
redirect to("/animals")
end
def query_db(sql_statement)
# puts sql_statement # Optional feature which is nice for debugging
db = SQLite3::Database.new 'database.sqlite3'
db.results_as_hash = true
results = db.execute sql_statement
db.close
results # Implicit return
end
=begin
Copyright 2012-2013 inBloom, Inc. and its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require "date"
require "logger"
# Date Utility class
class DateUtility
# generates a random date on the specified interval (inclusive of the specified years)
def self.random_date_from_years(random, year1, year2 = year1)
if year1 != year2
year = random_year(random, year1, year2)
else
year = year1
end
month = random_month(random)
day = random_day(random, month, year)
random_date = Date.new(year, month, day)
random_date
end
# generates a random date on the specified interval (inclusive of the specified dates)
def self.random_date_on_interval(random, date1, date2 = date1)
raise(ArgumentError, ":date1 must be before :date2") if date1 > date2
dates = Array.new((date1..date2).step(1).to_a)
dates[random.rand(dates.size) - 1]
end
# generates a random school day on the specified interval (inclusive of the specified dates)
def self.random_school_day_on_interval(random, date1, date2 = date1)
raise(ArgumentError, ":date1 must be before :date2") if date1 > date2
if date1 == date2
raise(ArgumentError, ":dates must not fall on a weekend") if is_weekend_day(date1)
return date1
end
random_date = random_date_on_interval(random, date1, date2)
if is_saturday(random_date) or is_sunday(random_date)
if random_date == date2
# move date backward
random_date = random_date - 1 until ((random_date.wday + 7) % 7) == 5 or random_date == date1
if is_saturday(random_date) or is_sunday(random_date)
random_date = random_date + 1 until ((random_date.wday + 7) % 7) == 1 or random_date == date1
end
else
# move date forward
random_date = random_date + 1 until ((random_date.wday + 7) % 7) == 1 or random_date == date2
if is_saturday(random_date) or is_sunday(random_date)
random_date = random_date - 1 until ((random_date.wday + 7) % 7) == 5 or random_date == date1
end
end
end
random_date
end
# get a random month on the specified interval
def self.random_month(random, month1 = 1, month2 = 12)
random_on_interval(random, month1, month2)
end
# get a random day for the month (and year)
def self.random_day(random, month, year = Date.today.year)
if is_leap_year(year) and month == 2
return random_on_interval(random, 1, 29)
else
return random_on_interval(random, 1, get_num_days(month))
end
end
# generates a random year on the specified interval (inclusive of the specified years)
def self.random_year(random, year1, year2)
random_on_interval(random, year1, year2)
end
def self.random_on_interval(random, first, last)
random.rand(first..last)
end
# returns true if the specified year is a leap year, and false otherwise
def self.is_leap_year(year)
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0
end
# get the number of days for the month (excludes leap year calculation)
def self.get_num_days(month)
if month == 2
return 28
elsif month == 4 or month == 6 or month == 9 or month == 11
return 30
else
return 31
end
end
# get school holidays for specified year (start year for school year)
def self.get_school_holidays(random, year)
if year == nil
raise(ArgumentError, ":year must must not be null")
end
holidays = []
# get first monday of september (labor day)
labor_day = Date.new(year, 9, 1)
labor_day = labor_day + 1 until labor_day.wday == 1
holidays << labor_day
# get second monday of october
columbus_day = Date.new(year, 10, 1)
monday_counter = 0
until columbus_day.wday == 1 and monday_counter == 1 do
if columbus_day.wday == 1
monday_counter += 1
end
columbus_day += 1
end
holidays << columbus_day
# get second friday in november
veterans_day = Date.new(year, 11, 1)
friday_counter = 0
until veterans_day.wday == 5 and friday_counter == 1 do
if veterans_day.wday == 5
friday_counter += 1
end
veterans_day += 1
end
holidays << veterans_day
# get third thursday of november (and friday)
thanksgiving = Date.new(year, 11, 1)
thursday_counter = 0
until thanksgiving.wday == 4 and thursday_counter == 3 do
if thanksgiving.wday == 4
thursday_counter += 1
end
thanksgiving += 1
end
holidays << thanksgiving
holidays << thanksgiving + 1
# get christmas eve and christmas days off
christmas_eve = Date.new(year, 12, 24)
christmas_day = Date.new(year, 12, 25)
if christmas_eve.wday == 0
christmas_eve += 1
christmas_day = christmas_eve + 1
elsif christmas_eve.wday == 6
christmas_eve -= 1
christmas_day += 1
elsif christmas_eve.wday == 5
christmas_day += 2
end
holidays << christmas_eve << christmas_day
# get new year's eve and new year's day off
new_years_eve = Date.new(year, 12, 31)
new_years_day = Date.new(year+1, 1, 1)
if new_years_eve.wday == 0
new_years_eve += 1
new_years_day += 1
elsif new_years_eve.wday == 6
new_years_eve -= 1
new_years_day += 1
elsif new_years_eve.wday == 5
new_years_day += 2
end
holidays << new_years_eve << new_years_day
# pick a random week in march for spring break
monday_of_break = random_on_interval(random, 1, 3)
monday_counter = 0
spring_break = Date.new(year+1, 3, 1)
until spring_break.wday == 1 and monday_counter == monday_of_break do
if spring_break.wday == 1
monday_counter += 1
end
spring_break += 1
end
holidays << spring_break << spring_break + 1 << spring_break + 2 << spring_break + 3 << spring_break + 4
holidays
end
# finds the dates to evenly spread the specified number of events between the start and end date
def self.get_school_days_over_interval(start_date, end_date, num_events, holidays = [])
raise(ArgumentError, ":start_date must be before :end_date") if start_date > end_date
return [] if num_events == 0
dates = []
if start_date == end_date or num_events == 1
dates << end_date
return dates
end
num_dates = end_date - start_date
days_between_events = (num_dates / num_events).floor
days_between_events = 1 if days_between_events == 0
# iterate from start to end date using 'days_between_events'
(start_date..end_date).step(days_between_events) do |date|
next if dates.size >= num_events
if is_sunday(date)
# if the day is sunday, shift forward one day to monday
# -> check to make sure monday isn't a holiday (if it is, shift forward until a non-holiday date is found)
new_date = date + 1
new_date += 1 until !holidays.include?(new_date)
dates << new_date unless dates.include?(new_date)
elsif is_saturday(date)
# if the day is saturday, shift back one day to friday
# -> check to make sure friday isn't a holiday (if it is, shift backward until a non-holiday date is found)
new_date = date - 1
new_date -= 1 until !holidays.include?(new_date)
dates << new_date unless dates.include?(new_date)
else
# check to see if the day is a holiday
# -> if it is, shift forward to a non-holiday date
if holidays.include?(date)
new_date = date
new_date += 1 until !holidays.include?(new_date)
dates << new_date unless dates.include?(new_date)
else
dates << date unless dates.include?(date)
end
end
end
dates
end
# checks if the specified 'date' is a weekend day
# -> returns false if the 'date' is a week day
# -> returns true if the 'date' is a weekend day
def self.is_weekend_day(date)
is_saturday(date) or is_sunday(date)
end
# returns true if the specified day is a Saturday, and false otherwise
def self.is_saturday(date)
date.wday == 6
end
# returns true if the specified day is a Sunday, and false otherwise
def self.is_sunday(date)
date.wday == 0
end
# add school days function?
end
true
6592cec9af88e32c7637e3159e3ee04e97065c43
Ruby
lawrenae/sportsgamr
/lib/resultscalculator.rb
UTF-8
624
3.015625
3
[]
no_license
class ResultsCalculator
# attr_accessor :description, :estimate
def self.calculate_moneyline_winnings line, bet, win
line_as_integer = line.to_i
if line_as_integer > 0 then
percentage = line/100.0
return (bet*percentage).to_i
else
return (bet/line.abs.to_f * 100).round(2)
end
return 0
end
def self.calculate_moneyline_probability line
if line.to_i > 0 then
x = 100/(line+100).to_f*100
else
abs_line = line.abs
x = abs_line/(100+abs_line).to_f*100
end
return x.ceil
end
end
true
6c54d9b0ea1c75c023e6e3521de24be42ce27093
Ruby
librarySI2UNAL/BookShare_BackEnd
/app/daos/users_dao.rb
UTF-8
701
2.78125
3
[]
no_license
class UsersDAO
def self.validate_email( email )
User.exists_user_with_email( email )
end
def self.create_user( user_h )
latitude = user_h[:latitude]
longitude = user_h[:longitude]
user_h[:city] = City.load_city_by_position( latitude, longitude )
user_h[:interests] = Interest.load_interests_by_ids( user_h[:interests] )
User.create( user_h )
end
def self.update_user( id, user_h )
user = User.load_user_by_id( id )
user_h[:interests] = Interest.load_interests_by_ids( user_h[:interests] )
user.update( user_h )
return user
end
def self.delete_user( id )
user = User.load_user_by_id( id )
if user == nil
return false
end
user.destroy
return true
end
end
true
73f506153ce7326de2faf9368141bed4c1cbebbd
Ruby
vishB/vehicle_factory
/spec/models/vehicle_spec.rb
UTF-8
1,197
2.53125
3
[]
no_license
require 'spec_helper'
describe Vehicle do
it "should get created with proper values" do
FactoryGirl.build(:vehicle).should be_valid
end
end
describe Vehicle do
it "Should not be valid without an identifier" do
vehicle = FactoryGirl.build(:vehicle, v_identifier:nil)
vehicle.should_not be_valid
end
end
describe Vehicle do
it "should not be valid without an engine " do
vehicle = FactoryGirl.build(:vehicle, engine_id:nil)
vehicle.should_not be_valid
end
end
describe Vehicle do
it "should not accept character values for identifiers" do
vehicle = FactoryGirl.build(:vehicle, v_identifier: "abcd")
vehicle.should_not be_valid
end
end
describe Vehicle do
it "should not accept more than 4 digits for identifiers" do
vehicle = FactoryGirl.build(:vehicle, v_identifier: 12345454)
vehicle.should_not be_valid
end
end
describe Vehicle do
it "should have number of occupants a numeric value" do
vehicle = FactoryGirl.build(:vehicle, occupants: "occupants")
vehicle.occupants.should eq(0)
end
end
describe Vehicle do
it "Should have an engine" do
vehicle = FactoryGirl.build(:vehicle)
vehicle.should be_valid
end
end
true
aa07d39d9d810b8b6a6466d6a82eaab2a268cf68
Ruby
hdeploy/hdeploy
/api/lib/hdeploy/api.rb
UTF-8
13,109
2.609375
3
[]
no_license
require 'sinatra/base'
require 'json'
require 'hdeploy/conf'
require 'hdeploy/database'
require 'hdeploy/policy'
require 'pry'
#require 'hdeploy/policy'
module HDeploy
class API < Sinatra::Base
def initialize
super
@conf = HDeploy::Conf.instance
@db = HDeploy::Database.factory
# Decorator load - this is a bit of a hack but it's really nice to have this syntax
# We just write @something before a action and the system will parse it
end
@@api_help = {}
def self.api_endpoint(method, uri, policy_action_name, description, &block)
# Magic: we are reading app/env from block args
# Why am I doing this here rather than inside a single send? Because that way
# it's evaluated only at startup, vs evaluated at each call
@@api_help["#{method.upcase} #{uri}"] = {
policy_action_name: policy_action_name,
description: description,
}
if policy_action_name.nil?
# This is a no authorization thing - just send as-is
send(method, uri, &block)
else
if block.parameters.map{|p| p.last}.include? :app
send(method, uri) do |*args|
authorized?(policy_action_name, params[:app], params[:env])
instance_exec(*args, &block)
end
elsif block.parameters.map{|p| p.last}.include? :env
send(method, uri) do |*args|
authorized?(policy_action_name, args.first, params[:env])
# The instance exec passes the env such as request params etc
instance_exec(*args, &block)
end
else
# No specifics - env defaults to nil
send(method, uri) do |*args|
authorized?(policy_action_name, args.first)
instance_exec(*args, &block)
end
end
end
end
# -----------------------------------------------------------------------------
# Some Auth stuff
# This processes Authentication and authorization
def authorized?(action, app, env=nil)
raise "app must match /^[A-Za-z0-9\\-\\_\\.]+$/" unless app =~ /^[A-Za-z0-9\-\_\.]+$/
raise "env must match /^[A-Za-z0-9\\-\\_]+$/" unless env =~ /^[A-Za-z0-9\-\_]+$/ or env.nil?
puts "Process AAA #{action} app:#{app} env:#{env}"
# We do first authentication and then once we know who we are, we do authorization
auth = Rack::Auth::Basic::Request.new(request.env)
if auth.provided? and auth.basic?
user,pass = auth.credentials
# First search in local authorizations
begin
user = HDeploy::User.search_local(user,pass) # This will raise an exception if the user exists but it's a wrong pw
rescue Exception => e
puts "#{e} - #{e.backtrace}"
denyacl("Authentication failed 1")
end
# If not, search in LDAP
# TODO
if user.nil? or user == false
denyacl("No user")
end
# OK so in the variable user we have the current user with the loaded policies etc
if user.evaluate(action, "#{app}:#{env}")
# User was authorized
else
denyacl("Authorization failed", 403)
end
else
denyacl("No authentication provided")
end
end
def denyacl(msg,code=401)
puts "Denied ACL: #{msg}"
headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
halt(code, "Not authorized #{msg}\n")
end
api_endpoint(:get, '/health', nil, "Basic health check") do
#FIXME: query db?
"OK"
end
api_endpoint(:get, '/ping', nil, "Basic ping (for load balancer)") do
"OK"
end
api_endpoint(:get, '/help', nil, "Help for the API") do
@@api_help.sort.map do |uri, data|
"#{uri} - #{data[:policy_action_name].nil? ? 'no perms/open' : 'requires: ' + data[:policy_action_name] } - #{data[:description]}\n"
end.join()
end
# -----------------------------------------------------------------------------
api_endpoint(:put, '/distribute_state/:hostname', 'PutDistributeState', "Server self reporting endpoint") do |hostname|
#FIXME: these are SRV actions not user actions, not sure how to ACL them - might need a special treatment
#FIXME: how can you only allow the servers to update their own IP or name or something??
data = JSON.parse(request.body.read)
#FIXME: very syntax of API call
# each line contains an artifact or a target.
# I expect a hash containing app, which in turn contain envs, contains current and a list of artifacts
data.each do |row|
puts "Current for #{hostname}: #{row['current']}"
@db.put_distribute_state(row['app'], row['env'], hostname, row['current'], row['artifacts'].sort.join(','))
end
#FIxmE: add check if ok
"OK - Updated server #{hostname}"
end
# -----------------------------------------------------------------------------
api_endpoint(:put, '/srv/keepalive/:hostname', 'PutSrvKeepalive', "Server self reporting endpoint") do |hostname|
##protected! if @env['REMOTE_ADDR'] != '127.0.0.1'
ttl = request.body.read.force_encoding('US-ASCII') || '20'
@db.put_keepalive(hostname,ttl)
"OK - Updated server #{hostname}"
end
# -----------------------------------------------------------------------------
api_endpoint(:put, '/artifact/:app/:artifact', 'PutArtifact', "Registers artifact for given app") do |app,artifact|
authorized?('PutArtifact', app)
##protected! if @env['REMOTE_ADDR'] != '127.0.0.1'
raw_source = request.body.read
source = JSON.parse(raw_source)
# FIXME: check for source and format of source. It's a JSON that contains:
# - filename
# - decompress (or not) flag
# - source URL
# - alternative source URL
#
# OR inline_content instead of URL
#
# - checksum
# If OK just register with a reformat.
@db.put_artifact(artifact, app, JSON.generate(source))
"OK - registered artifact #{artifact} for app #{app}"
end
api_endpoint(:delete, '/artifact/:app/:artifact', 'DeleteArtifact', "Delete an artifact (unregister)") do |app,artifact|
# FIXME: don't allow to delete a target artifact.
# FIXME: add a doesn't exist warning?
@db.delete_artifact(app,artifact)
"OK - delete artifact #{artifact} for app #{app}"
end
# -----------------------------------------------------------------------------
api_endpoint(:put, '/target/:app/:env', 'PutTarget', 'Sets current target artifact in a given app/environment') do |app,env|
#FIXME check that the target exists
artifact = request.body.read.force_encoding('US-ASCII')
@db.put_target(app,env,artifact)
"OK set target for app #{app} in environment #{env} to be #{artifact}"
end
api_endpoint(:get, '/target/:app/:env','GetTarget', 'Current target artifact for this app/env') do |app,env|
artifact = "unknown"
@db.get_target_env(app,env).each do |row|
artifact = row['artifact']
end
artifact
end
api_endpoint(:get, '/target/:app', 'GetTarget', 'Current target artifacts for this app') do |app|
JSON.pretty_generate(@db.get_target(app).map(&:values).to_h)
end
# -----------------------------------------------------------------------------
api_endpoint(:get, '/distribute/:app/:env', 'GetDistribute', 'Currently distributed artifacts for this app/env') do |app,env|
# NOTE: cassandra implementation uses active_env since it doesn't know how to do joins
r = {}
target = @db.get_target_env(app,env)
@db.get_distribute_env(app,env).each do |row|
artifact = row.delete 'artifact'
row['target'] = target.first ? (target.first.values.first == artifact) : false
r[artifact] = row
end
JSON.pretty_generate(r)
end
# -----------------------------------------------------------------------------
api_endpoint(:get, '/distribute/:app', 'GetDistribute', 'All distributed artifacts for this app') do |app|
r = {}
@db.get_distribute(app).each do |row|
env = row['env'] || 'nowhere'
r[env] ||= []
r[env] << row['artifact']
end
JSON.pretty_generate(r)
end
# -----------------------------------------------------------------------------
# This call is just a big dump. The client can handle the sorting / formatting.
api_endpoint(:get, '/target_state/:app/:env', 'GetTargetState', "Target state for app/env") do |app,env|
JSON.pretty_generate(@db.get_target_state(app,env))
end
# -----------------------------------------------------------------------------
# This call is just a big dump. The client can handle the sorting / formatting.
api_endpoint(:get, '/distribute_state/:app','GetDistributeState', "Big dump of distribute state") do |app|
authorized?('GetDistributeState',app)
r = []
@db.get_distribute_state(app).each do |row|
row['artifacts'] = row['artifacts'].split(',')
r << row
end
JSON.pretty_generate(r)
end
# -----------------------------------------------------------------------------
api_endpoint(:get, '/artifact/:app', 'GetArtifact', 'List of artifacts') do |app|
r = {}
@db.get_artifact_list(app).each do |row| # The reason it's like that is that we can get
artifact = row.delete 'artifact'
r[artifact] = row
end
JSON.pretty_generate(r)
end
# -----------------------------------------------------------------------------
api_endpoint(:put, '/distribute/:app/:env', 'PutDistribute', "Distribute an artifact (in body) to app/env") do |app,env|
artifact = request.body.read.force_encoding('US-ASCII')
if @db.get_artifact(app,artifact).count == 1
@db.put_distribute(artifact,app,env)
"OK set artifact #{artifact} for app #{app} to be distributed in environment #{env}"
else
"No such artifact #{artifact} for app #{app}"
end
end
delete '/distribute/:app/:env/:artifact' do |app,env,artifact|
authorized?('DeleteDistribute',app,env)
@db.delete_distribute(app,env,artifact)
"OK will not distribute artifact #{artifact} for app #{app} in environment #{env}"
end
# -----------------------------------------------------------------------------
api_endpoint(:get, '/distribute_lock/:app/:env', 'GetDistributeLock', "Read a lock for auto-consistency checks") do |app,env|
r = @db.get_distribute_lock(app,env)
r.count == 1 ? r.first["comment"] : "UNLOCKED"
end
api_endpoint(:put, '/distribute_lock/:app/:env', 'PutDistributeLock', "Set a lock for auto-consistency checks") do |app,env|
comment = request.body.read
comment = "From #{env['REMOTE_ADDR']}" if comment.length == 0 or comment == "UNLOCKED"
@db.put_distribute_lock(app,env,comment)
"OK - locked app/env #{app}/#{env}"
end
api_endpoint(:delete, '/distribute_lock/:app/:env', 'DeleteDistributeLock', "Delete a lock for auto-consistency checks") do |app,env|
@db.delete_distribute_lock(app,env)
"OK - deleted lock from app/env"
end
# -----------------------------------------------------------------------------
api_endpoint(:get, '/srv/by_app/:app/:env', 'GetSrvByApp', "For fabric ssh") do |app,env|
# this gets the list that SHOULD have things distributed to them...
r = {}
@db.get_srv_by_app_env(app,env).each do |row|
r[row['hostname']] = {
'current' => row['current'],
'artifacts' => row['artifacts'].split(','),
}
end
JSON.pretty_generate(r)
end
# -----------------------------------------------------------------------------
api_endpoint(:get, '/dump/:type', 'GetDump', 'Dumping tools') do |type|
binding.pry
q = case type
when 'distributed_app'
@db.get_distributed_apps()
when 'configured_app'
@db.get_configured_apps()
when 'distribute_state'
@db.get_full_distribute_state()
when 'target'
@db.get_full_target()
when 'artifacts'
@db.get_full_artifacts()
else
halt 500, "try among distribute_app, configured_app, distribute_state, target, artifacts"
end
r = []
q.each do |row|
r << row
end
JSON.pretty_generate(r)
end
# -----------------------------------------------------------------------------
api_endpoint(:get, '/demo_only_repo/:app/:file', nil, "Don't use this in production") do |app,file|
# No auth here
halt 500,"wrong file name" if file =~ /[^A-Za-z0-9\.\-\_]/ or file.length < 1
fullfile = File.expand_path "~/hdeploy_build/artifacts/#{app}/#{file}"
if File.file? fullfile
send_file(fullfile, disposition: 'attachment', filename: file)
else
puts "Debug: non existent file #{fullfile}"
halt 404, "non existent file #{file}"
end
end
end
end
true
5b4a2daf656815812c87a61c7b85949a5379f8a7
Ruby
livash/learn_ruby
/10_timer/timer.rb
UTF-8
744
3.625
4
[]
no_license
########################
# @author Olena Ivashyna
# @date April 14, 2013
#######################
class Timer
def initialize
@seconds = 0
end
def seconds=(seconds)
@seconds = seconds.to_i
end
def seconds
@seconds
end
def time_string
hours = 0
min = 0
seconds = @seconds
if seconds>59
min = @seconds/60
seconds = @seconds%60
if min>59
hours = min/60
min = min - hours*60
end
end
padded(hours.to_i) + ":" + padded(min.to_i) + ":" + padded(seconds.to_i)
end
def padded(value)
toRet = ""
if value < 10
toRet = "0" + value.to_s
else
toRet = value.to_s
end
toRet
end
end
#t=Timer.new
#t.seconds=12
#puts t.time_string
true
159452871d6eaab55eeabcae02cfcef0bf52302c
Ruby
Owlyes/codewars
/q02_6kyu.rb
UTF-8
710
3.734375
4
[]
no_license
# Your order, please
def order(words)
words_array = []
words_order = []
ws = 0; pre_i = 0
words.size.times do |i|
if words[i] == " "
words_array[ws] = words[pre_i .. (i - 1)]
pre_i = i + 1; ws += 1
elsif i == words.size - 1
words_array[ws] = words[pre_i .. i]
else
end
if (words[i] =~ /\d/).is_a?(Numeric)
words_order[ws] = words[i]
end
end
words_hash = [words_order, words_array].transpose.to_h
ordered_words = ""
words_hash.size.times do |j|
(j == words_hash.size - 1) ? space = "" : space = "_"
ordered_words = ordered_words + words_hash[(j + 1).to_s] + space
end
return ordered_words
end
puts order("3a b4ook thi1s i2s !!5")
true
7f15854eadb7ef70319bdcd5ac29abcf687b246f
Ruby
JonathanYiv/project-euler
/problem-two.rb
UTF-8
185
3.5
4
[]
no_license
sum = 0;
a = 1;
b = 2;
while a < 4000000 and b < 4000000
if a % 2 == 0
sum = sum + a;
end
if b % 2 == 0
sum = sum + b;
end
a = a + b;
b = a + b;
end
puts sum
true
364605b903fce05e362fe87124cb0ad4c0ded67a
Ruby
tangod0wn/rubyexcercises
/excersize.rb
UTF-8
2,553
3.734375
4
[]
no_license
class Customer
def initialize(customer)
@customer = customer
end
def print_customer_name
puts @customer["first_name"] + " " + @customer["surname"]
end
def print_balance
puts "Your balance is " + @balance["balance"]
end
end
puts "Home",
"1. Add customer",
"2. Remove customer",
"3.Edit customer",
"4.Make a deposit",
"5.Make a withdrawal",
"6.Display details"
puts "first name?"
name = gets.chomp
puts "Hello" + name + ". What would you like to do?"
puts "What is your first name?"
response_firstname = gets.chomp
sally = Customer.new({"first_name" => response_firstname, "surname" => "Smith", "Age" => 26, "balance" => 200})
sally.makedeposit("600")
john = Customer
sally.print_customer_name
array_of_names = [1, 4, 2, 3, 5]
array_of_names.each do |person|
person.print_customer_name
end
puts "customers name?"
name = gets.chomp
puts " are you sure you want to delete account?"
answer = gets.chomp
if true == delete
else puts "Account has not been deleted"
end
puts "what is your name?"
name = gets.chomp
@makedeposit =Makedeposit.new [{"balance" => @balance.to_i + amount})
puts "#{amount} was put to your account. Your new balance is #{@balance}"
end
@withdrawal =MakeAWithdrawal.new [{@balance => @balance.to_i - amount}]
puts "#{amount} was withdrawn from your account. Your new balance is #{@balance }"
end
def account_withdraw
#do the code to withdraw
end
def account_deposit
puts "How much would you like to deposit"
@amount = gets.chomp
@amount = @amount.to_i
end
def make_bank_
puts "-- Type (create) new Customer"
puts "-- Type (removeCustomer) to removeCustomer"
puts "-- Type (withdraw) to withdraw money"
puts "-- Type (deposit) to deposit money"
puts "-- Type (DisplayDetails) to Display Details"
puts "What would you like to do?"
@@userinput = gets.chomp
while @@userinput != "exit"
case @@userinput
when "create"
puts "please enter your name"
@name = gets.chomp
puts "please enter balance"
@balance = gets.chomp
@my_account = Account.new(@name,@balance)
when "withdraw"
puts "How much would you like to withdraw?"
@amount = gets.chomp
@amount = @amount.to_i
when "deposit"
account_deposit
else
puts "command not found!"
puts "-- Type (create) to create account"
puts "-- Type (withdraw) to withdraw money"
puts "-- Type (deposit) to deposit money"
puts "-- Type (exit) to quit"
end
end
action
true
11e7be444b36af1d27bf847dadf3bab7228f6438
Ruby
dimasumskoy/ruby
/part_2/task_3.rb
UTF-8
167
2.984375
3
[]
no_license
# Заполнить массив числами фибоначчи до 100
array = [0, 1]
while (count = array[-1] + array[-2]) < 100
array << count
end
p array
true
700948765dcd5613307f18102e994512973bc077
Ruby
raywu/eulers
/problem1.rb
UTF-8
994
4.59375
5
[]
no_license
#Problem 1
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#Use inject method on arrays
a = (0...1000).to_a #array of 0 to 999
#first, create an array of the satisfying elements
multiples = a.inject([]) { |result, element|
result << element if element % 3 == 0 || element % 5 == 0
result
}
p multiples.inspect
#add up the sum
answer = multiples.inject { |result, element| result + element } #inject takes a iterates over each element in the array through the block
puts "first iteration: #{answer}"
#Can anyone refactor the first iteration above and combine the two injects? This second iteration doesn't work. Ruby claims 'result' is a NilClass (on line 17) and cannot take '+' operator
# answerTwo = a.inject(0) { |result, element|
# result + element if element % 3 == 0 || element % 5 == 0
# }
# puts "second iteration: #{answerTwo}"
module TextRazor
# * Represents a single abstract topic extracted from the input text.
# Requires the "topics" extractor to be added to the TextRazor request.
class Topic < TextRazorObject
attr_accessor :_topic_json
attr_accessor :link_index
self.descr = %w(id label score wikipedia_link)
def initialize(topic_json, link_index)
self._topic_json = topic_json
link_index.fetch(["topic", id], []).each do |callback, arg|
args = arg + Array(self)
callback.call(*args)
end
end
# The unique id of this annotation within its annotation set.
def id
_topic_json.fetch("id", nil)
end
# Returns the label for this topic.
def label
_topic_json.fetch("label", "")
end
# Returns a link to Wikipedia for this topic, or None if this topic
# couldn't be linked to a wikipedia page.
def wikipedia_link
_topic_json.fetch("wikiLink", nil)
end
# Returns the relevancy score of this topic to the query document.
def score
_topic_json.fetch("score", 0)
end
def to_s
super + "with label '%s'" % [label]
end
def hash
label.hash
end
def ==(other_topic)
label == other_topic.label
end
def eql?(other_topic)
other_topic.is_a?(TextRazor::Topic) && self.hash == other_topic.hash
end
end
end
true
670c84573a599a481b6dfe6af784e3f2d2a4f169
Ruby
wpliao1989/debugging_like_a_pro
/ruby/8_find_where_object_is_mutated.rb
UTF-8
383
3.53125
4
[]
no_license
#####################################################################
# An object is being mutated, but I don’t know where
#####################################################################
def level_1
arg = 'hello'
# arg.freeze
level_2 arg
end
def level_2(arg)
arg.replace('world')
level_3 arg
end
def level_3(arg)
puts arg
end
def index
level_1
end
index
true
aabbe0ef0b9c073346195d40b9f05bac11bcb1e4
Ruby
Kaamio/learn_ruby
/04_pig_latin/pig_latin.rb
UTF-8
2,290
3.359375
3
[]
no_license
#write your code here
# Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.
#
# Rule 2: If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.
=begin
def translate string
sanat = string.split #[kapina aapinen mainos]
for i in 0...sanat.length # sanat.length = 3
kirjaimet = sanat[i].chars # eka kirjaimet = sanat[0].chars eli k a p i n a
if onkovokaali kirjaimet[0] #onko eka kirjain vokaali?
kirjaimet.push ("ay") #jos on, loppuun ay
sanat[i] = kirjaimet.join("") #liitetään tämän sanan kirjaimet yhteen.
else
while !(onkovokaali kirjaimet[0]) #jos eka kirjain on konsonantti
if kirjaimet[0] == "q"
if kirjaimet[1] == "u" #jos sana alkaa qu
konsonantti = kirjaimet.shift #konsonantista tulee sanan eka kirjain, joka poistuu
kirjaimet.push(konsonantti) #konsonantti kirjainten perään
u = kirjaimet.shift #sama toiseen kertaan
kirjaimet.push(u)
end
else #jos eka kirjain ei ole vokaali eikä q tai u
konsonantti = kirjaimet.shift #konsonantista tulee sanan eka kirjain, joka poistuu
kirjaimet.push(konsonantti) #konsonantti kirjainten perään
end
end
kirjaimet.push ("ay") #loppuun ay
sanat[i] = kirjaimet.join("") #kirjaimet liitetään yhteen
end
end
vastaus = sanat.join(" ")
return vastaus
end
def onkovokaali kirjain
kir = kirjain.downcase
if kir == "a" or kir == "e" or kir == "i" or kir == "o" or kir == "u"
return true
else
false
end
end
puts translate "kapina aapinen mainos quorn kkkkapina"
=end
def translate lause
sanat = lause.split(" ")
for i in (0...sanat.length)
kirjaimet = sanat[i].chars
if onkovokaali kirjaimet[0]
kirjaimet.push("ay")
else
while !onkovokaali(kirjaimet[0])
if kirjaimet[0]=="q" && kirjaimet[1] == "u"
kirjaimet.shift(2)
kirjaimet.push("qu")
break
end
vika = kirjaimet[0]
kirjaimet.push(vika)
kirjaimet.shift
end
kirjaimet.push("ay")
end
sanat[i] = kirjaimet.join("")
end
sanat.join(" ")
end
def onkovokaali kirjain
vokaalit = ["a", "e", "i", "o", "u", "y"]
if vokaalit.include?(kirjain)
return true
else
return false
end
end
puts translate ("mun aasi quorn kkjaina quiet")
true
c99c7cd3b287582ffdcd1b09245793654c111f55
Ruby
toriejw/headcount
/test/headcount_analyst_test.rb
UTF-8
1,673
2.578125
3
[]
no_license
require_relative '../lib/headcount_analyst'
class HeadcountAnalystTest < Minitest::Test
attr_reader :ha
def setup
directory = File.expand_path 'fixtures', __dir__
dr = DistrictRepository.new(DataParser.new(directory))
@ha = HeadcountAnalyst.new(dr)
end
def test_initializes_with_a_repo
assert ha.repo
end
def test_can_return_top_statewide_testing_year_over_year_growth_for_top_district
skip
expected = ['the top district name', 0.123]
assert_equal expected, ha.top_statewide_testing_year_over_year_growth_in_3rd_grade(:subject => :math)
end
def test_can_return_top_statewide_testing_year_over_year_growth_for_top_few_districts
skip
expected = [['top district name', growth_1],['second district name', growth_2],['third district name', growth_3]]
assert_equal expected, ha.top_statewide_testing_year_over_year_growth_in_3rd_grade(:top => 3, :subject => :math)
end
def test_can_return_top_statewide_testing_year_over_year_growth_for_top_district_across_all_subjects
skip
expected = ['the top district name', 0.123]
assert_equal expected, ha.top_statewide_testing_year_over_year_growth_in_3rd_grade
end
def test_can_return_top_statewide_testing_year_over_year_growth_for_top_district_across_all_subjects_for_given_weighting
skip
expected = ['the top district name', 0.123]
assert_equal expected, ha.top_statewide_testing_year_over_year_growth_in_3rd_grade(:weighting => {:math => 0.5, :reading => 0.5, :writing => 0.0})
end
def test_top_statewide_testing_year_over_year_growth_for_top_district_across_all_subjects_for_given_weighting_checks_weights_add_to_1
skip
end
end
true
5a5df0d56b005339b74bd4afef2584f910ac9bda
Ruby
UnknownBlack/god_test
/simple.rb
UTF-8
68
2.640625
3
[]
no_license
data = ''
loop do
echo 'Hello'
100000.times { data << 'x' }
end
true
ea24e1e5451c74d43e36bd4f65c900904a2ed7ae
Ruby
DanDaMan23/eCommerceSportsCards
/db/seeds.rb
UTF-8
1,362
2.609375
3
[]
no_license
require 'rest-client'
Card.delete_all
Player.delete_all
Team.delete_all
def create_players(number_of_players)
number_of_players.times do
player = Faker::Sports::Basketball.unique.player
Player.create(name: player)
end
end
def create_teams
team_url = "https://www.balldontlie.io/api/v1/teams"
response = RestClient.get(team_url)
parsed = JSON.parse(response)
teams = parsed["data"]
teams.each do |team|
Team.create(name: team["name"], city: team["city"])
end
end
def create_cards(number_of_cards)
card_url = "https://nba-players.herokuapp.com/players-stats"
response = RestClient.get(card_url)
cards = JSON.parse(response)
(0..number_of_cards).each do |i|
player = Player.find_or_create_by(name: "#{cards[i]["name"]}")
team = Team.where("name LIKE '#{cards[i]["team_name"].split(' ')[-1]}'")
Card.create(price: 10, quantity: 2, brand: "No Name", player: player, team: team[0])
end
end
create_players(20)
create_teams
create_cards(110)
puts "Players created: #{Player.count}"
puts "Teams created #{Team.count}"
puts "Cards created: #{Card.count}"
if Rails.env.development?
AdminUser.create!(email: '[email protected]', password: 'password', password_confirmation: 'password')
end
# AdminUser.create!(email: '[email protected]', password: 'password', password_confirmation: 'password') if Rails.env.development?
# https://leetcode.com/problems/delete-node-in-a-linked-list/
# Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
# Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
def delete_node(node)
node.val = node.next.val
node.next = node.next.next
end
node1 = new ListNode(1)
node2 = new ListNode(2)
node3 = new ListNode(3)
node4 = new ListNode(4)
node1.next = node2
node2.next = node3
true
2b2ce7c5ef894c0e6b72077ffc7ea149dd829fe9
Ruby
joaomosm/adventofcode
/2021/7/7_part_one.rb
UTF-8
666
3.515625
4
[]
no_license
require './../module_helpers.rb'
class Day07PartOne
include Helpers
class << self
def run
new.run
end
end
def initialize
@numbers = read_input_chomp('7_input.txt')
.map { |number| number.split(',') }
.flatten
.map(&:to_i)
@min_distance = nil
end
def run
max_iterations = @numbers.max
max_iterations.times { |iteration| calculate_distance(iteration) }
@min_distance
end
def calculate_distance(iteration)
distance = @numbers.map { |number| (number - iteration).abs }.sum
@min_distance = distance if @min_distance.nil? || distance < @min_distance
end
end
puts Day07PartOne.run
class Artist
attr_accessor :name, :songs
@@all = []
def initialize(name)
@name = name
@songs = []
save
end
def self.all
@@all
end
def add_song(name)
@songs << name
end
def save
@@all << self
end
def self.find_or_create_by_name(input_name)
self.all.find {|x| x.name == (input_name) } || self.new(input_name)
end
def print_songs
@songs.each {|x| puts x.name }
end
end
true
94153aa9b8ad48255c401dbf4bfd36cd30cb40d8
Ruby
rails/rails
/activesupport/test/json/decoding_test.rb
UTF-8
5,941
2.53125
3
[
"MIT",
"Ruby"
]
permissive
# frozen_string_literal: true
require_relative "../abstract_unit"
require "active_support/json"
require "active_support/time"
require_relative "../time_zone_test_helpers"
class TestJSONDecoding < ActiveSupport::TestCase
include TimeZoneTestHelpers
class Foo
def self.json_create(object)
"Foo"
end
end
TESTS = {
%q({"returnTo":{"\/categories":"\/"}}) => { "returnTo" => { "/categories" => "/" } },
%q({"return\\"To\\":":{"\/categories":"\/"}}) => { "return\"To\":" => { "/categories" => "/" } },
%q({"returnTo":{"\/categories":1}}) => { "returnTo" => { "/categories" => 1 } },
%({"returnTo":[1,"a"]}) => { "returnTo" => [1, "a"] },
%({"returnTo":[1,"\\"a\\",", "b"]}) => { "returnTo" => [1, "\"a\",", "b"] },
%({"a": "'", "b": "5,000"}) => { "a" => "'", "b" => "5,000" },
%({"a": "a's, b's and c's", "b": "5,000"}) => { "a" => "a's, b's and c's", "b" => "5,000" },
# multibyte
%({"matzue": "松江", "asakusa": "浅草"}) => { "matzue" => "松江", "asakusa" => "浅草" },
%({"a": "2007-01-01"}) => { "a" => Date.new(2007, 1, 1) },
%({"a": "2007-01-01 01:12:34 Z"}) => { "a" => Time.utc(2007, 1, 1, 1, 12, 34) },
%(["2007-01-01 01:12:34 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34)],
%(["2007-01-01 01:12:34 Z", "2007-01-01 01:12:35 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34), Time.utc(2007, 1, 1, 1, 12, 35)],
# no time zone
%({"a": "2007-01-01 01:12:34"}) => { "a" => Time.new(2007, 1, 1, 1, 12, 34, "-05:00") },
# invalid date
%({"a": "1089-10-40"}) => { "a" => "1089-10-40" },
# xmlschema date notation
%({"a": "2009-08-10T19:01:02"}) => { "a" => Time.new(2009, 8, 10, 19, 1, 2, "-04:00") },
%({"a": "2009-08-10T19:01:02Z"}) => { "a" => Time.utc(2009, 8, 10, 19, 1, 2) },
%({"a": "2009-08-10T19:01:02+02:00"}) => { "a" => Time.utc(2009, 8, 10, 17, 1, 2) },
%({"a": "2009-08-10T19:01:02-05:00"}) => { "a" => Time.utc(2009, 8, 11, 00, 1, 2) },
# needs to be *exact*
%({"a": " 2007-01-01 01:12:34 Z "}) => { "a" => " 2007-01-01 01:12:34 Z " },
%({"a": "2007-01-01 : it's your birthday"}) => { "a" => "2007-01-01 : it's your birthday" },
%({"a": "Today is:\\n2020-05-21"}) => { "a" => "Today is:\n2020-05-21" },
%({"a": "2007-01-01 01:12:34 Z\\nwas my birthday"}) => { "a" => "2007-01-01 01:12:34 Z\nwas my birthday" },
%([]) => [],
%({}) => {},
%({"a":1}) => { "a" => 1 },
%({"a": ""}) => { "a" => "" },
%({"a":"\\""}) => { "a" => "\"" },
%({"a": null}) => { "a" => nil },
%({"a": true}) => { "a" => true },
%({"a": false}) => { "a" => false },
'{"bad":"\\\\","trailing":""}' => { "bad" => "\\", "trailing" => "" },
%q({"a": "http:\/\/test.host\/posts\/1"}) => { "a" => "http://test.host/posts/1" },
%q({"a": "\u003cunicode\u0020escape\u003e"}) => { "a" => "<unicode escape>" },
'{"a": "\\\\u0020skip double backslashes"}' => { "a" => "\\u0020skip double backslashes" },
%q({"a": "\u003cbr /\u003e"}) => { "a" => "<br />" },
%q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => { "b" => ["<i>", "<b>", "<u>"] },
# test combination of dates and escaped or unicode encoded data in arrays
%q([{"d":"1970-01-01", "s":"\u0020escape"},{"d":"1970-01-01", "s":"\u0020escape"}]) =>
[{ "d" => Date.new(1970, 1, 1), "s" => " escape" }, { "d" => Date.new(1970, 1, 1), "s" => " escape" }],
%q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) =>
[{ "d" => Date.new(1970, 1, 1), "s" => "http://example.com" },
{ "d" => Date.new(1970, 1, 1), "s" => "http://example.com" }],
# tests escaping of "\n" char with Yaml backend
%q({"a":"\n"}) => { "a" => "\n" },
%q({"a":"\u000a"}) => { "a" => "\n" },
%q({"a":"Line1\u000aLine2"}) => { "a" => "Line1\nLine2" },
# prevent JSON unmarshalling
'{"json_class":"TestJSONDecoding::Foo"}' => { "json_class" => "TestJSONDecoding::Foo" },
# JSON "fragments" - these are invalid JSON, but ActionPack relies on this
'"a string"' => "a string",
"1.1" => 1.1,
"1" => 1,
"-1" => -1,
"true" => true,
"false" => false,
"null" => nil
}
TESTS.each_with_index do |(json, expected), index|
fail_message = "JSON decoding failed for #{json}"
test "JSON decodes #{index}" do
with_tz_default "Eastern Time (US & Canada)" do
with_parse_json_times(true) do
silence_warnings do
if expected.nil?
assert_nil ActiveSupport::JSON.decode(json), fail_message
else
assert_equal expected, ActiveSupport::JSON.decode(json), fail_message
end
end
end
end
end
end
test "JSON decodes time JSON with time parsing disabled" do
with_parse_json_times(false) do
expected = { "a" => "2007-01-01 01:12:34 Z" }
assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"}))
end
end
def test_failed_json_decoding
assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%(undefined)) }
assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({a: 1})) }
assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({: 1})) }
assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%()) }
end
def test_cannot_pass_unsupported_options
assert_raise(ArgumentError) { ActiveSupport::JSON.decode("", create_additions: true) }
end
private
def with_parse_json_times(value)
old_value = ActiveSupport.parse_json_times
ActiveSupport.parse_json_times = value
yield
ensure
ActiveSupport.parse_json_times = old_value
end
end
true
47efd0cfdb178d2afc7e6d80fcb788fb4e2ac429
Ruby
DamienNeuman/Chess
/chess/display.rb
UTF-8
805
3
3
[]
no_license
require "colorize"
require_relative "board.rb"
require_relative "cursor.rb"
require "byebug"
class Display
attr_reader :board, :cursor
def initialize(board)
@cursor = Cursor.new([0,0],board)
@board = board
end
def render()
#debugger
board.grid.each do |row|
r = []
row.each_index do |idx|
if [row, idx] == cursor.cursor_pos
r << row[idx].colorize(:background => :light_yellow)
else
r << row[idx]
end
end
puts r.join(" ")
end
end
def run
loop do
#system('clear')
render
cursor.get_input
p cursor.cursor_pos
p cursor.selected
end
end
end
if __FILE__ == $PROGRAM_NAME
board = Board.new
display = Display.new(board)
display.run
end
module Utilrb
# Find configuration files within the pathes given
# by ROCK_CONFIG_PATH environment variable
#
class ConfigurationFinder
# Find a file by searching through paths defined by an environment variable
# and a given package directory. Package name is appended to all pathes found
# in the environment
#
# Returns the path to the file on success, otherwise nil
def self.findWithEnv(filename, pkg_name, environment_search_path)
env_var = ENV[environment_search_path]
if env_var
# Extract search path from environment variable
configuration_path = Array.new
env_var.split(':').each do | path |
# Extract path and append package name folder
configuration_path << File.join(path.gsub(/:$/,''), pkg_name)
end
end
if configuration_path == nil
raise "ConfigurationFinder: Environment variable #{environment_search_path} is not set!\n"
else
configuration = search(filename, configuration_path)
end
configuration
end
# Search for a file within [ $ROCK_CONFIG_PATH ]/<packagename>/
# Will not perform a recursive search
#
# Returns the path to the file on success, otherwise nil
def self.find(filename, pkg_name)
findWithEnv(filename, pkg_name, 'ROCK_CONFIG_PATH')
end
# Search for a file only in the given search directories
#
# Returns the path to the file on success, otherwise nil
def self.search(filename, search_dirs)
search_dirs.each do |path|
file = File.join(path,filename)
if File.exist?(file)
return file
end
end
return
end
# Search for a file using the system id (<basename>_<id>)
#
# returns the configuration found in [ $ROCK_CONFIG_PATH ]/<basename>/<id>/, performs
# a fallback search in <basename> and returns nil if no config could
# be found
def self.findSystemConfig(filename, system_id)
id_components = system_id.split('_')
if(id_components.size != 2)
raise "ConfigurationFinder: Invalid system identifier #{system_id} provided. " +
"Use <basename>_<id>"
end
base_pkg_name = id_components[0]
id_pkg_name = File.join(base_pkg_name, id_components[1])
system_config = find(filename, id_pkg_name)
if !system_config
system_config = find(filename, base_pkg_name)
end
system_config
end
end
end
true
41a4c6ee3a05b45a7c913a69771260fb175957fe
Ruby
shaoevans/aA-Classwork
/W4D4/tdd_project/lib/tdd.rb
UTF-8
1,215
3.5
4
[]
no_license
class Array
def my_uniq
results = []
self.each { |ele| results << ele if !results.include?(ele) }
results
end
def two_sum
pairs = []
(0...self.length).each do |i|
(i+1...self.length).each do |j|
pairs << [i,j] if self[i] + self[j] == 0
end
end
pairs
end
end
def my_transpose(arr)
raise ArgumentError if !arr.is_a?(Array)
return arr if arr.empty?
raise IndexError if arr.map(&:length).uniq.length != 1
results = Array.new(arr[0].length) {Array.new(arr.length)}
arr.each_with_index do |sub, i|
sub.each_with_index do |ele, j|
results[j][i] = arr[i][j]
end
end
results
end
def stock_picker(arr)
raise ArgumentError if !arr.is_a?(Array)
max_diff = 0
pair = nil
(0...arr.length).each do |i|
(i+1...arr.length).each do |j|
if arr[j] - arr[i] > max_diff
max_diff = arr[j] - arr[i]
pair = [i,j]
end
end
end
pair
end
# 1. make sure argument is an array
# 2. returns days on which price diff is greatest (indices)
# 3. sell date must be greater than purchase date
# 4. should return nil if no days profitable
# 5. return first day pair if multiple days have same max diff
true
c9cc81f9a091e6f6dd566fb53df85698c12e7499
Ruby
cyx/cyrildavid.com
/lib/project.rb
UTF-8
243
2.5625
3
[]
no_license
class Project
attr :title
attr :description
attr :url
def initialize(atts)
@title = atts[:title]
@description = atts[:description]
@url = atts[:url]
end
def self.all
DB.projects.map { |atts| new(atts) }
end
end
true
a8781468edff20d43ae42e37f06cd3630fe58a8d
Ruby
bomberstudios/rack-footnotes
/lib/rack/footnotes.rb
UTF-8
1,018
2.59375
3
[]
no_license
require "rack"
class Rack::FootNotes
VERSION = "0.0.4"
def initialize(app, options = {}, &block)
puts("Using rack-footnotes " + VERSION)
@app = app
@options = {
:notes_path => 'notes',
:css => "position: fixed; bottom: 0; left: 0; width: 100%; padding: 1em; background-color: rgba(245,242,137,0.6); margin: 0 auto;",
:extra_css => ""
}.merge(options)
instance_eval(&block) if block_given?
end
def call(env)
status, headers, body = @app.call(env)
if headers['Content-Type'] == 'text/html'
route = env['PATH_INFO']
file = Dir.pwd + "/#{@options[:notes_path]}" + route.gsub(/\/$/,'') + '.txt'
if File.exists?(file)
note = File.readlines(file).to_s
body = body.body.to_s
body = body.gsub("</body>","<div id='racknotes'>#{note}</div><style>#racknotes { #{@options[:css]} #{@options[:extra_css]} }</style></body>")
end
end
@response = Rack::Response.new(body, status, headers)
@response.to_a
end
end
true
cb1408fba23f36738390ad67581e426aec00b08a
Ruby
unindented/unindented-rails
/app/decorators/partial_date_decorator.rb
UTF-8
480
2.53125
3
[
"MIT"
]
permissive
class PartialDateDecorator < ModelDecorator
delegate_all
def localize
array = to_a
format = [:year, :month, :day][array.length - 1]
l(Date.new(*array), format: format)
end
def route
convert_to_route(to_a)
end
def parent_route
convert_to_route(to_a[0...-1])
end
private
def convert_to_route(array)
array = array.map { |v| v.to_s.rjust(2, '0') }
send("archive_#{category}_path", Hash[[:year, :month, :day].zip(array)])
end
end
true
55dce64fe3c5b718d251906a747e8a182482d3d0
Ruby
digital-york/arch1
/lib/tasks/concepts.rake
UTF-8
4,242
2.6875
3
[]
no_license
namespace :concepts do
require 'csv'
desc "TODO"
task load_subjects: :environment do
puts 'Creating the Concept Scheme'
begin
#@scheme = ConceptScheme.find('cj82k759n')
@scheme = ConceptScheme.new
@scheme.preflabel = "Borthwick Institute for Archives Subject Headings for the Archbishops' Registers"
@scheme.description = "Borthwick Institute for Archives Subject Headings for the Archbishops' Registers. Produced from data created during the Archbishop's Registers Pilot project, funded by the Mellon Foundation."
@scheme.rdftype = @scheme.add_rdf_types
@scheme.save
puts "Concept scheme for subjects created at #{@scheme.id}"
rescue
puts $!
end
puts 'Processing the subjects. This may take some time ... '
arr = CSV.read(Rails.root + 'lib/assets/lists/subjects.csv')
this_row = ''
concept = nil
arr.each do |c|
begin
# if the top concept hasn't been created, create it
unless c[0] == this_row
hh = Concept.new
#create main heading
hh.rdftype = hh.add_rdf_types
#hh.id = hh.create_id(@scheme.id)
hh.preflabel = c[0].strip
hh.concept_scheme = @scheme
hh.istopconcept = 'true'
@scheme.concepts += [hh]
@scheme.topconcept += [hh]
@scheme.save
hh.save
puts "Top heading for #{hh.preflabel} created at #{hh.id}"
end
# create sub-heading
h = Concept.new
h.rdftype = h.add_rdf_types
h.preflabel = c[1].strip
#h.id = h.create_id(@scheme.id)
h.concept_scheme = @scheme
unless c[2].nil?
if c[2].include? ';'
a = c[2].gsub('; ', ';')
b = a.split(';')
h.altlabel = b
else
h.altlabel = [c[2]]
end
end
unless c[3].nil?
h.definition = c[3]
end
begin
if hh
h.broader += [hh]
else
hh = Concept.find(concept)
h.broader += [hh]
end
rescue
puts $!
end
h.save
@scheme.concepts += [h]
@scheme.save
puts "Sub heading for #{h.preflabel} created at #{h.id} with broader #{hh.preflabel}"
this_row = c[0]
concept = hh.id
rescue
puts $!
end
end
puts 'Finished!'
end
desc "TODO"
task load_terms: :environment do
path = Rails.root + 'lib/'
# .csv files should exist in the specified path
# removed as too short to be worth having a list for 'certainty', 'date_types'
# removed as usued at present 'folio_faces', 'folio_types', 'formats'
list = ['currencies', 'languages', 'place_types', 'descriptors', 'person_roles', 'place_roles', 'date_roles', 'section_types', 'entry_types']
#list = ['currencies']
list.each do |i|
puts 'Creating the Concept Scheme'
begin
#@scheme = ConceptScheme.find('zc77sq08x')
@scheme = ConceptScheme.new
@scheme.preflabel = i
@scheme.description = "Terms for #{i} produced from data created during the Archbishop's Registers Pilot project, funded by the Mellon Foundation."
@scheme.rdftype = @scheme.add_rdf_types
@scheme.save
puts "Concept scheme for #{i} created at #{@scheme.id}"
rescue
puts $!
end
puts 'Processing ' + i + '. This may take some time ... '
arr = CSV.read(path + "assets/lists/#{i}.csv")
arr = arr.uniq # remove any duplicates
arr.each do |c|
begin
h = Concept.new
h.rdftype = h.add_rdf_types
#h.id = h.create_id(@scheme.id)
h.preflabel = c[0].strip
h.concept_scheme = @scheme
unless c[1].nil?
if c[1].include? ';'
a = c[1].gsub('; ', ';')
b = a.split(';')
h.altlabel += b
else
h.altlabel += [c[1]]
end
end
h.save
@scheme.concepts += [h]
puts "Term for #{c[0]} created at #{h.id}"
rescue
puts $!
end
end
end
puts 'Finished!'
end
end
true
f8e5dda9328fea97c0d656d88332005625781398
Ruby
uzairali19/linter-ruby
/spec/linter_spec.rb
UTF-8
6,285
3.0625
3
[]
no_license
require 'linter'
# rubocop:disable Layout/LineLength
RSpec.describe 'Linter Check' do
subject(:lint) { Linter.new('../test.rb') }
describe 'Empty line' do
context 'If line is empty' do
it 'Returns Error' do
empty_line_test = lint.empty_line(' ', 1)
expect(empty_line_test).to eq(["\e[0;31;49mEmpty line at 2\e[0m"])
end
end
context 'If line is not empty' do
it 'Does not returns' do
empty_line_test = lint.empty_line('Something written', 1)
expect(empty_line_test).not_to eq(["\e[0;31;49mEmpty line at 2\e[0m"])
end
end
end
describe 'Max Line Length' do
context 'If line exceeeds 100 characters' do
it 'returns Error' do
max_line_test = lint.max_line_length(
'This is a long string. This is a long string. This is a long string. This is a long string. This is a long string. This is a long string. This is a long string. This is a long string', 2
)
expect(max_line_test).to eq(["\e[0;31;49mMaximum characters exceeded on line 3\e[0m"])
end
end
context 'If line does not exceeeds 100 characters' do
it 'Does not returns Error' do
max_line_test = lint.max_line_length('This is a short string.', 2)
expect(max_line_test).not_to eq(["\e[0;31;49mMaximum characters exceeded on line 3\e[0m"])
end
end
end
describe 'Trailing White Space' do
context 'If the line has white space at the end' do
it 'Returns Error' do
white_space_test = lint.trailing_white_space('white space ', 3)
expect(white_space_test).to eq(["\e[0;31;49mTrailing white space detected at line 4\e[0m"])
end
end
context 'If the line has white space at the end' do
it 'Does not returns Error' do
white_space_test = lint.trailing_white_space('white space', 3)
expect(white_space_test).not_to eq(["\e[0;31;49mTrailing white space detected at line 4\e[0m"])
end
end
end
describe 'Empty End Line' do
context 'If the line has white space at the end' do
it 'Returns Error' do
line_end_test = lint.empty_end_line('end', 4)
expect(line_end_test).to eq(["\e[0;31;49mAdd an empty line after line 5\e[0m"])
end
end
context 'If the line has white space at the end' do
it 'Does not returns Error' do
line_end_test = lint.empty_end_line('not ending with end keyword', 4)
expect(line_end_test).not_to eq(["\e[0;31;49mAdd an empty line after line 5\e[0m"])
end
end
end
describe 'Start Without Function' do
context 'If the code does not start with a function [def,class or module] keyword' do
it 'Returns Error' do
function_start_test = lint.start_without_function('not satrting with a function keyword', 0)
expect(function_start_test).to eq(["\e[0;31;49mfile starting without a function 'def,class or module' at line 1\e[0m"])
end
end
context 'If the code starts with a [def,class or module] keyword' do
it 'Does not returns Error' do
function_start_test = lint.start_without_function('def starting with a function keyword', 0)
expect(function_start_test).not_to eq(["\e[0;31;49mfile starting without a function 'def,class or module' at line 1\e[0m"])
end
end
end
describe 'Empty Start Line' do
context 'If the code has an empty line on top' do
it 'Returns Error' do
empty_start_test = lint.empty_start_line('', 0)
expect(empty_start_test).to eq(["\e[0;31;49mExtra empty line at line 1\e[0m"])
end
end
context 'If the code starts with a [def,class or module] keyword' do
it 'Does not returns Error' do
empty_start_test = lint.empty_start_line('not empty line', 0)
expect(empty_start_test).not_to eq(["\e[0;31;49mExtra empty line at line 1\e[0m"])
end
end
end
describe 'Brackets Check' do
context 'If the line has uneven brackets' do
it 'Returns Error for ]' do
brackets_test = lint.brackets_check('[', 4)
expect(brackets_test).to eq(["\e[0;31;49mBrackets error at 5. Expecting ]\e[0m"])
end
it 'Returns Error for [' do
brackets_test = lint.brackets_check(']', 4)
expect(brackets_test).to eq(["\e[0;31;49mBrackets error at 5. Expecting [\e[0m"])
end
end
context 'If the code starts with a [def,class or module] keyword' do
it 'Does not returns Error' do
empty_start_test = lint.brackets_check('[]', 0)
expect(empty_start_test).not_to eq(["\e[0;31;49mExtra empty line at line 1\e[0m"])
end
end
end
describe 'Parenthesis Check' do
context 'If the line has uneven parenthesis' do
it 'Returns Error for )' do
parenthesis_test = lint.parenthesis_check('(', 4)
expect(parenthesis_test).to eq(["\e[0;31;49mParenthesis error at 5. Expecting )\e[0m"])
end
it 'Returns Error for (' do
parenthesis_test = lint.parenthesis_check(')', 4)
expect(parenthesis_test).to eq(["\e[0;31;49mParenthesis error at 5. Expecting (\e[0m"])
end
end
context 'If the code starts with a [def,class or module] keyword' do
it 'Does not returns Error' do
parenthesis_test = lint.parenthesis_check('()', 4)
expect(parenthesis_test).not_to eq(["\e[0;31;49mParenthesis error at 5. Expecting (\e[0m"])
end
end
end
describe 'Curly Brackets Check' do
context 'If the line has uneven Curly Brackets' do
it 'Returns Error for }' do
curly_brackets_test = lint.curly_brackets_check('{', 4)
expect(curly_brackets_test).to eq(["\e[0;31;49mCurly Brackets error at 5. Expecting }\e[0m"])
end
it 'Returns Error for {' do
curly_brackets_test = lint.curly_brackets_check('}', 4)
expect(curly_brackets_test).to eq(["\e[0;31;49mCurly brackets error at 5. Expecting {\e[0m"])
end
end
context 'If the code starts with a [def,class or module] keyword' do
it 'Does not returns Error' do
curly_brackets_test = lint.curly_brackets_check('{}', 4)
expect(curly_brackets_test).not_to eq(["\e[0;31;49mParenthesis error at 5. Expecting (\e[0m"])
end
end
end
end
# rubocop:enable Layout/LineLength
class Request < ApplicationRecord
attr_reader :message
belongs_to :created_by, :class_name => "User"
belongs_to :user, :class_name => "User"
# belongs_to :user
belongs_to :role
# validates :user_confirm, presence: true #nil is pending, false is declined
# validates :owner_confirm, presence: true #nil is pending, false is declined
# validates :owner_message, presence: true
# validates :user_message, presence: true
validates :created_by, presence: true
def status(current_user)
@request = self
@role = @request.role
if @role.project.owner == current_user
owner_status_logic
elsif @request.user == current_user
user_status_logic
end
end
private
def owner_status_logic
if @request.created_by == @request.role.project.owner
# you invited user
if @request.user_confirm
@message = "#{@request.user.full_name} joined #{@role.project.title}!"
elsif @request.user_confirm == false
@message = "#{@request.user.full_name} declined your request to join #{@role.project.title}"
else
@message = "You requested #{@request.user.full_name} to join #{@role.project.title}"
end
else
# user requested to join your project
@message = "#{@request.user.full_name} requested to join #{@role.project.title}!"
@message = "You declined #{@request.user.full_name}'s request to join #{@role.project.title}" if @request.owner_confirm == false
end
end
def user_status_logic
if @request.created_by == @request.user
# you requested to join owner's project
@message = "You requested to join"
@message = "#{@role.project.owner.full_name} declined your request to join #{@role.project.title}" if @request.owner_confirm == false
else
# owner invited you to join their project
if @request.user_confirm
@message = "You joined #{@role.project}!"
elsif @request.user_confirm == false
"#You declined {@role.owner.full_name}'s request for you to join #{@role.project.title}!"
else
@message = "#{@role.owner.full_name} requested you to join #{@role.project.title}!"
end
end
end
end
true
fd6b8ce2263743642d89c14f9e07f6c8b33ac71d
Ruby
NatdanaiBE/ruby-and-rails
/ruby-scripts/03_triangle_stars.rb
UTF-8
131
2.671875
3
[]
no_license
print '> '
input = $stdin.gets.to_i
for i in 0..input do
for j in 0..(input - i - 1) do
print '* '
end
print "\n"
end
true
81c828bd501bfc5a8c405088ac276788dae2fbf1
Ruby
alicodes/hello_world
/assessment_109_practice/small_problems/16.rb
UTF-8
64
3
3
[]
no_license
(1..99).each do |index|
if index.odd?
puts index
end
end
true
fa70111cd047c23a694928ad63225df40695ec37
Ruby
marekaleksy/learn_ruby
/exercise_11.rb
UTF-8
247
4.15625
4
[]
no_license
print "How old are you?"
age = gets.chomp.to_i
print "How tall are you?"
height = gets.chomp.to_i # centimetres
print "How much do you weight?" # kilograms
weight = gets.chomp.to_i
puts "So you're #{age} old, #{height} tall and #{weight} heavy."
true
68e29648c4faa2c9ab5656e9d7aba60e4d71018e
Ruby
yggie/intro-to-rust-for-web-devs
/ruby/code_breaker.rb
UTF-8
2,279
3.625
4
[
"MIT"
]
permissive
class CodeBreaker
attr_accessor :dictionary
def initialize(dictionary, key_length, &block)
@dictionary = dictionary
@cipher_factory = block
@key_length = key_length
end
def crack(ciphertext, plaintext)
counter = 0
each_possible_dictionary_combination do |guess|
cipher = @cipher_factory.call(guess)
return guess if cipher.encrypt(plaintext) == ciphertext
counter = counter + 1
if counter % 1000 == 0
puts %Q{Trying: "#{guess}"}
end
end
raise 'Could not solve the problem!'
end
private
def each_sentence_within_length(max_length)
dictionary.each do |word|
if word.length <= max_length
yield(word)
each_sentence_within_length(max_length - word.length - 1) do |small_sentence|
yield("#{word} #{small_sentence}")
end
end
end
end
def each_possible_dictionary_combination
each_sentence_within_length(@key_length) do |sentence|
yield(sentence)
end
end
end
require_relative './cipher/base64_encoding.rb'
require_relative './cipher/repeating_key_xor.rb'
require 'test/unit'
class TestCodeBreaker < Test::Unit::TestCase
def test_crack
expected_key = 'apple pie'
cipher = Cipher::Base64Encoder.new(Cipher::RepeatingKeyXOR.new(expected_key))
plaintext = 'This is the text to be encrypted'
code_breaker = CodeBreaker.new(['bananas', 'apple', 'pie', 'cherry'], 10) do |key|
Cipher::Base64Encoder.new(Cipher::RepeatingKeyXOR.new(key))
end
computed_key = code_breaker.crack(cipher.encrypt(plaintext), plaintext)
assert_equal(computed_key, expected_key)
end
def test_crack_guesses
expected_key = 'a long a'
cipher = Cipher::Base64Encoder.new(Cipher::RepeatingKeyXOR.new(expected_key))
plaintext = 'This is the text to be encrypted'
guesses = []
code_breaker = CodeBreaker.new(['long', 'a', 'letter'], 8) do |key|
guesses << key
Cipher::Base64Encoder.new(Cipher::RepeatingKeyXOR.new(key))
end
computed_key = code_breaker.crack(cipher.encrypt(plaintext), plaintext)
assert_equal(expected_key, computed_key)
assert_equal([
'long',
'long a',
'long a a',
'a',
'a long',
'a long a',
], guesses)
end
end
true
6315c2c3fce7a96bbe4586f1916458bbba59d4f8
Ruby
bocalo/black_jack
/deck.rb
UTF-8
377
3.078125
3
[]
no_license
# frozen_string_literal: true
require_relative 'card'
class Deck
attr_reader :deck
def initialize
@deck = create_deck
end
# def deal_cards
# @deck.pop
# end
def create_deck
all_cards = []
Card::VALUES.each do |value|
Card::SUITS.each do |suit|
all_cards << Card.new(suit, value)
end
end
all_cards.shuffle
end
end
true
f7bf2dc2f39731b7cf150fb0da4605704c4e26b5
Ruby
justindelacruz/youtube-captions
/lib/youtube/api.rb
UTF-8
3,954
2.890625
3
[]
no_license
require 'googleauth'
require 'google/apis/youtube_v3'
module Youtube
class Api
Youtube = Google::Apis::YoutubeV3
def initialize(api_key: nil)
@youtube = Youtube::YouTubeService.new
@youtube.key = api_key || 'YOUR_API_KEY'
end
# Return the "uploads" channel for a given user.
def get_upload_channel_id(username)
upload_channel = nil
puts 'Channels:'
channels = list_channels(username)
channels.items.each do |item|
puts "# #{item.id}"
puts "- uploads #{item.content_details.related_playlists.uploads}"
upload_channel = item.content_details.related_playlists.uploads
end
upload_channel
end
# @param [Integer] max_results
# The maximum number of items that should be returned in the result set. Acceptable values are 0 to 50,
# inclusive. If not provided, it will use the YouTube API default value, which is 5.
#
# @yield [result] Parsed result if block supplied
def get_episodes_from_playlist(playlist_id, max_results: nil)
results_to_fetch = max_results
next_page_token = nil
loop do
items = list_playlist_items(playlist_id, page_token: next_page_token, max_results: [results_to_fetch, 50].min)
results_to_fetch -= items.items.length
next_page_token = items.next_page_token
items.items.each do |item|
if item.snippet
yield item
end
end
break unless next_page_token and results_to_fetch > 0
end if block_given?
end
# Return whether a video has captions defined.
#
# @param [String] video_id
# The YouTube video ID of the video for which the API should return caption tracks.
# @param [String] lang
# The language of the caption track.
# @param [String] trackKind
# Valid values:
# - ASR: A caption track generated using automatic speech recognition.
# - forced: A caption track that plays when no other track is selected in the player.
# For example, a video that shows aliens speaking in an alien language might
# have a forced caption track to only show subtitles for the alien language.
# - standard: A regular caption track. This is the default value.
#
# @return [Boolean]
def video_has_caption?(video_id, lang: 'en', trackKind: 'standard')
captions = get_captions(video_id)
captions.items.each do |item|
if item.snippet.track_kind == trackKind && item.snippet.language == lang
return true
end
end
false
end
private
# Returns a collection of zero or more channel resources
def list_channels(username)
@youtube.list_channels('contentDetails', max_results: 1, for_username: username)
end
# Returns a collection of playlist items
#
# @param [String] playlist_id
# Unique ID of the playlist for which you want to retrieve playlist items.
# @param [String] page_token
# A specific page in the result set that should be returned.
# @param [Integer] max_results
# The maximum number of items that should be returned in the result set. Acceptable values are 0 to 50,
# inclusive. If not provided, it will use the YouTube API default value, which is 5.
#
# @yield [result, err] Result & error if block supplied
#
# @return [Google::Apis::YoutubeV3::ListPlaylistItemsResponse] Parsed result
def list_playlist_items(playlist_id, page_token: nil, max_results: nil)
@youtube.list_playlist_items('snippet,contentDetails', playlist_id: playlist_id, page_token: page_token, max_results: max_results)
end
# Returns a list of caption tracks that are associated with a specified video.
def get_captions(video_id)
@youtube.list_captions('snippet', video_id)
end
end
end
true
f4e0b905788a10bb397e420313c677f7b42807a0
Ruby
kierendavies/cs-honours-project
/scripts/gen_axioms.rb
UTF-8
4,685
2.875
3
[]
no_license
#!/usr/bin/env ruby
require 'singleton'
CLASS_NAMES = %w(C D E F G H I J K)
OBJECT_PROPERTY_NAMES = %w(r s t u v w x y z)
module OneOfSubclasses
def subclasses
ObjectSpace.each_object(singleton_class).select { |c| c.superclass == self }
end
def all depth
subclasses.map { |sc| sc.all depth }.flatten
end
end
module ConcreteExpression
def initialize *params
@params = params
end
def self.name
self.class.to_s
end
def normalize
self
end
def to_s class_names, object_property_names
"#{self.class.name}(#{@params.map { |p| p.to_s class_names, object_property_names }.join ' '})"
end
end
class Axiom
extend OneOfSubclasses
end
class ClassAxiom < Axiom; end
# class ObjectPropertyAxiom < Axiom; end
# class DataPropertyAxiom < Axiom; end
# class DatatypeDefinition < Axiom; end
# class HasKey < Axiom; end
# class Assertion < Axiom; end
# class AnnotationAxiom < Axiom; end
class SubClassOf < ClassAxiom
include ConcreteExpression
def self.all depth
ClassExpression.all(depth-1).repeated_permutation(2).map do |left, right|
self.new left, right
end
end
end
class EquivalentClasses < ClassAxiom
include ConcreteExpression
def self.all depth
ClassExpression.all(depth-1).repeated_combination(2).map do |left, right|
self.new left, right
end
end
end
class DisjointClasses < ClassAxiom
include ConcreteExpression
def self.all depth
ClassExpression.all(depth-1).repeated_combination(2).map do |left, right|
self.new left, right
end
end
end
class DisjointUnion < ClassAxiom
include ConcreteExpression
def self.all depth
ClassExpression.all(depth-1).repeated_combination(2).map do |left, right|
self.new ClassLiteral.instance, left, right
end
end
end
class ClassExpression
extend OneOfSubclasses
def self.all depth
if depth < 1
raise
elsif depth == 1
ClassLiteral.all 1
else
subclasses.map { |sc| sc.all depth }.flatten
end
end
end
class ClassLiteral < ClassExpression
include Singleton
def self.all depth
[self.instance]
end
def normalize
self
end
def to_s class_names, object_property_names
class_names.shift
end
end
class ObjectIntersectionOf < ClassExpression
include ConcreteExpression
def self.all depth
ClassExpression.all(depth-1).repeated_combination(2).map do |left, right|
self.new left, right
end
end
end
class ObjectUnionOf < ClassExpression
include ConcreteExpression
def self.all depth
ClassExpression.all(depth-1).repeated_combination(2).map do |left, right|
self.new left, right
end
end
end
class ObjectComplementOf < ClassExpression
include ConcreteExpression
def self.all depth
ClassExpression.all(depth-1).map do |ce|
self.new ce
end
end
end
# class ObjectOneOf < ClassExpression; end
class ObjectSomeValuesFrom < ClassExpression
include ConcreteExpression
def self.all depth
ObjectPropertyExpression.all(depth-1).map do |pe|
ClassExpression.all(depth-1).map do |ce|
self.new pe, ce
end
end.flatten
end
end
class ObjectAllValuesFrom < ClassExpression
include ConcreteExpression
def self.all depth
ObjectPropertyExpression.all(depth-1).map do |pe|
ClassExpression.all(depth-1).map do |ce|
self.new pe, ce
end
end.flatten
end
end
# class ObjectHasValue < ClassExpression; end
# class ObjectHasSelf < ClassExpression; end
# class ObjectMinCardinality < ClassExpression; end
# class ObjectMaxCardinality < ClassExpression; end
# class ObjectExactCardinality < ClassExpression; end
# class DataSomeValuesFrom < ClassExpression; end
# class DataAllValuesFrom < ClassExpression; end
# class DataHasValue < ClassExpression; end
# class DataMinCardinality < ClassExpression; end
# class DataMaxCardinality < ClassExpression; end
# class DataExactCardinality < ClassExpression; end
class ObjectPropertyExpression
extend OneOfSubclasses
def self.all depth
if depth < 1
raise
elsif depth == 1
ObjectProperty.all 1
else
subclasses.map { |sc| sc.all depth }.flatten
end
end
end
class ObjectProperty < ObjectPropertyExpression
include Singleton
def self.all depth
[self.instance]
end
def normalize
self
end
def to_s class_names, object_property_names
object_property_names.shift
end
end
class ObjectInverseOf < ObjectPropertyExpression
include ConcreteExpression
def self.all depth
ObjectProperty.all(depth).map do |prop|
self.new prop
end
end
end
puts Axiom.all(ARGV[0].to_i).map { |a| a.normalize.to_s CLASS_NAMES.dup, OBJECT_PROPERTY_NAMES.dup }
true
a920c7427ba77c98184ab18cb344e7dcec495314
Ruby
rmangaha/phw
/rb/ex12a.rb
UTF-8
122
3.5625
4
[]
no_license
print "Give me a dollar amount: "
dollar = gets.chomp.to_f
tip = dollar * 0.1
puts "Ten percent of #{dollar} is #{tip}"
def two_sum(nums, target)
num_hash = {}
nums.each_with_index do |num, i|
remainder = target - num
if num_hash[remainder]
remainder_i = nums.find_index(remainder)
return [remainder_i,i]
end
num_hash[num] = true
end
nil
end
true
8e4d6854b4bc009e0528dabe28df5db23ee68be4
Ruby
Mitchmer/palindrome_checker
/brainteaser2.rb
UTF-8
591
3.796875
4
[]
no_license
def user_input
puts "What would you like to input as your palindrome?"
input = gets.strip.downcase
checkinput(input)
end
def checkinput(word)
checkprep = word.gsub(/[ ]/, '').split(//)
initialarr = checkprep.map {|x| x}
reversearr = []
while checkprep.length > 0
reversearr << checkprep.pop
end
if initialarr == reversearr
puts "What up! Nice palindrome"
else
puts "That's definitely not a palindrome. Try again."
end
puts "Would you like to try again? (y/n)"
choice = gets.strip
if choice == 'y'
user_input
else
exit
end
end
user_input
true
263b1b319f794129898bad0ddd3c9dd059e41622
Ruby
justinhamlin/ttt-6-position-taken-rb-q-000
/lib/position_taken.rb
UTF-8
121
2.953125
3
[]
no_license
# code your #position_taken? method here!
def position_taken?(board, position)
if board[0] == " "
"false"
end
end
true
4962ca8c39e931d799511f54e51b9666f0ee4997
Ruby
twohlix/database_cached_attribute
/spec/database_cached_attribute_spec.rb
UTF-8
5,148
2.546875
3
[
"MIT"
]
permissive
require 'temping'
require 'database_cached_attribute'
ActiveRecord::Base.establish_connection("sqlite3:///:memory:")
Temping.create :no_include_class do
with_columns do |t|
t.string :string_attribute
t.integer :integer_attribute
end
end
Temping.create :include_class do
include DatabaseCachedAttribute
database_cached_attribute :string_attribute
database_cached_attribute :integer_attribute
with_columns do |t|
t.string :string_attribute
t.integer :integer_attribute
end
end
describe DatabaseCachedAttribute do
# JUST INCLUDED TESTS
context "included" do
before do
@test_obj = IncludeClass.new
end
it "creates functions for invalidating cache" do
expect(@test_obj.respond_to? :invalidate_cache).to eq(true)
end
it "creates functions for saving cache" do
expect(@test_obj.respond_to? :update_cache)
end
it "using database_cached_attribute in the model adds nice functions to invalidate cache" do
expect(@test_obj.respond_to? :invalidate_string_attribute).to eq(true)
expect(@test_obj.respond_to? :invalidate_integer_attribute).to eq(true)
expect(@test_obj.respond_to? :invalidate_non_attribute).to eq(false)
end
it "using database_cached_attribute in the model adds nice functions to save caches" do
expect(@test_obj.respond_to? :cache_string_attribute).to eq(true)
expect(@test_obj.respond_to? :cache_integer_attribute).to eq(true)
expect(@test_obj.respond_to? :cache_non_attribute).to eq(false)
end
end
# NEW OBJECT TESTS
context "new objects not yet saved" do
before(:each) do
@test_obj = IncludeClass.new
@test_obj.string_attribute = "original string"
expect(@test_obj.new_record?).to eq(true)
expect(@test_obj.persisted?).to eq(false)
end
it "does not persist cache updates" do
@test_obj.cache_string_attribute
@test_obj.string_attribute = "new string"
@test_obj.cache_string_attribute
expect(@test_obj.new_record?).to eq(true)
expect(@test_obj.persisted?).to eq(false)
end
it "does not persist cache invalidations" do
@test_obj.invalidate_string_attribute
@test_obj.string_attribute = "new string"
@test_obj.invalidate_string_attribute
expect(@test_obj.new_record?).to eq(true)
expect(@test_obj.persisted?).to eq(false)
end
it "using .invalidate_attribute_name does change the data" do
expect(@test_obj.string_attribute).to eq("original string")
@test_obj.invalidate_string_attribute
expect(@test_obj.string_attribute).to eq(nil)
end
it "using .cache_attribute_name does not change the data" do
expect(@test_obj.string_attribute).to eq("original string")
@test_obj.cache_string_attribute
expect(@test_obj.string_attribute).to eq("original string")
end
end
# SAVED OBJECT TESTS
context "objects persisted in the database" do
before(:each) do
@test_obj = IncludeClass.new
@test_obj.string_attribute = "original string"
@test_obj.save
expect(@test_obj.new_record?).to eq(false)
expect(@test_obj.persisted?).to eq(true)
end
it "persists a cache invalidation" do
expect(@test_obj.string_attribute).to eq("original string")
@test_obj.invalidate_string_attribute
expect(@test_obj.string_attribute).to eq(nil)
@compare_obj = IncludeClass.last
expect(@compare_obj.id).to eq(@test_obj.id)
expect(@compare_obj.string_attribute).to eq(nil)
end
it "persists a cache update" do
expect(@test_obj.string_attribute).to eq("original string")
@test_obj.string_attribute = "new string"
@test_obj.cache_string_attribute
expect(@test_obj.string_attribute).to eq("new string")
@compare_obj = IncludeClass.last
expect(@compare_obj.id).to eq(@test_obj.id)
expect(@compare_obj.string_attribute).to eq("new string")
end
it "does not persist cache invalidation with other changes" do
expect(@test_obj.string_attribute).to eq("original string")
@test_obj.integer_attribute = 1337
@test_obj.invalidate_string_attribute
expect(@test_obj.string_attribute).to eq(nil)
@compare_obj = IncludeClass.last
expect(@compare_obj.id).to eq(@test_obj.id)
expect(@compare_obj.string_attribute).to eq("original string")
expect(@compare_obj.integer_attribute).to eq(nil)
end
it "does not persist cache updates with other changes" do
expect(@test_obj.string_attribute).to eq("original string")
@test_obj.string_attribute = "new string"
@test_obj.integer_attribute = 1337
@test_obj.cache_string_attribute
expect(@test_obj.string_attribute).to eq("new string")
@compare_obj = IncludeClass.last
expect(@compare_obj.id).to eq(@test_obj.id)
expect(@compare_obj.string_attribute).to eq("original string")
expect(@compare_obj.integer_attribute).to eq(nil)
end
end
end
def sort_array_asc(array)
array.sort
end
def sort_array_desc(array)
array.sort.reverse
end
def sort_array_char_count(array)
array.sort do |a, b|
a.length <=> b.length
end
end
def swap_elements(array)
array[1], array[2] = array[2], array[1]
array
end
def swap_elements_from_to(array, index, destination_index)
array[index], array[destination_index] = array[destination_index], array[index]
array
end
def reverse_array(array)
array.reverse
end
def kesha_maker(array)
tempArray = []
tempString = ""
array.each do |string|
tempString = string[0,2] + "$" + string[3,string.length]
tempArray << tempString
end
tempArray
end
def find_a(array)
array.select {|word| word.start_with?("a")}
end
def sum_array(array)
tempNum = 0
array.each do |num|
tempNum += num
end
tempNum
end
def add_s(array)
array.each_with_index.collect do |element, index|
if index != 1
element << "s"
else
element
end
end
end
true
d002c38233aa7cc396b4afb79d95b6bd1f100a56
Ruby
donaldpiret/google_data_source
/lib/google_data_source/base.rb
UTF-8
4,216
2.71875
3
[
"MIT"
]
permissive
module GoogleDataSource
def self.included(base)
base.extend(ClassMethods)
end
##
# Class Methods
module ClassMethods
def google_data_source(params, options = {})
joins = options[:joins]
result = self.connection.execute(Parser.query_string_to_sql(params[:tq], self, joins))
cols = Column.from_result(result)
datasource = GoogleDataSource::Base.from_params(params)
datasource.set(cols, result)
return datasource
end
end
class Base
attr_reader :data, :cols, :errors
# Creates a new instance and validates it.
# Protected method so it can be used from the subclasses
def initialize(gdata_params)
@params = gdata_params
@errors = {}
@cols = []
@data = []
@version = "0.6"
@coltypes = [ "boolean", "number", "string", "date", "datetime", "timeofday"]
@colkeys = [ :type, :id, :label, :pattern]
validate
end
protected :initialize
def self.from_params(params)
# Exract GDataSource params from the request.
gdata_params = {}
tqx = params[:tqx]
unless tqx.blank?
gdata_params[:tqx] = true
tqx.split(';').each do |kv|
key, value = kv.split(':')
gdata_params[key.to_sym] = value
end
end
# Create the appropriate GDataSource instance from the gdata-specific parameters
gdata_params[:out] ||= "json"
gdata = from_gdata_params(gdata_params)
end
# Factory method to create a GDataSource instance from a serie of valid GData
# parameters, as described in the official documentation (see above links).
#
# +gdata_params+ can be any map-like object that maps keys (like +:out+, +:reqId+
# and so forth) to their values. Keys must be symbols.
def self.from_gdata_params(gdata_params)
case gdata_params[:out]
when "json"
JsonData.new(gdata_params)
when "html"
HtmlData.new(gdata_params)
when "csv"
CsvData.new(gdata_params)
else
InvalidData.new(gdata_params)
end
end
# Access a GData parameter. +k+ must be symbols, like +:out+, +:reqId+.
def [](k)
@params[k]
end
# Sets a GData parameter. +k+ must be symbols, like +:out+, +:reqId+.
# The instance is re-validated afterward.
def []=(k, v)
@params[k] = v
validate
end
# Checks whether this instance is valid (in terms of configuration parameters)
# or not.
def valid?
@errors.size == 0
end
# Manually adds a new validation error. +key+ should be a symbol pointing
# to the invalid parameter or element.
def add_error(key, message)
@errors[key] = message
return self
end
# Sets the data to be exported. +data+ should be a collection of activerecord object. The
# first index should iterate over rows, the second over columns. Column
# ordering must be the same used in +add_col+ invokations.
#
# Anything that behaves like a 2-dimensional array and supports +each+ is
# a perfectly fine alternative.
def set(cols, data)
cols.each do |col|
raise ArgumentError, "Invalid column type: #{col.type}" if [email protected]?(col.type)
@cols << col.data
end
# @data should be a 2-dimensional array
@data = []
data.each do |record|
@data << record
end
#data
return self
end
# Validates this instance by checking that the configuration parameters
# conform to the official specs.
def validate
@errors.clear
if @params[:tqx]
add_error(:reqId, "Missing required parameter reqId") unless @params[:reqId]
if @params[:version] && @params[:version] != @version
add_error(:version, "Unsupported version #{@params[:version]}")
end
end
end
# Empty method. This is a placeholder implemented by subclasses that
# produce the response according to a given format.
def response
end
# Empty method. This is a placeholder implemented by subclasses that return the correct format
def format
end
end
end
true
d5c6565fdf6b7c29d29cba98140aa1ce50f257fc
Ruby
secrgb/randomsnippets
/rails_host_without_www.rb
UTF-8
1,480
2.53125
3
[
"MIT"
]
permissive
# RandomSnippets by Jaan Janesmae <[email protected]>
#
# Copyright (c) 2009-2010 Jaan Janesmae
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# ===============================================================
@host = host_without_www(request.host)
def host_without_www(host)
parts = host.split('.')
if parts[0] == 'www' and parts.count <= 3 # in case there is a domain like www.tld then the www won't be erased
host = parts[1..parts.count-1].join('.')
end
return host
end
true
e9416d5d3fae3f440d793a9bc3401c9247d47c7e
Ruby
influxdata/influxdb-scripts
/generators/gaussian.rb
UTF-8
1,679
3
3
[]
no_license
require "influxdb"
ACTIONS = [
{mean: 500, stddev: 75, name: "welcome#index", count: 50_000},
{mean: 1000, stddev: 100, name: "users#new", count: 500},
{mean: 200, stddev: 10, name: "sessions#create", count: 5000},
{mean: 5000, stddev: 800, name: "exceptions#create", count: 200},
{mean: 400, stddev: 10, name: "logs#show", count: 20_000}
]
TIMESPAN = 24*60*60
class RandomGaussian
def initialize(mean, stddev, rand_helper = lambda { Kernel.rand })
@rand_helper = rand_helper
@mean = mean
@stddev = stddev
@valid = false
@next = 0
end
def rand
if @valid then
@valid = false
return @next
else
@valid = true
x, y = self.class.gaussian(@mean, @stddev, @rand_helper)
@next = y
return x
end
end
private
def self.gaussian(mean, stddev, rand)
theta = 2 * Math::PI * rand.call
rho = Math.sqrt(-2 * Math.log(1 - rand.call))
scale = stddev * rho
x = mean + scale * Math.cos(theta)
y = mean + scale * Math.sin(theta)
return x, y
end
end
influxdb = InfluxDB::Client.new "ops",
username: "user",
password: "pass",
host: "sandbox.influxdb.org",
port: 9061
points = []
ACTIONS.each do |action|
r = RandomGaussian.new(action[:mean], action[:stddev])
(action[:count]).times do |n|
timestamp = Time.now.to_i - (TIMESPAN * rand).floor
value = r.rand.to_i.abs
points << {action: action[:name], value: value, time: timestamp*1000}
puts "#{action[:name]} => #{value}"
end
end
points.each_slice(10_000) do |data|
begin
puts "Writing #{data.length} points."
influxdb.write_point("transactions", data)
rescue
retry
end
end
true
b414b5f2cbde99ec026fadefbd546bf562db6cca
Ruby
ltarnowski1/Ruby_Projekt3
/spec/manager_spec.rb
UTF-8
1,212
2.6875
3
[]
no_license
require 'rspec'
require_relative '../spec/spec_helper'
describe 'Manager' do
obj = Manager.new
it 'should add book' do
expect{
obj.addBook("title", "author", "release_year", "price")
}.not_to raise_error
end
it 'should get books' do
expect {
obj.getBooks
}.not_to raise_error
end
it 'should delete book' do
expect{
obj.deleteBook(1)
}.not_to raise_error
end
it 'should edit book' do
expect{
obj.updateBook(1, "title", "author", "release_year", "price")
}.not_to raise_error
end
it 'should get class variable' do
expect{
Manager.books
}.not_to raise_error
end
it 'should add rent' do
expect{
obj.addRent("id_book", "rent_date", "return_date")
}.not_to raise_error
end
it 'should get rents' do
expect {
obj.getRents
}.not_to raise_error
end
it 'should delete rent' do
expect{
obj.deleteRent(1)
}.not_to raise_error
end
it 'should edit rent' do
expect{
obj.updateRent(1, "id_book", "rent_date", "return_date")
}.not_to raise_error
end
it 'should get class variable' do
expect{
Manager.rents
}.not_to raise_error
end
end
require 'therapeutor/questionnaire/question'
class Therapeutor::Questionnaire::Section
include ActiveModel::Validations
attr_accessor :name, :description, :questions, :questionnaire
validates :name, presence: {allow_blank: false}
validates :questionnaire, presence: true
validate :validate_questions
def initialize(opts={})
opts.symbolize_keys!
@name = opts[:name]
@description = opts[:description]
@questionnaire = opts[:questionnaire]
@questions = (opts[:questions]||[]).map do |question_data|
Therapeutor::Questionnaire::Question.new(question_data.merge(section: self))
end
end
def inspect
properties = %w(name description).map do |key|
"#{key}=#{send(key).inspect}"
end.join(' ')
"<#{self.class.name} #{properties}>"
end
def validate_questions
section_reference = name ? "section '#{name}'" : 'unnamed section'
questions.each.with_index do |question, i|
unless question.valid?
question.errors.full_messages.each do |e|
errors.add(:questions, "Question #{i+1} for #{section_reference} invalid: #{e}")
end
end
end
end
def self.validate_set(sections)
(sections.map.with_index do |section, i|
unless section.valid?
error_to_add = section.errors.full_messages.join(', ')
"Section ##{i+1} invalid: #{error_to_add}"
end
end).compact
end
end
true
bff1b5abdfaf5ba8c74fac8124323b9f111b989b
Ruby
Ami-tnk/rubybook
/chapter4/drinks5.rb
UTF-8
182
3.21875
3
[]
no_license
drinks = ["モカ", "コーヒー", "カフェラテ"]
# 配列の末尾から要素を1つ削除
drinks.pop
p drinks
# 配列の先頭から要素を1つ削除
drinks.shift
p drinks
true
ffd87731f4f33452e2d2cac152e891fad61fbb6a
Ruby
stoic-plus/backend_prework
/day_7/10_little_monkeys.rb
UTF-8
816
4
4
[]
no_license
def in_words(int)
numbers_to_name = {
1 => "One",
2 => "Two",
3 => "Three",
4 => "Four",
5 => "Five",
6 => "Six",
7 => "Seven",
8 => "Eight",
9 => "Nine",
10 => "Ten",
}
return numbers_to_name[int] || int
end
# Will only print rhyme with word numbers for 1 - 10 times.
def print_monkeys(times=10)
if times < 1
return p "Please select a number greater than 0"
end
i = times
while i >= 1 do
puts "> #{in_words(i)} little monkeys jumping on the bed, "
puts "> One fell off and bumped his head,"
puts "> Mama called the doctor and the doctor said,"
puts "> 'No more monkeys jumping on the bed!'"
puts ">"
i -= 1
end
end
puts "How many times would you like to hear a nursery rhyme?"
print "> "
times = gets.to_i
print_monkeys(times)
require 'spec_helper'
describe Ramda::List do
let(:r) { described_class }
context '#all' do
it 'test' do
equals3 = R.equals(3)
expect(r.all(equals3, [3, 3, 3, 3])).to be_truthy
expect(r.all(equals3, [3, 3, 1, 3])).to be_falsey
end
it 'is curried' do
equals3 = R.equals(3)
expect(r.all(equals3).call([3, 3, 3])).to be_truthy
end
end
context '#any' do
it 'test' do
greater_than0 = R.lt(1)
greater_than2 = R.lt(2)
expect(r.any(greater_than0, [0, 1])).to be_falsey
expect(r.any(greater_than2, [2, 3])).to be_truthy
end
it 'is curried' do
greater_than0 = R.lt(1)
expect(r.any(greater_than0)[[0, 1]]).to be_falsey
end
end
context '#append' do
it 'from docs' do
expect(r.append('tests', ['write', 'more'])).to eq(['write', 'more', 'tests'])
expect(r.append('tests', [])).to eq(['tests'])
expect(r.append(['tests'], ['write', 'more'])).to eq(['write', 'more', ['tests']])
end
it 'is curried' do
expect(R.append(1).call([4, 3, 2])).to eq([4, 3, 2, 1])
end
end
context '#concat' do
it 'from docs' do
expect(r.concat('ABC', 'DEF')).to eq('ABCDEF')
expect(r.concat([4, 5, 6], [1, 2, 3])).to eql([4, 5, 6, 1, 2, 3])
expect(r.concat([], [])).to eql([])
end
it 'is curried' do
expect(r.concat('ABC').call('DEF')).to eq('ABCDEF')
end
end
context '#contains' do
it 'from docs' do
expect(r.contains(3, [1, 2, 3])).to be_truthy
expect(r.contains(4, [1, 2, 3])).to be_falsey
expect(r.contains({ name: 'Fred' }, [{ name: 'Fred' }])).to be_truthy
expect(r.contains([42], [[42]])).to be_truthy
end
it 'is curried' do
expect(r.contains(3).call([1, 2, 3]))
end
end
context '#drop' do
it 'from docs' do
expect(r.drop(1, ['foo', 'bar', 'baz'])).to eq(['bar', 'baz'])
expect(r.drop(2, ['foo', 'bar', 'baz'])).to eq(['baz'])
expect(r.drop(3, ['foo', 'bar', 'baz'])).to eq([])
expect(r.drop(4, ['foo', 'bar', 'baz'])).to eq([])
expect(r.drop(3, 'ramda')).to eq('da')
end
it 'is curried' do
expect(r.drop(3).call('ramda')).to eq('da')
end
end
context '#filter' do
def is_even
->(n) { n.even? }
end
it 'from docs' do
expect(r.filter(is_even, [1, 2, 3, 4])).to eq([2, 4])
expect(r.filter(is_even, a: 1, b: 2, c: 3, d: 4)).to eq(b: 2, d: 4)
end
it 'is curried' do
expect(r.filter(is_even).call([1, 2, 3, 4])).to eq([2, 4])
end
end
context '#find' do
it 'from docs' do
list = [{ a: 1 }, { a: 2 }, { a: 3 }]
expect(r.find(R.prop_eq(:a, 2), list)).to eq(a: 2)
expect(r.find(R.prop_eq(:a, 4), list)).to be_nil
end
it 'is curried' do
list = [{ a: 1 }, { a: 2 }, { a: 3 }]
expect(r.find(R.prop_eq(:a, 2)).call(list)).to eq(a: 2)
end
end
context '#flatten' do
it 'from docs' do
expect(r.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]))
.to eq([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
end
end
context '#group_by' do
it 'from docs' do
by_grade = lambda do |student|
case student.fetch(:score)
when 0...65 then 'F'
when 0...70 then 'D'
when 0...80 then 'C'
when 0...90 then 'B'
else
'A'
end
end
students = [
{ name: 'Abby', score: 84 },
{ name: 'Eddy', score: 58 },
{ name: 'Jack', score: 69 }
]
expect(r.group_by(by_grade, students)).to eq(
'D' => [{ name: 'Jack', score: 69 }],
'F' => [{ name: 'Eddy', score: 58 }],
'B' => [{ name: 'Abby', score: 84 }]
)
end
it 'is curried' do
students = [
{ name: 'Mike', age: 30 },
{ name: 'Tom', age: 25 },
{ name: 'Tom', age: 20 }
]
group_by_name = r.group_by(->(a) { a.fetch(:name) })
expect(group_by_name.call(students)).to eq(
'Tom' => [{ name: 'Tom', age: 25 }, { name: 'Tom', age: 20 }],
'Mike' => [{ name: 'Mike', age: 30 }]
)
end
end
context '#head' do
it 'from docs' do
expect(r.head(['fi', 'fo', 'fum'])).to eq('fi')
expect(r.head([])).to be_nil
expect(r.head('abc')).to eq('a')
expect(r.head('')).to eq('')
end
end
context '#index_of' do
it 'from docs' do
expect(r.index_of(3, [1, 2, 3, 4])).to be(2)
expect(r.index_of(1, [1, 2, 3, 4])).to be(0)
expect(r.index_of(10, [1, 2, 3, 4])).to be(-1)
end
end
context '#join' do
it 'from docs' do
expect(r.join('|', [1, 2, 3])).to eq('1|2|3')
end
it 'is curried' do
spacer = r.join(' ')
expect(spacer.call(['a', 2, 3.4])).to eq('a 2 3.4')
end
end
context '#last_index_of' do
it 'from docs' do
expect(r.last_index_of(3, [-1, 3, 3, 0, 1, 2, 3, 4])).to be(6)
expect(r.last_index_of(10, [1, 2, 3, 4])).to be(-1)
end
end
context '#length' do
it 'from docs' do
expect(r.length([])).to eq(0)
expect(r.length([1, 2, 3])).to eq(3)
end
end
context '#map' do
it 'from docs' do
double_fn = ->(x) { x * 2 }
expect(r.map(double_fn, [1, 2, 3])).to eq([2, 4, 6])
expect(r.map(double_fn, x: 1, y: 2, z: 3)).to eq(x: 2, y: 4, z: 6)
end
it 'is curried' do
double_fn = ->(x) { x * 2 }
expect(r.map(double_fn).call([1, 2, 3])).to eq([2, 4, 6])
end
end
context '#nth' do
it 'from docs' do
list = ['foo', 'bar', 'baz', 'quux']
expect(r.nth(1, list)).to eq('bar')
expect(r.nth(-1, list)).to eq('quux')
expect(r.nth(-99, list)).to be_nil
expect(r.nth(2, 'abc')).to eq('c')
expect(r.nth(3, 'abc')).to eq('')
end
end
context '#pluck' do
it 'from docs' do
expect(r.pluck(:a).call([{ a: 1 }, { a: 2 }])).to eq([1, 2])
expect(r.pluck(0).call([[1, 2], [3, 4]])).to eq([1, 3])
end
end
context '#prepend' do
it 'from docs' do
expect(r.prepend('fee').call(['fi', 'fo', 'fum'])).to eq(['fee', 'fi', 'fo', 'fum'])
end
end
context '#range' do
it 'from docs' do
expect(r.range(1, 5)).to eq([1, 2, 3, 4])
expect(r.range(50, 53)).to eq([50, 51, 52])
end
end
context '#reduce' do
it 'from docs' do
# ((((0 - 1) - 2) - 3) - 4) = -10
expect(r.reduce(R.subtract, 0, [1, 2, 3, 4])).to be(-10)
end
end
context '#reduce_right' do
def avg
->(a, b) { (a + b) / 2 }
end
it 'from docs' do
# (1 - (2 - (3 - (4 - 0)))))
expect(r.reduce_right(R.subtract, 0, [1, 2, 3, 4])).to be(-2)
end
it 'returns the accumulator for an empty array' do
expect(r.reduce_right(avg, 0, [])).to eq(0)
end
it 'is curried' do
something = r.reduce_right(avg, 54)
rcat = r.reduce_right(R.concat, '')
expect(something.call([12, 4, 10, 6])).to eq(12)
expect(rcat.call(['1', '2', '3', '4'])).to eq('1234')
end
end
context '#reverse' do
it 'from docs' do
expect(r.reverse([1, 2, 3])).to eq([3, 2, 1])
expect(r.reverse([1, 2])).to eq([2, 1])
expect(r.reverse([1])).to eq([1])
expect(r.reverse([])).to eq([])
expect(r.reverse('abc')).to eq('cba')
expect(r.reverse('ab')).to eq('ba')
expect(r.reverse('a')).to eq('a')
expect(r.reverse('')).to eq('')
end
end
context '#reject' do
it 'from docs' do
is_odd = ->(n) { n.odd? }
expect(r.reject(is_odd, [1, 2, 3, 4])).to eq([2, 4])
expect(r.reject(is_odd, a: 1, b: 2, c: 3, d: 4)).to eq(b: 2, d: 4)
end
end
context '#sort' do
it 'from docs' do
diff = ->(a, b) { a - b }
expect(r.sort(diff, [4, 2, 7, 5])).to eq([2, 4, 5, 7])
end
end
context '#tail' do
it 'from docs' do
expect(r.tail([1, 2, 3])).to eq([2, 3])
expect(r.tail([1, 2])).to eq([2])
expect(r.tail([1])).to eq([])
expect(r.tail([])).to eq([])
expect(r.tail('abc')).to eq('bc')
expect(r.tail('ab')).to eq('b')
expect(r.tail('a')).to eq('')
expect(r.tail('')).to eq('')
end
end
context '#take' do
it 'is curried' do
personnel = [
'Dave Brubeck',
'Paul Desmond',
'Eugene Wright',
'Joe Morello',
'Gerry Mulligan',
'Bob Bates',
'Joe Dodge',
'Ron Crotty'
]
take_five = r.take(5)
expect(take_five.call(personnel)).to eq(
['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan']
)
end
it 'can operate on arrays' do
expect(r.take(10, [])).to eq([])
expect(r.take(4, ['foo', 'bar', 'baz'])).to eq(['foo', 'bar', 'baz'])
expect(r.take(3, ['foo', 'bar', 'baz'])).to eq(['foo', 'bar', 'baz'])
expect(r.take(2, ['foo', 'bar', 'baz'])).to eq(['foo', 'bar'])
expect(r.take(1, ['foo', 'bar', 'baz'])).to eq(['foo'])
expect(r.take(0, ['foo', 'bar', 'baz'])).to eq([])
end
it 'can operate on strings' do
expect(r.take(10, 'Ramda')).to eq('Ramda')
expect(r.take(3, 'Ramda')).to eq('Ram')
expect(r.take(2, 'Ramda')).to eq('Ra')
expect(r.take(1, 'Ramda')).to eq('R')
expect(r.take(0, 'Ramda')).to eq('')
end
end
context '#take_while' do
it 'from docs' do
is_not_four = ->(x) { x != 4 }
expect(r.take_while(is_not_four, [1, 2, 3, 4, 3, 2, 1])).to eq([1, 2, 3])
expect(r.take_while(is_not_four, [1, 2, 3])).to eq([1, 2, 3])
end
end
context '#uniq' do
it 'from docs' do
expect(r.uniq([1, 1, 2, 1])).to eq([1, 2])
expect(r.uniq([1, '1'])).to eq([1, '1'])
expect(r.uniq([[42], [42]])).to eq([[42]])
end
end
context '#xprod' do
it 'from docs' do
expect(r.xprod([1, 2], ['a', 'b']))
.to eq([[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']])
end
end
context '#zip' do
it 'from docs' do
expect(r.zip([1, 2, 3], ['a', 'b', 'c'])).to eq([[1, 'a'], [2, 'b'], [3, 'c']])
expect(r.zip([1, 2, 3], ['a', 'b', 'c', 'd'])).to eq([[1, 'a'], [2, 'b'], [3, 'c']])
end
end
context '#zip_with' do
it 'from docs' do
f = ->(x, y) { Ramda.join('', [x, y]) }
expect(r.zip_with(f, [1, 2, 3], ['a', 'b', 'c'])).to eq(['1a', '2b', '3c'])
end
end
end
true
bf29e029dcadba17b74d4a5c51d463dacad455cd
Ruby
wf1101/MediaRanker
/test/models/work_test.rb
UTF-8
1,852
2.53125
3
[]
no_license
require "test_helper"
describe Work do
describe "validations" do
before do
@work = Work.new
end
it "is valid when a work has a unique title " do
title_ex = "coolbanana"
@work.title = title_ex
result = @work.valid?
result.must_equal true
end
it "is invalid when a work does not have a title" do
@work.title = nil
result = @work.valid?
result.must_equal false
end
it "is invalid when a work has a deplicate title" do
work_dup = Work.last
@work.title = work_dup.title
result = @work.valid?
result.must_equal false
end
end
describe "relations" do
before do
@work = works(:one)
end
it "is valid when a work connects votes" do
vote = Vote.first
@work.votes << vote
@work.vote_ids.must_include vote.id
end
end
describe "self.show_spotlight" do
it "can return the work with most votes" do
result = Work.show_spotlight
result.must_equal works(:two)
end
it "can raise Argument error if there is no work" do
skip
Work.all.each do |w|
w.destroy
end
proc {
Work.show_spotlight
}.must_raise ArgumentError
end
end
describe "self.show_albums" do
it "can return all albums from the works" do
albums = Work.show_albums
albums.each do |al|
al.category.must_equal "album"
end
end
end
describe "self.show_books" do
it "can turn all books from the works" do
books = Work.show_books
books.each do |book|
book.category.must_equal "book"
end
end
end
describe "self.show_movies" do
it "can return all movies from the works" do
movies = Work.show_movies
movies.each do |mov|
mov.category.must_equal "movie"
end
end
end
end
true
7d2d5d25ae278c36616a4eae61cb5b7297db6642
Ruby
jserme/ruby-study
/01基本环境/helloworld.rb
UTF-8
284
3.546875
4
[]
no_license
#双引号的内转义字符会被处理
print("hello world from ruby\n")
#单引号的不处理
print('hello world from ruby\n')
#puts自动加上换行
puts "hello world"
#p方法明确显示是字符串还是数字
p 100
p "100"
p '100'
#输出中文
puts "听说我是中文"
true
94bb09fe1895f4528b1ba763805a4766b7f00034
Ruby
AleaToir3/20exo
/exo/exo_10.rb
UTF-8
72
2.5625
3
[]
no_license
puts "Donne moi ton année de naissance"
ddn = gets.to_i
puts 2017 - ddn