text
stringlengths
10
2.61M
class Blurb < ActiveRecord::Base belongs_to :day # attr_accessible :text has_many :tag_types, as: :taggable has_many :tags, through: :tag_types end
class AddIndexToKindAndTitleOfStory < ActiveRecord::Migration[5.1] def change add_index :stories, %i(kind title), unique: true end end
module Parse def parse(score_line) rolls = score_line.chars.map {|char| Roll.new(char)} rolls.each_cons(2) do |roll, next_roll| next_roll.previous = roll roll.next = next_roll end frames = [] until rolls.empty? frames << pop_frame(rolls, frames.size == 9) end frames end def pop_frame(rolls, is_last) return StrikeOrSpareFrame.new((rolls.shift 3).first) if is_last and rolls.size == 3 first_roll = rolls.shift return StrikeOrSpareFrame.new(first_roll) if first_roll.strike? second_roll = rolls.shift return StrikeOrSpareFrame.new(first_roll) if second_roll.spare? Frame.new(first_roll) end end class Roll attr_writer :previous attr_accessor :next def initialize(char) @char = char end def strike? @char == 'X' end def spare? @char == "/" end def gutter? @char == "-" end def score case when gutter? then 0 when strike? then 10 when spare? then 10 - @previous.score else @char.to_i end end def and_the_next(number) return [self] if number == 0 return [self] + self.next.and_the_next(number-1) end end class AbstractFrame def initialize(first_roll) @first_roll = first_roll end protected def sum_of(rolls) rolls.map(&:score).inject(:+) end end class Frame < AbstractFrame def score sum_of(@first_roll.and_the_next(1)) end end class StrikeOrSpareFrame < AbstractFrame def score sum_of(@first_roll.and_the_next(2)) end end class Game def score(score_line) frames = parse(score_line) frames.inject(0) do |total_score, frame| total_score + frame.score end end private include Parse end
class Author attr_accessor :name @@authors = [] def initialize(name) @name = name @post_list = [] @@authors << self end def posts @post_list end def add_post(posting) posting.author = self posts << posting end def add_post_by_title(post_name) posting = Post.new(post_name) posting.author = self posts << posting end def self.post_count count = 0 @@authors.each {|author| count += author.posts.length} count end end
class RemoveEntryStatusFromLectureStudent < ActiveRecord::Migration def change remove_column :lecture_students, :entry_status, :string end end
require File.dirname(__FILE__) + '/../spec_helper' describe ChartsTimelineController do include Redmine::I18n before do Time.set_current_date = Time.mktime(2010,3,12) Setting.default_language = 'en' @controller = ChartsTimelineController.new @request = ActionController::TestRequest.new @request.session[:user_id] = 1 end it "should return data with range weeks offset 0" do get :index, :project_id => 15041, :project_ids => 15041, :limit => 10, :range => 'weeks', :offset => 0 response.should be_success body = ActiveSupport::JSON.decode(assigns[:data]) body['x_axis']['min'].should == 0 body['x_axis']['steps'].should == 1 body['x_axis']['max'].should == 9 body['x_axis']['labels']['labels'].size.should == 10 body['elements'][0]['values'].size.should == 10 body['x_axis']['labels']['labels'][0].should == '4 - 10 Jan 10' body['x_axis']['labels']['labels'][1].should == "" body['x_axis']['labels']['labels'][2].should == '18 - 24 Jan 10' body['x_axis']['labels']['labels'][3].should == "" body['x_axis']['labels']['labels'][4].should == '1 - 7 Feb 10' body['x_axis']['labels']['labels'][5].should == "" body['x_axis']['labels']['labels'][6].should == '15 - 21 Feb 10' body['x_axis']['labels']['labels'][7].should == "" body['x_axis']['labels']['labels'][8].should == '1 - 7 Mar 10' body['x_axis']['labels']['labels'][9].should == "" end it "should return data with range weeks offset 10" do get :index, :project_id => 15041, :project_ids => 15041, :offset => 10, :limit => 10, :range => 'weeks' response.should be_success body = ActiveSupport::JSON.decode(assigns[:data]) body['x_axis']['labels']['labels'].size.should == 10 body['elements'][0]['values'].size.should == 10 body['x_axis']['labels']['labels'][0].should == '26 Oct - 1 Nov 09' body['x_axis']['labels']['labels'][1].should == "" body['x_axis']['labels']['labels'][2].should == '9 - 15 Nov 09' body['x_axis']['labels']['labels'][3].should == "" body['x_axis']['labels']['labels'][4].should == '23 - 29 Nov 09' body['x_axis']['labels']['labels'][5].should == "" body['x_axis']['labels']['labels'][6].should == '7 - 13 Dec 09' body['x_axis']['labels']['labels'][7].should == "" body['x_axis']['labels']['labels'][8].should == '21 - 27 Dec 09' body['x_axis']['labels']['labels'][9].should == "" end it "should return data with range weeks offset 20" do get :index, :project_id => 15041, :project_ids => 15041, :offset => 20, :limit => 20, :range => 'weeks' response.should be_success body = ActiveSupport::JSON.decode(assigns[:data]) body['x_axis']['labels']['labels'].size.should == 20 body['elements'][0]['values'].size.should == 20 body['x_axis']['labels']['labels'][0].should == '8 - 14 Jun 09' body['x_axis']['labels']['labels'][1].should == "" body['x_axis']['labels']['labels'][2].should == "" body['x_axis']['labels']['labels'][3].should == "" body['x_axis']['labels']['labels'][4].should == '6 - 12 Jul 09' body['x_axis']['labels']['labels'][5].should == "" body['x_axis']['labels']['labels'][6].should == "" body['x_axis']['labels']['labels'][7].should == "" body['x_axis']['labels']['labels'][8].should == '3 - 9 Aug 09' body['x_axis']['labels']['labels'][9].should == "" body['x_axis']['labels']['labels'][10].should == "" body['x_axis']['labels']['labels'][11].should == "" body['x_axis']['labels']['labels'][12].should == '31 Aug - 6 Sep 09' body['x_axis']['labels']['labels'][13].should == "" body['x_axis']['labels']['labels'][14].should == "" body['x_axis']['labels']['labels'][15].should == "" body['x_axis']['labels']['labels'][16].should == '28 Sep - 4 Oct 09' body['x_axis']['labels']['labels'][17].should == "" body['x_axis']['labels']['labels'][18].should == "" body['x_axis']['labels']['labels'][19].should == "" end it "should return data with range months with offset 0" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'months', :limit => 10, :offset => 0 response.should be_success body = ActiveSupport::JSON.decode(assigns[:data]) body['x_axis']['labels']['labels'].size.should == 10 body['elements'][0]['values'].size.should == 10 body['x_axis']['labels']['labels'][0].should == 'Jun 09' body['x_axis']['labels']['labels'][1].should == "" body['x_axis']['labels']['labels'][2].should == 'Aug 09' body['x_axis']['labels']['labels'][3].should == "" body['x_axis']['labels']['labels'][4].should == 'Oct 09' body['x_axis']['labels']['labels'][5].should == "" body['x_axis']['labels']['labels'][6].should == 'Dec 09' body['x_axis']['labels']['labels'][7].should == "" body['x_axis']['labels']['labels'][8].should == 'Feb 10' body['x_axis']['labels']['labels'][9].should == "" end it "should return data with range days with offset 0" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :limit => 10, :offset => 0 response.should be_success body = ActiveSupport::JSON.decode(assigns[:data]) body['x_axis']['labels']['labels'].size.should == 10 body['elements'][0]['values'].size.should == 10 body['x_axis']['labels']['labels'][0].should == '03 Mar 10' body['x_axis']['labels']['labels'][1].should == "" body['x_axis']['labels']['labels'][2].should == '05 Mar 10' body['x_axis']['labels']['labels'][3].should == "" body['x_axis']['labels']['labels'][4].should == '07 Mar 10' body['x_axis']['labels']['labels'][5].should == "" body['x_axis']['labels']['labels'][6].should == '09 Mar 10' body['x_axis']['labels']['labels'][7].should == "" body['x_axis']['labels']['labels'][8].should == '11 Mar 10' body['x_axis']['labels']['labels'][9].should == "" end it "should return data without grouping" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :limit => 10, :offset => 0 response.should be_success body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 1 body['y_axis']['max'].should be_close(9, 1) body['y_legend']['text'].should == l(:charts_timeline_y) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(7.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 7.6 : 7.7 body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(6.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 6.6 : 6.7 body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(7.4, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(7.4, 2, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with range days with offset 0" do get :index, :project_id => 15041, :project_ids => [15041, 15042], :range => 'days', :limit => 10, :offset => 0 response.should be_success body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'][0]['value'].should be_close(14.9, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 14.9 : 15.0 body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 3, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(6.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 6.6 : 6.7 body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(7.4, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(7.4, 2, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with grouping by users" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'user_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 3 body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == 'John Smith' body['elements'][1]['values'][0]['value'].should be_close(3.3, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(3.3, 1, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == 'Dave Lopper' body['elements'][0]['values'][0]['value'].should be_close(0, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') body['elements'][2]['values'].size.should == 4 body['elements'][2]['text'].should == 'Redmine Admin' body['elements'][2]['values'][0]['value'].should be_close(3.3, 0.1) body['elements'][2]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(3.3, 1, '09 Mar 10') body['elements'][2]['values'][1]['value'].should be_close(0, 0.1) body['elements'][2]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '10 Mar 10') end it "should return data with grouping_by_priorities" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'priority_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == 'High' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == l(:charts_group_none) body['elements'][1]['values'][0]['value'].should be_close(0, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') end it "should return data with grouping_by_authors" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'author_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == l(:charts_group_none) body['elements'][1]['values'][0]['value'].should be_close(0, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == 'Redmine Admin' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') end it "should return data with grouping_by_projects" do get :index, :project_id => 15041, :grouping => 'project_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 1 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == '#15041 Project1' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(7.4, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(7.4, 2, '10 Mar 10') end it "should return data with grouping_by_statuses" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'status_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == 'New' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == l(:charts_group_none) body['elements'][1]['values'][0]['value'].should be_close(0, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') end it "should return data with grouping_by_trackers" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'tracker_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == 'Bug' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == l(:charts_group_none) body['elements'][1]['values'][0]['value'].should be_close(0, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') end it "should return data with grouping_by_issues" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'issue_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == '#15045 Issue5' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == l(:charts_group_none) body['elements'][1]['values'][0]['value'].should be_close(0, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') end it "should return data with grouping_by_versions" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'fixed_version_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == '2.0' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == l(:charts_group_none) body['elements'][1]['values'][0]['value'].should be_close(0, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') end it "should return data with grouping_by_categories" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'category_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == 'Category2' body['elements'][0]['values'][0]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == l(:charts_group_none) body['elements'][1]['values'][0]['value'].should be_close(0, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') end it "should return data with grouping_by_activities" do get :index, :project_id => 15041, :project_ids => 15041, :grouping => 'activity_id', :range => 'days', :limit => 4, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'].size.should == 2 body['elements'][0]['values'].size.should == 4 body['elements'][0]['text'].should == 'Design' body['elements'][0]['values'][0]['value'].should be_close(3.3, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(3.3, 1, '09 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][1]['values'].size.should == 4 body['elements'][1]['text'].should == 'Development' body['elements'][1]['values'][0]['value'].should be_close(3.3, 0.1) body['elements'][1]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(3.3, 1, '09 Mar 10') body['elements'][1]['values'][1]['value'].should be_close(5.1, 0.1) body['elements'][1]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') end it "should return data with users_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :user_ids => 1, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(4.3, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 4.3 : 4.4 body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 1, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(0, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(3.3, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(3.3, 1, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(0, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with issues_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :issue_ids => 15045, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(0, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(0, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(0, 0.1) body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "") .should == get_label(0, 0, '12 Mar 10') end it "should return data with activities_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :activity_ids => 9, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 4.3 : 4.4 body['elements'][0]['values'][0]['value'].should be_close(4.3, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 1, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(6.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 6.6 : 6.7 body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(3.3, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(3.3, 1, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(5.1, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(5.1, 1, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with priorities_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :priority_ids => 4, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(7.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 7.6 : 7.7 body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(0, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(0, 0.1) body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(0, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(0, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with trackers_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :tracker_ids => 1, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(0, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(0, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(0, 0.1) body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with versions_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :limit => 10, :fixed_version_ids => 15042, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(7.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 7.6 : 7.7 body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(0, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(0, 0.1) body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with categories_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :category_ids => 15042, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(7.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 7.6 : 7.7 body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(6.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 6.6 : 6.7 body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(6.6, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(6.6, 2, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with status_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :status_ids => 2, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(7.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 7.6 : 7.7 body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(6.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 6.6 : 6.7 body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(0, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(0, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with author_condition" do get :index, :project_id => 15041, :project_ids => 15041, :range => 'days', :author_ids => 2, :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][0]['value'].should be_close(0, 0.1) body['elements'][0]['values'][0]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '03 Mar 10') body['elements'][0]['values'][1]['value'].should be_close(0, 0.1) body['elements'][0]['values'][1]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '04 Mar 10') body['elements'][0]['values'][2]['value'].should be_close(2.3, 0.1) body['elements'][0]['values'][2]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(2.3, 1, '05 Mar 10') body['elements'][0]['values'][3]['value'].should be_close(6.6, 0.1) tmp = ActiveRecord::Base.connection.adapter_name =~ /postgresql|sqlite/i ? 6.6 : 6.7 body['elements'][0]['values'][3]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(tmp, 2, '06 Mar 10') body['elements'][0]['values'][4]['value'].should be_close(0, 0.1) body['elements'][0]['values'][4]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '07 Mar 10') body['elements'][0]['values'][5]['value'].should be_close(0, 0.1) body['elements'][0]['values'][5]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '08 Mar 10') body['elements'][0]['values'][6]['value'].should be_close(0, 0.1) body['elements'][0]['values'][6]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '09 Mar 10') body['elements'][0]['values'][7]['value'].should be_close(0, 0.1) body['elements'][0]['values'][7]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '10 Mar 10') body['elements'][0]['values'][8]['value'].should be_close(0, 0.1) body['elements'][0]['values'][8]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '11 Mar 10') body['elements'][0]['values'][9]['value'].should be_close(0, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(0, 0, '12 Mar 10') end it "should return data with sub_tasks" do if RedmineCharts.has_sub_issues_functionality_active get :index, :project_id => 15044, :project_ids => 15044, :range => 'weeks', :limit => 10, :offset => 0 body = ActiveSupport::JSON.decode(assigns[:data]) body['elements'][0]['values'].size.should == 10 body['elements'][0]['text'].should == l(:charts_group_all) body['elements'][0]['values'][9]['value'].should be_close(13.2, 0.1) body['elements'][0]['values'][9]['tip'].gsub("\\u003C", "<").gsub("\\u003E", ">").gsub("\000", "").should == get_label(13.2, 4, '8 - 14 Mar 10') end end it "should return data with all_conditions" do get :index, :project_id => 15041, :category_ids => 15043, :tracker_ids => 15043, :fixed_version_ids => 15043, :fixed_version_ids => 15041, :user_ids => 15043, :issue_ids => 15043, :activity_ids => 15043, :author_ids => 1, :status_ids => 5 response.should be_success end def get_label(hours, entries, date) if(hours > 0) "#{l(:charts_timeline_hint, :hours => hours, :entries => entries)}<br>#{date}" else "#{l(:charts_timeline_hint_empty)}<br>#{date}" end end end
class ASIAttachment < ActiveRecord::Base attr_accessible :filename, :description, :s3_path, :asi_id belongs_to :asi, class_name: "ASI", foreign_key: "asi_id" validates :filename, :s3_path, :asi_id, presence: true end
class AddSentMoneyAndReceiptMoneyToUsers < ActiveRecord::Migration def change add_column :users, :sent_money, :decimal,precision: 16, scale: 2, default: 0.00 add_column :users, :receipt_money, :decimal, precision: 16, scale: 2, default: 0.00 remove_column :users, :income end end
# frozen_string_literal: true module Admin # MetaTagController class MetaTagsController < AdminController before_action :set_meta_tag, only: %i[show edit update destroy] before_action :show_history, only: %i[index] before_action :authorization, except: %i[reload] include ObjectQuery # GET /meta_tags def index @q = MetaTag.ransack(params[:q]) @meta_tags = @q.result(distinct: true) @objects = @meta_tags.page(@current_page).order(position: :desc) @total = @meta_tags.size redirect_to_index(@objects) respond_to_formats(@meta_tags) end # GET /meta_tags/1 def show; end # GET /meta_tags/new def new @meta_tag = MetaTag.new end # GET /meta_tags/1/edit def edit; end # POST /meta_tags def create @meta_tag = MetaTag.new(meta_tag_params) if @meta_tag.save redirect(@meta_tag, params) else render :new end end # PATCH/PUT /meta_tags/1 def update if @meta_tag.update(meta_tag_params) redirect(@meta_tag, params) else render :edit end end def clone @meta_tag = MetaTag.clone_record params[:meta_tag_id] if @meta_tag.save redirect_to admin_meta_tags_path else render :new end end # DELETE /meta_tags/1 def destroy @meta_tag.destroy redirect_to admin_meta_tags_path, notice: actions_messages(@meta_tag) end def destroy_multiple MetaTag.destroy redefine_ids(params[:multiple_ids]) redirect_to( admin_meta_tags_path(page: @current_page, search: @query), notice: actions_messages(@meta_tag) ) end def upload MetaTag.upload(params[:file]) redirect_to( admin_meta_tags_path(page: @current_page, search: @query), notice: actions_messages(@meta_tag) ) end def download @meta_tags = MetaTag.all respond_to_formats(@meta_tags) end def reload @objects = MetaTag.order(:position) end def sort MetaTag.sorter(params[:row]) render :index end private def authorization authorize MetaTag end # Use callbacks to share common setup or constraints between actions. def set_meta_tag @meta_tag = MetaTag.find(params[:id]) end # Only allow a trusted parameter "white list" through. def meta_tag_params params.require(:meta_tag).permit(:title, :description, :meta_tags, :url, :position) end def show_history get_history(MetaTag) end end end
require 'test/unit' require_relative '../crm_contact' class TestContact < Test::Unit::TestCase def test_initialize_with_valid_params_works contact = Contact.new(5, "Will", "Richman", "will@bitmakerlabs.com", "") # Assert that the variables passed in are retrievable and therefore saved correctly # Assert that you get back an instance of a contact assert contact.is_a?(Contact) assert_equal 5, contact.id end end
class Oniguruma < Formula homepage "http://www.geocities.jp/kosako3/oniguruma/" url "http://www.geocities.jp/kosako3/oniguruma/archive/onig-5.9.6.tar.gz" sha1 "08d2d7b64b15cbd024b089f0924037f329bc7246" bottle do cellar :any sha1 "12f394ce6f8694efa03d1a7ce2d18fc9a069a75c" => :yosemite sha1 "5243422d56451c96768528739932c5651e7a10d7" => :mavericks sha1 "62ca1e24ca20cecb83b8cbeeaf1335b94faffe4b" => :mountain_lion end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end end
class TimeSlot < ActiveRecord::Base has_many :positions validates "time_slots.starts_at", "time_slots.ends_at", :overlap => { :query_options => {:includes => :positions}, :scope => {"positions.user_id" => proc{|time_slot| time_slot.positions.map(&:user_id)} } } end
class PasswordsController < DeviseTokenAuth::PasswordsController def update if @resource @resource.allow_password_change = true end super end end
class Matches < ROM::Relation[:sql] schema(:matches, infer: true) do associations do belongs_to :teams, as: :home_team, foreign_key: :home_team_id belongs_to :teams, as: :away_team, foreign_key: :away_team_id end end def by_id(id) where(id: id) end def all order(:kick_off) end def with_teams combine(:home_team, :away_team) .node(:home_team) { |relation| relation.select(:id, :name) } .node(:away_team) { |relation| relation.select(:id, :name) } end end
require 'spec_helper' describe Robot do let(:robot){Robot.new} let(:position){CellPosition.new(0,0,'N')} let(:table){TableTop.new(5,5)} describe 'is_placed?' do it 'should return false when robot is not placed' do expect(robot.is_placed?).to be false end it 'should return true when robot is placed' do robot.position = position expect(robot.is_placed?).to be true end end describe 'move' do it 'should call move command' do robot.position = position move = Move.new(robot, table) Move.should_receive(:new).once.and_return(move) move.should_receive(:execute).once robot.move(table) end end describe 'left' do it 'should call left command' do left = Left.new(robot) Left.should_receive(:new).once.and_return(left) left.should_receive(:execute).once robot.left end end describe 'right' do it 'should call right command' do right = Right.new(robot) Right.should_receive(:new).once.and_return(right) right.should_receive(:execute).once robot.right end end describe 'report' do it 'should call report command' do report = Report.new(robot) Report.should_receive(:new).once.and_return(report) report.should_receive(:execute).once robot.report end end describe 'place' do it 'should call place command' do place = Place.new(robot, table, position) Place.should_receive(:new).once.and_return(place) place.should_receive(:execute).once robot.place(table, position) end end end
Trunk::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Print deprecation notices to the stderr config.active_support.deprecation = :stderr end FEATURE_LOGINS_ENABLED = true FACEBOOK_APP_ID = "221310351230872" FACEBOOK_APP_SECRET = "98db48a9fd117ab622ff3a500d24e1c6" TWITTER_SECRET_KEY = "9fVkuQ55t8Z6wfvnuA0oL2HXd6y5ixhxDlQMxjKMm0M" TWITTER_CONSUMER_KEY = "fWqlifbApc14jPJWErfQ" MYSPACE_OAUTH_KEY = "129a778985934769a01e98c85f0496b1" MYSPACE_OAUTH_SECRET = "3f0b59f73fc947868f403f5e025fba2d5d1efc14e6c64dac882f39e2688f6219" #Flickr #http://www.flickr.com/services/apps/72157626418174343/auth/ #App Creator: bradsmithinc@ymail.com FLICKR_KEY = "ffa00b627e93f748069131eb6fc1ca3f" FLICKR_SECRET = "56ba4e8669deee83" #Tumblr TUMBLR_OAUTH_KEY = "LO8YVBI64F4qSAN5OhQDB2ZyET51PNhEKTRwP9W1tqivyrabYA" TUMBLR_OAUTH_SECRET = "CTP7UdYAv5eoQsYVsDr96mdWjgjV2UHyA6SOyabGyVQNUwfFQV"
require 'spec_helper' describe "acls/index.html.erb" do before(:each) do @org = assign(:org, stub_model(Org, :display_name => 'VMWare')) @project = stub_model(Project, :org => @org, :display_name => 'Cloud Foundry') @user = stub_model(User, :first_name => 'Monica', :last_name => 'Wilkinson', :display_name => 'Monica W') @user2 = stub_model(User, :first_name => 'Peter', :last_name => 'Jenkins', :display_name => 'Jenkins') @acl = stub_model(Acl, :route => "/groups/*", :entity => @user, :permission_set => PermissionManager::ALL, :project => @project) @acl2 = stub_model(Acl, :route => "/apps/*", :entity => @user, :permission_set => PermissionManager::ALL, :project => @project) @acl3 = stub_model(Acl, :route => "/apps/*", :entity => @user2, :permission_set => PermissionManager::ALL, :project => @project) assign(:entities, {@acl.entity_display_name => [@acl, @acl2], @acl3.entity_display_name => [@acl3]}) end it "renders a list of acls" do render assert_select "h4", :text => "#{@acl.entity_display_name} has", :count => 1 end end
module Outputs module MessageMediaType include Types::BaseInterface include Types::ActiveRecord field :url, String, null: false field :location, String, null: false, deprecation_reason: "Renamed to url" field :content_type, String, null: false field :type, String, null: false, deprecation_reason: "Renamed to contentType" field :filename, String, null: false field :extension, String, null: false def content_type @object.blob.content_type end alias type content_type def url RouteHelper.rails_blob_url(@object) end alias location url def filename @object.filename.to_s end def extension @object.filename.extension end orphan_types MessageMediaFileType, MessageMediaImageType definition_methods do def resolve_type(object, _context) if object.image? MessageMediaImageType else MessageMediaFileType end end end end end
class ChangeDeadOfEvents < ActiveRecord::Migration[5.0] def change change_column :events, :dead, :date end end
module Recliner module Conversions extend self class ConversionError < TypeError end def clear! conversions.clear end def convert(from, to, options={}) return nil if from.nil? return from if to.is_a?(Class) && from.kind_of?(to) source = options[:source] || from.class if block = conversion(source, to) from.instance_eval(&block) rescue nil else raise ConversionError, "No registered conversion from #{source} to #{to.inspect}" end end def convert!(from, to, options={}) return nil if from.nil? return from if to.is_a?(Class) && from.kind_of?(to) source = options[:source] || from.class if block = conversion(source, to) begin from.instance_eval(&block) rescue => e raise ConversionError, "Conversion block raised exception" end else raise ConversionError, "No registered conversion from #{source} to #{to.inspect}" end end def register(from, to, &block) conversions[from][to] = block end private def conversion(from, to) while from return conversions[from][to] if conversions[from] && conversions[from][to] from = from.is_a?(Class) ? from.superclass : nil end nil end def conversions @conversions ||= Hash.new { |hash, key| hash[key] = {} } end end end Dir[File.dirname(__FILE__) + "/conversions/*.rb"].sort.each do |path| filename = File.basename(path) require "recliner/conversions/#{filename}" end
class Board attr_accessor :cells def initialize @cells = [" "," "," "," "," "," "," "," "," "] end def reset! @cells = [" "," "," "," "," "," "," "," "," "] end def display puts " #{cells[0]} | #{cells[1]} | #{cells[2]} " puts "-----------" puts " #{cells[3]} | #{cells[4]} | #{cells[5]} " puts "-----------" puts " #{cells[6]} | #{cells[7]} | #{cells[8]} " end def position(num) num = num.to_i cells[num-1] end def full? value = true cells.each do |cell| if cell == " " value = false end end return value end def turn_count value = 0 cells.each do |cell| if cell != " " value +=1 end end return value end def taken?(num) value = false if position(num) == "X" || position(num) == "O" value = true end return value end def valid_move?(num) value = false if num.class != Fixnum num = num.to_i end if num <= 9 && num >= 1 value = true end if full? || taken?(num) value = false end return value end def update(num, player) if valid_move?(num) num = num.to_i @cells[num-1] = player.token end end end
class Api::Users::SignInOp class << self def execute(login, password) Auth.authenticate(login, password) end def allowed?(*) true end end end
class BookingsController < ApplicationController def new #pass it the parameters from submitting the last form @booking = Booking.new @flight = Flight.find(params[:flightChoice]) @passenger = Passenger.new end def create @booking = Booking.new(booking_params) if @booking.save PassengerMailer.welcome_email(@booking.passenger).deliver_now redirect_to root_path else end end def index end def show end private def booking_params params.require(:booking).permit(:flight_id, passenger_attributes: [:name, :email]) end end
module RailsParam module ErrorMessages class MustBeAStringMessage < RailsParam::ErrorMessages::BaseMessage def to_s "Parameter #{param_name} must be a string if using the format validation" end end end end
module Yard2steep class Type class TypeBase def to_s raise "Must be implemented in child class" end end class AnyType < TypeBase # @return [String] def to_s 'any' end end class NormalType < TypeBase # @param [String] type def initialize(type:) @type = type end def to_s @type end end class ArrayType < TypeBase # @param [TypeBase] type def initialize(type:) @type = type end # @return [String] def to_s "Array<#{@type}>" end end class HashType < TypeBase # @param [TypeBase] key # @param [TypeBase] val def initialize(key:, val:) @key = key @val = val end # @return [String] def to_s "Hash<#{@key}, #{@val}>" end end class UnionType < TypeBase def initialize(types:) Util.assert! { types.size > 0 } @types = types end # @return [String] def to_s @types.map { |t| t.to_s }.uniq.join(' | ') end end end end
require 'httparty' class TogglReport include HTTParty base_uri "https://toggl.com/reports/api/v2" def details(*args) params = { basic_auth: {username: config["toggl_api_key"], password: "api_token"}, query: { user_agent: "toggl_to_harvest Ruby gem", workspace_id: config["toggl_workspace_id"], user_ids: config["toggl_user_ids"].join(","), } } response = self.class.get("/details", params) if response.code == 200 json_response = JSON.parse(response.body) json_response["data"] else raise "ERROR! Could not get time entries from Toggl API. Response status: #{response.code}\n #{response.body}" end end def config @config ||= YAML.load_file(File.expand_path("~/.toggl-to-harvest.yml")) @config end end
class FixTypeColumnNameInStatus < ActiveRecord::Migration def self.up rename_column :facebook_statuses, :type, :feed_type end def self.down rename_column :facebook_statuses, :feed_type, :type end end
module TicTacToe class Game attr_reader :board attr_reader :type HUMAN_VS_HUMAN = :hvh HUMAN_VS_COMPUTER = :hvc COMPUTER_VS_COMPUTER = :cvc COMPUTER_VS_HUMAN = :cvh def initialize(game_type = :hvh, board = TicTacToe::Board.empty_board) @type = game_type @board = board end def current_player_human? human_v_human_game? || human_turn_on_human_v_computer? || false end def make_move(position) board = @board.make_move(position, @board.current_player) Game.new(type, board) end def drawn? board.remaining_moves.count == 0 end def won? board.game_won? end def over? drawn? || won? end private def human_turn_on_human_v_computer? return type == HUMAN_VS_COMPUTER if board.remaining_moves.count.odd? end def human_v_human_game? return true if type == HUMAN_VS_HUMAN end end end
# frozen_string_literal: true class ImagesDownloadService def initialize(file_path, batch_size) @file_path = file_path @batch_size = batch_size @target_folder = File.join(File.dirname(file_path), 'images') end def call @failed_downloads = [] File.foreach(file_path).each_slice(batch_size) do |batch_urls| failed_downloads.concat(ImageBatchesDownloadService.new(batch_urls.map(&:strip), target_folder).call) end failed_downloads end private attr_reader :file_path, :batch_size, :target_folder, :failed_downloads end
class CoursesController < ApplicationController # you need to be able to pick a course to be authorized for it skip_before_action :authorize_user_for_course, only: [ :index, :new, :create ] # if there's no course, there are no persistent announcements for that course skip_before_action :update_persistent_announcements, only: [ :index, :new, :create ] skip_before_action :authenticate_for_action def index courses_for_user = User.courses_for_user current_user if courses_for_user.any? @listing = categorize_courses_for_listing courses_for_user else redirect_to home_no_user_path and return end render layout: "home" end def new # check for permission if !current_user.administrator? then flash[:error] = "Permission denied." redirect_to root_path and return end @newCourse = Course.new @newCourse.late_penalty = Penalty.new @newCourse.version_penalty = Penalty.new end def create # check for permission if !current_user.administrator? then flash[:error] = "Permission denied." redirect_to root_path and return end @newCourse = Course.new(new_course_params) @newCourse.display_name = @newCourse.name # fill temporary values in other fields @newCourse.late_slack = 0 @newCourse.grace_days = 0 @newCourse.start_date = Time.now @newCourse.end_date = Time.now @newCourse.late_penalty = Penalty.new @newCourse.late_penalty.kind = "points" @newCourse.late_penalty.value = "0" @newCourse.version_penalty = Penalty.new @newCourse.version_penalty.kind = "points" @newCourse.version_penalty.value = "0" if @newCourse.save then instructor = User.where(email: params[:instructor_email]).first # create a new user as instructor if he didn't exist if (instructor.nil?) instructor = User.instructor_create(params[:instructor_email], @newCourse.name) end newCUD = @newCourse.course_user_data.new newCUD.user = instructor newCUD.instructor = true if newCUD.save then flash[:success] = "New Course #{@newCourse.name} successfully created!" redirect_to edit_course_path(@newCourse) and return else # roll back course creation @newCourse.destroy flash[:error] = "Can't create instructor for the course." render action: 'new' and return end else flash[:error] = "Course creation failed. Check all fields" render action: 'new' and return end end def show redirect_to course_assessments_url(@course) end action_auth_level :edit, :instructor def edit end action_auth_level :update, :instructor def update if @course.update(edit_course_params) then flash[:success] = "Success: Course info updated." redirect_to edit_course_path(@course) else flash[:error] = "Error: There were errors editing the course." end end # DELETE courses/:id/ action_auth_level :destroy, :administrator def destroy if !current_user.administrator? flash[:error] = "Permission denied." redirect_to courses_path and return end course = Course.find(params[:id]) if course.nil? flash[:error] = "Course doesn't exist." redirect_to courses_path and return end course.destroy flash[:success] = "Course destroyed." redirect_to courses_path and return end # Non-RESTful Routes Below def report_bug if request.post? CourseMailer.bug_report( params[:title], params[:summary], current_user, @course ).deliver end end # Only instructor (and above) can use this feature # to look up user accounts and fill in cud fields action_auth_level :userLookup, :instructor def userLookup if params[:email].length == 0 then flash[:error] = "No email supplied for LDAP Lookup" render action: :new, layout: false and return end # make sure that user already exists in the database user = User.where(email: params[:email]).first if user.nil? then render json: nil and return end @user_data = { :first_name => user.first_name, :last_name=> user.last_name, :email => user.email } return render json: @user_data end private def new_course_params params.require(:newCourse).permit(:name, :semester) end def edit_course_params params.require(:editCourse).permit(:name, :semester, :late_slack, :grace_days, :display_name, :start_date, :end_date, :disabled, :exam_in_progress, :version_threshold, :gb_message, late_penalty_attributes: [:kind, :value], version_penalty_attributes: [:kind, :value]) end def categorize_courses_for_listing(courses) listing = {} listing[:disabled] = [] # temporal listing[:current] = [] listing[:completed] = [] listing[:upcoming] = [] # categorize courses.each do |course| if course.disabled? listing[:disabled] << course else listing[course.temporal_status] << course end end listing end end
require 'spec_helper' describe StripBuilder do subject { described_class.new } describe :exists? do it 'should return true when exists a strip with this number' do create :strip, number: 1 subject.exists?(1).should be_true end it 'should return false when do not exists a strip with this number' do subject.exists?(1).should be_false end end describe :latest do before do latest = File.new Rails.root.join 'spec/fixtures/latest.html' stub_request(:get, 'www.malvados.com.br').to_return(body: latest, status: 200) end it 'should return the latest strip number' do subject.latest.should eq 666 end end describe :previous do it 'should return the previous strip number' do create :strip, number: 666 subject.previous(666).should == 665 end context :exceptions do it 'TODO: remember which strip has the wrong latest' end end describe :build do let(:base_url){ subject.settings[:base_url] } let(:strip){ subject.build number } let(:modified){ Time.now.utc } let(:number){ 666 } context "should create a strip with parsed content with" do before do stub_strip number, 'index_with_header', modified end it(:number){ strip[:number].should eq 666 } it(:previous){ strip[:previous].should eq 665 } it(:updated_at){ strip[:updated_at].equal? modified } it(:header){ strip[:header].should eq "#{base_url}logo#{number}.gif" } it(:image){ strip[:image].should eq "#{base_url}tirinha#{number}.gif" } end context 'exeptions' do it 'should handle not have a header image' do stub_strip number, 'index_without_header', modified strip[:header].should be_nil end it 'should have different url when number is 123' do stub_strip 123, 'index_with_header', modified, 'htm' subject.build 123 WebMock.should have_requested(:get, "#{base_url}index123.htm") end end end private def stub_strip number, fixture, modified_date, extension = 'html' body = File.new Rails.root.join "spec/fixtures/#{fixture}.html" stub_request(:get, "http://www.malvados.com.br/index#{number}.#{extension}") .to_return(body: body, status: 200, header: { last_modified: modified_date }) end end
class ChangePriceToBeFloatInProducts < ActiveRecord::Migration[5.2] def change change_column :products, :price, :float end # rollback def down change_column :products, :price, :integer end end
class Word @@words =[] attr_reader(:name, :definitions, :id) def initialize attributes @name = attributes[:name] @definitions = [] @id = @@words.length + 1 end def add_definition definition @definitions<<definition end def save @@words<<self end def self.all @@words end def self.clear @@words = [] end def self.find identification @@words.each do |word| if word.id == identification return word end end end end
class AddRoundToCompetitionMatches < ActiveRecord::Migration[4.2] def change add_column :competition_matches, :round, :integer, null: true, default: nil end end
require_relative 'snack.rb' class Pack attr_accessor :pack_size, :items PACK_SIZE = 5 def initialize @pack_size = PACK_SIZE @items = [] end def add_item(item) @items.push(item) end def remove_item(item) @items.delete(item) end def list_items @items.each do | item | item.describe_item end end end
class UserMailer < ActionMailer::Base FEEDBACK_EMAIL = "dorotawnuk11@o2.pl" def feedback_email(feedback) @feedback = feedback mail(:from => feedback.username, :to => FEEDBACK_EMAIL, :subject => "Skauting Jurajski - Wiadomość z serwisu") end end
# frozen_string_literal: true class CreateBasketItems < ActiveRecord::Migration[5.2] def change create_table :basket_items do |table| table.belongs_to :basket, index: true table.integer :count table.belongs_to :product_item, index: true table.belongs_to :product, index: true table.timestamps end end end
def caesar_cipher(str, factor) result = '' #puts "\nString: #{str} Factor: #{factor}" str.each_char do |c| char_num = c.ord if char_num < 66 || char_num > 122 # Special character #printf "#{c}" result << c next end if (65..90).include?(char_num) # Upper case leters char_num += factor char_num = char_num > 90 ? char_num - 26 : char_num #printf"#{char_num.chr}" result << char_num.chr next elsif (97..122).include?(char_num) # Lower case letter char_num += factor char_num = char_num > 122 ? char_num - 26 : char_num #printf"#{char_num.chr}" result << char_num.chr next end end return result end
# == Schema Information # # Table name: votes # # id :integer not null, primary key # user_id :integer # match_id :integer # yes :boolean # created_at :datetime not null # updated_at :datetime not null # class VotesController < ApplicationController include ApplicationHelper skip_before_filter :verify_authenticity_token def create if check_token get_params Vote.match_vote(@vote_params) if @vote_params[:match_id] u = User.find(@vote_params[:user_id]) if u.uid != nil resp = u.get_votable_match resp['fb_connected'] = true render json: resp.to_json else render json: {'fb_connected': false} end else render json: {status: 401} end end private def get_params @vote_params = params.permit(:user_id, :match_id, :yes) end end
require File.join( File.dirname( __FILE__ ), "..", "spec_helper" ) class Configurator describe Client do context "guessing SCM" do before :each do @basedir = Client::REPOSITORY_BASE_DIRECTORY @ip = "192.168.0.1" @node = mock( "node" ) @node.stub!( :name ).and_return( "NODE_NAME" ) @node.stub!( :ip_address ).and_return( @ip ) @ssh = mock( "ssh" ) SSH.stub!( :new ).and_return( @ssh ) end it "should determine that SCM is Mercurial" do @ssh.should_receive( :sh ).with( @ip, "ls -1 -d /var/lib/lucie/ldb/.*" ).and_return( "/var/lib/lucie/ldb/.hg" ) Client.guess_scm( @node ).should == "Mercurial" end it "should determine that SCM is Git" do @ssh.should_receive( :sh ).with( @ip, "ls -1 -d /var/lib/lucie/ldb/.*" ).and_return( "/var/lib/lucie/ldb/.git" ) Client.guess_scm( @node ).should == "Git" end it "should determine that SCM is Subversion" do @ssh.should_receive( :sh ).with( @ip, "ls -1 -d /var/lib/lucie/ldb/.*" ).and_return( "/var/lib/lucie/ldb/.svn" ) Client.guess_scm( @node ).should == "Subversion" end it "should raise if failed to determine SCM" do @ssh.should_receive( :sh ).with( @ip, "ls -1 -d /var/lib/lucie/ldb/.*" ).and_return( "/var/lib/lucie/ldb/.unknown" ) lambda do Client.guess_scm( @node ) end.should raise_error( "Cannot determine SCM used on NODE_NAME:/var/lib/lucie/ldb" ) end end context "creating a configuration repository clone on a client" do before :each do @ssh = mock( "ssh" ).as_null_object SSH.stub!( :new ).and_return( @ssh ) end it "should create a configurator base directory if not found" do @ssh.should_receive( :sh ).with( "CLIENT_IP", "test -d /var/lib/lucie/config" ).and_raise( "test -d failed" ) @ssh.should_receive( :sh ).with( "CLIENT_IP", "mkdir -p /var/lib/lucie/config" ) Client.new( :mercurial ).install "SERVER_IP", "CLIENT_IP", "ssh://myrepos.org//lucie" end it "should not create a configurator base directory if found" do @ssh.should_receive( :sh ).with( "CLIENT_IP", "test -d /var/lib/lucie/config" ) Client.new( :mercurial ).install "SERVER_IP", "CLIENT_IP", "ssh://myrepos.org//lucie" end it "should make a clone repository on the client" do ssh = mock( "ssh" ).as_null_object SSH.stub!( :new ).and_return( ssh ) Configuration.stub!( :temporary_directory ).and_return( "/tmp/lucie" ) ssh.should_receive( :sh_a ).with( "DUMMY_CLIENT_IP", /^scp/ ) Client.new( :mercurial ).install "DUMMY_SERVER_IP", "DUMMY_CLIENT_IP", "ssh://myrepos.org//lucie" end end context "updating configuration repository" do it "should update configuration repository" do ssh = mock( "ssh" ).as_null_object SSH.stub!( :new ).and_return( ssh ) ssh.stub!( :sh ).with( "DUMMY_IP_ADDRESS", "ls -1 /var/lib/lucie/config" ).and_return( "LDB_CHECKOUT_DIRECTORY" ) ssh.should_receive( :sh_a ).with( "DUMMY_IP_ADDRESS", /hg pull/ ) ssh.should_receive( :sh_a ).with( "DUMMY_IP_ADDRESS", /hg update/ ) Client.new( :mercurial ).update "DUMMY_IP_ADDRESS", "SERVER_IP" end end context "starting configuration process" do it "should execute configuration tool" do ssh = mock( "ssh" ) SSH.stub!( :new ).and_return( ssh ) ssh.stub!( :sh ).with( "DUMMY_IP_ADDRESS", "ls -1 /var/lib/lucie/config" ).and_return( "LDB_CHECKOUT_DIRECTORY" ) ssh.should_receive( :sh_a ).with( "DUMMY_IP_ADDRESS", /make$/ ) Client.new.start "DUMMY_IP_ADDRESS" end end end end ### Local variables: ### mode: Ruby ### coding: utf-8 ### indent-tabs-mode: nil ### End:
# frozen_string_literal: true class Product < ApplicationRecord belongs_to :provider has_many :purchases end
class Song attr_accessor :name, :artist def initialize(name) @name = name end def self.new_by_filename(file) temp=file.split(" - ") temp[1] = temp[1].split(".")[0] new_song = Artist.find_or_create_by_name(temp[0]).add_song(temp[1]) new_song end end
# # Cookbook Name:: aet # Recipe:: activemq # # AET Cookbook # # Copyright (C) 2016 Cognifide Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This recipe is based on ActiveMQ on Supermarket, but allows for much more # customization and is way more secure. # PREREQUISITES ############################################################################### include_recipe 'java::default' # INSTALLATION ############################################################################### # Create dedicated group group node['aet']['activemq']['group'] do action :create end # Create dedicated user user node['aet']['activemq']['user'] do group node['aet']['activemq']['group'] system true shell '/bin/bash' action :create end # Create root dir for ActiveMQ directory node['aet']['activemq']['root_dir'] do owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] mode '0755' recursive true end # Create root dir for Logs directory node['aet']['activemq']['log_dir'] do owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] recursive true end # Get ActiveMQ binaries file name from link filename = get_filename(node['aet']['activemq']['source']) # Download ActiveMQ binaries remote_file "#{node['aet']['activemq']['root_dir']}/#{filename}" do owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] mode '0644' source node['aet']['activemq']['source'] end # Get ActiveMQ binaries filename after extraction basename = ::File.basename(filename, '-bin.tar.gz') # Extract ActiveMQ binaries execute 'extract activemq' do command "tar xvf #{node['aet']['activemq']['root_dir']}/#{filename}" cwd node['aet']['activemq']['root_dir'] user node['aet']['activemq']['user'] group node['aet']['activemq']['group'] not_if do ::File.exist?("#{node['aet']['activemq']['root_dir']}/"\ "#{basename}/bin/activemq") end end # Pre check to stop service before updating symlink # This is required because graceful shutdown requires old directory execute 'symlink-check' do command 'echo' action :run notifies :stop, 'service[activemq]', :immediately not_if do ::File.identical?( "#{node['aet']['activemq']['root_dir']}/current", "#{node['aet']['activemq']['root_dir']}/#{basename}" ) end end # Create link from extracted folder with version in name to universal one link "#{node['aet']['activemq']['root_dir']}/current" do to "#{node['aet']['activemq']['root_dir']}/#{basename}" end # Change permissions on activemq main file file "#{node['aet']['activemq']['root_dir']}/current/bin/activemq" do owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] mode '0755' end # Create ActiveMQ init file template "#{node['aet']['activemq']['root_dir']}/current/bin/env" do source 'content/activemq/current/bin/env.erb' owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] cookbook node['aet']['activemq']['src_cookbook']['env'] mode '0755' notifies :restart, 'service[activemq]', :delayed end # Link init file link '/etc/init.d/activemq' do to "#{node['aet']['activemq']['root_dir']}/current/bin/activemq" end # Overwrite ActiveMQ core settings template "#{node['aet']['activemq']['root_dir']}/current/conf/activemq.xml" do source 'content/activemq/current/conf/activemq.xml.erb' owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] cookbook node['aet']['activemq']['src_cookbook']['activemq_xml'] mode '0644' notifies :restart, 'service[activemq]', :delayed end # Overwrite ActiveMQ logging settings template "#{node['aet']['activemq']['root_dir']}/current"\ '/conf/log4j.properties' do source 'content/activemq/current/conf/log4j.properties.erb' owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] cookbook node['aet']['activemq']['src_cookbook']['log4j_prop'] mode '0644' notifies :restart, 'service[activemq]', :delayed end # Overwrite ActiveMQ credentials template "#{node['aet']['activemq']['root_dir']}/current"\ '/conf/jetty-realm.properties' do source 'content/activemq/current/conf/jetty-realm.properties.erb' owner node['aet']['activemq']['user'] group node['aet']['activemq']['group'] cookbook node['aet']['activemq']['src_cookbook']['jetty_prop'] mode '0644' notifies :restart, 'service[activemq]', :delayed end # Start and enable ActiveMQ service service 'activemq' do supports restart: true, status: true action [:enable, :start] end
class User < ActiveRecord::Base has_many :adventurers has_many :items, through: :adventurers has_many :battles, through: :adventurers has_many :enemies, through: :adventurers @@prompt = TTY::Prompt.new def self.main_menu_sign_in puts "Sign in or create new account below: " username_input = @@prompt.ask("username:", active_color: :red) User.find_or_create_by(name: username_input) end def create_adventurer adventurer_choice = @@prompt.select("Choose your adventurer type:", ["Juggernaut", "Street Rat", "Warrior", "Tax Collector", "Con Artist"], active_color: :cyan) system("clear") case adventurer_choice when "Juggernaut" luck = [1, 2].sample new_adventurer = Adventurer.create(class_type: "Juggernaut", atk: [2, 3].sample + luck, blk: [5, 6, 7].sample + luck, hp: [5, 6, 7].sample + luck, luck: luck, currency: [3, 4, 5].sample) juggernaut() sleep(1.5) when "Street Rat" luck = [1, 2].sample new_adventurer = Adventurer.create(class_type: "Street Rat", atk: [14, 15, 16].sample + luck, blk: [2, 3].sample + luck, hp: [2, 3].sample + luck, luck: luck, currency: [1, 2].sample) street_rat() sleep(1.5) when "Warrior" luck = [1, 2].sample new_adventurer = Adventurer.create(class_type: "Warrior", atk: [5, 6, 7].sample + luck, blk: [3, 4, 5].sample + luck, hp: [5, 6, 7].sample + luck, luck: luck, currency: [3, 4, 5].sample) warrior() sleep(1.5) when "Tax Collector" luck = [1, 2].sample new_adventurer = Adventurer.create(class_type: "Tax Collector", atk: [1, 2].sample + luck, blk: [1, 2].sample + luck, hp: [1, 2].sample + luck, luck: luck, currency: [14, 15, 16].sample) tax_collector() sleep(1.5) when "Con Artist" luck = [5, 6, 7].sample new_adventurer = Adventurer.create(class_type: "Con Artist", atk: [2, 3].sample + luck, blk: [2, 3].sample + luck, hp: [2, 3].sample + luck, luck: luck, currency: [5, 6, 7].sample) con_artist() sleep(1.5) end self.adventurers << new_adventurer new_adventurer.update(base_atk: new_adventurer.atk, base_blk: new_adventurer.blk, base_hp: new_adventurer.hp, base_luck: new_adventurer.luck, base_currency: new_adventurer.currency) new_adventurer end ## LEADERBOARDS ================================================= def self.leaderboard puts "LEADERBOARD".center(112) puts "" puts "" puts "Total Treks completed: #{self.treks_completed}".center(112) puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~".center(112) puts "Total Successful Treks: #{self.total_successful_treks}".center(112) puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~".center(112) puts "Total Losing Treks: #{self.total_losing_treks}".center(112) puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~".center(112) puts "Most Winning Users:".center(112) self.top_five_users puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~".center(112) puts "" puts "" puts "" puts "" puts "" puts "" end def self.treks_completed total_adventurers = self.all.map{|user| user.adventurers.count}.sum end def self.all_adventurers self.all.map{|user| user.adventurers }.flatten end def self.total_losing_treks all_adventurers.select{|adventurer| adventurer.result == "lose"}.count end def self.total_successful_treks all_adventurers.select{|adventurer| adventurer.result == "win"}.count end def single_user_win_count adventurers.all.select{|adventurers| adventurers.result == "win"}.count end def self.top_five_users all_users_compiled_with_wins = self.all.map{|user| {username: user.name, win_count: user.single_user_win_count}} all_users_wins = all_users_compiled_with_wins.sort_by{|user| user[:win_count]} puts "#{all_users_wins[-1][:username]}: #{all_users_wins[-1][:win_count]} wins".center(112) puts "#{all_users_wins[-2][:username]}: #{all_users_wins[-2][:win_count]} wins".center(112) puts "#{all_users_wins[-3][:username]}: #{all_users_wins[-3][:win_count]} wins".center(112) puts "#{all_users_wins[-4][:username]}: #{all_users_wins[-4][:win_count]} wins".center(112) puts "#{all_users_wins[-5][:username]}: #{all_users_wins[-5][:win_count]} wins".center(112) end ## MUSIC ====================================================== def self.starting_music pid = fork{exec 'afplay', "./title.mp3"} end def self.exploration_music pid = fork{exec 'afplay', "./exploration.mp3"} end def self.shop_music pid = fork{exec 'afplay', "./shop.mp3"} end def self.ambush_music pid = fork{exec 'afplay', "./Ambush!.mp3"} end def self.game_over_music pid = fork{exec 'afplay', "./Gameover.mp3"} end def self.victory_music pid = fork{exec 'afplay', "./victory.mp3"} end def self.castle_music pid = fork{exec 'afplay', "./castle_intro.mp3"} end def self.boss_victory_music pid = fork{exec 'afplay', "./boss_victory_music.mp3"} end def self.boss_fight_music pid = fork{exec 'afplay', "./boss.mp3"} end def self.news_music pid = fork{exec 'afplay', "./news.mp3"} end def self.stop_music pid = fork{exec 'killall', "afplay"} sleep(0.01) end end
require 'test_helper' class BlockFieldBlockPartsControllerTest < ActionDispatch::IntegrationTest setup do @block_field_block_part = block_field_block_parts(:one) end test "should get index" do get block_field_block_parts_url assert_response :success end test "should get new" do get new_block_field_block_part_url assert_response :success end test "should create block_field_block_part" do assert_difference('BlockFieldBlockPart.count') do post block_field_block_parts_url, params: { block_field_block_part: { block_field_id: @block_field_block_part.block_field_id, block_part_id: @block_field_block_part.block_part_id } } end assert_redirected_to block_field_block_part_url(BlockFieldBlockPart.last) end test "should show block_field_block_part" do get block_field_block_part_url(@block_field_block_part) assert_response :success end test "should get edit" do get edit_block_field_block_part_url(@block_field_block_part) assert_response :success end test "should update block_field_block_part" do patch block_field_block_part_url(@block_field_block_part), params: { block_field_block_part: { block_field_id: @block_field_block_part.block_field_id, block_part_id: @block_field_block_part.block_part_id } } assert_redirected_to block_field_block_part_url(@block_field_block_part) end test "should destroy block_field_block_part" do assert_difference('BlockFieldBlockPart.count', -1) do delete block_field_block_part_url(@block_field_block_part) end assert_redirected_to block_field_block_parts_url end end
require 'minitest/autorun' require './lib/task_store' class TestTaskStore < Minitest::Test def setup sleep 0.2 @my_store = TaskStore.new @my_own_store = TaskStore.new(101) end def test_initialize assert_match(/\/tmp\//, @my_store.path) # a /tmp/ path has been called assert_equal(@my_own_store.path,"./userdata/101.yml") end def test_determine_path # if an ID is passed, I'll get back /userdata/<id> assert_equal(@my_store.determine_path(123),"./userdata/123.yml") # if no ID is passed, I'll get back /tmp/<something> assert_match(/.\/tmp\/\d*.yml/, @my_store.determine_path) end def test_delete_path @my_store.delete_path assert_nil(@my_store.path) end end
require 'rails_helper' feature 'user can add new clinician' do background do visit new_clinician_path end scenario "user adds new clinician with valid information" do expect(page).to have_content("New Clinician Information") fill_in "clinician_first_name", with: "David" fill_in "clinician_last_name", with: "Liang" fill_in "clinician_practice_name", with: "The Stanford University Center for Marfan Syndrome and Aortic Disorders" fill_in "clinician_address_line_1", with: "Stanford University Medical Center Cardiology Clinic, 2nd Floor of Main Hospital" fill_in "clinician_address_line_2", with: "300 Pasteur Drive" fill_in "clinician_address_line_3", with: "Room H2157" fill_in "clinician_city", with: "Stanford" fill_in "clinician_state", with: "CA" fill_in "clinician_postal_code", with: "94305" fill_in "clinician_country", with: "United States" click_button "Add New Clinician" expect(page).to have_content("Clinician Liang, David successfully added!") expect(page).to have_content("All Clinicians") end scenario "user adds new clinician with invalid information" do expect(page).to have_content("New Clinician Information") fill_in "clinician_first_name", with: "Abraham" fill_in "clinician_last_name", with: "Lincoln" click_button "Add New Clinician" expect(page).to have_content("Please re-check information and/or fill required fields.") expect(page).to have_content("New Clinician Information") end end
WIN_COMBINATIONS = [ [0,1,2], #top row [3,4,5], #middle row [6,7,8], #bottom row [0,3,6], #first column [1,4,7], #second column [2,5,8], #third column [0,4,8], #diagonal from left top down [6,4,2] #diagonal from right top down ] def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts " ----------- " puts " #{board[3]} | #{board[4]} | #{board[5]} " puts " ----------- " puts " #{board[6]} | #{board[7]} | #{board[8]} " end def move(board, input, current_player = "X") board[input.to_i-1] = current_player end def position_taken?(board, location) board[location] != " " && board[location] != "" end def valid_move?(board, position) !position_taken?(board, position.to_i-1) && position.to_i.between?(1,9) end def turn(board) puts "Please enter 1-9:" input = gets.strip if valid_move?(board, input) move(board, input, current_player(board)) else turn(board) end display_board(board) end def play(board) until over?(board) == true turn(board) end if draw?(board) puts "Cats Game!" elsif winner(board) == "X" puts "Congratulations X!" elsif winner(board) == "O" puts "Congratulations O!" end end def turn_count(board) board.count{|space| space == "O" || space == "X"} end def current_player(board) if turn_count(board) % 2 == 0 return "X" else return "O" end end def won?(board) WIN_COMBINATIONS.each do |wincombo| win1 = wincombo[0] win2 = wincombo[1] win3 = wincombo[2] position1 = board[win1] position2 = board[win2] position3 = board[win3] if position1 == "X" && position2 == "X" && position3 == "X" return wincombo elsif position1 == "O" && position2 == "O" && position3 == "O" return wincombo end end false end def full?(board) board.all? do |index| index == "X" || index == "O" end end def draw?(board) if !(won?(board)) && full?(board) true else false end end def over?(board) if won?(board) || draw?(board) || full?(board) true else false end end def winner(board) winning_location = won?(board) if winning_location board[winning_location[0]] else return nil end end
require "rails_helper" RSpec.describe BulkApiImport::Importer do before { FactoryBot.create(:facility) } # needed for our bot import user describe "#import" do let(:organization) { FactoryBot.build_stubbed(:organization) } let(:facility) { Facility.first } let(:facility_identifier) do create(:facility_business_identifier, facility: facility, identifier_type: :external_org_facility_id) end let(:patient) { build_stubbed(:patient) } let(:patient_identifier) do build_stubbed(:patient_business_identifier, patient: patient, identifier_type: :external_import_id) end it "imports patient resources" do resources = 2.times.map do build_patient_import_resource .merge(managingOrganization: [{value: facility_identifier.identifier}]) .except(:registrationOrganization) end expect { described_class.new(resource_list: resources).import } .to change(Patient, :count).by(2) end it "imports appointment resources" do resources = 2.times.map do build_appointment_import_resource.merge( appointmentOrganization: {identifier: facility_identifier.identifier}, appointmentCreationOrganization: nil ) end expect { described_class.new(resource_list: resources).import } .to change(Appointment, :count).by(2) end it "imports observation resources" do resources = [ build_observation_import_resource(:blood_pressure) .merge(performer: [{identifier: facility_identifier.identifier}], subject: {identifier: patient_identifier.identifier}), build_observation_import_resource(:blood_sugar) .merge(performer: [{identifier: facility_identifier.identifier}], subject: {identifier: patient_identifier.identifier}) ] expect { described_class.new(resource_list: resources).import } .to change(BloodPressure, :count).by(1) .and change(BloodSugar, :count).by(1) .and change(Encounter, :count).by(2) .and change(Observation, :count).by(2) end it "imports medication request resources" do resources = 2.times.map do build_medication_request_import_resource.merge( performer: {identifier: facility_identifier.identifier}, subject: {identifier: patient_identifier.identifier} ) end expect { described_class.new(resource_list: resources).import } .to change(PrescriptionDrug, :count).by(2) end it "imports condition resources" do resources = 2.times.map do build_condition_import_resource.merge( subject: {identifier: patient_identifier.identifier} ) end expect { described_class.new(resource_list: resources).import } .to change(MedicalHistory, :count).by(2) end end describe "#resource_importer" do it "fetches the correct importer" do importer = described_class.new(resource_list: []) [ {input: {resourceType: "Patient"}, expected_importer: BulkApiImport::FhirPatientImporter}, {input: {resourceType: "Appointment"}, expected_importer: BulkApiImport::FhirAppointmentImporter}, {input: {resourceType: "Observation"}, expected_importer: BulkApiImport::FhirObservationImporter}, {input: {resourceType: "MedicationRequest"}, expected_importer: BulkApiImport::FhirMedicationRequestImporter}, {input: {resourceType: "Condition"}, expected_importer: BulkApiImport::FhirConditionImporter} ].each do |input:, expected_importer:| expect(importer.resource_importer(input)).to be_an_instance_of(expected_importer) end end end end
class CreateDrawOnAssets < ActiveRecord::Migration def change create_table :draw_on_assets do |t| t.string :draw_on_asset_file_name t.string :draw_on_asset_content_type t.integer :draw_on_asset_file_size t.datetime :draw_on_asset_updated_at t.integer :si_draw_on_id t.timestamps end end end
begin load_script 'rubyctest.so' rescue Exception => e report_exception(e) flag_error(e) end
require 'spec_helper' describe "User confirmation requests" do # Request a new confirmation token describe "POST /users/confirmation" do let(:user) { create :user, :unconfirmed } subject{ post user_confirmation_url, email: user.unconfirmed_email, format: :json } context 'if successfully sent' do it 'resends confirmation email to the user' do expect_any_instance_of(User).to receive :resend_confirmation_instructions subject email = MandrillMailer::deliveries.detect { |mail| mail.template_name == 'confirmation-instructions' && mail.message['to'].any? { |to| to[:email] == user.unconfirmed_email } } expect(email).to_not eq nil end it 'responds with 201' do expect(subject).to eq 201 end end context 'if the user is not found' do before { allow(user).to receive(:unconfirmed_email).and_return :foo } it 'responds with 422' do expect(subject).to eq 422 end end end # Confirm the account describe 'GET /users/confirmation?confirmation_token=foo' do let(:user) { create :user, :unconfirmed } let(:confirmation_token) do # Required because the raw token is not available outside of the class. # This is a bit of a hack. raw_confirmation_token, db_confirmation_token = Devise.token_generator.generate(User, :confirmation_token) user.update_attributes!(confirmation_token: db_confirmation_token) raw_confirmation_token end subject { get user_confirmation_url(confirmation_token: confirmation_token, format: :json) } it 'changes an unconfirmed user to confirmed' do expect{ subject }.to change{ user.reload.confirmed? }.to true end it '200s an already confirmed user' do user = create(:user) user.confirm! expect(subject).to eq 200 end context 'if the confirmation token is unknown' do let(:confirmation_token) { 'fooo' } it 'responds with 422' do expect(subject).to eq 422 end end end end
require_relative '../helpers/dependency_graph' module OpenBEL module ConfigurePlugins def check_configuration(plugins, config) sorted_plugin_config_ids = build_dependency_graph(config) all_errors = [] valid_plugins = {} sorted_plugin_config_ids.each do |plugin_config_id| # validate plugin configuration... plugin_config = config[plugin_config_id.to_s] # ...check plugin defines required properties ['type', 'plugin'].each do |p| errors << %Q{The "#{p}" property (defined in "#{plugin_config_id}") does not define a type.} unless plugin_config.has_key?(p) next end type = plugin_config['type'] plugin_id = plugin_config['plugin'] # ...check if any plugin(s) are loaded for specified type if plugins.none? { |p| p.type.to_s.to_sym == type.to_s.to_sym } errors << %Q{The "#{type}" type (defined in "#{plugin_config_id}") does not have any registered plugins.} end # ...check if plugin exists plugin = plugins.find { |p| p.id == plugin_id } unless plugin errors << %Q{The "#{plugin_id}" plugin (defined in "#{plugin_config_id}") does not have any registered plugins.} end # ...check plugin extensions extensions = plugin_config['extensions'] || {} extensions.values.find_all { |ext| not valid_plugins.has_key? ext.to_s }.each do |ext| all_errors << %Q{The "#{ext}" extension (defined in "#{plugin_config_id}") is not valid.} end # ...prepare extensions/options for plugin validation extensions = Hash[extensions.map { |ext_type, ext_id| [ext_type.to_s.to_sym, valid_plugins[ext_id.to_s]] }] options = Hash[(plugin_config['options'] || {}).map { |k, v| [k.to_s.to_sym, v] }] # ...call plugin-specific validation plugin_errors = [plugin.validate(extensions.dup, options.dup)].flatten.map(&:to_s) if plugin_errors.empty? valid_plugins[plugin_config_id.to_s] = plugin else all_errors.concat(plugin_errors) end # TODO Log successful plugin check if verbose. end all_errors end def configure_plugins(plugins, config) sorted_plugin_config_ids = build_dependency_graph(config) sorted_plugin_config_ids.inject({}) { |plugins_by_id, plugin_config_id| plugin_config = config[plugin_config_id.to_s] plugin_id = plugin_config['plugin'] plugin = plugins.find { |p| p.id == plugin_id } extensions = Hash[(plugin_config['extensions'] || {}).map { |type, id| [type.to_s.to_sym, plugins_by_id[id.to_s]] }] options = Hash[(plugin_config['options'] || {}).map { |k, v| [k.to_s.to_sym, v] }] plugin.configure(extensions.dup, options.dup) plugin.on_load plugins_by_id[plugin_config_id.to_s] = plugin plugins_by_id } end private def build_dependency_graph(config) dependency_graph = Helpers::DependencyGraph.new config.keys.each do |plugin_key| block = config[plugin_key] dependencies = (block['extensions'] || {}).each_value.to_a.map { |v| v.to_s.to_sym } dependency_graph.add_dependency(plugin_key.to_s, *dependencies) end dependency_graph.tsort end end end
class Store class EmployeeLockersController < StoreController load_and_authorize_resource def create @employee_locker = EmployeeLocker.new(employee_locker_params) @employee_locker.products = @employee_locker.locker.products @employee_locker.save @employee_locker.locker.update_columns(status: 'occupé') end def update if @employee_locker.total_price == @employee_locker.locker.total_price @employee_locker.employee.lockers.update_all(status: 'libre') @employee_locker.update(employee_locker_params) @employee_locker.products = @employee_locker.locker.products @employee_locker.save @employee_locker.locker.update_columns(status: 'occupé') render 'create.js' else flash[:error] = "Impossible: il y'a des pertes dans le casier précédent" render 'reload.js' end end def lost @employee_locker.update(employee_locker_params) end private def employee_locker_params params.require(:employee_locker).permit(:employee_id, :locker_id, :status, :product_ids => []) end end end
require "net/http" require "tasks/scripts/refresh_bsnl_sms_jwt" require "tasks/scripts/get_bsnl_template_details" require "tasks/scripts/get_bsnl_account_balance" # Usage instructions at: doc/howto/bsnl/sms_reminders.md namespace :bsnl do desc "Fetch a fresh JWT for BSNL Bulk SMS and overwrite the old token" task refresh_sms_jwt: :environment do service_id = ENV["BSNL_SERVICE_ID"] username = ENV["BSNL_USERNAME"] password = ENV["BSNL_PASSWORD"] token_id = ENV["BSNL_TOKEN_ID"] RefreshBsnlSmsJwt.new(service_id, username, password, token_id).call end desc "Get BSNL template details from the API" task get_template_details: :environment do GetBsnlTemplateDetails.new.write_to_config end desc "List pending notification strings to be uploaded to DLT and BSNL dashboard" task notification_strings_summary: :environment do GetBsnlTemplateDetails.new.notification_strings_summary end desc "Fetch BSNL account balance" task get_account_balance: :environment do GetBsnlAccountBalance.new.print end desc "Fetch BSNL account balances and alert if we're running low or close to expiry" task alert_on_low_balance: :environment do GetBsnlAccountBalance.new.alert end end
#encoding: utf-8 class SpecimenTypeVersion < ActiveRecord::Base # Constants # Put here constants for SpecimenTypeVersion # Relations belongs_to :specimen_type # Callbacks # Put here custom callback methods for SpecimenTypeVersion # Validations # validates :specimen_type, <validations> # validates :name, <validations> # validates :data, <validations> # Scopes (used for search form) # Put here custom queries for SpecimenTypeVersion scope :by_name, ->(name) { where("name ILIKE ?", "%#{name}%") } # Scope for search # Instance methods # Override to_s method def to_s "#{name} (#{created_at.to_formatted_s(:short)})" end end
require 'rails_helper' RSpec.describe 'team creation' do # As a user # When I visit a competition's show page # Then I see a link to register a new team # When I click this link # Then I am taken to a new page where I see a form # When I fill in this form with a team's hometown and nickname # And I click submit # Then I am redirected back to the competition's show page # And I see the new team I created listed it 'has a link to register a new team' do comp1 = Competition.create!(name: 'Chuck Stuff', location: 'Denver', sport: 'Axe Throwing') visit "/competitions/#{comp1.id}/show" expect(page).to have_link('Register') click_on('Register') expect(current_path).to eq("/competitions/#{comp1.id}/teams/new") end it 'has a link to register a new team' do comp1 = Competition.create!(name: 'Chuck Stuff', location: 'Denver', sport: 'Axe Throwing') visit "/competitions/#{comp1.id}/teams/new" fill_in 'Hometown', with: 'Boulder' fill_in 'Nickname', with: 'Boulderers' click_button 'Submit' expect(current_path).to eq("/competitions/#{comp1.id}/show") expect(page).to have_content('Boulderers') end end
class RemoveUserIdFromDishes < ActiveRecord::Migration[5.0] def change remove_column :dishes, :user_id, :integer end end
class Article < ApplicationRecord validates :title, presence: true, length: { in: 2..100 } validates :text, presence: true, length: { in: 2..1000 } scope :order_by_most_recent, -> { order(updated_at: :desc) } belongs_to :author, class_name: 'User' has_many :votes has_and_belongs_to_many :categories end
class Game SUITS = ["Clubs", "Spades", "Hearts", "Diamonds"] NUMBERS = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"] attr_reader :deck, :player, :dealer def initialize @deck = [] end def create_deck SUITS.each do |suit| NUMBERS.each do |num| @deck << Card.new(suit, num) end end end def shuffle_deck @deck.shuffle! end def hit(hand) hand << @deck.pop end end class Card attr_reader :suit, :number attr_accessor :face_up def initialize(suit, number) @suit = suit @number = number @face_up = false end def flip @face_up = true end end class Player attr_accessor :hand, :total def initialize @hand = [] @total = 0 end end
require "rubygems/cli/filtered" module Gem module CLI class List < Gem::CLI::Filtered def self.active? true end def self.args %w([pattern]) end def self.description "List gems in the repo." end def self.verbs %w(list ls) end def run runtime, args results = narrow(runtime.repo.gems).search args.shift, *requirements versioned results do |name, versions| puts "#{name} (#{versions.join ', '})" end end end end end
FactoryGirl.define do factory :url do name 'http://test.com' end end
class MessagesController < ApplicationController before_action :authenticate_user!, except: [:index] before_action :search_message, only: [:index, :search] def index @q = Message.ransack(params[:q]) @messages = Message.includes(:user).order("created_at DESC") end def new @message_tag = MessageTag.new end def create @message_tag = MessageTag.new(message_params) if @message_tag.valid? @message_tag.save return redirect_to root_path else render :new end end def show @message = Message.find(params[:id]) end def destroy @message = Message.find(params[:id]) if current_user.id == @message.user.id @message.destroy redirect_to root_path end end def search set_search end private def message_params params.require(:message_tag).permit(:title, :message, :whom, :open_plan, :name, :video, images: []).merge(user_id: current_user.id) end def update_message_params params.require(:message).permit(:title, :message, :whom, :open_plan, :name, :video, images: []).merge(user_id: current_user.id) end def search_message @m = Message.ransack(params[:q]) end def set_search @search = Message.ransack(params[:q]) @search_messages = @search.result(distinct: true).order(created_at: "DESC").includes(:user) end end
Given(/^"([^"]*)" has navigated to Google Page$/) do |customer| visit(Google_Page) on(Google_Page).loaded?.should be true @user=customer end When(/^he searches for "([^"]*)"$/) do |query| on(Google_Page).enter_query(query) on(Google_Page).submit end Then(/^System should display "([^"]*)" as result$/) do |title| on(Google_Page_Results).loaded?.should be true on(Google_Page_Results).page_results.include?(title).should == true date = DateTime.now.strftime("%d%b%Y%H%M%S") screenshot = "#{@suser.to_s.gsub(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}#{date}.png" @browser.screenshot.save("#{Dir.pwd}/report/#{screenshot}") end
class Consult < ApplicationRecord has_many :comments belongs_to :user enum question_type: [ :法律咨询, :立案咨询, :司法确认, :案件流程查询, :举报投诉, :信访申诉 ] mount_uploader :attachment, AttachmentUploader end
class PayrollOtherPayment::EmploymentSubsidy include Mongoid::Document include Mongoid::Timestamps field :subsidy_caused, type: Money field :subsidy_paid, type: Money belongs_to :payroll_other_payment end
class WorkoutsController < ApplicationController before_action :authorize def index @workouts = Workout.all flash[:alert] = "HI" end def new @workout = Workout.new end def create @workout = Workout.create(workout_params) @hopper = Hopper.new(style: @workout.style, number_of_movements: @workout.number_of_movements) @workout.hoppers << @hopper @hopper.choose_movements.each { |movement| @workout.movements << movement} @workout.name = @workout.faker @user_id = session[:user_id] @user = User.find_by(id: @user_id) @workout.users << @user if @workout.save redirect_to workout_path(@workout) else redirect_to end end def show @workout = Workout.find_by(id: params[:id]) @hopper = @workout.hoppers.last @reps_array = @hopper.assign_reps(@hopper.workout.movements) @stopwatch = Stopwatch.new end private def workout_params params.require(:workout).permit(:time_domain) end end
namespace :generate do desc 'generate error files' task :errors do on roles(:web) do |_| %w(404 422 500).each do |code| obj = OpenStruct.new code: code template 'error.html.erb', "#{release_path}/public/#{code}.html", obj.instance_eval { binding } end end end end def template(from, to, obj) template_path = File.expand_path("../../../../config/deploy/templates/#{from}", __FILE__) template = ERB.new(File.new(template_path).read).result obj upload! StringIO.new(template), to end after 'deploy', 'generate:errors'
class AddDoneToBetMatch < ActiveRecord::Migration def change add_column :bet_matches, :done, :boolean,:default => false add_column :bet_fixtures, :result, :string end end
class StudentPaymentDecorator < Draper::Decorator delegate_all def charge_value h.number_to_currency(object.charge_value / 100.00) end def month_name object.payment_deadline.strftime("%B") end def payment_deadline object.payment_deadline.strftime("%d %B %Y") end def payment_date object.payment_date ? object.payment_date.strftime("%d %B %Y") : "" end def paid object.paid ? h.t('general.yes') : h.t('general.no') end end
=begin #BombBomb #We make it easy to build relationships using simple videos. OpenAPI spec version: 2.0.831 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.3.1 =end require "uri" module BombBomb class SocialsApi attr_accessor :api_client def initialize(api_client = ApiClient.default) @api_client = api_client end # Gets facebook pages # Gets facebook pages by client id # @param [Hash] opts the optional parameters # @return [nil] def get_facebook_pages(opts = {}) get_facebook_pages_with_http_info(opts) return nil end # Gets facebook pages # Gets facebook pages by client id # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def get_facebook_pages_with_http_info(opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.get_facebook_pages ..." end # resource path local_var_path = "/socials/facebook/pages" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#get_facebook_pages\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Gets the social email properties # Gets the social email properties # @param email_id This is the email Id for the email url # @param social_content_id This is the social content Id # @param [Hash] opts the optional parameters # @return [nil] def get_social_article_properties(email_id, social_content_id, opts = {}) get_social_article_properties_with_http_info(email_id, social_content_id, opts) return nil end # Gets the social email properties # Gets the social email properties # @param email_id This is the email Id for the email url # @param social_content_id This is the social content Id # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def get_social_article_properties_with_http_info(email_id, social_content_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.get_social_article_properties ..." end # verify the required parameter 'email_id' is set if @api_client.config.client_side_validation && email_id.nil? fail ArgumentError, "Missing the required parameter 'email_id' when calling SocialsApi.get_social_article_properties" end # verify the required parameter 'social_content_id' is set if @api_client.config.client_side_validation && social_content_id.nil? fail ArgumentError, "Missing the required parameter 'social_content_id' when calling SocialsApi.get_social_article_properties" end # resource path local_var_path = "/socials/properties" # query parameters query_params = {} query_params[:'emailId'] = email_id query_params[:'socialContentId'] = social_content_id # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#get_social_article_properties\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Get authorizations for all social integration # Get authorizations and autoshares for all social integration and has redirect for user to login # @param [Hash] opts the optional parameters # @option opts [String] :client_group_id ID of the client group association # @return [nil] def get_social_authorizations(opts = {}) get_social_authorizations_with_http_info(opts) return nil end # Get authorizations for all social integration # Get authorizations and autoshares for all social integration and has redirect for user to login # @param [Hash] opts the optional parameters # @option opts [String] :client_group_id ID of the client group association # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def get_social_authorizations_with_http_info(opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.get_social_authorizations ..." end # resource path local_var_path = "/socials/authorizations" # query parameters query_params = {} query_params[:'clientGroupId'] = opts[:'client_group_id'] if !opts[:'client_group_id'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#get_social_authorizations\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Gets the profile properties # Gets the social profile properties # @param social_type The social type # @param [Hash] opts the optional parameters # @return [nil] def get_social_profile_properties(social_type, opts = {}) get_social_profile_properties_with_http_info(social_type, opts) return nil end # Gets the profile properties # Gets the social profile properties # @param social_type The social type # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def get_social_profile_properties_with_http_info(social_type, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.get_social_profile_properties ..." end # verify the required parameter 'social_type' is set if @api_client.config.client_side_validation && social_type.nil? fail ArgumentError, "Missing the required parameter 'social_type' when calling SocialsApi.get_social_profile_properties" end # resource path local_var_path = "/socials/profile" # query parameters query_params = {} query_params[:'socialType'] = social_type # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#get_social_profile_properties\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Get social stats for a prompt # Get social stats for a prompt by id # @param prompt_id ID of the prompt # @param [Hash] opts the optional parameters # @return [nil] def get_social_stats(prompt_id, opts = {}) get_social_stats_with_http_info(prompt_id, opts) return nil end # Get social stats for a prompt # Get social stats for a prompt by id # @param prompt_id ID of the prompt # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def get_social_stats_with_http_info(prompt_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.get_social_stats ..." end # verify the required parameter 'prompt_id' is set if @api_client.config.client_side_validation && prompt_id.nil? fail ArgumentError, "Missing the required parameter 'prompt_id' when calling SocialsApi.get_social_stats" end # resource path local_var_path = "/socials/{promptId}/stats".sub('{' + 'promptId' + '}', prompt_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#get_social_stats\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Creates social content # Creates social content for an email # @param email_id The email&#39;s id # @param [Hash] opts the optional parameters # @return [nil] def post_social_content(email_id, opts = {}) post_social_content_with_http_info(email_id, opts) return nil end # Creates social content # Creates social content for an email # @param email_id The email&#39;s id # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def post_social_content_with_http_info(email_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.post_social_content ..." end # verify the required parameter 'email_id' is set if @api_client.config.client_side_validation && email_id.nil? fail ArgumentError, "Missing the required parameter 'email_id' when calling SocialsApi.post_social_content" end # resource path local_var_path = "/socials/content" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} form_params["emailId"] = email_id # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#post_social_content\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Sends social content # Sends social content that failed for a user via their associated prompt # @param prompt_id The prompt id # @param [Hash] opts the optional parameters # @return [nil] def retry_social_send(prompt_id, opts = {}) retry_social_send_with_http_info(prompt_id, opts) return nil end # Sends social content # Sends social content that failed for a user via their associated prompt # @param prompt_id The prompt id # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def retry_social_send_with_http_info(prompt_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.retry_social_send ..." end # verify the required parameter 'prompt_id' is set if @api_client.config.client_side_validation && prompt_id.nil? fail ArgumentError, "Missing the required parameter 'prompt_id' when calling SocialsApi.retry_social_send" end # resource path local_var_path = "/socials/send/retry" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} form_params["promptId"] = prompt_id # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#retry_social_send\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Sends social content # Sends social content for a user via their associated prompt # @param prompt_id The prompt id # @param social_type The destination for social content # @param [Hash] opts the optional parameters # @return [nil] def send_social(prompt_id, social_type, opts = {}) send_social_with_http_info(prompt_id, social_type, opts) return nil end # Sends social content # Sends social content for a user via their associated prompt # @param prompt_id The prompt id # @param social_type The destination for social content # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def send_social_with_http_info(prompt_id, social_type, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.send_social ..." end # verify the required parameter 'prompt_id' is set if @api_client.config.client_side_validation && prompt_id.nil? fail ArgumentError, "Missing the required parameter 'prompt_id' when calling SocialsApi.send_social" end # verify the required parameter 'social_type' is set if @api_client.config.client_side_validation && social_type.nil? fail ArgumentError, "Missing the required parameter 'social_type' when calling SocialsApi.send_social" end # resource path local_var_path = "/socials/send" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} form_params["promptId"] = prompt_id form_params["socialType"] = social_type # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#send_social\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Gets the auto shares from the client group assoc id # Gets the auto shares from the client group assoc id # @param send_mechanism The send mechanism for the prompt # @param client_group_id ID of the client group association # @param [Hash] opts the optional parameters # @option opts [String] :enabled Is the send mechanism enabled? # @return [nil] def update_client_group_send_mechanism(send_mechanism, client_group_id, opts = {}) update_client_group_send_mechanism_with_http_info(send_mechanism, client_group_id, opts) return nil end # Gets the auto shares from the client group assoc id # Gets the auto shares from the client group assoc id # @param send_mechanism The send mechanism for the prompt # @param client_group_id ID of the client group association # @param [Hash] opts the optional parameters # @option opts [String] :enabled Is the send mechanism enabled? # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def update_client_group_send_mechanism_with_http_info(send_mechanism, client_group_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.update_client_group_send_mechanism ..." end # verify the required parameter 'send_mechanism' is set if @api_client.config.client_side_validation && send_mechanism.nil? fail ArgumentError, "Missing the required parameter 'send_mechanism' when calling SocialsApi.update_client_group_send_mechanism" end # verify the required parameter 'client_group_id' is set if @api_client.config.client_side_validation && client_group_id.nil? fail ArgumentError, "Missing the required parameter 'client_group_id' when calling SocialsApi.update_client_group_send_mechanism" end # resource path local_var_path = "/socials/client/sendMechanism" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} form_params["sendMechanism"] = send_mechanism form_params["clientGroupId"] = client_group_id form_params["enabled"] = opts[:'enabled'] if !opts[:'enabled'].nil? # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#update_client_group_send_mechanism\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Toggles the prompt campaigns in a users account # Toggles the prompt campaigns in a users account for a social integrations on or off # @param send_mechanism The send mechanism for the prompt # @param enabled Is the send mechanism enabled? # @param [Hash] opts the optional parameters # @return [nil] def update_client_groups_send_mechanism(send_mechanism, enabled, opts = {}) update_client_groups_send_mechanism_with_http_info(send_mechanism, enabled, opts) return nil end # Toggles the prompt campaigns in a users account # Toggles the prompt campaigns in a users account for a social integrations on or off # @param send_mechanism The send mechanism for the prompt # @param enabled Is the send mechanism enabled? # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def update_client_groups_send_mechanism_with_http_info(send_mechanism, enabled, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.update_client_groups_send_mechanism ..." end # verify the required parameter 'send_mechanism' is set if @api_client.config.client_side_validation && send_mechanism.nil? fail ArgumentError, "Missing the required parameter 'send_mechanism' when calling SocialsApi.update_client_groups_send_mechanism" end # verify the required parameter 'enabled' is set if @api_client.config.client_side_validation && enabled.nil? fail ArgumentError, "Missing the required parameter 'enabled' when calling SocialsApi.update_client_groups_send_mechanism" end # resource path local_var_path = "/socials/client/sendMechanisms" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} form_params["sendMechanism"] = send_mechanism form_params["enabled"] = enabled # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#update_client_groups_send_mechanism\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Updates facebook page Ids # Updates facebook page Ids to be sent to for prompts # @param page_ids Page Ids for the prompt # @param [Hash] opts the optional parameters # @return [nil] def update_facebook_pages(page_ids, opts = {}) update_facebook_pages_with_http_info(page_ids, opts) return nil end # Updates facebook page Ids # Updates facebook page Ids to be sent to for prompts # @param page_ids Page Ids for the prompt # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def update_facebook_pages_with_http_info(page_ids, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.update_facebook_pages ..." end # verify the required parameter 'page_ids' is set if @api_client.config.client_side_validation && page_ids.nil? fail ArgumentError, "Missing the required parameter 'page_ids' when calling SocialsApi.update_facebook_pages" end # resource path local_var_path = "/socials/facebook/pages" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} form_params["pageIds"] = page_ids # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#update_facebook_pages\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Updates social content # Updates social content for an email # @param social_id The social id # @param [Hash] opts the optional parameters # @option opts [String] :title The title for the article # @option opts [String] :description The article description # @option opts [String] :picture_url The article picture url # @option opts [String] :suggested_message The suggested message to use # @return [nil] def update_social_content(social_id, opts = {}) update_social_content_with_http_info(social_id, opts) return nil end # Updates social content # Updates social content for an email # @param social_id The social id # @param [Hash] opts the optional parameters # @option opts [String] :title The title for the article # @option opts [String] :description The article description # @option opts [String] :picture_url The article picture url # @option opts [String] :suggested_message The suggested message to use # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def update_social_content_with_http_info(social_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: SocialsApi.update_social_content ..." end # verify the required parameter 'social_id' is set if @api_client.config.client_side_validation && social_id.nil? fail ArgumentError, "Missing the required parameter 'social_id' when calling SocialsApi.update_social_content" end # resource path local_var_path = "/socials/content" # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} form_params["socialId"] = social_id form_params["title"] = opts[:'title'] if !opts[:'title'].nil? form_params["description"] = opts[:'description'] if !opts[:'description'].nil? form_params["pictureUrl"] = opts[:'picture_url'] if !opts[:'picture_url'].nil? form_params["suggestedMessage"] = opts[:'suggested_message'] if !opts[:'suggested_message'].nil? # http body (model) post_body = nil auth_names = ['BBOAuth2'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: SocialsApi#update_social_content\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end end end
class ListingsController < ApplicationController before_action :authenticate_user! def index @listings = Listing.all end def new @listing = Listing.new end def create @listing = Listing.new listing_params.merge(user_id: current_user.id) if @listing.save == true flash[:notice] = "You have succesfully created a Listing" redirect_to all_listings_path else render :new end end def edit @listing = Listing.find params[:id] end def update @listing = Listing.find params[:id] if @listing.update_attributes listing_params flash[:notice] = "Listing Updated" redirect_to all_listings_path else render :edit end end def destroy @listing = Listing.find params[:id] @listing.delete flash[:notice] = "Succesfully Deleted" end def show @listing = Listing.find params[:id] end private def listing_params params.require(:listing).permit(:user_id, :address, :city, :state, :lease_start, :lease_length, :lease_type, :rooms, :description, :email, :phone, :photo, :rent, :zipcode, :latitude, :longitude) end end
require_relative "../helpers/validator" require_relative "../helpers/display" require_relative "../helpers/utility" require "pry" class Character include Validator include Display # TODO: Move to Hero class instead. Not sure monsters need this? include Procs include Utility attr_accessor :attack, :defense, :level, :money, :experience, :max_hp attr_reader :name, :class, :main_class, :health def initialize(character_args = {}) # Monsters don't need it, since we are using the dungeon levels to initialize them, # but left it in case monsters may need to level up in the future @level = character_args[:level] || 1 @name = 'Nameless One' @health = character_args[:health] || 100 @max_hp = @health # max_hp and health should be the same when initialized @attack = character_args[:attack] || 10 @defense = character_args[:defense] || 10 @money = character_args[:money] || 0 @experience = character_args[:experience] || 0 @description = character_args[:description] || '' @main_class = self.to_s.match(/^#<(\w+):.*/).captures.first end def health=(new_health) @health = if new_health < 0 0 elsif new_health > @max_hp @max_hp else new_health end end def dead? @health.zero? end def alive? !dead? end # hero.do_damage_to(monster) # monster.do_damage_to(hero) def do_damage_to(receiver) damage = (attack/100.0 * receiver.defense + attack%100.abs * level).ceil receiver.health -= damage damage end end
class Ticket < ActiveRecord::Base belongs_to :project validates :title, :description, presence: true, length: {minimum: 10} end
#!/usr/bin/env ruby # encoding: UTF-8 # # Copyright © 2012-2017 Cask Data, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative 'utils' require 'resolv' class FogProviderAWS < Coopr::Plugin::Provider include FogProvider # plugin defined resources @ssh_key_dir = 'ssh_keys' class << self attr_accessor :ssh_key_dir end def create(inputmap) @flavor = inputmap['flavor'] @image = inputmap['image'] @hostname = inputmap['hostname'] fields = inputmap['fields'] begin # Our fields are fog symbols fields.each do |k, v| instance_variable_set('@' + k, v) end # Update some variables @security_groups = @security_groups.split(',') if @security_groups @security_group_ids = @security_group_ids.split(',') if @security_group_ids # Run EC2 credential validation validate! # Create the server log.debug "Creating #{hostname} on AWS using flavor: #{flavor}, image: #{image}" log.debug 'Invoking server create' server = connection.servers.create(create_server_def) # Process results @result['result']['providerid'] = server.id.to_s @result['result']['ssh-auth']['user'] = @task['config']['sshuser'] || 'root' @result['result']['ssh-auth']['identityfile'] = File.join(Dir.pwd, self.class.ssh_key_dir, @ssh_key_resource) unless @ssh_key_resource.nil? @result['status'] = 0 rescue Excon::Errors::Unauthorized msg = 'Provider credentials invalid/unauthorized' @result['status'] = 201 @result['stderr'] = msg log.error(msg) rescue => e log.error('Unexpected Error Occurred in FogProviderAWS.create: ' + e.inspect) @result['stderr'] = "Unexpected Error Occurred in FogProviderAWS.create: #{e.inspect}" else log.debug "Create finished successfully: #{@result}" ensure @result['status'] = 1 if @result['status'].nil? || (@result['status'].is_a?(Hash) && @result['status'].empty?) end end def confirm(inputmap) providerid = inputmap['providerid'] fields = inputmap['fields'] begin # Our fields are fog symbols fields.each do |k, v| instance_variable_set('@' + k, v) end # Run EC2 credential validation validate! # Confirm server log.debug "Invoking server confirm for id: #{providerid}" server = connection.servers.get(providerid) # Wait until the server is ready fail "Server #{server.id} is in ERROR state" if server.state == 'ERROR' log.debug "Waiting for server to come up: #{providerid}" server.wait_for(600) { ready? } # Get domain name by dropping first dot domainname = @task['config']['hostname'].split('.').drop(1).join('.') hostname = if !server.dns_name.nil? && @provider_hostname server.dns_name elsif !server.public_ip_address.nil? && @provider_hostname Resolv.getname(server.public_ip_address) else @task['config']['hostname'] end # Handle tags hashed_tags = {} @tags.map { |t| key, val = t.split('='); hashed_tags[key] = val } unless @tags.nil? # Always set the Name tag, so we display correctly in AWS console UI unless hashed_tags.keys.include?('Name') hashed_tags['Name'] = hostname end create_tags(hashed_tags, providerid) unless hashed_tags.empty? bootstrap_ip = if server.public_ip_address server.public_ip_address else Resolv.getaddress(server.dns_name) unless server.dns_name.nil? end if bootstrap_ip.nil? log.error 'No IP address available for bootstrapping.' fail 'No IP address available for bootstrapping.' else log.debug "Bootstrap IP address #{bootstrap_ip}" end bind_ip = server.private_ip_address wait_for_sshd(bootstrap_ip, 22) log.debug "Server #{server.id} sshd is up" # Process results @result['ipaddresses'] = { 'access_v4' => bootstrap_ip, 'bind_v4' => bind_ip } @result['hostname'] = hostname @result['result']['ssh_host_keys'] = { 'rsa' => ssh_keyscan(bootstrap_ip) } # do we need sudo bash? sudo = 'sudo -E' unless @task['config']['ssh-auth']['user'] == 'root' set_credentials(@task['config']['ssh-auth']) # login with pseudotty and turn off sudo requiretty option log.debug "Attempting to ssh to #{bootstrap_ip} as #{@task['config']['ssh-auth']['user']} with credentials: #{@credentials} and pseudotty" Net::SSH.start(bootstrap_ip, @task['config']['ssh-auth']['user'], @credentials) do |ssh| sudoers = true begin ssh_exec!(ssh, 'test -e /etc/sudoers', 'Checking for /etc/sudoers') rescue CommandExecutionError log.debug 'No /etc/sudoers file present' sudoers = false end cmd = "#{sudo} sed -i -e '/^Defaults[[:space:]]*requiretty/ s/^/#/' /etc/sudoers" ssh_exec!(ssh, cmd, 'Disabling requiretty via pseudotty session', true) if sudoers end # Validate connectivity Net::SSH.start(bootstrap_ip, @task['config']['ssh-auth']['user'], @credentials) do |ssh| ssh_exec!(ssh, 'ping -c1 www.google.com', 'Validating external connectivity and DNS resolution via ping') ssh_exec!(ssh, "#{sudo} hostname #{hostname}", "Setting hostname to #{hostname}") # Setting up disks log.debug 'Starting disk configuration' if server.root_device_type == 'ebs' log.debug 'EBS-backed instance detected...' begin extfs = true ssh_exec!(ssh, "mount | grep xvde | awk '{print $5}' | grep -e 'ext[3-4]'", 'Checking filesystem') rescue extfs = false end if extfs log.debug 'File-system is EXT3/EXT4' # resize2fs is safe to execute ssh_exec!(ssh, "test -x /sbin/resize2fs && #{sudo} /sbin/resize2fs /dev/xvde", 'Resizing filesystem') end else log.debug 'Instance store detected...' begin # m1.small uses /dev/xvda2 for data xvda = true xvdb = false xvdc = false ssh_exec!(ssh, 'test -e /dev/xvda2', 'Checking for /dev/xvda2') rescue xvda = false begin xvdb = true ssh_exec!(ssh, 'test -e /dev/xvdb', 'Checking for /dev/xvdb') # Do we have /dev/xvdc, too? begin xvdc = true ssh_exec!(ssh, 'test -e /dev/xvdc', 'Checking for /dev/xvdc') rescue xvdc = false end rescue xvdb = false end end log.debug 'Found the following:' log.debug "- xvda = #{xvda}" log.debug "- xvdb = #{xvdb}" log.debug "- xvdc = #{xvdc}" # Now, do the right thing if xvdc # Check for APT begin apt = true ssh_exec!(ssh, 'which apt-get', 'Checking for apt-get') rescue apt = false end # Install mdadm if apt ssh_exec!(ssh, "#{sudo} apt-get update", 'Running apt-get update') # Setup nullmailer ssh_exec!(ssh, "echo 'nullmailer shared/mailname string localhost' | #{sudo} debconf-set-selections && echo 'nullmailer nullmailer/relayhost string localhost' | #{sudo} debconf-set-selections", 'Configuring nullmailer') ssh_exec!(ssh, "#{sudo} apt-get install nullmailer -y", 'Installing nullmailer') ssh_exec!(ssh, "#{sudo} apt-get install mdadm -y", 'Installing mdadm') else ssh_exec!(ssh, "#{sudo} yum install mdadm -y", 'Installing mdadm') end ssh_exec!(ssh, "mount | grep ^/dev/xvdb 2>&1 >/dev/null && #{sudo} umount /dev/xvdb || true", 'Unmounting /dev/xvdb') # Setup RAID log.debug 'Setting up RAID0' ssh_exec!(ssh, "echo yes | #{sudo} mdadm --create /dev/md0 --level=0 --raid-devices=$(ls -1 /dev/xvd[b-z] | wc -l) $(ls -1 /dev/xvd[b-z])", 'Creating /dev/md0 RAID0 array') if apt ssh_exec!(ssh, "#{sudo} su - -c 'mdadm --detail --scan >> /etc/mdadm/mdadm.conf'", 'Write /etc/mdadm/mdadm.conf') else ssh_exec!(ssh, "#{sudo} su - -c 'mdadm --detail --scan >> /etc/mdadm.conf'", 'Write /etc/mdadm.conf') end ssh_exec!(ssh, "#{sudo} sed -i -e 's:xvdb:md0:' /etc/fstab", 'Update /etc/fstab for md0') ssh_exec!(ssh, "#{sudo} /sbin/mkfs.ext4 /dev/md0 && #{sudo} mkdir -p /data && #{sudo} mount -o _netdev /dev/md0 /data", 'Mounting /dev/md0 as /data') elsif xvdb ssh_exec!(ssh, "mount | grep ^/dev/xvdb 2>&1 >/dev/null && #{sudo} umount /dev/xvdb && #{sudo} /sbin/mkfs.ext4 /dev/xvdb && #{sudo} mkdir -p /data && #{sudo} mount -o _netdev /dev/xvdb /data", 'Mounting /dev/xvdb as /data') elsif xvda ssh_exec!(ssh, "mount | grep ^/dev/xvda2 2>&1 >/dev/null && #{sudo} umount /dev/xvda2 && #{sudo} /sbin/mkfs.ext4 /dev/xvda2 && #{sudo} mkdir -p /data && #{sudo} mount -o _netdev /dev/xvda2 /data", 'Mounting /dev/xvda2 as /data') else log.debug 'No additional instance store disks detected' end ssh_exec!(ssh, "#{sudo} sed -i -e 's:/mnt:/data:' /etc/fstab", 'Updating /etc/fstab for /data') end end # disable SELinux Net::SSH.start(bootstrap_ip, @task['config']['ssh-auth']['user'], @credentials) do |ssh| cmd = "if test -x /usr/sbin/sestatus ; then #{sudo} /usr/sbin/sestatus | grep disabled || ( test -x /usr/sbin/setenforce && #{sudo} /usr/sbin/setenforce Permissive ) ; fi" ssh_exec!(ssh, cmd, 'Disabling SELinux') end # Return 0 @result['status'] = 0 rescue Fog::Errors::TimeoutError log.error 'Timeout waiting for the server to be created' @result['stderr'] = 'Timed out waiting for server to be created' rescue Net::SSH::AuthenticationFailed => e log.error("SSH Authentication failure for #{providerid}/#{bootstrap_ip}") @result['stderr'] = "SSH Authentication failure for #{providerid}/#{bootstrap_ip}: #{e.inspect}" rescue => e log.error('Unexpected Error Occurred in FogProviderAWS.confirm: ' + e.inspect) @result['stderr'] = "Unexpected Error Occurred in FogProviderAWS.confirm: #{e.inspect}" else log.debug "Confirm finished successfully: #{@result}" ensure @result['status'] = 1 if @result['status'].nil? || (@result['status'].is_a?(Hash) && @result['status'].empty?) end end def delete(inputmap) providerid = inputmap['providerid'] fields = inputmap['fields'] begin # Our fields are fog symbols fields.each do |k, v| instance_variable_set('@' + k, v) end begin # Run EC2 credential validation validate! rescue log.warn 'Credential validation failed, assuming nothing created, setting providerid to nil' providerid = nil end # Delete server log.debug 'Invoking server delete' begin fail ArgumentError if providerid.nil? || providerid.empty? server = connection.servers.get(providerid) server.destroy rescue ArgumentError log.debug "Invalid provider id #{providerid} specified on delete... skipping" rescue NoMethodError log.warn "Could not locate server '#{providerid}'... skipping" end # Return 0 @result['status'] = 0 rescue => e log.error('Unexpected Error Occurred in FogProviderAWS.delete: ' + e.inspect) @result['stderr'] = "Unexpected Error Occurred in FogProviderAWS.delete: #{e.inspect}" else log.debug "Delete finished sucessfully: #{@result}" ensure @result['status'] = 1 if @result['status'].nil? || (@result['status'].is_a?(Hash) && @result['status'].empty?) end end # Shared definitions (borrowed from knife-ec2 gem, Apache 2.0 license) def connection # Create connection # rubocop:disable UselessAssignment @connection ||= begin connection = Fog::Compute.new( provider: 'AWS', aws_access_key_id: @api_user, aws_secret_access_key: @api_password, region: @aws_region ) end # rubocop:enable UselessAssignment end def iam_name_from_profile(profile) # The IAM profile object only contains the name as part of the arn if profile && profile.key?('arn') name = profile['arn'].split('/')[-1] end name || '' end def validate!(keys = [@api_user, @api_password]) errors = [] # Check for credential file and load it unless @aws_credential_file.nil? unless (keys & [@api_user, @api_password]).empty? errors << 'Either provide a credentials file or the access key and secret keys but not both.' end # File format: # AWSAccessKeyId=somethingsomethingdarkside # AWSSecretKey=somethingsomethingcomplete entries = Hash[*File.read(@aws_credential_file).split(/[=\n]/).map(&:chomp)] @aws_access_key_id = entries['AWSAccessKeyId'] @aws_secret_access_key = entries['AWSSecretKey'] end # Validate keys keys.each do |k| pretty_key = k.to_s.gsub(/_/, ' ').gsub(/\w+/) { |w| (w =~ /(ssh)|(aws)/i) ? w.upcase : w.capitalize } errors << "You did not provide a valid '#{pretty_key}' value." if k.nil? end # Check for errors fail 'Credential validation failed!' if errors.each { |e| log.error(e) }.any? end def vpc_mode? # Amazon Virtual Private Cloud requires a subnet_id !@subnet_id.nil? end def ami @ami ||= connection.images.get(@image) end def tags tags = @tags if !tags.nil? && tags.length != tags.to_s.count('=') log.error 'Tags should be entered in a key=value pair' fail 'Tags should be entered in a key=value pair' end tags end def create_server_def server_def = { flavor_id: @flavor, image_id: @image, groups: @security_groups, security_group_ids: @security_group_ids, key_name: @ssh_keypair, availability_zone: @availability_zone, placement_group: @placement_group, iam_instance_profile_name: @iam_instance_profile } server_def[:subnet_id] = @subnet_id if vpc_mode? server_def[:tenancy] = 'dedicated' if vpc_mode? && @dedicated_instance server_def[:associate_public_ip] = 'true' if vpc_mode? && @associate_public_ip fail 'Invalid AMI specified' if ami.nil? # Handle EBS-backed volume sizes if ami.root_device_type == 'ebs' ami_map = ami.block_device_mapping.first root_ebs_size = if @aws_root_ebs_size Integer(@aws_root_ebs_size).to_s elsif @aws_ebs_size Integer(@aws_ebs_size).to_s else ami_map['volumeSize'].to_s end root_delete_term = if @aws_root_ebs_delete_on_term || @aws_ebs_delete_on_term 'true' else 'false' end server_def[:block_device_mapping] = [{ 'DeviceName' => ami_map['deviceName'], 'Ebs.DeleteOnTermination' => root_delete_term, 'Ebs.VolumeSize' => root_ebs_size, 'Ebs.VolumeType' => @aws_root_ebs_volume_type }] end server_def end def create_tags(hashed_tags, providerid) hashed_tags.each_pair do |key, val| connection.tags.create key: key, value: val, resource_id: providerid end end end
class List < ApplicationRecord validates :title, presence: true has_many :list_words, dependent: :destroy has_many :words, through: :list_words, source: :word has_many :definitions, through: :words, source: :definitions has_many :examples, through: :words, source: :examples has_many :user_lists, dependent: :destroy has_many :users, through: :user_lists, source: :user def self.create_list(user, arg_words, list) ActiveRecord::Base.transaction do list.save! list.user_lists.create!(user_id: user.id) arg_words.each do |arg_word| word = Word.find_by_word(arg_word) word.list_words.create!(list_id: list.id) if word end end end end
class Computer < Player def move(board) if !board.taken?('5')#If middle isn't taken '5'#take middle (cell[5-1]) else best_move(board) + 1 #select the best move #Add 1 to offset index value returned by best_move(board) end end def best_move(board) win(board) || block(board) || corner(board) || random #Go for Win or Block a win or Select a Corner or Random #in order of prefrence end def corner(board) [0,2,6,8].detect{|cell| !board.taken?(cell+1)} #find the first corner that isnt taken and move #Add 1 because taken? method refers to string, not index #index = cell, cell + 1 = string end def complete_combo?(board, token) #check if win combo is near completion Game::WIN_COMBINATIONS.detect do |combo| ( (board.cells[combo[0]] == token && board.cells[combo[1]] == token) && !board.taken?(combo[2]+1) ) || ( (board.cells[combo[1]] == token && board.cells[combo[2]] == token) && !board.taken?(combo[0]+1) ) || ( (board.cells[combo[0]] == token && board.cells[combo[2]] == token) && !board.taken?(combo[1]+1) ) end end def win(board) # puts "...checking for win for #{token} on #{board.cells}" winning_combo = complete_combo?(board, self.token) if winning_combo && winning_combo.count{|index| board.position(index+1) == self.token} == 2 puts "...found winning combo #{winning_combo}" winning_combo.detect{|index| !board.taken?(index+1)} #check if computer combo is near completion #Win (fill remaining index with self.token end end def block(board) # puts "...checking for block for #{token} on #{board.cells}" blocking_combo = complete_combo?(board, self.opponent_token) if blocking_combo && blocking_combo.count{|index| board.position(index+1) == self.opponent_token} == 2 puts "...found blocking combo #{blocking_combo}" blocking_combo.detect{|index| !board.taken?(index+1)} #check if an opponent combo is near completion #Block (fill remaining index with self.token) end end def opponent_token self.token == "X" ? "O" : "X" # determine opponent's token and set computer token to opposite end def random (0..8).to_a.sample #make an array of 0-8, and sample(random) end end
class PeopleMailingAddress < ActiveRecord::Base belongs_to :people belongs_to :mailing_address end
Gem::Specification.new do |s| s.name = %q{rollcall-xmpp} s.version = "0.0.1" s.authors = ["Matt Zukowski"] s.date = %q{2012-05-17} s.summary = %q{Rollcall plugin for automatically creating XMPP accounts via in-band registration} s.email = %q{matt dot zukowski at utoronto dot ca} s.files = `git ls-files`.split("\n") s.homepage = %q{http://github.com/educoder/rollcall-xmpp} s.rdoc_options = ["--main", "README"] s.require_paths = ["lib"] s.rubyforge_project = %q{rollcall-xmpp} s.add_dependency("xmpp4r") end
require 'rails_helper' describe Activity, type: :model do it 'is valid with a name' do activity = Activity.new(name: "runjumping") expect(activity).to be_valid end it 'is invalid without a name' do activity = Activity.new activity.valid? expect(activity.errors[:name]).to include("can't be blank") end end
# frozen_string_literal: true class RemoveFieldsFromAttendanceAndAddOthers < ActiveRecord::Migration[4.2] def change remove_column :attendances, :address, :string remove_column :attendances, :neighbourhood, :string remove_column :attendances, :twitter_user, :string remove_column :attendances, :zipcode, :string add_column :attendances, :organization_size, :string add_column :attendances, :job_role, :string add_column :attendances, :years_of_experience, :string add_column :attendances, :experience_in_agility, :string add_column :attendances, :school, :string add_column :attendances, :education_level, :string end end
# -*- encoding: utf-8 -*- module SendGrid4r::REST # # SendGrid Web API v3 Mail # module Mail Personalization = Struct.new( :to, :subject, :cc, :bcc, :headers, :substitutions, :custom_args, :send_at ) do def to=(to) tap { |s| s[:to] = to.map(&:to_h) } end def cc=(cc) tap { |s| s[:cc] = cc.map(&:to_h) } end def bcc=(bcc) tap { |s| s[:bcc] = bcc.map(&:to_h) } end def send_at=(send_at) tap { |s| s[:send_at] = send_at.to_i } end def to_h super.reject { |_key, value| value.nil? } end end end end
# == Schema Information # # Table name: discussions # # id :integer not null, primary key # title :string # description :text # created_at :datetime not null # updated_at :datetime not null # class Discussion < ActiveRecord::Base belongs_to :user belongs_to :project has_many :comments, dependent: :destroy validates :title, presence: true end
require "application_system_test_case" class ClassPeriodsTest < ApplicationSystemTestCase setup do @class_period = class_periods(:one) end test "visiting the index" do visit class_periods_url assert_selector "h1", text: "Class Periods" end test "creating a Class period" do visit class_periods_url click_on "New Class Period" fill_in "Attendance count", with: @class_period.attendance_count fill_in "Date", with: @class_period.date fill_in "Week day", with: @class_period.week_day click_on "Create Class period" assert_text "Class period was successfully created" click_on "Back" end test "updating a Class period" do visit class_periods_url click_on "Edit", match: :first fill_in "Attendance count", with: @class_period.attendance_count fill_in "Date", with: @class_period.date fill_in "Week day", with: @class_period.week_day click_on "Update Class period" assert_text "Class period was successfully updated" click_on "Back" end test "destroying a Class period" do visit class_periods_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Class period was successfully destroyed" end end
require 'rails_helper' describe Item, type: :model do describe "validations" do it { should validate_presence_of :name } it { should validate_presence_of :description } it { should validate_presence_of :price } it { should validate_presence_of :image } it { should validate_presence_of :inventory } # it { should validate_inclusion_of(:active?).in_array([true,false]) } it "should default to active" do @bike_shop = Merchant.create(name: "Brian's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80203) @chain = @bike_shop.items.create(name: "Chain", description: "It'll never break!", price: 50, image: "https://www.rei.com/media/b61d1379-ec0e-4760-9247-57ef971af0ad?size=784x588", inventory: 5) expect(@chain.active?).to eq(true) end end describe "relationships" do it {should belong_to :merchant} it {should have_many :reviews} it {should have_many :item_orders} it {should have_many(:orders).through(:item_orders)} end describe "instance methods" do before(:each) do @bike_shop = Merchant.create(name: "Brian's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80203) @chain = @bike_shop.items.create(name: "Chain", description: "It'll never break!", price: 50, image: "https://www.rei.com/media/b61d1379-ec0e-4760-9247-57ef971af0ad?size=784x588", inventory: 5) @review_1 = @chain.reviews.create(title: "Great place!", content: "They have great bike stuff and I'd recommend them to anyone.", rating: 5) @review_2 = @chain.reviews.create(title: "Cool shop!", content: "They have cool bike stuff and I'd recommend them to anyone.", rating: 4) @review_3 = @chain.reviews.create(title: "Meh place", content: "They have meh bike stuff and I probably won't come back", rating: 1) @review_4 = @chain.reviews.create(title: "Not too impressed", content: "v basic bike shop", rating: 2) @review_5 = @chain.reviews.create(title: "Okay place :/", content: "Brian's cool and all but just an okay selection of items", rating: 3) end it "calculate average review" do expect(@chain.average_review).to eq(3.0) end it "sorts reviews" do top_three = @chain.sorted_reviews(3,:desc) bottom_three = @chain.sorted_reviews(3,:asc) expect(top_three).to eq([@review_1,@review_2,@review_5]) expect(bottom_three).to eq([@review_3,@review_4,@review_5]) end it 'no orders' do expect(@chain.no_orders?).to eq(true) order = Order.create(name: 'Meg', address: '123 Stang Ave', city: 'Hershey', state: 'PA', zip: 17033) order.item_orders.create(item: @chain, price: @chain.price, quantity: 2) expect(@chain.no_orders?).to eq(false) end it 'quantity ordered' do brian = Merchant.create(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210) pull_toy = brian.items.create(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32) order_1 = Order.create!(name: 'Meg', address: '123 Stang Ave', city: 'Hershey', state: 'PA', zip: 17033) order_2 = Order.create!(name: 'Yo', address: 'Whatever', city: 'Place', state: 'PA', zip: 17033) order_1.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 4) order_2.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 3) expect(pull_toy.quantity_ordered(pull_toy.id)).to eq(7) end it 'never ordered?' do dog_shop = Merchant.create!(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210) merchant = User.create!(name: 'Jim', address: '456 Blah Blah Blvd', city: 'Denver', state: 'CO', zip: '12345', email: 'regularjim@me.com', password: 'alsosecret', role: 1, merchant_id: dog_shop.id) pull_toy = dog_shop.items.create!(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32) dog_bone = dog_shop.items.create!(name: "Dog Bone", description: "They'll love it!", price: 21, image: "https://img.chewy.com/is/image/catalog/54226_MAIN._AC_SL1500_V1534449573_.jpg", inventory: 21) order_1 = Order.create!(name: 'Meg', address: '123 Stang Ave', city: 'Hershey', state: 'PA', zip: 17033) order_1.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 4) expect(dog_bone.never_ordered?).to eq(true) expect(pull_toy.never_ordered?).to eq(false) end it '#fulfilled?' do dog_shop = Merchant.create!(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210) merchant = User.create!(name: 'Jim', address: '456 Blah Blah Blvd', city: 'Denver', state: 'CO', zip: '12345', email: 'regularjim@me.com', password: 'alsosecret', role: 1, merchant_id: dog_shop.id) pull_toy = dog_shop.items.create!(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32) dog_bone = dog_shop.items.create!(name: "Dog Bone", description: "They'll love it!", price: 21, image: "https://img.chewy.com/is/image/catalog/54226_MAIN._AC_SL1500_V1534449573_.jpg", inventory: 21) kong = dog_shop.items.create!(name: "Kong", description: "Tasty treat!", price: 10, image: "https://images-na.ssl-images-amazon.com/images/I/719dcnCnHfL._AC_SL1500_.jpg", inventory: 50) bed = dog_shop.items.create!(name: "Dog Bed", description: "Sleepy time!", price: 21, image: "https://images-na.ssl-images-amazon.com/images/I/71IvYiQYcAL._AC_SY450_.jpg", inventory: 40) order = Order.create!(name: 'Meg', address: '123 Stang Ave', city: 'Hershey', state: 'PA', zip: 17033, status: 'Pending') pull = order.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 4) order.item_orders.create!(item: kong, price: kong.price, quantity: 51) expect(pull_toy.fulfilled?(order.id)).to eq(false) pull.status = true pull.save expect(pull_toy.fulfilled?(order.id)).to eq(true) end it '#insufficient_quantity?' do dog_shop = Merchant.create!(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210) merchant = User.create!(name: 'Jim', address: '456 Blah Blah Blvd', city: 'Denver', state: 'CO', zip: '12345', email: 'regularjim@me.com', password: 'alsosecret', role: 1, merchant_id: dog_shop.id) pull_toy = dog_shop.items.create!(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32) dog_bone = dog_shop.items.create!(name: "Dog Bone", description: "They'll love it!", price: 21, image: "https://img.chewy.com/is/image/catalog/54226_MAIN._AC_SL1500_V1534449573_.jpg", inventory: 21) kong = dog_shop.items.create!(name: "Kong", description: "Tasty treat!", price: 10, image: "https://images-na.ssl-images-amazon.com/images/I/719dcnCnHfL._AC_SL1500_.jpg", inventory: 50) bed = dog_shop.items.create!(name: "Dog Bed", description: "Sleepy time!", price: 21, image: "https://images-na.ssl-images-amazon.com/images/I/71IvYiQYcAL._AC_SY450_.jpg", inventory: 40) order = Order.create!(name: 'Meg', address: '123 Stang Ave', city: 'Hershey', state: 'PA', zip: 17033, status: 'Pending') pull = order.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 4) order.item_orders.create!(item: kong, price: kong.price, quantity: 51) expect(kong.insufficient_quantity?(order.id)).to eq(true) expect(pull_toy.insufficient_quantity?(order.id)).to eq(false) end end describe 'class methods' do it '.top_five' do meg = Merchant.create(name: "Meg's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80203) brian = Merchant.create(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210) tire = meg.items.create(name: "Gatorskins", description: "They'll never pop!", price: 100, image: "https://www.rei.com/media/4e1f5b05-27ef-4267-bb9a-14e35935f218?size=784x588", inventory: 12) pull_toy = brian.items.create(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32) dog_bone = brian.items.create(name: "Dog Bone", description: "They'll love it!", price: 21, image: "https://img.chewy.com/is/image/catalog/54226_MAIN._AC_SL1500_V1534449573_.jpg", active?:false, inventory: 21) bike_pump = meg.items.create(name: "Bike Pump", description: "To pump it up!", price: 25, image: "https://images-na.ssl-images-amazon.com/images/I/615GENPCD5L._AC_SX425_.jpg", inventory: 15) bike_chain = meg.items.create(name: "Bike Chain", description: "Better chainz!", price: 75, image: "https://images-na.ssl-images-amazon.com/images/I/51cafKW0NgL._AC_.jpg", inventory: 75) bike_tool = meg.items.create(name: "Bike Tool", description: "Make it tight!", price: 30, image: "https://www.rei.com/media/product/718804", inventory: 100) kong = brian.items.create(name: "Kong", description: "Tasty treat!", price: 10, image: "https://images-na.ssl-images-amazon.com/images/I/719dcnCnHfL._AC_SL1500_.jpg", inventory: 50) bed = brian.items.create(name: "Dog Bed", description: "Sleepy time!", price: 21, image: "https://images-na.ssl-images-amazon.com/images/I/71IvYiQYcAL._AC_SY450_.jpg", inventory: 40) order_1 = Order.create!(name: 'Meg', address: '123 Stang Ave', city: 'Hershey', state: 'PA', zip: 17033) order_2 = Order.create!(name: 'Yo', address: 'Whatever', city: 'Place', state: 'PA', zip: 17033) order_1.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 4) order_2.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 3) order_1.item_orders.create!(item: tire, price: tire.price, quantity: 6) order_2.item_orders.create!(item: bed, price: bed.price, quantity: 5) order_1.item_orders.create!(item: kong, price: kong.price, quantity: 4) order_1.item_orders.create!(item: bike_tool, price: bike_tool.price, quantity: 3) order_2.item_orders.create!(item: bike_chain, price: bike_chain.price, quantity: 2) order_2.item_orders.create!(item: bike_pump, price: bike_pump.price, quantity: 1) expect(Item.all.top_five).to eq([pull_toy, tire, bed, kong, bike_tool]) end it '.bottom_five' do meg = Merchant.create(name: "Meg's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80203) brian = Merchant.create(name: "Brian's Dog Shop", address: '125 Doggo St.', city: 'Denver', state: 'CO', zip: 80210) tire = meg.items.create(name: "Gatorskins", description: "They'll never pop!", price: 100, image: "https://www.rei.com/media/4e1f5b05-27ef-4267-bb9a-14e35935f218?size=784x588", inventory: 12) pull_toy = brian.items.create(name: "Pull Toy", description: "Great pull toy!", price: 10, image: "http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg", inventory: 32) dog_bone = brian.items.create(name: "Dog Bone", description: "They'll love it!", price: 21, image: "https://img.chewy.com/is/image/catalog/54226_MAIN._AC_SL1500_V1534449573_.jpg", active?:false, inventory: 21) bike_pump = meg.items.create(name: "Bike Pump", description: "To pump it up!", price: 25, image: "https://images-na.ssl-images-amazon.com/images/I/615GENPCD5L._AC_SX425_.jpg", inventory: 15) bike_chain = meg.items.create(name: "Bike Chain", description: "Better chainz!", price: 75, image: "https://images-na.ssl-images-amazon.com/images/I/51cafKW0NgL._AC_.jpg", inventory: 75) bike_tool = meg.items.create(name: "Bike Tool", description: "Make it tight!", price: 30, image: "https://www.rei.com/media/product/718804", inventory: 100) kong = brian.items.create(name: "Kong", description: "Tasty treat!", price: 10, image: "https://images-na.ssl-images-amazon.com/images/I/719dcnCnHfL._AC_SL1500_.jpg", inventory: 50) bed = brian.items.create(name: "Dog Bed", description: "Sleepy time!", price: 21, image: "https://images-na.ssl-images-amazon.com/images/I/71IvYiQYcAL._AC_SY450_.jpg", inventory: 40) order_1 = Order.create!(name: 'Meg', address: '123 Stang Ave', city: 'Hershey', state: 'PA', zip: 17033) order_2 = Order.create!(name: 'Yo', address: 'Whatever', city: 'Place', state: 'PA', zip: 17033) order_1.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 4) order_2.item_orders.create!(item: pull_toy, price: pull_toy.price, quantity: 3) order_1.item_orders.create!(item: tire, price: tire.price, quantity: 6) order_2.item_orders.create!(item: bed, price: bed.price, quantity: 5) order_1.item_orders.create!(item: kong, price: kong.price, quantity: 4) order_1.item_orders.create!(item: bike_tool, price: bike_tool.price, quantity: 3) order_2.item_orders.create!(item: bike_chain, price: bike_chain.price, quantity: 2) order_2.item_orders.create!(item: bike_pump, price: bike_pump.price, quantity: 1) expect(Item.all.bottom_five).to eq([bike_pump, bike_chain, bike_tool, kong, bed]) end end end
# == Schema Information # # Table name: questions # # id :integer not null, primary key # text :string # isactive :boolean # isspam :boolean # image_url :string # created_at :datetime # updated_at :datetime # user_id :integer # topic_id :integer # class Question < ActiveRecord::Base belongs_to :user belongs_to :topic has_many :answers has_many :comments, :through => :answers validates :text, :presence => true end
class ReservationMailer < ApplicationMailer default from: "libapp517@gmail.com" def reservation_mail(member) @member = member mail(to: @member.email, subject: 'Reservation') end def release_mail(member) @member = member mail(to: @member.email, subject: 'Release room') end end
class AddRoleToTeamUsers < ActiveRecord::Migration def change add_column :team_users, :role, :string end end
class RemoveSequenceFromContact < ActiveRecord::Migration[5.0] def change remove_column :contacts, :sequence, :integer remove_column :contacts, :is_primary, :boolean remove_column :contacts, :is_visible, :boolean end end
describe do attr :published, Date.new(2013, 2, 1) # 1 Feb. 2013 attr :title, "Introduction" attr :is_article, true content file('article/1-introduction.md') end
class AddImageToEventPost < ActiveRecord::Migration[5.1] def change add_column :event_posts, :image_filename, :string end end
class GithubApi PROTOCOL = "https" HOST = "api.github.com" attr_reader :github_user def initialize github_user @github_user = github_user end def self.get github_user, path GithubApi.new(github_user).get(path) end def get path uri = (path =~ /^http(s)?/) ? path : "#{PROTOCOL}://#{HOST}#{path}" RestClient.get(uri, accept: "application/vnd.github.moondragon-preview+json", authorization: "token #{github_user.token}") end end
# Write your code here require 'net/http' require 'open-uri' require 'json' class GetRequester attr_accessor :url def initialize(url_address) self.url = url_address end def get_response_body uri = URI.parse(self.url) response = Net::HTTP.get_response(uri) response.body end def parse_json JSON.parse(self.get_response_body) end end
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require "Countdown" describe "Countdown" do it "should calculate seconds until expiration" do now = Time.now end_time = now + 100 countdown = Countdown.new(end_time) countdown.seconds_until_expiration(now).should == 100 end it "should calculate hours until expiration" do now = Time.now not_yet_1_hour = now + 3599 exactly_1_hour = now + 3600 over_1_hour = now + 3601 countdown = Countdown.new(not_yet_1_hour) countdown.hours_until_expiration(now).should == 0 countdown = Countdown.new(exactly_1_hour) countdown.hours_until_expiration(now).should == 1 countdown = Countdown.new(over_1_hour) countdown.hours_until_expiration(now).should == 1 end it "should calculate days until expiration" do now = Time.now not_yet_1_day = now + 86399 exactly_1_day = now + 86400 over_1_day = now + 86401 countdown = Countdown.new(not_yet_1_day) countdown.days_until_expiration(now).should == 0 countdown = Countdown.new(exactly_1_day) countdown.days_until_expiration(now).should == 1 countdown = Countdown.new(over_1_day) countdown.days_until_expiration(now).should == 1 end it "should return days and hours until expiration" do now = Time.now day_and_1_hour = now + 90000 countdown = Countdown.new(day_and_1_hour) day, hour = countdown.days_and_hours_until_expiration day.should == 1 hour.should == 1 end it "should throw an exeption case the countdown expired" do now = Time.now day_and_1_hour = now - 90000 lambda{Countdown.new(day_and_1_hour)}.should raise_error end end
module Binged class Synonyms include Enumerable attr_reader :client, :query BASE_URI = 'https://api.datamarket.azure.com/Bing/Synonyms/GetSynonyms' # @param [Binged::Client] client # @param [String] query The search term to be sent to Bing def initialize(client, query=nil) @client = client @query = { :Query => [] } related(query) if query && query.strip != '' end def fetch if @fetch.nil? response = perform @fetch = Hashie::Mash.new(response["d"]) end @fetch end # Add query to search # # @param [String] query The search term to be sent to Bing # @return [self] def related(query) @query[:Query] << query self end def perform url = URI.parse BASE_URI query = @query.dup query[:Query] = query[:Query].join(' ') query.each do |key, value| query[key] = %{'#{value}'} unless key[0] == '$' end query_options = default_options.merge(query).to_query query_options.gsub! '%2B', '+' url.query = query_options response = connection.get(url) begin JSON.parse(response.body) rescue JSON::ParserError => e raise StandardError, response.body.strip end end def connection Faraday.new.tap do |faraday| faraday.basic_auth(@client.account_key, @client.account_key) end end # @yieldreturn [Hash] A result from a Bing query def each fetch().results.each { |r| yield r } end private def default_options { '$format' => 'JSON' } end end end
class User < ApplicationRecord has_many :tweets has_many :group_users has_many :groups, through: :group_users end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Search results displays field', type: :system, clean: true do before do solr = Blacklight.default_index.connection solr.add([dog]) solr.commit end let(:dog) do { id: '111', title_tesim: 'Jack or Dan the Bulldog', creator_tesim: 'Me and You', abstract_tesim: 'Binding: white with gold embossing.', alternativeTitle_tesim: 'The Yale Bulldogs', description_tesim: 'in black ink on thin white paper', format: 'three dimensional object', fulltext_tesim: ["fulltext text one.\n\nThis is for dog\n"], callNumber_tesim: 'Osborn Music MS 4', published_ssim: "1997", language_ssim: ['en', 'eng', 'zz'], publisher_tesim: 'Printed for Eric', resourceType_tesim: "Music (Printed & Manuscript)", sourceCreated_tesim: 'The Whale', subjectGeographic_tesim: 'United States--Maps, Manuscript', subjectTopic_tesim: 'Phrenology--United States', subjectName_tesim: 'Price, Leo', visibility_ssi: 'Public' } end context 'Within search results' do subject(:content) { find(:css, '#content') } it 'highlights title when a term is queried' do visit '/catalog?search_field=all_fields&q=Dan' expect(page.html).to include "Jack or <span class='search-highlight'>Dan</span> the Bulldog" end it 'highlights abstract when a term is queried' do visit '/catalog?search_field=all_fields&q=white' expect(page.html).to include "Binding: <span class='search-highlight'>white</span> with gold embossing." end it 'highlights publisher when a term is queried' do visit '/catalog?search_field=all_fields&q=Eric' expect(page.html).to include "Printed for <span class='search-highlight'>Eric</span>" end it 'highlights description when a term is queried' do visit '/catalog?search_field=all_fields&q=white' expect(page.html).to include "in black ink on thin <span class='search-highlight'>white</span> paper" end it 'highlights created source when a term is queried' do visit '/catalog?search_field=all_fields&q=Whale' expect(page.html).to include "The <span class='search-highlight'>Whale</span>" end it 'highlights geographic subject when a term is queried' do visit '/catalog?search_field=all_fields&q=Maps' expect(page.html).to include "United States--<span class='search-highlight'>Maps</span>, Manuscript" end it 'highlights topic subject when a term is queried' do visit '/catalog?search_field=all_fields&q=Phrenology' expect(page.html).to include "<span class='search-highlight'>Phrenology</span>--United States" end it 'highlights author when a term is queried' do visit '/catalog?search_field=all_fields&q=You' expect(page.html).to include "Me and <span class='search-highlight'>You</span>" end it 'highlights name subject when a term is queried' do visit '/catalog?search_field=all_fields&q=Leo' expect(page.html).to include "Price, <span class='search-highlight'>Leo</span>" end it 'highlights the resource type when a term is queried' do visit '/catalog?search_field=all_fields&q=Music' expect(page.html).to include "<span class='search-highlight'>Music</span> (Printed & Manuscript)" end it 'highlights the call number when a term is queried' do visit '/catalog?search_field=all_fields&q=Music' expect(page.html).to include "Osborn <span class='search-highlight'>Music</span> MS 4" end it 'highlights the full text when a term is queried' do visit '/catalog?search_field=fulltext_tesim&q=text' expect(page.html).to include 'fulltext <span class="search-highlight">text</span> one' end it 'highlights the full text when multiple terms are queried' do visit '/catalog?search_field=fulltext_tesim&q=text+dog' expect(page.html).to include 'fulltext <span class="search-highlight">text</span> one. This is for <span class="search-highlight">dog</span>' end end end
require 'prawn_charts/layers/layer' module PrawnCharts module Layers # Provides a generic way for stacking graphs. This may or may not # do what you'd expect under every situation, but it at least kills # a couple birds with one stone (stacked bar graphs and stacked area # graphs work fine). class Stacked < Layer include PrawnCharts::Helpers::LayerContainer # Returns new Stacked graph. # # You can provide a block for easily adding layers during (just after) initialization. # Example: # Stacked.new do |stacked| # stacked << PrawnCharts::Layers::Line.new( ... ) # stacked.add(:bar, 'My Bar', [...]) # end # # The initialize method passes itself to the block, and since stacked is a LayerContainer, # layers can be added just as if they were being added to Graph. def initialize(options={}, &block) super(options) block.call(self) # Allow for population of data with a block during initialization. end # Overrides Base#render to fiddle with layers' points to achieve a stacked effect. def render(pdf, options = {}) #TODO ensure this works with new points current_points = points layers.each do |layer| real_points = layer.points layer.points = current_points layer_options = options.dup layer_options[:color] = layer.preferred_color || layer.color || options[:theme].next_color layer.render(pdf, layer_options) options.merge(layer_options) layer.points = real_points layer.points.each_with_index { |val, idx| current_points[idx] -= val } end end # A stacked graph has many data sets. Return legend information for all of them. def legend_data if relevant_data? retval = [] layers.each do |layer| retval << layer.legend_data end retval else nil end end # TODO, special points accessor def points longest_arr = layers.inject(nil) do |longest, layer| longest = layer.points if (longest.nil? || longest.size < layer.points.size) longest end summed_points = (0...longest_arr.size).map do |idx| layers.inject(nil) do |sum, layer| if sum.nil? && !layer.points[idx].nil? sum = layer.points[idx] elsif !layer.points[idx].nil? sum += layer.points[idx] end sum end end summed_points end def points=(val) throw ArgumentsError, "Stacked layers cannot accept points, only other layers." end end # Stacked end # Layers end # PrawnCharts
module HashSyntax Token = Struct.new(:type, :body, :line, :col) do # Unpacks the token from Ripper and breaks it into its separate components. # # @param [Array<Array<Integer, Integer>, Symbol, String>] token the token # from Ripper that we're wrapping def initialize(token) (self.line, self.col), self.type, self.body = token end def width body.size end def reg_desc if type == :on_op && body == '=>' 'hashrocket' else type.to_s.sub(/^on_/, '') end end end end
class ChangeInstockFromProduceOrderItems < ActiveRecord::Migration def change change_column :produce_order_items, :instock, :string change_column :produce_order_items, :quantity, :string end end