text stringlengths 10 2.61M |
|---|
# input: 3 integers (scores)
# output: string (letter value associated with the grade)
# tested values are between 0 and 100, there are no negative nunmbers and none that are greater than 100
# calculate the mean average of all 3 grades and use that value to determine the grade
# data structure: integer
# algo:
# use case when structure for determining grade
# set a variable as the mean average score of the 3 grades
# use case and when for all letter grades to return appropriate one for the mean score
def get_grade(score1, score2, score3)
mean = (score1 + score2 + score3) / 3
case mean
when 90..100
'A'
when 80..89
'B'
when 70..79
'C'
when 60..69
'D'
when 0..59
'F'
end
end
# or
def get_grade(s1, s2, s3)
result = (s1 + s2 + s3)/3
case result
when 90..100 then 'A'
when 80..89 then 'B'
when 70..79 then 'C'
when 60..69 then 'D'
else 'F'
end
end |
class ActivitiesController < ApplicationController
def index
## check if activity.main_photo.blank?
### @activty_url = ....
@activities = Activity.includes(:sessions)
query = params[:query]
if query.present?
@activities = Activity.global_search(query)
else
@activities = Activity.all.order("created_at DESC")
end
end
def new
@activity = Activity.new
end
def create
@user = current_user
@activity = Activity.new(activity_params)
@activity.organizer = @user
@activity.save
# raise
redirect_to activities_path
end
def edit
@activity = Activity.find(params[:id])
end
def update
@activity = Activity.find(params[:id])
@activity.update(activity_params)
redirect_to activity_path(@activity)
end
def show
@activity = Activity.find(params[:id])
@sessions = @activity.sessions.order("start_time ASC")
end
def remove_tag
@activity.tag_list.remove(params[:tag])
@activity.save!
# redirect_to activities_path(@activity)
end
def tagged
if params[:tag].present?
@activities = Activity.tagged_with(params[:tag])
else
@activities = Activity.all
end
end
private
def activity_params
params.require(:activity).permit(:title, :description, :main_photo, :photo_1, :photo_2, :photo_3, :price, :rating, :address, :latitude, :longitude, :tag_list)
end
end
|
#==============================================================================
# ** Game_Player
#------------------------------------------------------------------------------
# This class handles the player. It includes event starting determinants and
# map scrolling functions. The instance of this class is referenced by
# $game_player.
#==============================================================================
class Game_Player < Game_Character
#--------------------------------------------------------------------------
# * Processing of Movement via Input from Directional Buttons
#--------------------------------------------------------------------------
alias move_by_input_dnd move_by_input
def move_by_input
return if $tactic_enabled || $game_party.leader.state?(2)
return if $game_system.story_mode?
return unless controlable?
move_by_input_dnd
end
#--------------------------------------------------------------------------
# Alias: update
#--------------------------------------------------------------------------
alias update_dndAI update
def update
update_dndAI
process_party_movement
return unless $game_party.leader.state?(2)
update_followers_attack
update_follower_movement
end
#-------------------------------------------------------------------------
def update_cancel_action
@action_cancel_timer += 1
return unless @action_cancel_timer > 3
@action_cancel_timer = 0
cancel_action_without_penalty
end
#-------------------------------------------------------------------------
def process_party_movement
process_pathfinding_movement
trigger_target_event if @target_event
end
#-------------------------------------------------------------------------
def trigger_target_event
if distance_to(@target_event.x, @target_event.y) <= 1
@target_event.start
@target_event = nil
end
end
#-------------------------------------------------------------------------
end
|
class AddInvoiceTitleToAuctions < ActiveRecord::Migration
def change
add_column :auctions, :invoice_title, :string, limit: 50
end
end
|
require "benchmark"
time = Benchmark.measure do
i = 1
j = 2
next_num = 0
sum = 2
loop do
next_num = i + j
break if next_num > 4000000
sum += next_num if next_num.even?
i = j
j = next_num
end
puts "The sum of the even-valued terms of the Fibonacci sequence whose values do not exceed four million is #{sum}"
end
puts "Time elapsed (in seconds): #{time}"
|
# frozen_string_literal: true
module SystemCtl
class PlistToServiceFileConverter
def convert(definition)
service = {
:Unit => {},
:Service => {},
:Install => {},
}
unsupported_keys = []
definition.plist.each do |key, value|
case key
when 'KeepAlive'
service[:Service][:Restart] = 'always'
when 'Label'
service[:Unit][:Description] = value
when 'ProgramArguments'
service[:Service][:ExecStart] = value.map { |arg| "'#{arg}'" }.join(' ')
when 'RunAtLoad'
# AFAIK, there is neither and equivalent nor a real need for this.
when 'StandardErrorPath'
service[:Service][:StandardError] = "file:#{value}"
when 'WorkingDirectory'
service[:Service][:WorkingDirectory] = value
else
unsupported_keys.push(key)
end
end
unless unsupported_keys.empty?
opoo("The following plist keys are not yet supported, and were ignored: '#{unsupported_keys.join("', '")}'.")
end
service[:Service][:Type] = 'simple'
service[:Install][:WantedBy] = 'default.target'
service_lines = []
service.each do |section, values|
service_lines.push("[#{section}]")
values.each do |key, value|
service_lines.push("#{key}=#{value}")
end
service_lines.push('')
end
service_lines.join("\n")
end
end
end
|
# == Schema Information
#
# Table name: task_recurrences
#
# id :integer not null, primary key
# schedule :text
# user_id :integer
# task :text
# note :text
# created_at :datetime not null
# updated_at :datetime not null
#
class TaskRecurrence < ActiveRecord::Base
attr_accessible :parent_id, :populated_until, :schedule, :user_id
attr_accessor :recurrence
serialize :schedule, Hash
has_many :tasks, :dependent => :nullify
def recurrence
@recurrence ||= IceCube::Schedule.from_hash(self.schedule)
end
before_create :initialize_from_prototype
after_create :populate_tasks
# this method initializes the task_recurrence from the prototype task
# the prototype task will create a task recurrence when necessary during a create or update operation on the task
def initialize_from_prototype
prototype_task = self.tasks.first
self.note = prototype_task.note
self.task = prototype_task.task
self.recurrence = IceCube::Schedule.new(start = prototype_task.due_date)
self.recurrence.add_recurrence_rule RecurringSelect.dirty_hash_to_rule(prototype_task.recurrence_rule)
# Possibly unnecessary, since this is set in the populate tasks
self.schedule = self.recurrence.to_hash
end
# this method populates tasks from the start date to the populated until time (default - 6 months)
def populate_tasks(time_forward = 3.months)
inserts = []
places = []
timestamp = Time.now.strftime('%Y-%m-%d %H:%M:%S')
# Make sure not to populate the same event twice at boundaries
due_dates = self.recurrence.occurrences(Date.today + time_forward)
if due_dates.size > 0 && due_dates[0].to_date == self.recurrence.start_time.to_date
due_dates.delete_at(0)
end
due_dates.each do |due_date|
places.push "(?,?,?,?,?,?,?)"
inserts.push(*[self.id, self.user_id, self.task, self.note, due_date.strftime('%Y-%m-%d'), timestamp, timestamp])
end
if places.length > 0
sql_arr = ["INSERT INTO tasks (task_recurrence_id, user_id, task, note, due_date, created_at, updated_at) VALUES #{places.join(", ")}"] + inserts
sql = ActiveRecord::Base.send(:sanitize_sql_array, sql_arr)
ActiveRecord::Base.connection.execute(sql)
end
if due_dates.size > 0
self.recurrence.start_time = due_dates[-1]
self.schedule = self.recurrence.to_hash
self.save
end
end
# This method deletes all incomplete tasks for this recurrence and then destroys the task_recurrence object
# (note that this also nullifies the task_recurrence_id foreign key column on all completed task association records)
def self_destruct
self.tasks.where("completed_on is NULL").delete_all
self.destroy
end
end
|
class Person
def initialize(name, profession)
@name, @profession = name, profession
end
def name
@name
end
def info
"Name: #{@name}, Profession: #{@profession}"
end
def setProfession(profession)
@profession = profession
end
end
p = Person.new("John", "Doctor")
p.setProfession("Computer Engineer")
puts p.info
|
class BranchesController < ApplicationController
def index
respond_to do |format|
format.html do
page_n = params[:page]
@branches = Branch.listing(params[:id] || nil)
.page(page_n).per(Settings.branches.listing.pages)
if request.xhr? == 0 # request is ajax
case params[:selector].to_sym
when :listing
locals = {branches: @branches}
if params[:id]
locals[:id] = params[:id]
end
render partial: 'branches/listing', locals: locals
end
end
end
format.json do
case params[:selector].to_sym
when :summary
render(json: Branch.summary(params[:id]))
end
end
end
end
def show
@branch = Branch.find(params[:id])
respond_to do |format|
page_n = params[:page]
format.html do
# ==> FETCH THE INFORMATIONS TO RENDER THE VIEW
# Yin-Yang
@yinyang = Branch.builds_yinyang(@branch.id)
gon.yinyang = @yinyang
# Builds
@builds = Build.listing(@branch.id)
.page(page_n).per(Settings.builds.listing.pages)
if request.xhr? != 0 # request isn't ajax
# ==> RESOURCES SELECTORS SETUP
@resources_avail = :builds, :steps, :actions
gon.current_resource = {
id: @branch.id,
type: :branches
}
end
render layout: (request.xhr? != 0)
end
end
end
end
|
class DesignationFile < ActiveRecord::Base
belongs_to :organization
validates :organization, presence: true
mount_uploader :file, DesignationFileUploader
validates_presence_of :file
end
|
# First Refactor
$VERBOSE = nil # Allows for Prime.new for ruby vers < 1.9
require 'prime'
def first_n_primes(n)
return "n must be an integer." unless n.is_a? Integer
return "n must be greater than 0." if n <= 0
prime_array ||= []
prime = Prime.new
n.times { prime_array << (prime.next) }
prime_array
end
first_n_primes(10)
|
class User < ActiveRecord::Base
EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i
validates :name, presence: true
validates :password, presence: true, on: :create
validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: EMAIL_REGEX }
has_many :secrets
has_many :likes, dependent: :destroy
has_many :liked_secrets, source: :secrets
after_validation :downcase_email
has_secure_password
private
def downcase_email
self.email.downcase!
end
end
|
module Ludo
# hash that holds the starting position for each color
# SP - short for 'starting positions'
SP = { "Red" => 0, "Blue" => 10, "Green" => 20, "Black" => 30 }
class Game
attr_reader :game_status, :players, :current_player
def initialize(game_status = 'playing')
@game_status = game_status
@players = set_players
end
def start
starting_message
while @game_status != 'finished' do
game_turn
end
end
private
def game_turn
puts "#{@current_player.color} player moves. If the pawn chosed can not move you will lose your turn."
print_players_pawns
adv = dice_roll
pawn_move(adv)
@current_player.remove_finished_pawns
check_winner
print_players_pawns
# display_board
set_current_player(adv)
display_board
end
def set_players
# sets the players ant their colors
colors = SP.keys[0..(rand(1..3))]
players = []
colors.each { |x| players << Player.new(x) }
players
end
def current_player_index
@players.index(@current_player)
end
def set_current_player(dice)
# set the current player based on the dice roll, if player gets 6 he moves again
if dice != 6
if @current_player == @players[-1]
@current_player = @players[0]
else
@current_player = @players[current_player_index + 1]
end
else
@current_player
end
puts @current_player.color
end
def dice_roll
# random between 1 to 6
rand(1..6)
end
def print_players_pawns
# prints the current user pawns status, position, counter
current_player.pawns.each_with_index do |p, i|
puts "The pawn #{i} has the status #{p.status}, position on the board #{p.position} and counter #{p.counter}"
end
end
def display_board
#displays the board and updates the position of the pawns
@board = Array.new(40) {'X'}
@players.each do |player|
player.pawns.each_with_index do |pawn, i|
@board[pawn.position] = player.color + "-" + i.to_s if pawn.position != -1
end
end
p @board
end
def choose_pawn
#lets player select the pawn he wants to move
arr = [0,1,2,3]
puts "#{@current_player.color} choose a pawn! Press the number of the pawn to move it."
pawn_input = gets.chomp
return pawn_input.to_i if arr.include?(pawn_input.to_i)
choose_pawn
end
def check_winner
#check for a winner and changes game status to finished
if @current_player.has_won?
puts "#{@current_player.color} has won the game!"
@game_status = 'finished'
end
end
def starting_message
# Displays the players in game and the starting player
display_players
puts "#{@current_player.color} will start the game."
end
def display_players
# displays the players colors and sets the starting player
@players.each do |p|
puts p.color
end
@current_player = set_initial_player
end
def set_initial_player
# choses starting player based on dice roll
results = []
@players.each { |x| results << dice_roll}
h = Hash[@players.zip results]
h.max_by{|key,val| val}[0]
end
def pawn_move(adv)
puts "Dice roll: #{ adv }"
current_pawn = choose_pawn
pawn = @current_player.pawns[current_pawn.to_i]
if pawn.status == 'home'
#pawn start the game if the player gets 1 or 6, and he starts from the
#position that corresponds to its color
if adv ==1 || adv == 6
pawn.start(SP[current_player.color])
end
elsif pawn.status == 'in_play'
#if the pawn is already in play, it is gonna advance and
# eliminate other players pawns
if pawn.position + adv >= @board.length
pawn.position = (pawn.position + adv) - @board.length
else
if @board[pawn.position + adv] != 'X'
# eliminates the opponents pawn
dead_pawn = @board[pawn.position + adv].split(/-/)
if @current_player.color != dead_pawn[0]
intruder = @players.select{|player| player.color == dead_pawn[0]}
intruder[0].pawns[dead_pawn[1].to_i].send_home
end
end
pawn.position += adv
end
pawn.counter += adv
else
puts "Pawn has already finished."
end
end
end
end
|
require 'spec_helper'
describe 'hiera_lookups::two' do
context 'with actual hiera lookup' do
it { is_expected.to contain_user('user2').with_password(/.+/) }
end
context 'with fake hiera lookup' do
let(:hiera_config) { 'spec/fixtures/hiera-good.yaml' }
it do
is_expected.to contain_user('user2')
.with_password('another_fake_password_string')
end
end
context 'when lookup() specifies a default value' do
context 'when hieradb is missing' do
let(:hiera_config) { '/dev/null' }
it { is_expected.to_not compile }
it { is_expected.to raise_error(Puppet::PreformattedError) }
end
context 'when key is not in hiera but specifies a default value' do
let(:hiera_config) { 'spec/fixtures/hiera-bad.yaml' }
it { is_expected.to_not compile }
it { is_expected.to raise_error(Puppet::PreformattedError) }
end
end
end
|
module ActiveRecord
module Acts
module Overflowable
def self.included(base)
base.extend(ClassMethods)
end
#Available options
# :column - the column in the model that may have overflow.
# :overflow_limit - the maximum length of the column before it is saved as overflow
# :has_overflow_column - not a boolean. The model must have a flag denoting whether there is overflow. This option tells the
# the plugin what the column name of the flag is.
module ClassMethods
def acts_as_overflowable(options = {})
this_class = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
raise "No overflow column supplied in acts as overflowable for #{this_class}." if not options[:overflow_column]
raise "No overflow_limit option supplied in acts as overflowable for #{this_class}." if not options[:overflow_limit]
raise "No overflow_indicator option supplied in acts as overflowable for #{this_class}." if not options[:overflow_indicator]
raise "No overflow_table option supplied in acts as overflowable for #{this_class}." if not options[:overflow_table]
overflow_column = options[:overflow_column]
overflow_indicator = options[:overflow_indicator]
overflow_table = options[:overflow_table]
overflow_limit = options[:overflow_limit]
class_inheritable_reader :options
has_one overflow_table,
:foreign_key => :overflowable_id,
:conditions => ['overflowable_type = ?',this_class],
:dependent => :destroy
options.keys.each do |key|
class_eval "def #{key.to_s}() \"#{options[key]}\" end"
end
class_eval <<-EOV
#getter for the overflowable_text field. Dynamic, so it can be named anything.
def #{overflow_column.to_s}_with_overflow()
has_overflow = self.send("#{overflow_indicator}")
if has_overflow
self.send("#{overflow_table}").overflow
else
self[:#{overflow_column}]
end
end
def #{overflow_column.to_s}=(value)
limit = overflow_limit.to_i
overflow_model = self.send("#{overflow_table}")
if (not value.nil?) and (value.length >= (limit-1))
if overflow_model.nil?
self.send("create_#{overflow_table}", :overflowable_type => "#{this_class}")
end
overflow_model = self.send("#{overflow_table}")
overflow_field = overflow_model.overflow
if overflow_field.nil? or (value.length > limit and !overflow_field.eql?(value))
self.send("#{overflow_table}").overflow = value
self.send("#{overflow_indicator}=",true)
self[:#{overflow_column}] = value[0..(limit-1)]
overflow_model.save! unless self.new_record?
end
else
overflow_model.overflow = "" unless overflow_model.nil?
self[:#{overflow_column}] = value
self.send("#{overflow_indicator}=",false)
overflow_model.save! if !overflow_model.nil? and !self.new_record?
end
end
EOV
include InstanceMethods
extend SingletonMethods
end
end #ClassMethods
module SingletonMethods
end
module InstanceMethods
end #InstanceMethods
end
end
end
ActiveRecord::Base.send(:include, ActiveRecord::Acts::Overflowable)
|
require 'question_marks'
require 'spec_helper'
context "Tests that evaluate to True" do
it "should return true" do
expect(question_marks("arrb6???4xxbl5???eee5")).to be true
end
it "gaps between the questions marks should still return true" do
expect(question_marks("acc?7??sss?3rr1??????5")).to be true
end
it "should return true" do
expect(question_marks("9???1???9???1???9")).to be true
end
end
context "Tests that evaluate to False" do
it "if one set of numbers passes but another doesn't, the test fails" do
expect(question_marks("5??aaaaaaaaaaaaaaaaaaa?5?5")).to be false
end
it "should return false" do
expect(question_marks("aa6?9")).to be false
end
end
|
class CreateHotelGalleries < ActiveRecord::Migration
def change
create_table :hotel_galleries do |t|
t.references :hotel, index: true
t.timestamps
end
end
end
|
# You'll get a string and a boolean.
# When the boolean is true, return a new string containing all the odd characters.
# When the boolean is false, return a new string containing all the even characters.
#
# If you have no idea where to begin, remember to check out the cheatsheets for string and logic/control
#
# odds_and_evens("abcdefg",true) # => "bdf"
# odds_and_evens("abcdefg",false) # => "aceg"
def odds_and_evens(string, return_odds)
new_string = ''
i = return_odds ? 1 : 0
while (i<string.length)
new_string+=string[i]
i+=2
end
new_string
end
=begin
puts odds_and_evens("abcdefg",true)
puts odds_and_evens("abcdefg",false)
puts odds_and_evens("",true)
puts odds_and_evens("",false)
puts odds_and_evens("a",true)
puts odds_and_evens("a",false)
puts odds_and_evens("ab",true)
puts odds_and_evens("ab",false)
=end
|
require 'CSV'
require 'pry'
require 'json'
file_location = "map.csv"
class FormatMap
def initialize(location)
@data = CSV.read(location)
@transposed = @data.transpose
@msg_start = []
@hash_tags = ["#Trump", "#MAGA", "#Qanon", "#Q", "#TheStorm",
"#CBTS", "#FolllowTheWhiteRabbit", "#QClearance",
"#TickTock", "#Breadcrumbs", "#TheStormIsUponUs",
"#TheStormIsHere", "#CalmBeforeTheStorm", "#DonaldTrump",
"#Redpill", "#DrainTheSwamp", "#MuellerTime", "#Mueller",
"#AmericaFirst", "#NYT", "#Sessions",
"#TheStormIsComing", "#TheStormHasArrived",
"#SealedIndictments", "#TheGreatAwakening", "#HillaryClinton",
"#baking"]
@transposed[1].each_with_index do |cell, i|
if cell.nil?
cell = ""
end
if cell[0,2] == ">>"
@msg_start << i
end
end
end
def full_q_msg(start)
ceiling = @msg_start[start]
if @msg_start[start] == @msg_start.last
floor = @data.length
else
floor = @msg_start[start+1]
end
length = floor - ceiling
output = @data[ceiling, length]
end
def threaded_msg(msg_num)
full_msg = full_q_msg msg_num
output_array =[]
full_msg[1..-1].each_with_index do | line, index |
# remove extra cells
line = line[1,3]
output_array << threadify(line, index, msg_num, full_msg)
end
output_array
end
def threadify(line, index, msg_num, full_msg)
tweet_arr = []
q_msg_text = line[0]
concise_answer = line[1]
long_answer = line[2]
q_hello_arr = ["Q Time!", "Q Anon...", "Q Says..."]
expl_arr = ["And what does that mean?", "Here's what I think that means:", "Here's an explanation..."]
detail_arr = ["Even more details!", "Let's dig deeper!!!", "Rabbithole time! :)"]
first_line = %(#{msg_num+1}_#{index+1}_#{[*('a'..'z')].shuffle[0]}
)
expl_line = %(#{msg_num+1}_#{index+1}_#{[*('a'..'z')].shuffle[0]}
)
further_detail_line = %(#{msg_num+1}_#{index+1}_#{[*('a'..'z')].shuffle[0]}
)
hashtags ="#Trump #MAGA #Qanon #Q #TheStorm #CBTS #FolllowTheWhiteRabbit #QClearance #TickTock #Breadcrumbs \n\n"
if q_msg_text
tweet_arr.concat split_and_format_msg(get_hashtags(5) + q_msg_text,
q_hello_arr.shuffle()[0] + "\n" + first_line)
end
if concise_answer
tweet_arr.concat split_and_format_msg(get_hashtags(4) + concise_answer,
expl_arr.shuffle()[0] + "\n" + expl_line)
end
if long_answer
tweet_arr.concat split_and_format_msg(get_hashtags(4) + long_answer,
detail_arr.shuffle()[0] + "\n" + further_detail_line)
end
return tweet_arr
end
def get_hashtags(num)
if num > @hash_tags.length
num = @hash_tags.length
end
return @hash_tags.shuffle()[0,num].join(" ") + "\n\n"
end
def split_and_format_msg(msg, prepend_line)
out = []
chunked_msg = []
if msg.length > 260-(prepend_line.length+7)
chunked_msg = chunk(msg, 260-(prepend_line.length+5))
else
chunked_msg << msg
end
chunked_msg.each_with_index do |chunk, i|
full_msg = prepend_line +"\n[#{i+1}/#{chunked_msg.length}] "+chunk
out << full_msg
end
return out
end
def chunk(string, size)
arr = []
until string.length < size
last_space_index = string[0, size].rindex(/[\s\r\n\t]/)
arr << string[0..last_space_index]
string = string[last_space_index+1..-1]
end
arr << string
end
def format_all
output = []
@msg_start.each_with_index do | msg_num, index |
output << threaded_msg(index)
end
return output
end
end
output = FormatMap.new(file_location)
out = output.threaded_msg(3)[1]
puts out
out = output.format_all
json_hash = out.to_json
puts json_hash
file = File.open("map.json", "w")
file.write json_hash
file.close
# TODO
# Comment everything
|
require 'spec_helper'
RSpec.describe Stateoscope::Adapter do
around do |example|
old = described_class.registry
described_class.registry = Stateoscope::AdapterRegistry.new
example.call
described_class.registry = old
end
describe '.register' do
it 'registers the given adapter with the registry' do
adapter = double(Stateoscope::Adapter::Base)
expect(described_class.registry).to receive(:register).with(adapter)
described_class.register(adapter)
end
end
describe '.new_for' do
it 'finds and instantiates an adapter from the registry' do
klass = Class.new
state_machine_name = :foo
correct_adapter = class_double(Stateoscope::Adapter::Base, new: :correct)
expect(correct_adapter).to receive(:handle?).with(klass, state_machine_name).and_return(true)
described_class.register(correct_adapter)
wrong_adapter = class_double(Stateoscope::Adapter::Base, new: :wrong)
expect(wrong_adapter).to receive(:handle?).with(klass, state_machine_name).and_return(false)
described_class.register(wrong_adapter)
expect(described_class.new_for(klass, state_machine_name)).to eq(:correct)
end
end
end
|
class ApplicationController < ActionController::API
before_filter :set_request_headers
def set_request_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
end
protected
def errors(errors)
JSON.generate({errors: errors.as_json})
end
end
|
require 'spec_helper'
describe "Lispy.compile" do
it "should use a clean binding" do
p = Alf::Lispy.compile("lambda{ path }", "a path")
lambda{ p.call }.should raise_error(NameError)
end
it "should resolve __FILE__ correctly" do
p = Alf::Lispy.compile("__FILE__", "a path")
p.should == "a path"
end
end |
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
# max_pool_size is set to 1 to force a single connection being used for
# all operations in a client.
describe 'SCRAM-SHA auth mechanism negotiation' do
min_server_fcv '4.0'
require_no_external_user
require_topology :single, :replica_set, :sharded
# Test uses global assertions
clean_slate
let(:create_user!) do
root_authorized_admin_client.tap do |client|
users = client.database.users
if users.info(user.name).any?
users.remove(user.name)
end
client.database.command(
createUser: user.name,
pwd: password,
roles: ['root'],
mechanisms: server_user_auth_mechanisms,
)
client.close
end
end
let(:password) do
user.password
end
let(:result) do
client.database['admin'].find(nil, limit: 1).first
end
context 'when the configuration is specified in code' do
let(:client) do
opts = {
database: 'admin',
user: user.name,
password: password
}.tap do |o|
o[:auth_mech] = auth_mech if auth_mech
end
new_local_client(
SpecConfig.instance.addresses,
SpecConfig.instance.test_options.merge(opts).update(max_pool_size: 1)
)
end
context 'when the user exists' do
context 'when the user only can use SCRAM-SHA-1 to authenticate' do
let(:server_user_auth_mechanisms) do
['SCRAM-SHA-1']
end
let(:user) do
Mongo::Auth::User.new(
user: 'sha1',
password: 'sha1',
auth_mech: auth_mech
)
end
context 'when no auth mechanism is specified' do
let(:auth_mech) do
nil
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
context 'when SCRAM-SHA-1 is specified as the auth mechanism' do
let(:auth_mech) do
:scram
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
context 'when SCRAM-SHA-256 is specified as the auth mechanism' do
let(:auth_mech) do
:scram256
end
it 'fails with a Mongo::Auth::Unauthorized error' do
create_user!
expect { result }.to raise_error(Mongo::Auth::Unauthorized)
end
end
end
context 'when the user only can use SCRAM-SHA-256 to authenticate' do
let(:server_user_auth_mechanisms) do
['SCRAM-SHA-256']
end
let(:user) do
Mongo::Auth::User.new(
user: 'sha256',
password: 'sha256',
auth_mech: auth_mech
)
end
context 'when no auth mechanism is specified' do
let(:auth_mech) do
nil
end
it 'authenticates successfully' do
create_user!
expect { client.database['admin'].find(options = { limit: 1 }).first }.not_to raise_error
end
end
context 'when SCRAM-SHA-1 is specified as the auth mechanism' do
let(:auth_mech) do
:scram
end
it 'fails with a Mongo::Auth::Unauthorized error' do
create_user!
expect { result }.to raise_error(Mongo::Auth::Unauthorized)
end
end
context 'when SCRAM-SHA-256 is specified as the auth mechanism' do
let(:auth_mech) do
:scram256
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
end
context 'when the user only can use either SCRAM-SHA-1 or SCRAM-SHA-256 to authenticate' do
let(:server_user_auth_mechanisms) do
['SCRAM-SHA-1', 'SCRAM-SHA-256']
end
let(:user) do
Mongo::Auth::User.new(
user: 'both',
password: 'both',
auth_mech: auth_mech
)
end
context 'when no auth mechanism is specified' do
let(:auth_mech) do
nil
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
context 'when SCRAM-SHA-1 is specified as the auth mechanism' do
let(:auth_mech) do
:scram
end
before do
create_user!
end
it 'authenticates successfully' do
RSpec::Mocks.with_temporary_scope do
mechanism = nil
# With speculative auth, Auth is instantiated twice.
expect(Mongo::Auth).to receive(:get).at_least(:once).at_most(:twice).and_wrap_original do |m, user, connection|
# copy mechanism here rather than whole user
# in case something mutates mechanism later
mechanism = user.mechanism
m.call(user, connection)
end
expect do
result
end.not_to raise_error
expect(mechanism).to eq(:scram)
end
end
end
context 'when SCRAM-SHA-256 is specified as the auth mechanism' do
let(:auth_mech) do
:scram256
end
before do
create_user!
end
it 'authenticates successfully with SCRAM-SHA-256' do
RSpec::Mocks.with_temporary_scope do
mechanism = nil
# With speculative auth, Auth is instantiated twice.
expect(Mongo::Auth).to receive(:get).at_least(:once).at_most(:twice).and_wrap_original do |m, user, connection|
# copy mechanism here rather than whole user
# in case something mutates mechanism later
mechanism = user.mechanism
m.call(user, connection)
end
expect { result }.not_to raise_error
expect(mechanism).to eq(:scram256)
end
end
end
end
end
context 'when the user does not exist' do
let(:auth_mech) do
nil
end
let(:user) do
Mongo::Auth::User.new(
user: 'nonexistent',
password: 'nonexistent',
)
end
it 'fails with a Mongo::Auth::Unauthorized error' do
expect { result }.to raise_error(Mongo::Auth::Unauthorized)
end
end
context 'when the username and password provided require saslprep' do
let(:auth_mech) do
nil
end
let(:server_user_auth_mechanisms) do
['SCRAM-SHA-256']
end
context 'when the username and password as ASCII' do
let(:user) do
Mongo::Auth::User.new(
user: 'IX',
password: 'IX'
)
end
let(:password) do
"I\u00ADX"
end
it 'authenticates successfully after saslprepping password' do
create_user!
expect { result }.not_to raise_error
end
end
context 'when the username and password are non-ASCII' do
let(:user) do
Mongo::Auth::User.new(
user: "\u2168",
password: "\u2163"
)
end
let(:password) do
"I\u00ADV"
end
it 'authenticates successfully after saslprepping password' do
create_user!
expect { result }.not_to raise_error
end
end
end
end
context 'when the configuration is specified in the URI' do
let(:uri) do
Utils.create_mongodb_uri(
SpecConfig.instance.addresses,
username: user.name,
password: password,
uri_options: SpecConfig.instance.uri_options.merge(
auth_mech: auth_mech,
),
)
end
let(:client) do
new_local_client(uri, SpecConfig.instance.monitoring_options.merge(max_pool_size: 1))
end
context 'when the user exists' do
context 'when the user only can use SCRAM-SHA-1 to authenticate' do
let(:server_user_auth_mechanisms) do
['SCRAM-SHA-1']
end
let(:user) do
Mongo::Auth::User.new(
user: 'sha1',
password: 'sha1',
auth_mech: auth_mech,
)
end
context 'when no auth mechanism is specified' do
let(:auth_mech) do
nil
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
context 'when SCRAM-SHA-1 is specified as the auth mechanism' do
let(:auth_mech) do
:scram
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
context 'when SCRAM-SHA-256 is specified as the auth mechanism' do
let(:auth_mech) do
:scram256
end
it 'fails with a Mongo::Auth::Unauthorized error' do
create_user!
expect { result }.to raise_error(Mongo::Auth::Unauthorized)
end
end
end
context 'when the user only can use SCRAM-SHA-256 to authenticate' do
let(:server_user_auth_mechanisms) do
['SCRAM-SHA-256']
end
let(:user) do
Mongo::Auth::User.new(
user: 'sha256',
password: 'sha256',
auth_mech: auth_mech,
)
end
context 'when no auth mechanism is specified' do
let(:auth_mech) do
nil
end
it 'authenticates successfully' do
create_user!
expect { client.database['admin'].find(options = { limit: 1 }).first }.not_to raise_error
end
end
context 'when SCRAM-SHA-1 is specified as the auth mechanism' do
let(:auth_mech) do
:scram
end
it 'fails with a Mongo::Auth::Unauthorized error' do
create_user!
expect { result }.to raise_error(Mongo::Auth::Unauthorized)
end
end
context 'when SCRAM-SHA-256 is specified as the auth mechanism' do
let(:auth_mech) do
:scram256
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
end
context 'when the user only can use either SCRAM-SHA-1 or SCRAM-SHA-256 to authenticate' do
let(:server_user_auth_mechanisms) do
['SCRAM-SHA-1', 'SCRAM-SHA-256']
end
let(:user) do
Mongo::Auth::User.new(
user: 'both',
password: 'both',
auth_mech: auth_mech,
)
end
context 'when no auth mechanism is specified' do
let(:auth_mech) do
nil
end
it 'authenticates successfully' do
create_user!
expect { result }.not_to raise_error
end
end
context 'when SCRAM-SHA-1 is specified as the auth mechanism' do
let(:auth_mech) do
:scram
end
before do
create_user!
expect(user.mechanism).to eq(:scram)
end
it 'authenticates successfully' do
RSpec::Mocks.with_temporary_scope do
mechanism = nil
# With speculative auth, Auth is instantiated twice.
expect(Mongo::Auth).to receive(:get).at_least(:once).at_most(:twice).and_wrap_original do |m, user, connection|
# copy mechanism here rather than whole user
# in case something mutates mechanism later
mechanism = user.mechanism
m.call(user, connection)
end
expect { result }.not_to raise_error
expect(mechanism).to eq(:scram)
end
end
end
context 'when SCRAM-SHA-256 is specified as the auth mechanism' do
let(:auth_mech) do
:scram256
end
before do
create_user!
end
it 'authenticates successfully with SCRAM-SHA-256' do
RSpec::Mocks.with_temporary_scope do
mechanism = nil
# With speculative auth, Auth is instantiated twice.
expect(Mongo::Auth).to receive(:get).at_least(:once).at_most(:twice).and_wrap_original do |m, user, connection|
# copy mechanism here rather than whole user
# in case something mutates mechanism later
mechanism = user.mechanism
m.call(user, connection)
end
expect { result }.not_to raise_error
expect(mechanism).to eq(:scram256)
end
end
end
end
end
end
end
|
class Jobs::ClientsController < ApplicationController
def new
@client = Client.new
render layout: false
end
def create
@client = Client.create!(create_params)
# By default, this returns as content-type turbo-stream;
# How can we avoid forcing the content type?
render JobsClientSelectComponent.new(selected: @client), content_type: 'text/html'
end
private
def create_params
params.require(:client).permit(:name)
end
end
|
class AddColumnDraftToPayrollEntries < ActiveRecord::Migration
def change
add_column :payroll_entries, :draft, :boolean, :default => true
add_column :payroll_entries, :full_name, :string
add_column :payrolls, :out_of_date, :boolean, :default => false
end
end
|
class AddPriorityIndex < ActiveRecord::Migration
def change
add_index :project_subjects, :priority
end
end
|
# frozen_string_literal: true
require 'simplecov'
SimpleCov.start
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace('gem name')
config.include Capybara::DSL
Shoulda::Matchers.configure do |configs|
configs.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
config.before :all do
Shelter.destroy_all
Pet.destroy_all
Review.destroy_all
@shelter1 = Shelter.create(name: 'Test Name',
address: '123 Test Test',
city: 'Denver',
state: 'CO',
zip: '80205')
@shelter2 = Shelter.create(name: 'Test Paradise',
address: 'Test',
city: 'Denver',
state: 'CO',
zip: '80232')
@pet1 = Pet.create(image: 'https://i.imgur.com/wKls5bM.png',
name: 'Test name 1',
description: 'Test description 1',
age: 'Test age 1',
sex: 'Test sex 1',
status: 'Adoptable',
shelter_id: @shelter1.id)
@pet2 = Pet.create(image: 'https://i.imgur.com/wKls5bM.png',
name: 'Test name 2',
description: 'Test description 2',
age: 'Test age 2',
sex: 'Test sex 2',
status: 'Adoptable',
shelter_id: @shelter1.id)
@pet3 = Pet.create(image: 'https://i.imgur.com/wKls5bM.png',
name: 'Test name 3',
description: 'Test description 3',
age: 'Test age 3',
sex: 'Test sex 3',
status: 'Adoptable',
shelter_id: @shelter2.id)
@pet4 = Pet.create(image: 'https://i.imgur.com/wKls5bM.png',
name: 'Test name 4',
description: 'Test description 1',
age: 'Test age 4',
sex: 'Test sex 4',
status: 'Adoptable',
shelter_id: @shelter2.id)
@review1 = @shelter1.reviews.create({ title: 'This is Awesome!',
rating: '3',
content: 'Easy process and friendly staff.',
image: 'https://i.imgur.com/wKls5bM.png' })
@review2 = @shelter1.reviews.create({ title: 'Thank you!',
rating: '4',
content: 'Great selection and reasonable cost.',
image: 'https://lh3.googleusercontent.com/proxy/VH2o2pIhKaUrNNs8PUtOHgayKXVKlaF2lObH0Xmq06RQAu4b4T_U-ZwKqWRd8aSs4-q7WW9-P8JuFPqIvsVwqGMQrL51Q4y7s4GaXx2HZUtYKwYtxlFmwlLH4-aPDkOCMd1lK72FqL75-Viyg_F2NnLs-wypnocyYz0QrEk_f8PDHiZNVIN5WilLHZAir1RFiM617jhlogVQVln6oppZWEWUFk4e7K5CIzJiIbc8LItt6nYmIg' })
@review3 = @shelter2.reviews.create({ title: 'These guys were ok....ish',
rating: '2',
content: 'Puppies were cool, staff not so much.',
image: 'https://i.redd.it/zz62ggz08k021.jpg' })
end
end
|
class CheckoutPage < Howitzer::Web::Page
path '/checkout'
# validate :title, /^Review Your Order \| Famous Smoke Shop$/ #staging
validate :title, /^Shopping Cart | Famous Smoke$/ #tag
iframe :card_number, '#braintree-hosted-field-number'
iframe :card_expiration, '#braintree-hosted-field-expirationDate'
element :cvv, "[name='cvv']"
element :agree_terms, "[for='terms'] .fakecheck"
element :place_order, :xpath, "//button[text()='place order']", visible: true, match: :first
element :phone_verification, '.infotitle.oswald.cred'
element :new_price, :xpath, "//b[contains(.,'new price')]"
def fill_credit_card(number, expiration, cvv)
card_number_iframe { |frame| frame.fill_card_number(number) }
card_expiration_iframe { |frame| frame.fill_expiration_date(expiration) }
cvv_element.set(cvv)
end
def agree_terms
agree_terms_element.click
end
def place_order
place_order_element.click
end
end
|
class Member < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :omniauthable, :omniauth_providers => [:facebook]
has_one :cart, dependent: :nullify
has_many :orders, dependent: :nullify
after_commit :send_greeting_email, on: :create
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |member|
member.email = auth.info.email
member.name = auth.info.name
member.password = Devise.friendly_token[0,20]
member.avatar = auth.info.image
end
end
def self.new_with_session(params, session)
super.tap do |member|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
member.email = data["email"] if member.email.blank?
end
end
end
def send_greeting_email
MemberMailer.greeting(self).deliver_later
end
end
|
require 'amqp'
module QueueTester
module Interfaces
module AMQP
def enqueue_amqp(options)
::AMQP.start(
:host => options[:host],
:port => options[:port],
:user => options[:username],
:pass => options[:password]
) do |connection|
::AMQP::Channel.new(connection) do |channel, open_ok|
channel.on_error(&method(:handle_channel_exception))
exchange = channel.default_exchange
channel.queue(options[:queue], :durable => (options[:transient] != true)) do |queue, declare_ok|
options[:messages].each do |message|
log_debug "[AMQP] Publish message #{message}"
exchange.publish message, :routing_key => queue.name, :persistent => (options[:transient] != true)
progress(1)
end
EventMachine.add_timer(0.5) do
connection.disconnect { EventMachine.stop }
end
end
end
end
end
def dequeue_amqp(options)
messages = []
::AMQP.start(
:host => options[:host],
:port => options[:port],
:user => options[:username],
:pass => options[:password]
) do |connection|
::AMQP::Channel.new(connection) do |channel, open_ok|
channel.on_error(&method(:handle_channel_exception))
log_debug "[AMQP] Prefetch #{options[:number]}"
channel.prefetch(options[:number])
channel.queue(options[:queue], :durable => (options[:transient] != true)) do |queue, declare_ok|
queue.subscribe(:ack => true) do |header, message|
header.ack
messages << message
log_debug "[AMQP] Received message #{message}"
progress(1)
if (messages.size == options[:number])
queue.unsubscribe
connection.disconnect { EventMachine.stop }
end
end
end
end
end
return messages
end
def flush_amqp(options)
::AMQP.start(
:host => options[:host],
:port => options[:port],
:user => options[:username],
:pass => options[:password]
) do |connection|
::AMQP::Channel.new(connection) do |channel, open_ok|
channel.on_error(&method(:handle_channel_exception))
channel.queue(options[:queue], :durable => (options[:transient] != true)) do |queue, declare_ok|
EventMachine.add_timer(0.5) do
queue.purge
log_debug '[AMQP] Flush performed.'
progress(1)
connection.disconnect { EventMachine.stop }
end
end
end
end
end
def handle_channel_exception(channel, channel_close)
msg = "Oops... a channel-level exception: code = #{channel_close.reply_code}, message = #{channel_close.reply_text}"
puts msg
raise RuntimeError, msg
end
end
end
end
|
#
# Cookbook Name:: webapp
# Recipe:: sidekiq
#
worker_count = node[:application][:sidekiq][:worker_count]
template "/etc/monit/conf.d/sidekiq_#{node[:application][:name]}.conf" do
owner 'root'
group 'root'
mode 0644
source "monit/sidekiq.conf.erb"
notifies :reload, 'service[monit]', :delayed
end
template "/#{node[:application][:init_path]}/start_sidekiq" do
owner node[:application][:user][:name]
group node[:application][:user][:group]
mode 0755
source "start_sidekiq.erb"
end
template "/#{node[:application][:init_path]}/stop_sidekiq" do
owner node[:application][:user][:name]
group node[:application][:user][:group]
mode 0755
source "stop_sidekiq.erb"
end
execute "restart-sidekiq" do
command %Q{
echo "sleep 20 && monit -g #{node[:application][:name]}_sidekiq restart all" | at now
}
end
|
# GSPlan - Team commitment planning
#
# Copyright (C) 2008 Jan Schrage <jan@jschrage.de>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <http://www.gnu.org/licenses/>.
require 'test_helper'
class WorktypeReportTest < ActiveSupport::TestCase
include Report::Worktype
def test_worktype_tracking
wt_track = worktype_tracking('2008-08-01'.to_date, '2008-09-30'.to_date)
assert_equal 3,wt_track.size
assert wt_track.find { |wt| wt[:team_id] == 1 && wt[:worktype_id] == 1 && wt[:daysbooked] == 7 }
assert wt_track.find { |wt| wt[:team_id] == 1 && wt[:worktype_id] == 1 && wt[:daysbooked] == 6 }
assert wt_track.find { |wt| wt[:team_id] == 2 && wt[:worktype_id] == 1 && wt[:daysbooked] == 8 }
end
def test_worktype_cumul
wt_track = worktype_cumul('2008-08-01'.to_date, '2008-09-30'.to_date)
assert_equal 2,wt_track.size
assert wt_track.find { |wt| wt[:team_id] == 1 && wt[:worktype_id] == 1 && wt[:daysbooked] == 13 }
assert wt_track.find { |wt| wt[:team_id] == 2 && wt[:worktype_id] == 1 && wt[:daysbooked] == 8 }
end
def test_worktype_dist
# only worktype 1 filled, with 14 days
wt_track = calculate_worktype_distribution('2008-09-01'.to_date)
assert_equal 1,wt_track.size
assert_equal 14,wt_track[1][:daysbooked]
end
def test_worktype_adhoc
adhoc = worktype_adhoc('2008-08-01'.to_date, '2008-11-30'.to_date)
assert_equal 4, adhoc.size
assert adhoc.find { |ah| ah[:team_id] == 2 && ah[:month] == "AUG" && ah[:tasks] == 2 && ah[:percentage] == 100 }
assert adhoc.find { |ah| ah[:team_id] == 1 && ah[:month] == "NOV" && ah[:tasks] == 1 && ah[:percentage] == 50 }
assert adhoc.find { |ah| ah[:team_id] == 2 && ah[:month] == "NOV" && ah[:tasks] == 0 && ah[:percentage] == 0 }
end
end
|
require 'rails_helper'
describe CouponsController do
before :each do
@request.env["devise-mapping"] = Devise.mappings[:user]
end
shared_examples_for "another user's coupon" do
before :each do
@user_other = create :user, :seller
@coupon = create_coupon(@user_other)
end
it "does not let the user update the coupon" do
put :update, id: @coupon.id, code: "aaaaa", discount: 20, status: false
@coupon.reload
expect( @coupon.code ).not_to eq "aaaaa"
expect( @coupon.discount ).not_to eq 20
expect( @coupon.status ).not_to eq false
end
it "does not let you destroy someone else's coupon" do
delete :destroy, id: @coupon.id
expect( @coupon.reload ).to eq @coupon
end
end
describe "as a non-seller" do
before :each do
@user = create :user
sign_in @user
end
it "does not allow you to create a coupon" do
post :create, code: "abcde", discount: 10, status: true
expect( @user.coupons.count ).to eq 0
end
it_behaves_like "another user's coupon"
end
describe "as a seller" do
before :each do
@user = create :user, :seller
sign_in @user
end
it "lets you create a coupon" do
post :create, code: "abcde", discount: 10
expect( @user.coupons.count ).to eq 1
expect( @user.coupons.first.code ).to eq "abcde"
expect( @user.coupons.first.discount ).to eq 10
expect( @user.coupons.first.status ).to eq true
end
describe "with an existing coupon" do
before :each do
@coupon = create_coupon
end
it "lets you edit a coupon" do
code = [('a'..'z')].sample(5).join
put :update, id: @coupon.id, code: code, discount: 20, status: false
@coupon.reload
expect( @coupon.code ).to eq code
expect( @coupon.discount ).to eq 20
expect( @coupon.status ).to eq false
end
it "lets you delete your coupon" do
delete :destroy, id: @coupon.id
expect { @coupon.reload }.to raise_exception ActiveRecord::RecordNotFound
end
end
it_behaves_like "another user's coupon"
end
def create_coupon(user = nil)
user ||= @user
create :coupon, user: user, status: true
end
end |
class WeatherLabelsController < ApplicationController
before_action :authenticate_user!
helper_method :weather_presets, :category, :secondary_category
def samples
@decided = PackageLabel.weather_guessed.sample(10)
@construction_tasks = PackageLabel.weather_guessed.count
end
def index
@labels = scope_filters(PackageLabel.weather_not_labeled).sample(5)
@labeled = PackageLabel.weather_labeled.count
@left = PackageLabel.weather_not_labeled.count
end
def labeled
@labels = PackageLabel.weather_labeled.order(:name_en.asc).skip((current_page - 1)*page_size).limit(page_size)
@pages = (PackageLabel.weather_labeled.count.to_f / page_size.to_f).ceil
end
def test_set
@labels = PackageLabel.weather_for_test.sample(10)
@labeled = PackageLabel.weather_test_set.count
end
def update
id = params[:id]
label_params = allowed_params
@label = PackageLabel.find(id)
@label.weather_label ||= WeatherLabel.new
@label.weather_label.labeled = true
respond_to do |format|
format.html do
if @label.update_attributes label_params
@label.weather_label.update_attributes! labeled: true
redirect_to redirect_path, flash: { success: 'Saved!' }
else
redirect_to redirect_path, flash: { danger: 'Something went wrong!' }
end
end
format.js do
if @label.update_attributes label_params
@old_id = @label.id
category_params = params[:package_label]
@label = scope_filters(PackageLabel.weather_not_labeled, category_params).sample.first
end
end
end
rescue Mongoid::Errors::DocumentNotFound => e
Rails.logger.error e.message
redirect_to redirect_path, flash: { danger: 'Not found!' }
end
def update_test_set
id = params[:id]
label_params = allowed_params
@label = PackageLabel.find(id)
@label.weather_label ||= WeatherLabel.new
if @label.update_attributes({ test_set: true }.merge(label_params))
@label.weather_label.update_attributes! labeled: true, test_set: true
redirect_to test_set_weather_labels_path, flash: { success: 'Saved!' }
else
redirect_to test_set_weather_labels_path, flash: { danger: 'Something went wrong!' }
end
rescue Mongoid::Errors::DocumentNotFound => e
Rails.logger.error e.message
redirect_to package_labels_path, flash: { danger: 'Not found!' }
end
def weather_presets
@presets ||= WeatherPreset.order(:name.asc).to_a
end
def category
@category
end
# @return [Category]
def secondary_category
@secondary_category
end
private
def allowed_params
params.require(:package_label).permit(weather_label_attributes: [:placement, :corrected, presets_code_names: []])
end
def redirect_path
puts params
case params[:package_label][:action]
when 'samples'
samples_weather_labels_path
when 'not_decided'
not_decided_weather_labels_path
when 'labeled'
page = params[:weather_label] && params[:weather_label][:page] ? params[:weather_label][:page].to_i : 1
labeled_weather_labels_path(page: page)
else
weather_labels_path
end
end
def scope_filters(scope, local_params=params)
unless local_params['category_id'].blank?
@category = Category.find(local_params[:category_id])
scope = scope.for_category(@category)
end
unless local_params['secondary_category_id'].blank?
@secondary_category = Category.find(local_params[:secondary_category_id])
scope = scope.for_secondary_category(@secondary_category)
end
scope
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "rt_gem_sample_1/version"
Gem::Specification.new do |s|
s.name = "rt_gem_sample_1"
s.version = RtGemSample1::VERSION
s.authors = ["Russ Grover"]
s.email = ["rgrover@redtailtechnology.com"]
s.homepage = "https://github.com/rgroverRT/rt_gem_sample_1"
s.summary = %q{trivial gem as a sample}
s.description = %q{has one method to call to see if gem config and installation is working; intended as an example only}
s.rubyforge_project = "rt_gem_sample_1"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
# specify any dependencies here; for example:
# s.add_development_dependency "rspec"
# s.add_runtime_dependency "rest-client"
end
|
class PortCall < ApplicationRecord
belongs_to :voyage
belongs_to :terminal
has_many :shifts, dependent: :destroy
end
|
require 'httparty'
require 'net/http/post/multipart'
require 'multi_json'
require 'lrucache'
module YACCL
module Services
class CMISRequestError < RuntimeError; end
module Internal
class BrowserBindingService
def initialize(service_url, basic_auth_username=nil, basic_auth_password=nil, succinct_properties=true)
@service_url = service_url
@basic_auth_username = basic_auth_username
@basic_auth_password = basic_auth_password
@succinct_properties = succinct_properties
@repository_urls = LRUCache.new(ttl: 3600)
@root_folder_urls = LRUCache.new(ttl: 3600)
end
def perform_request(required_params={}, optional_params={})
url = get_url(required_params.delete(:repositoryId), required_params[:objectId])
required_params[:succinct] ||= @succinct_properties
optional_params.reject! { |_, v| v.nil? }
params = transform_hash(required_params.merge(optional_params))
check(params)
response = if params.has_key?(:cmisaction)
if params.has_key?(:content)
Basement.multipart_post(url, params)
else
Basement.post(url, body: params)
end
else
Basement.get(url, query: params)
end
result = response.body
if response.content_type == 'application/json'
result = MultiJson.load(result, symbolize_keys: true)
if result.is_a?(Hash) && result.has_key?(:exception)
raise CMISRequestError, "#{result[:exception]} -- #{result[:message]}"
end
end
result
end
private
def get_url(repository_id, object_id)
if repository_id.nil?
@service_url
else
if object_id.nil?
if @repository_urls.fetch(repository_id).nil?
raise "No configuration found for <#{repository_id}>. Does repository exist?" unless Basement.get(@service_url)[repository_id]
repository_url = Basement.get(@service_url)[repository_id]['repositoryUrl']
@repository_urls.store(repository_id, repository_url)
end
return @repository_urls.fetch(repository_id)
else
if @root_folder_urls.fetch(repository_id).nil?
root_folder_url = Basement.get(@service_url)[repository_id]['rootFolderUrl']
@root_folder_urls.store(repository_id, root_folder_url)
end
return @root_folder_urls.fetch(repository_id)
end
end
end
def check(hash)
check_in(hash, :includeRelationships, [:none, :source, :target, :both])
end
def check_in(hash, key, arr)
value = hash[key]
unless value.nil?
unless arr.include?(value)
raise ArgumentError, "#{key} must be one of #{arr}."
end
end
end
def transform_hash(hash)
if hash.has_key?(:content)
content = hash.delete(:content)
hash[:content] = UploadIO.new(content[:stream],
content[:mime_type],
content[:filename])
end
if hash.has_key?(:properties)
props = hash.delete(:properties)
if props.is_a?(Hash)
props.each_with_index do |(id, value), index|
if value.is_a?(Time) || value.is_a?(DateTime)
value = (value.to_f * 1000).to_i
end
hash.merge!("propertyId[#{index}]" => id,
"propertyValue[#{index}]" => value)
end
end
end
hash
end
class Basement
include HTTParty
basic_auth @basic_auth_username, @basic_auth_password unless @basic_auth_username.nil?
def self.multipart_post(url, options)
url = URI.parse(url)
req = Net::HTTP::Post::Multipart.new(url.path, options)
req.basic_auth @basic_auth_username, @basic_auth_password unless @basic_auth_username.nil?
Net::HTTP.start(url.host, url.port) { |http| http.request(req) }
end
end
end
end
end
end
|
# frozen_string_literal: true
require_relative '../lib/img4'
namespace :img4 do
desc 'Extract any img4 files in the tmp directory'
task :extract do
Dir.glob(File.join(TMP_DIR, '**/*.im4p')).each do |path|
file = Img4File.new(path)
file.extract_payload
end
end
end
|
# This class holds parameters that may frequently change between test runs, e.g the test environment
module RuntimeConstants
$TEST_ENV = :test_1
CLOSE_BROWSER_AFTER_TEST = true # close the browser if the test passed?
FORCE_CLOSE_BROWSER_AFTER_TEST = false # always close the browser?
MAKE_ERROR_SCREENSHOTS = true
ERROR_SCREENSHOT_LOCATION = "screenshots"
WRITE_CI_REPORTS = false
BROWSER = :chrome
RESULTS_CSV = "results.csv"
end
|
class CreateDestinations < ActiveRecord::Migration
def change
create_table :destinations do |t|
t.string :country
t.string :destination_type
t.string :destination_name
t.string :image1
t.string :image2
t.string :image3
t.string :image4
t.timestamps
end
end
end
|
class Beer
attr_reader :id, :name, :brewer, :rating
def initialize args
@id = args[:id]
@name = args[:name]
@brewer = args[:brewer]
@rating = args[:rating]
end
def edit input
@name = input[:name]
@brewer = input[:brewer]
@rating = input[:rating]
end
def to_s
"##{@id} #{@name} - #{@brewer} (#{@rating} / 100)"
end
end
class List
attr_reader :beers
def initialize
@id = 0
@beers = []
populate
end
def add_beer input
@beers << Beer.new(input.merge(generate_id))
end
def delete_beer id
@beers.delete_if { |b| b.id == id }
end
def edit_beer input, id
b = find_beer id
fail "No beer matching id #{id}" unless b
b.edit input
end
def find_beer id
@beers.find { |b| b.id == id }
end
def sort_by_brewer!
@beers.sort_by! { |b| b.brewer }
end
def sort_by_id!
@beers.sort_by! { |b| b.id }
end
def sort_by_name!
@beers.sort_by! { |b| b.name }
end
def sort_by_rating!
@beers.sort_by! { |b| 100 - b.rating }
end
private
def generate_id
{ id: @id += 1 }
end
def populate
list = [
{ name: "Dortmunder Gold", brewer: "Great Lakes", rating: 95 },
{ name: "Fat Tire", brewer: "New Belgium", rating: 78 },
{ name: "Ohio Native Lager", brewer: "Sibling Revelry", rating: 83 },
{ name: "Inverness", brewer: "Columbus Brewing Company", rating: 72 },
{ name: "Black & Tan", brewer: "Yuengling", rating: 80 },
]
list.each { |b| add_beer(b) }
end
end
|
class CollectAllTradedCompaniesMetadataJob < ApplicationJob
queue_as :default
def perform(*args)
letters = ("A".."Z").to_a
letters.each do |letter|
# We perform the jobs synchronously instead of asynch to avoid contention
# issues over database connections
RetrieveCompanyMetadataJob.perform_now(letter)
end
logger.info "Finished collecting all traded companies metadata"
end
end
|
ActiveAdmin.register Image do
permit_params :position,
:image_group_id,
:propability,
:offer_id,
attachment_images_attributes: [:file, :_destroy, :id],
image_infos_attributes: [:name, :_destroy, :id]
filter :name
filter :image_group
filter :created_at
index do
column(:offer_id)
column(:id)
column(:image_group)
column(:views_count)
column(:propability) { |object| "#{object.propability} %" }
column(:position)
column(:images) do |object|
div class: 'flex' do
object.attachment_images.each.with_index(1) do |attachment, i|
div do
h3 "Image ##{i}"
para do
image_tag attachment.file.url, width: 100, height: 100
end
end
end
para
end
end
column(:texts) do |object|
div class: 'flex' do
object.image_infos.each.with_index(1) do |info, i|
div do
h3 "Text ##{i}"
para info.name
end
end
para
end
end
actions
end
show do
attributes_table do
row :position
para do
resource.attachment_images.each.with_index(1) do |attachment, i|
h3 "Image ##{i}"
para do
image_tag attachment.file.url, width: 100, height: 100
end
end
end
para do
resource.image_infos.each.with_index(1) do |info, i|
h3 "Name ##{i}"
para do
info.name
end
end
end
end
end
form do |f|
f.inputs do
f.input :position
f.input :propability
f.has_many :attachment_images, allow_destroy: true do |j|
j.input :file, as: :file
end
f.has_many :image_infos, allow_destroy: true do |j|
j.input :name, as: :string
end
f.input :image_group
f.input :offer_id
actions
end
end
end
|
require_relative 'linked_list'
require 'set'
# Write code to remove duplicates from an unsorted
# linked list.
# using a hash set
# O(n) time & space complexity
def remove_dups(linkedlist)
hash_set = Set.new
node = linkedlist.head.next
tail = linkedlist.tail
while node != tail
hash_set.add(node.data)
node = node.next
end
result = LinkedList.new
hash_set.each do |data|
result.append(data)
end
result
end
# O(n^2) time complexity
# O(1) space complexity
def remove_dups1(linkedlist)
tail = linkedlist.tail
p1 = linkedlist.head.next
p2 = p1.next
while p1 != tail
while p2 != tail
if p2.data == p1.data
p2_prev = p2.prev
linkedlist.remove(p2)
p2 = p2_prev.next
else
p2 = p2.next
end
end
p1 = p1.next
p2 = p1.next
end
linkedlist
end
linkedlist = LinkedList.new
linkedlist.append(3)
linkedlist.append(1)
linkedlist.append(2)
linkedlist.append(5)
linkedlist.append(1)
linkedlist.append(6)
linkedlist.append(3)
linkedlist.append(3)
puts linkedlist.to_s
res = remove_dups(linkedlist)
puts res.to_s
|
class OptionsGroup < ActiveRecord::Base
STYLES = {
'任选一种' => 0,
'允许多种组合' => 1
}
belongs_to :wesell_item, counter_cache: true
has_many :wesell_item_options, dependent: :destroy
accepts_nested_attributes_for :wesell_item_options, allow_destroy: true
validates_presence_of :name, :style
validates_uniqueness_of :name, scope: [:wesell_item_id]
after_save :check_wesell_item_options
def human_style
STYLES.key(style)
end
def check_wesell_item_options
if wesell_item_options.blank?
self.destroy
end
end
end
|
require 'spec_helper'
describe Kilomeasure::Measure do
describe '#defaults' do
it 'is an empty hash by default' do
expect(described_class.new.defaults).to eq({})
end
it 'has its keys symbolized' do
measure = described_class.new(defaults: { 'blah' => 1 })
expect(measure.defaults).to eq(blah: 1)
end
end
specify '#run_calculations calls BulkCalculationRunner' do
calculations_set = instance_double(Kilomeasure::CalculationsSet)
calculation_runner = instance_double(
Kilomeasure::BulkCalculationsRunner,
results: calculations_set)
formulas = Kilomeasure::FormulasCollection.new
measure = described_class.new(formulas: formulas)
allow(Kilomeasure::BulkCalculationsRunner)
.to receive(:new)
.and_return(calculation_runner)
expect(
measure.run_calculations(
inputs: { foo: 3 })
).to eq(calculations_set)
expect(calculation_runner).to have_received(:results)
expect(Kilomeasure::BulkCalculationsRunner)
.to have_received(:new)
.with(measure: measure,
formulas: formulas,
inputs: { foo: 3 })
end
specify 'fields returns a list of fields' do
measure = described_class.new(
inputs: [:field1, :field2, :field3])
expect(measure.inputs).to eq([:field1, :field2, :field3])
end
end
|
json.array! @users do |user|
json.id user.id
json.name user.name
json.user_name user.user_name
json.email user.email
json.comment user.comment
json.password_digest user.password_digest
json.create_at user.created_at
end |
# frozen_string_literal: true
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/LineLength
require_relative '../test_helper'
module Excon
# IntegrationTest
#
# Verifies the Excon connection consuming HyperMedia APIs.
#
class IntegrationTest < HyperMediaTest
def test_request
response = api.rel('product', expand: { uid: 'bicycle' }).get
assert response.body.include?('/product/bicycle')
end
def test_request_using_link_rel
response = api.resource._links.product.rel(expand: { uid: 'bicycle' }).get
assert response.body.include?('/product/bicycle')
end
def test_nested_request
bicycle = api.rel('product', expand: { uid: 'bicycle' }).get
response = bicycle.rel('handlebar').get
assert_equal data(:handlebar)['material'], response.resource.material
end
def test_collection_request
bicycle = api.rel('product', expand: { uid: 'bicycle' }).get
wheels = bicycle.rel('wheels')
responses = wheels.map(&:get)
assert Array, wheels.class
assert_equal data(:front_wheel)['position'], responses.first.resource.position
end
def test_expand_in_get
response = api.rel('product').get(expand: { uid: 'bicycle' })
assert response.body.include?('/product/bicycle')
end
def test_link
response = api.rel('product', expand: { uid: 'bicycle' }).get
assert_equal data(:bicycle)['_links']['handlebar']['href'], response.resource._links.handlebar.href
end
def test_link_collection
response = api.rel('product', expand: { uid: 'bicycle' }).get
assert_equal Array, response.resource._links.wheels.class
assert_equal data(:bicycle)['_links']['wheels'][0]['href'], response.resource._links.wheels.first.href
end
def test_nested_attributes
response = api.rel('product', expand: { uid: 'bicycle' }).get
assert_equal 7, response.resource.derailleurs.back
end
def test_invalid_attribute
response = api.rel('product', expand: { uid: 'bicycle' }).get
assert_equal 'Mountain Bike', response.resource['bike-type']
assert_equal false, response.resource.bmx
end
def test_embedded_resource
response = api.rel('product', expand: { uid: 'bicycle' }).get
assert_equal Excon::HyperMedia::ResourceObject, response.resource._embedded.pump.class
assert_equal '2kg', response.resource._embedded.pump.weight
end
def test_embedded_resource_collection
response = api.rel('product', expand: { uid: 'bicycle' }).get
assert_equal Array, response.resource._embedded.wheels.class
assert_equal data(:front_wheel)['position'], response.resource._embedded.wheels.first.position
end
def test_request_with_json_content_type
response = api_v2.rel('product', expand: { uid: 'bicycle' }).get
assert response.body.include?('/product/bicycle')
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'visit the plan efforts page and plan an effort' do
let(:user) { users(:third_user) }
let(:admin) { users(:admin_user) }
let(:course) { courses(:hardrock_ccw) }
scenario 'The user is a visitor' do
visit plan_effort_course_path(course)
fill_in 'hh:mm', with: '38:00'
click_button 'Create my plan'
verify_page_content
end
scenario 'The user is a user' do
login_as user, scope: :user
visit plan_effort_course_path(course)
fill_in 'hh:mm', with: '38:00'
click_button 'Create my plan'
verify_page_content
end
scenario 'The user is an admin' do
login_as admin, scope: :user
visit plan_effort_course_path(course)
fill_in 'hh:mm', with: '38:00'
click_button 'Create my plan'
verify_page_content
end
scenario 'The user enters a time outside the normal scope' do
visit plan_effort_course_path(course)
fill_in 'hh:mm', with: '18:00'
click_button 'Create my plan'
verify_content_present(course)
expect(page).to have_content('Insufficient data to create a plan.')
end
scenario 'The course has had no events held on it' do
course = create(:course)
visit plan_effort_course_path(course)
verify_content_present(course)
expect(page).to have_content('No events have been held on this course.')
end
def verify_page_content
verify_content_present(course)
course.splits.each { |split| verify_content_present(split, :base_name) }
end
end
|
module Sqlserver::Sequence
module Testing
module ModelMacros
def spawn_model(klass, &block)
Object.instance_eval { remove_const klass } if Object.const_defined?(klass)
Object.const_set klass, Class.new(ActiveRecord::Base)
Object.const_get(klass).class_eval(&block) if block_given?
@spawned_models << klass.to_sym
end
end
end
end
|
RSpec.describe NHLStats::Team do
it "should exist" do
expect NHLStats::Team
end
describe "#current_roster" do
it "should return an array of Players" do
VCR.use_cassette("team_roster") do
players = NHLStats::Team.find(20).current_roster
expect(players).to all(be_instance_of(NHLStats::Player))
end
end
context "when requested for an inactive team" do
it "should not raise an error" do
VCR.use_cassette("team_roster_inactive") do
expect { NHLStats::Team.find(32).current_roster }.to_not raise_error
end
end
it "should return nothing" do
VCR.use_cassette("team_roster_inactive") do
expect(NHLStats::Team.find(32).current_roster).to eq []
end
end
end
end
describe "#roster_for_season" do
it "should return an array of Players" do
VCR.use_cassette("team_roster_for_1989") do
players = NHLStats::Team.find(20).roster_for_season("19881989")
expect(players).to all(be_instance_of(NHLStats::Player))
end
end
it "should return the correct roster of Players" do
VCR.use_cassette("team_roster_for_1989") do
players = NHLStats::Team.find(20).roster_for_season("19881989")
expect(players.map(&:full_name)).to match_array([
"Al MacInnis", "Brad McCrimmon", "Brian Glynn", "Brian MacLellan",
"Colin Patterson", "Dana Murzyn", "David Reierson", "Doug Gilmour",
"Gary Roberts", "Gary Suter", "Hakan Loob", "Jamie Macoun",
"Jim Peplinski", "Jiri Hrdina", "Joe Aloi", "Joe Mullen",
"Joe Nieuwendyk", "Joel Otto", "Ken Sabourin", "Lanny McDonald",
"Mark Hunter", "Mike Vernon", "Paul Ranheim", "Perry Berezan",
"Ric Nattress", "Richard Chernomaz", "Rick Lessard", "Rick Wamsley",
"Rob Ramage", "Sergei Priakin", "Shane Churla", "Stu Grimson",
"Theo Fleury", "Tim Hunter"
])
end
end
context "when requested for a season with no roster" do
it "should not raise an error" do
VCR.use_cassette("team_roster_non-existant") do
expect { NHLStats::Team.find(54).roster_for_season("19881989") }.to_not raise_error
end
end
it "should return nothing" do
VCR.use_cassette("team_roster_non-existant") do
expect(NHLStats::Team.find(54).roster_for_season("19881989")).to eq []
end
end
end
end
describe ".find" do
it "should return a single team" do
VCR.use_cassette("single_team") do
team = NHLStats::Team.find(20)
expect(team).to be_instance_of(NHLStats::Team)
end
end
[
{ :field => :id, :value => 20 },
{ :field => :name, :value => "Calgary Flames" },
{ :field => :abbreviation, :value => "CGY" },
].each do |hash|
it "should return the correct value for #{hash[:field]}" do
VCR.use_cassette("single_team") do
team = NHLStats::Team.find(20)
expect(team.send(hash[:field])).to eq hash[:value]
end
end
end
end
describe ".list" do
it "should return an array of teams" do
VCR.use_cassette("list_teams") do
teams = NHLStats::Team.list
expect(teams).to all(be_instance_of(NHLStats::Team))
end
end
it "should accept filters for a limited team" do
VCR.use_cassette("list_teams_filtered") do
teams = NHLStats::Team.list(:active => true)
expect(teams.size).to eq 31
end
end
end
end
|
class Game::StartSingle
def self.call(user)
return user.create_single_game! if user.can_create_game?
raise Givdo::Exceptions::GamesQuotaExeeded
end
end
|
FactoryGirl.define do
factory :structure_change do
measure_selection { create(:measure_selection) }
structure_type
end
end
|
require 'cgi'
module JsClientBridge #:nodoc:
module Responses #:nodoc:
module Error
# Generates a error response. If the first parameter is a string is will be
# used as the _status options. It will also honour custom optionss as long
# they don't clash with the standard ones.
#
# @param <String> message
# An optional message.
# @param <Hash> options
# Custom optionss.
#
# @return <Hash>
# The response as a Hash
def respond_with_error(*args)
respond_with('error', args).first
end
# Generates a error response. If the first parameter is a string is will be
# used as the _status options. It will also honour custom optionss as long
# they don't clash with the standard ones.
#
# @param <String> message
# An optional message.
# @param <Hash> options
# Custom optionss.
#
# @return <Hash>
# The response as a String encoded JSON object.
def render_error(*args)
format_response(*respond_with('error', args))
end
end # module Error
end # module Responses
end # module JsClientBridge |
# Given an array, output true or false if elements in array are a palindrome
# NONRECURSIVE
def palindrome?(given_array)
# an array is a palindrome if it's length is zero or one
if given_array.length <= 1
true
end
if given_array.reverse == given_array
true
else
false
end
end
# to do: write nonrecursive method using no built in methods
# RECURSIVE
def recursive_palindrome?(given_array)
# base case - an array is a palindrome if it has a length of zero or one
if given_array.length <= 1
true
end
if given_array[0] == given_array[-1]
recursive_palindrome?(given_array[1..-2])
else
false
end
end
p palindrome?([1, 2, 3, 5, 3, 2, 1])
p palindrome?([2, 3, 5, 5, 3, 2])
p palindrome?([1, 2, 3, 6, 7])
p recursive_palindrome?([1, 2, 3, 5, 3, 2, 1])
p recursive_palindrome?([2, 3, 5, 5, 3, 2])
p recursive_palindrome?([1, 2, 3, 6, 7])
|
class Fyle < ActiveRecord::Base
# self.table_name = 'fyles'
has_one :text
CONTENT_TYPE=[["Plain Text",1], ["XML (TEI)",2], ["PDF (text)",3], ["HTML (text)",4]]
FILE_EXT=[["txt",1], ["xml",2], ["pdf",3], ["html",4]]
PLAIN_TEXT=1
XML_TEI_TEXT=2
PDF_TEXT=3
HTML_TEXT=4
@http_request_logger=nil
def log_request(log_params)
log_params[:caller] = self.to_yaml
Rails.logger.info "grrrr #{log_params}"
@http_request_logger = HttpRequestLogger.new(log_params)
@http_request_logger.save
end
def log_request_errors
@http_request_logger.errors
end
require 'do_http'
def URI
self.URL
end
def snarf
materialize()[1]
rescue
":no_text => '#{$!.message} #{$!.backtrace}'"
end
#
# returns an array with two elements
# 0: the local_file
# 1: the stripped contents
#
def write_binary(name, data)
# read in binary as well?
written = File.open(name, 'wb') do |io| # write ASCII-8BIT (i.e. binary?)
io.write(data)
end
Rails.logger.info "(i) w_b #{name} - bytes written - #{written}"
Rails.logger.info "(i) w_b - *data bytes length* - #{data.bytes.length}"
written
end
def read_binary(name)
contents = nil
File.open(name, 'rb') { |io| contents = io.read }
# how could it be anything other than ASCII_8BIT ?
Rails.logger.info "(i) r_b from #{name} contents enc #{contents.encoding}"
# huh? duh
# contents.force_encoding(Encoding::ASCII_8BIT)
# Rails.logger.info "(i) r_b force ascii contents enc #{contents.encoding}"
# how could it be anything other than UTF-8 ?
Rails.logger.info "(i) r_b model encoding #{self.encoding}"
# if !encoding.blank?
# contents.force_encoding(encoding) # don't encode, treat it as being already encoded
# a bit blunt, no?
# if !contents.valid_encoding?
# contents.scrub!
# end
# end
# force_encoding does not raise/throw an exception
# https://stackoverflow.com/questions/10200544/ruby-1-9-force-encoding-but-check
# if e.class == Encoding::UndefinedConversionError and e.message == '"\x92" from ASCII-8BIT to UTF-8'
contents
end
def materialize
if self.cache_file.blank?
raise 'Not cached!' # proper specific exception hierarchy
else
str = nil
contents = nil # IO.read(cache_file, "rb")
if self.local_file.blank? # or self.dirty?
if self.type_negotiation == ::Fyle::PDF_TEXT
# PDF's have encoding within 'em
tmp_file = Fyle::gen_tmp_name('pdftotext-', '.tmp')
cmd_str = "pdftotext -enc UTF-8 #{cache_file} #{tmp_file}"
Rails.logger.info "cmd_str #{cmd_str}"
res = %x(#{cmd_str})
Rails.logger.info "res #{res}"
Rails.logger.info " $? #{$?}"
str = read_binary(tmp_file)
str.force_encoding('UTF-8')
if !str.valid_encoding?
raise "PDF rendered text not valid UTF-8 after requesting it"
else
self.encoding = 'UTF-8'
self.save
end
else
# bit of a waste when the type negotiation is unknown...?
# must handle compressed files
contents = read_binary(self.cache_file) # is ASCII_8BIT from this
if !encoding.blank?
contents.force_encoding(self.encoding)
if !contents.valid_encoding?
if self.encoding == 'UTF-8' and (contents.bytes.select{|a|a==0x92}.length) > 0
# should make byte sequence checks more rigorous
Rails.logger.info "says it is UTF-8 but appears (maybe?) to be Windows-1252 cuz of 0x92"
self.encoding = 'Windows-1252'
contents.force_encoding(self.encoding)
self.save
else
# figure out other quirks
raise 'Invalid encoding!' # proper specific exception hierarchy
end
end
end
if self.type_negotiation == ::Fyle::PLAIN_TEXT
str = contents.dup
# <BASE HREF="http://classics.mit.edu/Aristotle/politics.mb.txt"><table border=1 width=100%><tr><td><table border=1 bgcolor=#ffffff cellpadding=10 cellspacing=0 width=100% color=#ffffff><tr><td><font face=arial,sans-serif color=black size=-1>This is <b><font color=#0039b6>G</font><font color=#c41200>o</font><font color=#f3c518>o</font><font color=#0039b6>g</font><font color=#30a72f>l</font><font color=#c41200>e</font></b>'s <a href="http://www.google.com/intl/en_extra/help/features.html#cached">cache</a> of <A HREF="http://classics.mit.edu/Aristotle/politics.mb.txt"><font color=blue>classics.mit.edu/Aristotle/politics.mb.txt</font></a>.<br>
# <b><font color=#0039b6>G</font><font color=#c41200>o</font><font color=#f3c518>o</font><font color=#0039b6>g</font><font color=#30a72f>l</font><font color=#c41200>e</font></b>'s cache is the snapshot that we took of the page as we crawled the web.<br>
# The page may have changed since that time. Click here for the <A HREF="http://classics.mit.edu/Aristotle/politics.mb.txt"><font color=blue>current page</font></a> without highlighting.</font><br><br><center><font size=-2 color=black><i>Google is not affiliated with the authors of this page nor responsible for its content.</i></font></center></td></tr></table></td></tr></table><hr>
# <html><body><pre>
str.slice!(/<BASE HREF.+<\/table><hr>/m)
tmp_file = Fyle::gen_tmp_name('plain-', '.tmp')
elsif self.type_negotiation == ::Fyle::HTML_TEXT
doc = Nokogiri::HTML(contents)
str = doc.xpath('//body').text
Rails.logger.info "str from Nokogiri and xpath is now encoded #{str.encoding}"
if self.encoding != str.encoding.name
Rails.logger.info 'HTML and model encoding differs from Nokogiri and xpath'
if !str.valid_encoding?
raise 'Really? That is so unfair'
else
self.encoding = str.encoding.name
self.save
end
end
s_beg=/#{Regexp.escape("var _gaq")}/
s_end=/#{Regexp.escape("})();")}/
r = /#{s_beg}.+#{s_end}/m
str.slice!(r)
# $('.dropdown-toggle').dropdown();
#
#
#
# (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
# (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
# m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
# })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
#
# ga('create', 'UA-40353515-1', 'stanford.edu');
# ga('send', 'pageview');
s_beg=/#{Regexp.escape("$('.dropdown-toggle'")}/
s_end=/#{Regexp.escape("'pageview');")}/
r = /#{s_beg}.+#{s_end}/m
str.slice!(r)
tmp_file = Fyle::gen_tmp_name('html-', '.tmp')
elsif self.type_negotiation == ::Fyle::XML_TEI_TEXT
# XML has to be UTF-8, if fyle has other encoding then wtf?
if self.encoding != 'UTF-8'
Rails.logger.info 'XML but not UTF-8, huh?..'
contents.force_encoding('UTF-8')
if !contents.valid_encoding?
raise "... and can't covert to UTF-8"
else
self.encoding = 'UTF-8'
self.save
end
else
Rails.logger.info 'XML and was set as UTF-8, and checks out as valid'
end
doc = Nokogiri::XML(contents)
str = doc.xpath('//body').text
if str.encoding != Encoding::UTF_8
raise "Really? That is so messed up #{str.encoding}"
end
tmp_file = Fyle::gen_tmp_name('xml-', '.tmp')
else # lame-o!
foo = "Unhandled content!"
Rails.logger.info "huh? (#{type_negotiation}) #{foo}"
raise foo
end
written = write_binary(tmp_file, str)
end
self.local_file = tmp_file
self.save
else
contents = read_binary(self.local_file)
str = contents.dup
# should always work, but just in case anybody has changed it on disk badly
# should checksum it :)
if !encoding.blank?
str.force_encoding(self.encoding)
if !str.valid_encoding?
raise 'File changed on disk badly?'
end
end
end
[self.local_file, str[strip_start..(strip_end*-1)]]
end
end
def handle_type(response, body)
Rails.logger.info "handling the ol' type"
Rails.logger.info "response[content-type]: #{response['content-type']}"
content_type = response['content-type']
# TODO handle charset
ret = ""
# text/plain; charset=utf-8
if content_type.starts_with?('text/plain')
# http://www.davidverhasselt.com/set-attributes-in-activerecord/
ret = ::Fyle::PLAIN_TEXT
elsif content_type.starts_with?('text/xml')
doc = Nokogiri::XML(body)
if doc.root.name.starts_with?('TEI')
ret = ::Fyle::XML_TEI_TEXT
else
# aaaargh
ret = "do not know how to random XML content: #{doc.root.name}"
end
elsif content_type.starts_with?('text/html')
ret = ::Fyle::HTML_TEXT
elsif content_type.starts_with?('application/pdf')
ret = ::Fyle::PDF_TEXT
else
ret = "do not know yet how to handle content type: #{response['content-type']}"
end
return ret
end
def divine_type
Rails.logger.info "Divining the ol' type"
WRAP_HTTP::do_http2(self) do |uri, request, response, body|
content_type = "" # just to be on the safe side?
content_type = handle_type(response, body)
case content_type
when ::Fyle::PLAIN_TEXT
# http://www.davidverhasselt.com/set-attributes-in-activerecord/
self[:handled] = true
self[:type_negotiation] = ::Fyle::PLAIN_TEXT
when ::Fyle::XML_TEI_TEXT
self[:type_negotiation] = ::Fyle::XML_TEI_TEXT
when ::Fyle::HTML_TEXT
self[:type_negotiation] = ::Fyle::HTML_TEXT
when ::Fyle::PDF_TEXT
self[:type_negotiation] = ::Fyle::PDF_TEXT
else
Rails.logger.error content_type
end
return content_type
end
end
def self.gen_tmp_name(name, ext)
base_name = File.basename(Tempfile.new([name, ext]).path)
rails_tmp = Rails.root.join('tmp')
rails_tmp.join(base_name).to_path
end
def gen_cache_name(ext)
name = what.gsub(' ','_')
_ext = ".#{ext}"
Fyle::gen_tmp_name(name, _ext)
end
# require 'text_filter'
def cache
# what does do_type return ? [uri, request, response] ?
cache_name = gen_cache_name(::Fyle::FILE_EXT[type_negotiation-1][0])
# we have type already... could have changed of course...
what_happened = WRAP_HTTP::do_http2(self) do |uri, request, response, body|
# t = TextFilter.new type_negotiation
Rails.logger.info "(i) cache #{cache_name}"
str = ''
Rails.logger.info "(i) cache response['content-type'] #{response['content-type']}"
Rails.logger.info "(i) cache before str enc #{str.encoding}"
/(.+);\s?charset=(.+)/ =~ response['content-type']
foo = $~
bar = nil
if !foo.nil?
bar = $~[2]
end
Rails.logger.info "(i) cache $~ #{foo.inspect}"
Rails.logger.info "(i) cache $~[2] #{bar.inspect}"
str = body # seems to be always ASCII-8BIT encoded
Rails.logger.info "(i) cache after = str enc #{str.encoding}"
Rails.logger.info "(i) cache body enc #{body.encoding}"
# str.force_encoding(bar)
str.force_encoding(Encoding::ASCII_8BIT)
Rails.logger.info "(i) cache force ascii str enc #{str.encoding}"
# if str.encoding != 'UTF-8'
# str = str.encode('UTF-8')
# end
written = write_binary(cache_name, str)
if written == str.bytes.length
self[:cache_file] = cache_name
if !bar.nil?
self[:encoding] = bar.upcase
end
self.save
return ''
else
return 'cache not fully written'
end
end
if what_happened.blank?
return true
else
Rails.logger.info "(i) cache #{what_happened}"
return false
end
end
def sanitize
Rails.logger.info "start #{strip_start.inspect}"
Rails.logger.info "end #{strip_end.inspect}"
if strip_start.blank? or strip_start < 0
self[:strip_start] = 0
end
if strip_end.blank? or strip_end <= 0
self[:strip_end] = 1
end
Rails.logger.info "start #{strip_start.inspect}"
Rails.logger.info "end #{strip_end.inspect}"
end
def local
# url_helpers does not recognise relative_url_root !
# see: app/controllers/application_controller.rb
# and: config/initializers/deploy_to_a_subdir.rb
Rails.application.routes.url_helpers.local_fyle_url(self)
end
def strip_url
# same as above
Rails.application.routes.url_helpers.strip_fyle_url(self)
end
def strip_path
# same as above
Rails.application.routes.url_helpers.strip_fyle_path(self)
end
# little bit sneakier than the rest
def plain_url
# same as above
Rails.application.routes.url_helpers.plain_fyle_url(id: self.id.to_s.rjust(3, "0"), format: 'txt')
end
# little bit sneakier than the rest
def plain_path
# same as above
Rails.application.routes.url_helpers.plain_fyle_path(id: self.id.to_s.rjust(3, "0"), format: 'txt')
end
# chunked! for your pleasure
def chunk_url(c)
Rails.application.routes.url_helpers.chunk_fyle_url(id: self.id.to_s.rjust(3, "0"), chunk: c, format: 'txt')
end
# chunked! for your pleasure
def chunk_path(c)
Rails.application.routes.url_helpers.chunk_fyle_path(id: self.id.to_s.rjust(3, "0"), chunk: c, format: 'txt')
end
# little bit sneakier than the rest
def self.snapshot_url(n, id)
# same as above
Rails.application.routes.url_helpers.snapshot_fyle_path(n: n, id: id.to_s.rjust(3, "0"), format: 'txt')
end
#
# --- Display Fns
#
def cached_in_English
# self.cache_file.blank? ? 'no' : self.cache_file
# self.cache_file.blank? ? 'no' : File.basename(self.cache_file)
self.cache_file.blank? ? 'no' : 'yes'
end
def localed_in_English
self.local_file.blank? ? 'no' : 'yes'
end
def type_in_English
type_negotiation.blank? ? "undefined" : ::Fyle::CONTENT_TYPE[type_negotiation-1][0]
end
def display_cached
cached_in_English
end
def display_localed
localed_in_English
end
def display_type
type_in_English
end
def display_what
what
end
def display_strip_start
type_negotiation == ::Fyle::PLAIN_TEXT ? strip_start : '_'
end
def display_strip_end
type_negotiation == ::Fyle::PLAIN_TEXT ? strip_end : '_'
end
def display_URL
(self.URL.length>50) ? ((self.URL[0..49])+"…") : self.URL
end
def self.linked
Fyle.where(id: Text.select(:fyle_id).where("fyle_id IS NOT NULL").map(&:fyle_id))
end
def self.unlinked
Fyle.where.not(id: Text.select(:fyle_id).where("fyle_id IS NOT NULL").map(&:fyle_id))
end
end
|
##
# 나머지가 1이 되는 수 찾기
# 문제 설명
# 자연수 n이 매개변수로 주어집니다. n을 x로 나눈 나머지가 1이 되도록 하는 가장 작은 자연수 x를 return 하도록 solution 함수를 완성해주세요. 답이 항상 존재함은 증명될 수 있습니다.
#
# 제한사항
# 3 ≤ n ≤ 1,000,000
# 입출력 예
# n result
# 10 3
# 12 11
# 입출력 예 설명
# 입출력 예 #1
#
# 10을 3으로 나눈 나머지가 1이고, 3보다 작은 자연수 중에서 문제의 조건을 만족하는 수가 없으므로, 3을 return 해야 합니다.
# 입출력 예 #2
#
# 12를 11로 나눈 나머지가 1이고, 11보다 작은 자연수 중에서 문제의 조건을 만족하는 수가 없으므로, 11을 return 해야 합니다.
def solution(n)
(2..(n-1)).each do |i|
p [i, n%i]
return i if n % i == 1
end
return n
end
puts solution(3)
|
require 'spec_helper'
describe Product do
describe "#set_categories" do
context "When adding categories to a product" do
let!(:product) { Fabricate(:product) }
let!(:category) { Fabricate(:category) }
let!(:category2) { Fabricate(:category) }
it "sets a category" do
product.categories.length.should == 0
product.set_categories([category.id])
product.categories.length.should == 1
product.categories.include?(category).should == true
end
it "sets unique categories" do
product.set_categories([category.id, category.id])
product.categories.length.should == 1
end
it "sets multiple categories" do
product.set_categories([category.id, category2.id])
product.categories.length.should == 2
product.categories.include?(category).should == true
product.categories.include?(category2).should == true
end
end
end
describe "#price" do
context "when price is 50 cents" do
it "stores price of 50 cents" do
product = Product.new(:title => "Foo", :description => "", :price => ".50")
product.price.should == Money.new(50, "USD")
end
end
context "When price is an empty string" do
it "stores price as 0.00" do
product = Product.new(:title => "Foo", :description => "", :price => "")
product.price.should == Money.new(0, "USD")
end
end
context "When price is $1000" do
it "stores price as 1000.00" do
product = Product.new(:title => "Foo", :description => "", :price => "1000")
product.price.should == Money.new(100000, "USD")
end
end
context "When price is $10.65" do
it "stores price as 10.65" do
product = Product.new(:title => "Foo", :description => "", :price => "10.65")
product.price.should == Money.new(1065, "USD")
end
end
context "When price is $10.0" do
it "stores price as 10.00"
# product = Product.new(:title => "Foo", :description => "", :price => "10.0")
# product.price.should == Money.new(1000, "USD")
# end
end
end
describe "#display_retired" do
context "when retired" do
let!(:product) { Fabricate(:product, :retired => true) }
it "returns Retired" do
product.display_retired.should == "Retired"
end
end
context "when not retired" do
let!(:product) { Fabricate(:product, :retired => false) }
it "returns Active" do
product.display_retired.should == "Active"
end
end
end
context "validations" do
it "doesn't store empty title" do
lambda{ Fabricate(:product, :title => "") }.should raise_error
end
it "doesn't store empty description" do
lambda{ Fabricate(:product, :description => "") }.should raise_error
end
it "doesn't store empty price" do
lambda{ Fabricate(:product, :price => nil) }.should raise_error
end
it "stores unique products by name" do
Fabricate(:product, :title => "Foo")
lambda{ Fabricate(:product, :title => "Foo") }.should raise_error
end
it "stores positive prices" do
lambda{ Fabricate(:product, :price => "-5") }.should raise_error
end
it "stores prices greater than 0" do
lambda{ Fabricate(:product, :price => "0") }.should raise_error
end
end
end
|
class MicropostsController < ApplicationController
before_filter :authenticate, :only => [:create, :destroy]
before_filter :authorized_user, :only => :destroy
def index
@feed_items = current_user.feed.paginate(:page => params[:page])
end
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
@create_time = "Post created: ", @micropost.created_at
flash[:notice] = @create_time
redirect_to root_path
else
@feed_item = []
flash[:error] = "Oops, looks like something went wrong.."
render 'pages/home'
end
end
def destroy
@micropost.destroy
redirect_to root_path
flash[:succes] = "Post destroyed"
end
private
def authorized_user
@micropost = current_user.microposts.find_by_id(params[:id])
redirect_to root_path if @micropost.nil?
end
end
|
module Engine
module Game
class GameState
attr_reader :game_maps
attr_accessor :current_map, :character
def initialize(game_maps, character)
@character = character
@game_maps = game_maps
@current_map = game_maps.detect { |o| o.is_main }.map_id
end
# Returns current GameMap
def get_current_map
@game_maps.detect { |map| map.map_id == @current_map }
end
def render_map
get_current_map.draw(@character.x, @character.y)
end
def render_char
@character.draw
end
end
end
end |
module Shopware
module API
class Client
module Categories
def get_categories
response = self.class.get '/categories'
response['data']
end
def get_category(id)
response = self.class.get "/categories/#{id}"
response['data']
end
def find_category_by_name(name)
filter = "filter[0][property]=name&filter[0][expression]=%3D&filter[0][value]=#{name}"
response = self.class.get '/categories', { query: filter }
response['data'].empty? ? nil : response['data'].first
end
def create_category(properties)
response = self.class.post '/categories', body: properties
response['data']
end
def update_category(id, properties)
response = self.class.put "/categories/#{id}", body: properties
response['data']
end
def delete_category(id)
self.class.delete "/categories/#{id}"
end
end
end
end
end |
module Yabeda
module GraphQL
class Instrumentation
def before_query(query)
reset_cache!(query)
end
def after_query(query)
cache(query).each do |_path, options|
Yabeda.graphql.field_resolve_runtime.measure(options[:tags], options[:duration])
Yabeda.graphql.fields_request_count.increment(options[:tags])
end
end
private
def cache(query)
query.context.namespace(Yabeda::GraphQL)[:field_call_cache]
end
def reset_cache!(query)
query.context.namespace(Yabeda::GraphQL)[:field_call_cache] =
Hash.new { |h,k| h[k] = { tags: {}, duration: 0.0 } }
end
end
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string not null
# provider :string not null
# uid :string not null
# first_name :string not null
# last_name :string not null
# oauth_token :string not null
# oauth_expires_at :datetime not null
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
has_many :items, inverse_of: :consultant
has_many :sales, through: :items, source: :sales
has_many :customers, through: :sales
has_many(
:created_customers,
class_name: 'Customer',
foreign_key: :consultant_id
)
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.email = auth[:email]
user.provider = auth[:provider]
user.uid = auth[:uid]
user.first_name = auth[:first_name]
user.last_name = auth[:last_name]
user.oauth_token = auth[:oauth_token]
user.oauth_expires_at = auth[:oauth_expires_at]
user.save!
end
end
def name
"#{ first_name } #{ last_name }"
end
end
|
require 'board'
require 'player/human'
describe Board do
before do
@board = Board.new
@board.stub(:puts)
end
it "should have no move history" do
@board.move_history.should have(0).items
end
it "should have nine free positions" do
@board.free_positions.should have(9).items
end
it "should be able to mark a position with a marker" do
move_position = 0
@board.mark move_position, "x"
@board.free_positions.should have(8).items
@board.move_history.should have(1).item
@board.move_history.should include move_position
end
it "should know which mark goes next" do
@board.next_marker.should == "o"
end
it "should stop not allow same two marks in a row" do
@board.mark 0, "x"
lambda { @board.mark 1, "x" }.should raise_error
end
it "should know when the game is over because of a draw" do
@board.mark 0, "x"
@board.mark 1, "o"
@board.mark 2, "x"
@board.mark 4, "o"
@board.mark 3, "x"
@board.mark 6, "o"
@board.mark 5, "x"
@board.mark 8, "o"
@board.mark 7, "x"
@board.gameover?.should be_true
@board.winner.should be_nil
end
it "should know when the game is over because someone wins" do
@board.mark 0, "x"
@board.mark 3, "o"
@board.mark 1, "x"
@board.mark 5, "o"
@board.mark 2, "x"
@board.gameover?.should be_true
@board.winner.should == "x"
end
it "should know how to undo the last mark" do
@board.mark 0, "x"
@board.mark 3, "o"
@board.mark 1, "x"
@board.mark 5, "o"
@board.undo_last_mark!
previous_position = @board.move_history.last
previous_position.should == 1
@board[previous_position].should == "x"
end
it "should only allow marking a blank spot" do
@board.mark 0, "x"
@board.mark 3, "o"
@board.mark 1, "x"
@board.mark 5, "o"
lambda { @board.mark 5, "x" }.should raise_error
end
end |
class RoomAminity < ApplicationRecord
belongs_to :room
belongs_to :aminity
end
|
class RenameEventpicFilename < ActiveRecord::Migration[5.2]
def change
rename_column :events, :eventpic_filename, :eventpic
end
end
|
class Node
attr_accessor :value, :next
def initialize(value)
@value = value
@next = nil
end
end
class LinkedList
attr_accessor :head
def initialize(node = nil)
@head = node
end
def add(node)
#add a new node to the list
current_node = @head
while current_node.next
current_node = current_node.next
end
current_node.next = node
end
def print
#prints the entire list
current_node = @head
puts 'Node Value: ' + current_node.value.to_s
puts 'Next Node: ' + current_node.next.to_s
while current_node.next
current_node = current_node.next
puts 'Node Value: ' + current_node.value.to_s
puts 'Next Node: ' + current_node.next.to_s
end
end
def pop
current_node = @head
while current_node.next
previous_node = current_node
current_node = current_node.next
end
previous_node.next = nil
end
def splice(num)
current_node = @head
previous_node = current_node
if num == 1
@head = current_node.next
else
(num-1).times {
previous_node = current_node
current_node = current_node.next
}
previous_node.next = current_node.next
end
end
end
first = Node.new(1)
second = Node.new(2)
third = Node.new(3)
fourth = Node.new(4)
fifth = Node.new(5)
list = LinkedList.new(first)
list.add(second)
list.add(third)
list.add(fourth)
list.add(fifth)
list.print
puts "==================================="
list.splice(5)
list.print |
require 'test_helper'
require 'net/http'
require 'net/https'
require 'uri'
class GravatarifySubdomainTest < Test::Unit::TestCase
include Gravatarify::Base
def setup; reset_gravatarify! end
context "#subdomain(str)" do
should "return consistent subdomain for each and every run (uses Zlib.crc32 and not String#hash)" do
Gravatarify.subdomains = %w{a b c d e f g}
assert_equal "a.", Gravatarify.subdomain("c") # => 112844655 % 7 = 0
assert_equal "b.", Gravatarify.subdomain("asdf") # => 1361703869 % 7 = 1
assert_equal "c.", Gravatarify.subdomain("some string") # => 4182587481 % 7 = 2
assert_equal "d.", Gravatarify.subdomain("info@initech.com") # => 3555211446 % 7 = 3
assert_equal "e.", Gravatarify.subdomain("a") # => 3904355907 % 7 = 4
assert_equal "f.", Gravatarify.subdomain("support@initech.com") # => 3650283369 % 7 = 5
assert_equal "g.", Gravatarify.subdomain("didum") # => 3257626035 % 7 = 6
end
end
context "changing hosts through Gravatarify#subdomains" do
should "override default subdomains (useful to e.g. switch back to 'www' only)" do
Gravatarify.subdomains = %w{a b c d e f g}
assert_equal "http://d.gravatar.com/avatar/4979dd9653e759c78a81d4997f56bae2.jpg", gravatar_url('info@initech.com')
assert_equal "http://c.gravatar.com/avatar/d4489907918035d0bc6ff3f6c76e760d.jpg", gravatar_url('support@initech.com')
end
should "take in a string only argument, like www" do
Gravatarify.subdomains = 'www'
assert_equal "http://www.gravatar.com/avatar/4979dd9653e759c78a81d4997f56bae2.jpg", gravatar_url('info@initech.com')
assert_equal "http://www.gravatar.com/avatar/d4489907918035d0bc6ff3f6c76e760d.jpg", gravatar_url('support@initech.com')
end
should "still work as expected if passed in `nil` and return urls without subdomain (default)" do
Gravatarify.subdomains = []
assert_equal "http://gravatar.com/avatar/4979dd9653e759c78a81d4997f56bae2.jpg", gravatar_url('info@initech.com')
assert_equal "http://gravatar.com/avatar/d4489907918035d0bc6ff3f6c76e760d.jpg", gravatar_url('support@initech.com')
end
end
context "with Net::HTTP the gravatar.com subdomains" do
%w{ 0 1 2 3 www secure }.each do |subdomain|
should "respond to http://#{subdomain}.gravatar.com/" do
response = Net::HTTP.get_response URI.parse("http://#{subdomain}.gravatar.com/avatar/4979dd9653e759c78a81d4997f56bae2.jpg")
assert_equal 200, response.code.to_i
assert_equal "image/jpeg", response.content_type
end
should "respond to https://#{subdomain}.gravatar.com/ urls as well" do
http = Net::HTTP.new("#{subdomain}.gravatar.com", 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
response = http.get '/avatar/4979dd9653e759c78a81d4997f56bae2.jpg'
assert_equal 200, response.code.to_i
assert_equal "image/jpeg", response.content_type
end
end
should "not respond to 4.gravatar.com, if so add to subdomains dude!!!" do
assert_raises(SocketError) { Net::HTTP.get_response URI.parse('http://4.gravatar.com/avatar/4979dd9653e759c78a81d4997f56bae2.jpg') }
end
end
end
|
class CreateAttendees < ActiveRecord::Migration
def change
create_table :attendees do |t|
t.integer :schedule_id
t.integer :test_group_id
t.integer :user_id
t.string :remember_token
t.boolean :finish
t.timestamps
end
add_index :attendees, :schedule_id
add_index :attendees, :user_id
add_index :attendees, :remember_token
end
end |
class V1::StoriesController < V1::ApplicationController
def index
tasks = Task.all.uniq
result = tasks.where.not(:project_id => 100000).map do |t|
{
:project_id => t.project.pivotal_id,
:estimate => t.estimate,
:title => t.title,
:days_worked => days_worked(t),
:owner_id => t.user.pivotal_owner_id
}
end
render(
:json => {
:stories => result
}
)
end
private
def days_worked task
Task.where(:title => task.title, :current => true).count
end
end
|
require "rails_helper"
describe EnqueueTweetFetchJob::JobRunner do
describe ".execute!" do
subject { enqueue_tweet_fetch_job_job_runner.execute! }
let!(:enqueue_tweet_fetch_job_job_runner) { EnqueueTweetFetchJob::JobRunner.new }
let!(:frozen_now) { Time.zone.parse("2019/11/01 20:00:00") }
let!(:task_tweet_fetcher_double) { double(:task_tweet_fetcher) }
context "with featured event" do
let!(:event) { create(:event, start_at: Time.zone.parse("2019/11/01 19:00:00"), end_at: Time.zone.parse("2019/11/01 23:00:00"))}
it "enqueues TweetFetchJob" do
travel_to frozen_now do
subject
expect(TweetFetchJob).to(
have_been_enqueued.with(event)
)
end
end
end
context "without featured event" do
let!(:event) { create(:event, start_at: Time.zone.parse("2019/12/01 19:00:00"), end_at: Time.zone.parse("2019/12/01 23:00:00"))}
it "enqueues TweetFetchJob" do
travel_to frozen_now do
subject
expect(TweetFetchJob).not_to(
have_been_enqueued.with(event)
)
end
end
end
end
end
|
require 'support/scenarios/github'
require 'support/scenarios/payload'
require 'support/scenarios/scenario'
module Scenarios
class << self
def included(base)
base.send(:extend, ClassMethods)
base.before { allow(model(:ssl_key)).to receive(:create).and_return(nil) }
end
def scenarios
@scenarios ||= {}
end
end
module ClassMethods
def scenario(name, &block)
Scenarios.scenarios[name] = Scenario.new(&block)
end
end
attr_reader :scenario
def scenario!(name, options = {})
@scenario = Scenarios.scenarios[name]
# (options[:create_users] || []).each do |login|
# scenario.create_user(login)
# end
WebMock::StubRegistry.instance.request_stubs.clear
scenario.setup(self)
scenario.stub_github
end
def sync_user(*users)
users.each do |user|
Travis::GithubSync::Services::SyncUser::Repos.new(user.id).run
end
end
def verify(data)
data.each do |key, value|
expect(value).to send(:"be_#{key}")
end
end
end
|
# frozen_string_literal: true
class UserPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin?
scope.all
else
scope.where(id: user)
end
end
end
def permitted_attributes
permitted = %i(first_name last_name contact_number email
password password_confirmation mail_handle)
permitted.concat([:role]) if user.admin?
permitted
end
def new?
user.admin?
end
def create?
user.admin?
end
def show?
self_or_admin?
end
def destroy?
self_or_admin?
end
def update?
self_or_admin?
end
def self_or_admin?
record.id == user.id || user.admin?
end
end
|
class User < ActiveRecord::Base
# edit the User model to include the following associations
# 'has_many :visits'
# 'has_many :visited_locations, through: :visits, source: 'location''
# we want to be able to type '@user.visited_locations', which is we have to provide the additional options to the 'has_many :through' association
has_many :visits
has_many :visited_locations, through: :visits, source: 'location'
# edit the User model to read 'has_many :owned_locations, class_name: 'Location''
# we want to be able to say '@user.owned_locations', so make sure to specify the appropriate options here
has_many :owned_locations, class_name: 'Location', foreign_key: 'location_id'
# 'has_many :participates'
# 'has_many :participating_events, through: :participates, source: 'event''
# we want to be able to type '@user.participating_events', which is we have to provide the additional options to the 'has_many :through' association
has_many :participates
has_many :participating_events, through: :participates, source: 'event'
# edit the User model to read 'has_many :owned_events, class_name: 'Event''
# we want to be able to say '@user.owned_events', so make sure to specify the appropriate options here
has_many :owned_events, class_name: 'Event', foreign_key: 'event_id'
end |
class AddShortUrlIndex < ActiveRecord::Migration[5.1]
def change
add_index :short_urls, :short_url
end
end
|
class ChangePollsTypeColumn < ActiveRecord::Migration
def up
rename_column :polls, :type, :poll_type
end
def down
rename_column :polls, :poll_type, :type
end
end
|
class Idea < ApplicationRecord
validates(:name, { presence: true })
has_many :comments
end |
Rails.application.routes.draw do
resources :dresses
get 'welcome/index'
# The very first page when loading the app
root 'welcome#index'
devise_for :users, controllers: { registrations: "users/registrations", omniauth_callbacks: "users/omniauth_callbacks" }
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
require 'spec_helper'
describe Spree::PropertyCategory do
it { should have_many(:product_properties) }
it { should have_many(:product_property_categories) }
it { should validate_presence_of(:name) }
describe ".for_products" do
let!(:product) { create :product }
let!(:product_property) { create :product_property, product: product }
let!(:property_category) { create :property_category }
let!(:other_category) { create :property_category }
before do
product_property.property_category = property_category
product_property.save!
end
subject { described_class.for_products([product]) }
it "returns only the categories tied to the products indicated" do
expect(subject.to_a).to eql([property_category])
end
end
end
|
class Section < ActiveRecord::Base
include Concerns::SafeJson
REGEX = /([A-Z]{1,5})(?: EVE \()?[\s]?([0-9]{0,2})[:\.]?([0-9]{0,2})-?([0-9]{0,2})[:\.]?([0-9]{0,2}) ?([A-Z]{2})?\)?/
BASE_TIME = Time.new 0, 1, 1
class InvalidSection < ActiveRecord::ActiveRecordError; end;
belongs_to :mit_class
belongs_to :location
has_and_belongs_to_many :times, class_name: 'MitTime'
validates :number, presence: true, uniqueness: { scope: [:mit_class] }
enum size: [:lecture, :recitation, :lab]
delegate :semester, :course, to: :mit_class
def populate!(raw = nil)
raw ||= raw_data
case raw['type']
when 'RecitationSession'
recitation!
when 'LectureSession'
lecture!
when 'LabSession'
lab!
else
raise InvalidSection, raw['type']
end
time, place = raw['timeAndPlace'].split(' ')
if !time.include?('*') && !time.upcase.include?('TBD') && (match = REGEX.match time).present?
match[1].split('').each do |day|
next unless day = MitTime.char_to_day(day)
pm = match[6] == 'PM' || match[2].to_i <= 5
start_hour = pm ? match[2].to_i + 12 : match[2]
start = BASE_TIME.change hour: start_hour, min: match[3]
end_hour = match[4].present? ? (pm ? match[4].to_i + 12 : match[4]) : start.hour + 1
finish = BASE_TIME.change hour: end_hour, min: match[5]
times << MitTime.where(day: day, start: start, finish: finish).first_or_create!
end
end
self.location = Location.where(number: place).first_or_create!
save!
end
def conflicts?(other_sections)
conflicts_with_sections? Array.wrap(other_sections)
end
def as_json(opts = {})
super opts.reverse_merge(methods: [:location, :times])
end
private
def conflicts_with_sections?(other_sections)
other_sections.reject { |os| conflicts_with_section? os }.empty?
end
def conflicts_with_section?(other_section)
times.each do |time|
return false unless time.conflicts?(other_section.times)
end
true
end
def raw_data
HTTP::Coursews.new(semester, course).section(number)
end
end
|
class ContractsController < ApplicationController
def new
@contract = Contract.new
end
def create
@contract = Contract.new(contract_params)
@contract.save
redirect_to @contract
end
def show
@contract = Contract.find(params[:id])
end
private
def contract_params
params.require(:contract).permit(:customer, :equipment, :acquisition_price,
:delivery_address, :responsable, :cpf,
:rental_period, :initial_date, :amount,
:discount)
end
end
|
class SupplierPurchaseDecorator < Decorator
def supplier_name
@supplier_name ||= first_supplier_name
end
def ordered_from_supplier_at
if self.ordered_at.nil?
str = content_tag :i do
link_to "Please Fill Up", edit_supplier_purchase_path(decorated_object)
end
else
str = self.ordered_at.to_date.to_s(:long)
end
str
end
def client
@client ||= first_client
end
# FIXME : make me deal with non local currency amounts
def display_total_amount
@display_total_amount ||= if !supplier_orders.empty?
number_to_currency(supplier_orders.map(&:offer_total_buying_price).sum || 0, unit: Currency::LOCAL_CURRENCY) + total_amount_suffix
else
number_to_currency(0, unit: Currency::LOCAL_CURRENCY) + total_amount_suffix
end
end
def client_name
client.name if client
end
def offer
@offer ||= OfferDecorator.new(__getobj__.offer)
end
def supplier_orders
@supplier_orders ||= SupplierOrderDecorator.decorate_collection(__getobj__.supplier_orders)
end
private
def first_supplier_name
if !supplier_orders.empty?
supplier_orders.first.supplier_name
end
end
def first_client
if !supplier_orders.empty?
supplier_orders.first.offer.client
end
end
def total_amount_suffix
@total_amount_suffix ||= if supplier_orders.first
str = [supplier_orders.first.offer_price_vat_status, self.supplier_orders.first.offer_price_basis].compact.join(" ")
if !str.blank?
str ="(#{str})"
end
str
end
end
end
|
require 'open3'
module EasyExtensions
module Tests
class RakeTestParser
attr_reader :rakes
def initialize(rakes=[], parser = nil)
@rakes = rakes.collect{|rake| RakeRunner.new(rake, parser) }
@all_done = false
end
def add_rake(rake, parser=nil)
@rakes << RakeRunner.new(rake, parser)
@all_done = false
true
end
def run_all
@rakes.each do |rake|
unless rake.done?
puts 'Running rake ' + rake.rake + ' at ' + Time.now.strftime('%F %H:%M')
rake.run
puts 'Done.'
end
end
@all_done = true
end
def report
ensure_parsed
@rakes.collect{|rake| rake.result.to_s }
end
def get_results
ensure_parsed
@rakes.collect{|rake| rake.result }
end
private
def ensure_parsed
raise StandardError.new('Not parsed! call run_all first') unless @all_done
end
end
class RakeRunner
attr_reader :result, :rake
def done?
@done
end
def initialize(rake, parser=nil)
@rake = rake
@parser = parser
@done = false
end
def run
buffer = []
stdout_str, stderr_str, status = Open3::capture3('rake ' +@rake)
stdout_str.split("\n").each do |line|
buffer << line
end
empty = !buffer.any?
stderr_str.split("\n").each do |line|
buffer << line if empty
$stderr.puts line
end
buffer.each{|line| line.strip! }
@result = EasyExtensions::Tests::ParsedTestResult.new(@rake, buffer, @parser)
@done = true
@result
end
end
class ParsedTestResult
class NotYetParsedError < StandardError
end
PARSERS = {
'standard' => 'EasyExtensions::Tests::StandartRailsTestParser',
'rspec_json' => 'EasyExtensions::Tests::JsonRspecTestParser'
}
attr_reader :rake, :parsed
[:failured, :failure_abbr, :time_result, :text_result].each do |method|
src = <<-END_SRC
def #{method}
raise NotYetParsedError('Result is not parsed!') unless parsed?
@output_parser.#{method}
end
END_SRC
self.class_eval(src, __FILE__, __LINE__)
end
def parsed?
!!@parsed
end
def initialize(rake, output=[], parser = nil)
@rake, @output, @parsed = rake, output, false
@parser = parser
parse_output
end
def all_ok?
@parsed && @output_parser.failured.size == 0
end
def to_s
s = "#{rake} run, time info: #{@output_parser.time_result} and reported #{@output_parser.text_result}"
unless all_ok?
s << " errors:\n" + @output_parser.failured.collect{|fail| fail.to_s }.join("\n")
end
s
end
private
def parse_output
@output_parser = instantialize_parser
@parsed = @output_parser.parse
end
def instantialize_parser
parser = begin PARSERS[@parser||'standard'].constantize rescue StandartRailsTestParser end
return parser.new(@output)
end
end
class AbstractTestOutputParser
attr_reader :failured, :failure_abbr, :time_result, :text_result
class AbstractParsedFailure
attr_reader :type, :test_name, :test_set, :file, :file_line
def initialize(type)
@type = type
@initialized = false
@additional_info ||= []
@time_result ||= ''
@info ||= ''
end
def heading
s = "Test #{test_name} in test set #{test_set} "
unless error?
s << "in test file #{file} on line #{file_line} has failed!"
else
s << 'raised an error!'
end
s
end
def main_info
@info
end
def info(join="\n")
([main_info]+@additional_info).join(join)
end
def to_s
heading + info
end
def error?
type == 'Error'
end
end #AbstractParsedFailure
def initialize(output=[])
@output = output
@failured = []
@failure_abbr, @time_result, @text_result = '', '', ''
end
def parse
raise NotImplementedError, 'child responsibility'
end
end
class StandartRailsTestParser < AbstractTestOutputParser
class ParsedFilure < AbstractTestOutputParser::AbstractParsedFailure
# adds a line of output to this failure
def <<(line)
if !@initialized && m = line.match(init_regex)
@test_name = m[1]
@test_set = m[2]
#if error theese are nil
@file = m[3]
@file_line = m[4]
@initialized = true
return
end
return unless @initialized
unless @info
@info = line
else
@additional_info << line
end
end
private
def init_regex
if error?
/^(\S+)\((\S+)\).*$/
else
/^(\S+)\((\S+)\)\s\[([^:]*):(\d+)\].*$/
end
end
end #ParsedFailure
def parse
return false if !@output.is_a?(Array)
idx = -1
while idx < @output.count && ( @failure_abbr.blank? || @time_result.blank? )
idx += 1
# should match time result too, but what if it will change?...
if @output[idx] =~ /^[F.*]+$/
@failure_abbr = @output[idx]
idx += 2
@time_result = @output[idx]
end
end
return false if @failure_abbr.blank? || @time_result.blank?
while idx < @output.size
idx += 1
line = @output[idx]
if line =~ /^\s*$/
actual_failure = nil
next
end
if line =~ /^\s*\d+\)\s*(\w+):/
actual_failure = ParsedFilure.new($1)
failured << actual_failure
end
next unless actual_failure
actual_failure << line
end
@text_result = @output.last
if @text_result =~ /^ruby/
@text_result = @output[-3]
end
return true
end
end # StandartRailsTestParser
class JsonRspecTestParser < AbstractTestOutputParser
class ParsedFilure < AbstractTestOutputParser::AbstractParsedFailure
def initialize(example_hash)
@test_name = example_hash['full_description']
@test_set = example_hash['full_description'].split(/\s/).first
#if error theese are nil
@file = example_hash['file_path']
@file_line = example_hash['line_number']
@info = example_hash['exception']['message'] if example_hash['exception']
@additional_info = example_hash['exception']['backtrace']
@exception_type = example_hash['exception']['class']
super( error? ? 'Error' : 'Failure')
@initialized = true
end
def error?
@exception_type != "RSpec::Expectations::ExpectationNotMetError"
end
end
def parse
result = nil
@output.each do |line|
if line =~ /(\{.*\})[^}]*\Z/
begin
result = JSON.parse($1)
rescue
#maybe report it to the additional info
$stderr.puts "JSON tried out to parse a line: \"#{line}\""
end
end
end
@time_result = result['summary']['duration']
@text_result = result['summary_line'] + ' seed: ' + result['seed'].to_s
result['examples'].each do |example|
next if example['status'] == 'passed' || example['status'] == "pending"
failured << ParsedFilure.new(example)
end
end
end
end
end
|
# frozen_string_literal: true
require './lib/game.rb'
require './lib/player.rb'
describe Game do
attr_reader :board, :player
before do
allow($stdout).to receive(:write)
@player = double(:player, name: 'Andrew', first?: true)
end
describe '#query_move' do
it 'prompts for user input and returns it' do
# This line works if I call rspec on this specific file, but not if I call rspec files
# as a group. (Having to do with Kernel reading from where file was called).
# allow(subject).to receive(:gets).and_return('c')
allow_any_instance_of(Kernel).to receive(:gets).and_return('c')
# Using subject with the above Kernel mock causes expectation to read output on instantiation.
game = Game.new
expect { game.query_move(player) }.to output(
"Select column for Andrew's move: "
).to_stdout
expect(subject.query_move(player)).to eq 'c'
end
it 'does not accept invalid columns' do
# allow_any_instance_of does not support multiple returns, but adding it allows me to run
# rspec files as a group (whether I use Object or Kernel doesn't seem to matter here)
allow_any_instance_of(Object).to receive(:gets).and_return('*not_read*')
game = Game.new
allow(game).to receive(:gets).and_return('h', 'g')
expect { game.query_move(player) }.to output(
"Select column for Andrew's move: " \
"\e[1A" \
"\e[2K" \
"\e[31mSelect column for Andrew's move (e.g., b): \e[0m"
).to_stdout
expect(game.query_move(player)).to eq 'g'
end
end
describe '#query_name' do
it 'asks for name and returns response' do
# allow(subject).to receive(:gets).and_return('Andrew')
allow_any_instance_of(Object).to receive(:gets).and_return('Andrew')
game = Game.new
expect(game.query_name(1)).to eq('Andrew')
end
end
end
|
require 'spec_helper'
module Alf
module Lang
describe "Aggregation methods" do
include Functional
let(:input){[
{:tested => 1, :other => "b"},
{:tested => 30, :other => "a"},
]}
let(:expected){[
{:tested => 30, :other => "a", :upcase => "A"},
]}
context 'on sum' do
it "should have sum with immediate block" do
expect(sum{|t| t.qty }).to be_kind_of(Aggregator::Sum)
end
it "should have sum with a Proc" do
expect(sum(->(t){ qty })).to be_kind_of(Aggregator::Sum)
end
end
context 'on concat' do
it "should have concat with immediate block" do
expect(concat{|t| t.name }).to be_kind_of(Aggregator::Concat)
end
it "should have sum with a Proc" do
agg = concat(->(t){ t.name }, between: ', ')
expect(agg).to be_kind_of(Aggregator::Concat)
expect(agg.options[:between]).to eq(', ')
end
end
end
end
end
|
class Redpear::Store::Enumerable < Redpear::Store::Base
include ::Enumerable
# Returns the array as the record's value
# @see Redpear::Store::Base#value
alias_method :value, :to_a
# Alias for #length
# @return [Integer] the length
def size
length
end
# Alias for #length
# @return [Integer] the length
def count
length
end
end
|
require 'rack/test/utils'
# Reopen Rack::Test::Utils to fix a bug https://github.com/rack-test/rack-test/commit/ece681de8ffee9d0caff30e9b93f882cc58f14cb
# TODO: Remove when migrating to Rails 5.1+
module Rack
module Test
module Utils
def build_nested_query(value, prefix = nil)
case value
when Array
if value.empty?
"#{prefix}[]="
else
value.map do |v|
unless unescape(prefix) =~ /\[\]$/
prefix = "#{prefix}[]"
end
build_nested_query(v, "#{prefix}")
end.join("&")
end
when Hash
value.map do |k, v|
build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
end.join("&")
when NilClass
prefix.to_s
else
"#{prefix}=#{escape(value)}"
end
end
end
end
end
|
$:.push File.expand_path("../lib", __FILE__)
require 'jquery_sortable_tree/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'jquery_sortable_tree'
s.version = JquerySortableTree::VERSION
s.authors = ['Ilya N. Zykin', 'Jozsef Nyitrai', 'Mikhail Dieterle', 'Matthew Clark']
s.email = ['nyitrai@maximalink.com', 'zykin-ilya@ya.ru']
s.homepage = 'https://github.com/maximalink/jquery_sortable_tree'
s.summary = %q{Rails Drag&Drop GUI gem for managing awesom_nested_set.}
s.licenses = ['MIT']
s.description = %q{Drag&Drop GUI, inline node editing and new node creating. Ready for Rails 4}
s.rubyforge_project = 'jquery_sortable_tree'
s.extra_rdoc_files = ['README.md']
s.files = Dir["{app,config,db,lib}/**/*"] + ['MIT-LICENSE', 'Rakefile']
s.test_files = Dir['spec/**/*']
s.add_dependency 'rails', '>= 3.1'
s.add_development_dependency 'sqlite3', '~> 1.3'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_development_dependency 'rspec-rails', '~> 3.0'
s.add_development_dependency 'capybara'
s.add_development_dependency 'faker'
s.add_development_dependency 'awesome_nested_set', '~> 3.0.0.rc5'
end
|
class Portfolio < ApplicationRecord
include OwnerField
include Discard::Model
acts_as_tenant(:tenant)
default_scope -> { kept }
validates :name, :presence => true, :uniqueness => { :scope => %i(tenant_id discarded_at) }
validates :image_url, :format => { :with => URI::DEFAULT_PARSER.make_regexp }, :allow_blank => true
validates :enabled_before_type_cast, :format => { :with => /\A(true|false)\z/i }, :allow_blank => true
has_many :portfolio_items, :dependent => :destroy
before_discard :discard_portfolio_items
before_undiscard :undiscard_portfolio_items
def add_portfolio_item(portfolio_item)
portfolio_items << portfolio_item
end
private
CHILD_DISCARD_TIME_LIMIT = 30
def discard_portfolio_items
if portfolio_items.map(&:discard).any? { |result| result == false }
portfolio_items.kept.each do |item|
errors.add(item.name.to_sym, "PortfolioItem ID #{item.id}: #{item.name} failed to be discarded")
end
err = "Failed to discard items from Portfolio '#{name}' id: #{id} - not discarding portfolio"
Rails.logger.error(err)
raise Discard::DiscardError, err
end
end
def undiscard_portfolio_items
if portfolio_items_to_restore.map(&:undiscard).any? { |result| result == false }
portfolio_items_to_restore.select(&:discarded?).each do |item|
errors.add(item.name.to_sym, "PortfolioItem ID #{item.id}: #{item.name} failed to be restored")
end
err = "Failed to restore items from Portfolio '#{name}' id: #{id} - not restoring portfolio"
Rails.logger.error(err)
raise Discard::DiscardError, err
end
end
def portfolio_items_to_restore
portfolio_items
.with_discarded
.discarded
.select { |item| (item.discarded_at.to_i - discarded_at.to_i).abs < CHILD_DISCARD_TIME_LIMIT }
end
end
|
ENV['RACK_ENV'] ||= 'development'
require 'sinatra/base'
require 'data_mapper'
require_relative 'data_mapper_setup'
require 'sinatra/flash'
class Chitter < Sinatra::Base
enable :sessions
register Sinatra::Flash
use Rack::MethodOverride
get '/' do
redirect '/peeps'
end
get '/peeps' do
@user = current_user
@peeps = Peep.all
erb :'peeps/index'
end
get '/peeps/new' do
erb :'peeps/new'
end
post '/peeps' do
Peep.create(text: params[:peep], posted_on: DateTime.now, user: current_user)
redirect '/peeps'
end
get '/users/new' do
erb :'users/new'
end
post '/users' do
user = User.create(name: params[:name], handle: params[:handle], email: params[:email], password: params[:password])
session[:user_id] = user.id
if user.save
redirect '/peeps'
else
flash.now[:errors] = user.errors.full_messages
erb :'users/new'
end
end
post '/sessions/new' do
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
else
flash.now[:notice] = ['The email or password is incorrect']
erb :'sessions/new'
end
end
delete '/sessions' do
session[:user_id] = nil
flash.keep[:notice] = 'goodbye!'
redirect to '/peeps'
end
helpers do
def current_user
@current_user ||= User.get(session[:user_id])
end
end
end
|
class Category < ApplicationRecord
has_ancestry
has_many :categories_foods
has_many :foods, through: :categories_foods
end
|
class HasCategory < ApplicationRecord
belongs_to :article #esto agrega el references al crear el modelo la relacion automaticamente
belongs_to :category
end
|
require 'fast_dsl'
module CustomExtensions
class CustomExtension < ScannerExtensions::BaseExtension
def applicable?(object)
return false if CustomExtensions.custom_detects.empty?
CustomExtensions.custom_detects.values.any? { |detect| detect.applicable?(object) }
end
def initialize
@type = :detect
@general_object_type = :param
@extension_type = :vuln
@detect_type = :custom
@defaults = {}
end
def run(object, params)
CustomExtensions.custom_detects.each do |name, detect|
next unless detect.applicable?(object)
ctx = detect.run(object)
if !ctx.vuln? && !ctx.oob_callbacks.empty?
object.oob_callbacks << Proc.new do
ctx.oob_callbacks.each do |callback|
callback.call
break if ctx.vuln?
end
ctx.vuln? ? fill_vuln(object, ctx, name: name) : nil
end
end
next unless ctx.vuln?
fill_vuln(object, ctx, name: name)
end
end
private
def fill_vuln(object, ctx, params = {})
vuln = ctx.vulns.first
curl_hash = { value: vuln.insertion_point_value }
curl_hash[:resp] = vuln.exploit_stamp if vuln.type == :sync
curl = object.curl_helper(curl_hash)
vuln_params = ctx.meta_info.to_h
if vuln.type == :async
vuln_params[:footers] = {
additional: {
view: 'oob_dns',
splitter: "\n",
params: { hosts: vuln.oob_triggered_ip }
}
}
end
defaults = {
title: "Custom #{vuln_params[:type].to_s.upcase} issue",
description: 'N/A',
additional: 'N/A'
}
# default template
if vuln_params.values_at(*defaults.keys).compact.empty?
object.vuln(
template: 'fast',
scid: params[:name],
args: {
trigger: vuln.trigger_name,
payload: vuln.payload,
marker: vuln.marker,
target: :server,
exploit_example: curl
}.merge(vuln_params)
)
# custom template
else
defaults.each do |key, val|
vuln_params["custom_#{key}".to_sym] = vuln_params[key] || val
end
%i[title description addititonal].each { |key| vuln_params.delete(key) }
object.vuln(
template: 'custom',
scid: params[:name],
args: { exploit_example: curl, target: :server }.merge(vuln_params)
)
end
object
end
end
@custom_detects = {}
module_function
def custom_extension
@custom_extension ||= CustomExtension.new
end
def custom_detects
@custom_detects
end
def load(path)
@custom_detects = {}
Dir["#{path}/**.yaml"].each do |file|
ext = load_extension(file)
name = file.split('/').last.split('.').first
@custom_detects[name] = ext if ext
end
App.logger.info("Loaded #{@custom_detects.size} custom extensions")
end
def load_extension(file)
data = YAML.safe_load(IO::binread(file))
FastDsl::Detect.new(data)
rescue => ex
App.logger.error("Invalid custom extension '#{file.split('/').last}': #{ex}")
return nil
end
end
|
class Person
attr_accessor :name
def initialize(name)
@name = name
end
def greeting
puts "Hi, my name is #{@name}"
end
end
class Instructor < Person
def teach
puts "Everything in Ruby is an Object"
end
end
class Student < Person
def learn
puts "I get it!"
end
end
i = Instructor.new("Christina")
s = Student.new("Chris")
s.greeting
i.greeting
i.teach
s.learn
# s.teach
# there is no teach metohod for student
|
class Post < ApplicationRecord
validates :title, presence: true
validates :description, presence: true
belongs_to :user
belongs_to :subcommunity
has_many :comments, dependent: :destroy
end
|
# encoding: UTF-8
class InterestsController < ApplicationController
before_filter :check_autentication, only: [:edit, :update, :destroy]
layout 'page'
# GET /interests
# GET /interests.json
def index
@interests = Interest.all
end
# GET /interests/1
# GET /interests/1.json
def show
@interest = Interest.find(params[:id])
end
# GET /interests/new
# GET /interests/new.json
def new
@interest = Interest.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @interest }
end
end
# GET /interests/1/edit
def edit
@interest = Interest.find(params[:id])
end
# POST /interests
# POST /interests.json
def create
@interest = Interest.new(params[:interest])
respond_to do |format|
if @interest.save
format.html {
flash[:notice] = 'علاقه مندی جدید اضافه شد.'
redirect_to action: "index"
}
else
format.html { render action: "new" }
end
end
end
# PUT /interests/1
# PUT /interests/1.json
def update
@interest = Interest.find(params[:id])
respond_to do |format|
if @interest.update_attributes(params[:interest])
format.html {
flash[:notice] = 'ویرایش اطلاعات انجام شد.'
redirect_to action: "index"
}
else
format.html { render action: "edit" }
end
end
end
# DELETE /interests/1
# DELETE /interests/1.json
def destroy
@interest = Interest.find(params[:id])
@interest.destroy
end
end
|
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the HomeHelper. For example:
#
# describe HomeHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# helper.concat_strings("this","that").should == "this that"
# end
# end
# end
describe AclsHelper do
before(:each) do
pwd = 'cloud$'
@user = User.create! :first_name => 'Dale', :last_name => 'Olds', :display_name => 'Dale O.', :password => pwd, :confirm_password => pwd, :email => 'olds@vmware.com'
@org = Org.create! :display_name => 'VMWare', :creator => @user
@project = @org.default_project
@app = App.create! :display_name => 'Optimus', :creator => @user, :project => @project, :url => "optimus.cloudfoundry.com"
@owned_resource = @app.main_owned_resource
@org2 = Org.create! :display_name => 'DELL', :creator => @user
@project2 = @org2.default_project
@acl = @project.acls.build :owned_resource => @owned_resource, :entity => @user
@acl.save!
end
context "on read" do
describe "rendering urls" do
it "Should return the proper app path if owned resource is app" do
resource_url(@acl).should == "/apps/#{@app.id}"
end
it "Should return the proper service path if owned resource is service" do
s = Service.create! :display_name => 'Optimus', :project => @project, :creator => @user
service_res = s.reload.main_owned_resource
acl2 = @project.acls.build :owned_resource => service_res, :entity => @user
acl2.save!
resource_url(acl2).should == "/services/#{s.id}"
end
it "Should return the proper parent path if route used" do
acl3 = @project.acls.build :route => 'projects/*', :entity => @user
acl3.save!
resource_url(acl3).should == "/orgs/#{@org.id}/projects/"
end
end
end
end
|
class AdminsController < ApplicationController
before_filter :authenticate_user!, :ensure_admin
def ensure_admin
return true if current_user.admin
flash[:error] = "The page you requested is not available"
redirect_to root_path
end
end
|
class Review < ActiveRecord::Base
belongs_to :reservation
belongs_to :guest, :class_name => "User"
validates :rating, presence: true
validates :description, presence: true
validates :reservation_id, presence: true
validate :checkout_has_passed
def checkout_has_passed
if self.reservation_id && self.reservation.checkout > Date.today
errors.add(:checkout, "checkout date has not passed")
end
end
end
|
require "formula"
class Lmdb < Formula
homepage "http://symas.com/mdb/"
url "https://gitorious.org/mdb/mdb.git", :tag => "LMDB_0.9.14"
head "git://git.openldap.org/openldap.git", :branch => "mdb.master"
bottle do
cellar :any
sha1 "7e7e4fb592dccd7c34553760930a9cc59d58c7fb" => :yosemite
sha1 "835766327dd8a41e993a7e5e54ca415cceec1f15" => :mavericks
sha1 "5914b3dfe5980896f5242b67cf66fadfb59a0ce5" => :mountain_lion
end
def install
inreplace "libraries/liblmdb/Makefile" do |s|
s.gsub! ".so", ".dylib"
s.gsub! "$(DESTDIR)$(prefix)/man/man1", "$(DESTDIR)$(prefix)/share/man/man1"
end
man1.mkpath
bin.mkpath
lib.mkpath
include.mkpath
system "make", "-C", "libraries/liblmdb", "install", "prefix=#{prefix}"
end
test do
system "#{bin}/mdb_dump", "-V"
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.