text
stringlengths
10
2.61M
RSpec.feature "Users can view an activity's 'Change History' within a tab" do context "as a partner organisation user" do let(:user) { create(:partner_organisation_user) } let(:programme) { create(:programme_activity) } let(:activity) { create(:project_activity, organisation: user.organisation, parent: programme) } let(:report) do create( :report, :active, organisation: programme.organisation, fund: programme.parent, financial_quarter: 3, financial_year: 2020 ) end let(:reference) { "Update to Activity purpose" } let(:changes) do {"title" => ["Original title", "Updated title"], "description" => ["Original description", "Updated description"]} end before do authenticate!(user: user) end after { logout } def setup_historical_events(report:) HistoryRecorder .new(user: user) .call( changes: changes, activity: activity, trackable: activity, reference: reference, report: report ) end def expect_to_see_change_history_with_reference(reference:, events:) fail "We expect to see some Historical Events!" if events.empty? within ".historical-events .historical-event-group" do expect(page).to have_css(".historical_event", count: events.count) expect(page).to have_css(".reference", text: reference) expect(page).to have_css(".user", text: events.first.user.email) expect(page).to have_css(".timestamp", text: events.first.created_at.strftime("%d %b %Y at %R")) events.each do |event| within "#historical_event_#{event.id}" do expect(page).to have_css(".property", text: event.value_changed) expect(page).to have_css(".previous-value", text: event.previous_value) expect(page).to have_css(".new-value", text: event.new_value) if event.report expect(page).to have_css( ".report a[href='#{report_path(event.report)}']", text: event.report.financial_quarter_and_year ) end end end end end scenario "the activities page contains a _Change History_ tab" do setup_historical_events(report: report) visit organisation_activity_path(activity.organisation, activity) click_link "Change history" expect(page).to have_css("h2", text: t("page_title.activity.change_history")) expect(page).to have_content(t("page_content.tab_content.change_history.guidance")) expect_to_see_change_history_with_reference( events: HistoricalEvent.last(2), reference: reference ) end context "when the history is not associated with a report" do scenario "the _Change History_ is represented without error" do setup_historical_events(report: nil) visit organisation_activity_path(activity.organisation, activity) click_link "Change history" expect_to_see_change_history_with_reference( events: HistoricalEvent.last(2), reference: reference ) end end end end
class RemoveProjectFeedback < ActiveRecord::Migration[5.2] def change drop_table :project_feedbacks end end
class Height class Parser def initialize(input) @input = input metric_parser = Parsers::Metric.new(@input) imperial_parser = Parsers::Imperial.new(@input) if metric_parser.parsed? @millimeters = metric_parser.millimeters elsif imperial_parser.parsed? @millimeters = imperial_parser.inches.to_millimeters else raise ArgumentError.new("Could not parse `#{@input}` into valid height") end end def millimeters @millimeters end def centimeters millimeters.to_centimeters end def meters millimeters.to_meters end def inches millimeters.to_inches end def feet millimeters.to_feet end end end
module VanityRoutes module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../config", __FILE__) desc "Installs VanityRoutes Config Files" end end end
class AddProfileIdToRoute < ActiveRecord::Migration def change add_column :routes, :route_profile_id, :integer add_index :routes, :route_profile_id end end
module Relix def self.included(klass) super klass.extend ClassMethods end def self.index_types @index_types ||= {} end def self.register_index(index) index_types[index.kind.to_sym] = index end module ClassMethods def relix(&block) @relix ||= IndexSet.new(self, Relix) if block_given? @relix.instance_eval(&block) else @relix end end def lookup(&block) relix.lookup(&block) end def lookup_values(index) relix.lookup_values(index) end def lookup_count(index, value=nil) relix.count(index, value) end def deindex_by_primary_key!(pk) relix.deindex_by_primary_key!(pk) end end def relix self.class.relix end def index! relix.index!(self) end def deindex! relix.deindex!(self) end class Error < StandardError; end end
class Vote < ActiveRecord::Base belongs_to :user belongs_to :song validates_uniqueness_of :user_id, :scope => :song_id end
require 'boxzooka/inbound_cancellation_response_response' module Boxzooka # Response to the InboundCancellationRequest. class InboundCancellationResponse < BaseResponse collection :results, entry_field_type: :entity, entry_node_name: 'Response', entry_type: Boxzooka::InboundCancellationResponseResponse def success? results.all?(&:success?) end end end
require 'rake/rdoctask' namespace :doc do def application_files %w( doc/README_FOR_APP app/**/*.rb lib/**/*.rb ) end def framework_files %w( vendor/rails/railties/CHANGELOG vendor/rails/railties/MIT-LICENSE vendor/rails/activerecord/README vendor/rails/activerecord/CHANGELOG vendor/rails/activerecord/lib/active_record/**/*.rb vendor/rails/actionpack/README vendor/rails/actionpack/CHANGELOG vendor/rails/actionpack/lib/action_controller/**/*.rb vendor/rails/actionpack/lib/action_view/**/*.rb vendor/rails/actionmailer/README vendor/rails/actionmailer/CHANGELOG vendor/rails/actionmailer/lib/action_mailer/base.rb vendor/rails/actionwebservice/README vendor/rails/actionwebservice/CHANGELOG vendor/rails/actionwebservice/lib/action_web_service.rb vendor/rails/actionwebservice/lib/action_web_service/*.rb vendor/rails/actionwebservice/lib/action_web_service/api/*.rb vendor/rails/actionwebservice/lib/action_web_service/client/*.rb vendor/rails/actionwebservice/lib/action_web_service/container/*.rb vendor/rails/actionwebservice/lib/action_web_service/dispatcher/*.rb vendor/rails/actionwebservice/lib/action_web_service/protocol/*.rb vendor/rails/actionwebservice/lib/action_web_service/support/*.rb vendor/rails/activesupport/README vendor/rails/activesupport/CHANGELOG vendor/rails/activesupport/lib/active_support/**/*.rb ) end def plugin_files FileList['vendor/plugins/*/lib/**/*.rb'] + FileList['vendor/plugins/*/README'] end def all_files application_files + framework_files + plugin_files end desc "Build the comprehensive documentation, including the application, the framework and all plugins." Rake::RDocTask.new(:all) do |r| # Configuration options r.rdoc_dir = 'doc/all' r.options << '--line-numbers' << '--inline-source' r.title = "application_files + framework_files + plugin_files" r.template = "#{RAILS_ROOT}/doc/jamis.rb" if File.exist?("#{RAILS_ROOT}/doc/jamis.rb") all_files.each{ |f| r.rdoc_files.include(f) } r.rdoc_files.exclude('vendor/rails/activerecord/lib/active_record/vendor/*') end end
class ConfigGenerator def initialize(application:, database:) @application = application @database = database end def call if env_file_exists? Rails.logger.info "Old .env found. Moving to .env.old... " move_current_env end parse_env_example write_env_file end def parse_env_example contents = `cat #{APP_ROOT}/.env.example` template = ERB.new(contents) @output = template.result(binding) end def env_file_exists? File.file? "#{APP_ROOT}/.env" end def write_env_file File.open("#{APP_ROOT}/.env", "w+") { |f| f.write(output) } end def move_current_env if File.file? "#{APP_ROOT}/.env" `mv #{APP_ROOT}/.env #{APP_ROOT}/.env.old` true else false end end private attr_reader :output, :application, :database end
require 'bcrypt' class Group < ActiveRecord::Base has_many :agents has_many :tasks, as: :giver validates :name, presence: true, uniqueness: true def password @password ||= BCrypt::Password.new(password_hash) end def password=(new_password) @password = BCrypt::Password.create(new_password) self.password_hash = @password end def self.valid?(name, password) group = Group.find_by(name: name) if group && group.password == password group else nil end end end
class UserItem < ActiveRecord::Base validates :user, :item, presence: true validates :item_id, uniqueness: { scope: :user_id } belongs_to :user, inverse_of: :user_items belongs_to :item, inverse_of: :user_items end
#!/usr/bin/env ruby require_relative 'handle_attendees.rb' # read file, create arrays with invalid data and with valid data using the HandleAttendees module raw_attendees = HandleAttendees::read_line_by_line('./raw_attendees.csv') invalid_attendees = HandleAttendees::find_invalid_attendees(raw_attendees) valid_attendees = HandleAttendees::create_sanitized_attendee_list(raw_attendees, invalid_attendees) # create output files with required information HandleAttendees::write_new_json_file(valid_attendees, "valid_attendees.json") HandleAttendees::write_new_txt_file(invalid_attendees, "invalid_attendees.txt")
describe 'Symbol#uicolor' do it "should return css color names" do Symbol.css_colors.each do |name, val| color = val.uicolor color.to_s.should == "UIColor.color(#{name.inspect})" end end end
# frozen_string_literal: true require 'forwardable' # A description of a DNAnexus project module DX module Api module Project # A project description class Description extend Forwardable # Initialize a project description from a DX API response def self.from_response(resp) body = resp.body flags = Flags.from_response(resp) new( id: body.fetch('id'), name: body.fetch('name'), org: body.fetch('billTo'), summary: body.fetch('summary'), description: body.fetch('description'), flags: flags ) end attr_reader :id, :name, :org, :summary, :description, :flags # A value object that represents a described project created by a successful response from # DNAnexus Project Describe API call. # # https://documentation.dnanexus.com/developer/api/data-containers/projects#api-method-project-xxxx-describe # # @param id [String] The id of the DNAnexus project # @param name [String] The name of the project # @param org [String] The organization that owns the project # @param summary [String] A summary of the project # @param description [String] A description of the project # @param flags [Flags] Access flags of the project def initialize(id:, name:, org:, summary:, description:, flags:) @id = id @name = name @org = org @summary = summary @description = description @flags = flags end # Delegate flag methods (download_restricted, contains_phi, etc) to Flags object def_delegators :flags, :download_restricted, :contains_phi, :is_protected, :restricted # Helper class that represents a project's access flags class Flags # Initialize a Flags object from a DX API response # # @param resp [DX:Api::Respone] A response object from a project describe request def self.from_response(resp) body = resp.body new( download_restricted: body.fetch('downloadRestricted'), contains_phi: body.fetch('containsPHI'), restricted: body.fetch('restricted'), is_protected: body.fetch('protected') ) end attr_reader :download_restricted, :contains_phi, :is_protected, :restricted def initialize(download_restricted:, contains_phi:, is_protected:, restricted:) @download_restricted = download_restricted @contains_phi = contains_phi @is_protected = is_protected @restricted = restricted end end end end end end
# Preventing from session hijacking config.force_ssl = true class Session < ActiveRecord::Base def self.sweep(time = 1.hour) if time.is_a?(String) time = time.split.inject { |count, unit| count.to_i.send(unit) } end delete_all "updated_at < '#{time.ago.to_s(:db)}'" end end # Preventing CSRF <a href="" onclick=" var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = 'http://www.example.com/account/destroy'; f.submit(); return false;"> def handle_unverified_request super sign_out_user # Example method that will destroy the user cookies. end #SELECT * FROM Users WHERE name = '' OR 1 --' #SELECT * FROM Users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1 # SQL injection sanitize_sql() Model.where("login = ? AND password = ?", entered_user_name, entered_password).first Preventing AES 128 cipher = OpenSSL::Cipher.new 'AES-128-CBC' pass_phrase = '$password' key_secure = key.export cipher, pass_phrase open 'private.secure.pem', 'w' do |io| io.write key_secure end # Clickjacking # tells the browser that your application can only be framed by pages originating from the same domain. X-Frame-Options: SAMEORIGIN # Privileage Escalation @user = @current_user.find(params[:id]) # CSS Injection element.innerHTML = “<%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%>”; element.outerHTML = “<%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%>”; # Filtering malicious upload # Make sure file uploads don't overwrite important files and process media files asynchronously. def sanitize_filename(filename) returning filename.strip do |name| # NOTE: File.basename doesn't work right with Windows paths on Unix # get only the filename, not the whole path name.gsub! /^.*(\\|\/)/, '' # Finally, replace all non alphanumeric, underscore # or periods with underscore name.gsub! /[^\w\.\-]/, '_' end end # Preventing Heartbleed key2 = OpenSSL::PKey::RSA.new File.read 'private_key.pem' key2.public? # => true name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example' csr_cert = OpenSSL::X509::Certificate.new csr_cert.serial = 0 csr_cert.version = 2 csr_cert.not_before = Time.now csr_cert.not_after = Time.now + 600 csr_cert.subject = csr.subject csr_cert.public_key = csr.public_key csr_cert.issuer = ca_cert.subject extension_factory = OpenSSL::X509::ExtensionFactory.new extension_factory.subject_certificate = csr_cert extension_factory.issuer_certificate = ca_cert csr_cert.add_extension extension_factory.create_extension('basicConstraints', 'CA:FALSE') csr_cert.add_extension extension_factory.create_extension( 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature') csr_cert.add_extension extension_factory.create_extension('subjectKeyIdentifier', 'hash') csr_cert.sign ca_key, OpenSSL::Digest::SHA1.new open 'csr_cert.pem', 'w' do |io| io.write csr_cert.to_pem end # Peer Verification context.ca_file = 'ca_cert.pem' context.verify_mode = OpenSSL::SSL::VERIFY_PEER require 'socket' tcp_client = TCPSocket.new 'localhost', 5000 ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context ssl_client.connect ssl_client.puts "hello server!" puts ssl_client.gets
require './lib/checkout.rb' describe Checkout do subject {described_class.new promo: '60bucks' } it 'has a list of items' do expect(subject.products).not_to be nil end describe 'Invalid promo' do subject { described_class.new promo: 'grumpy'} it 'throws error if invalid promo entered' do expect do subject {described_class.new promo: 'invalid'} end.to raise_error 'Invalid promo' end end describe 'Basics' do subject {described_class.new promo: '60bucks' } before { subject.scan('blanket') } it 'allows user to add items to cart' do expect(subject.cart).not_to eq [] end it 'totals items in the cart' do expect(subject.total).to eq 19.95 end end describe 'Subject has checked out more than $60 of items' do subject {described_class.new promo: '60bucks' } before do subject.scan('lounger') subject.scan('lounger') subject.scan('lounger') end it 'allows for multiple items in cart' do expect(subject.total).to be > 60 end it 'gives a 10% discount when total goes over $60' do expect(subject.total).to eq 121.5 end end describe 'User has scanned two hotdogs' do subject {described_class.new promo: 'hotdogs' } before do subject.scan('blanket') subject.scan('hotdog') subject.scan('hotdog') end it 'reduces cost of hot dogs to 8.25' do expect(subject.total).to be 36.95 end end describe 'User meets both discount requirements' do subject {described_class.new promo: 'both' } before do subject.scan('blanket') subject.scan('lounger') subject.scan('hotdog') subject.scan('hotdog') end it 'subtracts 10% AND reduces hot dog price' do expect(subject.total).to be 73.76 end end describe 'Customer removes a hot dog from cart' do before do subject.scan('blanket') subject.scan('lounger') subject.scan('hotdog') subject.scan('hotdog') subject.remove_from_cart('hotdog') end it 'removes item from cart' do expect(subject.cart.length).to be 3 end it 'removes discounts when requirements no longer met' do expect(subject.total).to be 66.78 end end describe 'Customer goes under $60 by removing item' do subject { described_class.new promo: 'both'} before do subject.scan('blanket') subject.scan('lounger') subject.scan('hotdog') subject.scan('hotdog') subject.remove_from_cart('lounger') end it 'takes away 10% discount but keeps double hotdog discount' do expect(subject.total).to be 36.95 end end describe 'Customer attempts to remove an item not in his cart' do subject { described_class.new promo: 'both'} before do subject.scan('blanket') subject.scan('lounger') subject.scan('hotdog') subject.scan('hotdog') end it 'throws an error' do expect{ subject.remove_from_cart('adkj') }.to raise_error 'Item not found' end end end
require 'test_helper' class UserTest < ActiveSupport::TestCase setup do @user = User.find_by(name: "user_one") end test "should create a user sucessfully" do user = User.create(user_id: 3, points: 0, name: "test") assert user.errors.empty? end test "should validate uniqueness of user id" do user = User.create(user_id: @user.user_id, points: 0, name: "test") assert_equal user.errors.full_messages.first, "User is already taken" end test "should validate presence of user_id" do user = User.create messages = user.errors.full_messages assert messages.include?("User can't be blank") end end
require 'spec_helper' require 'rails_helper' require Rails.root.join("spec/helpers/restaurant_helper.rb") describe RestaurantsController, "test" do context "Manage action" do before :each do @user1 = create(:user) @user2 = create(:user) @restaurant = create(:restaurant, {user_id: @user1.id}) filter_ids = [Filter.find_by_name("Lenanese").id, Filter.find_by_name("Vietnamese").id] filter_shisha = FilterType.find_by_name("Shisha").filters.first.id filter_price = FilterType.find_by_name("Price").filters.first.id @params_update = {"disabled"=>"false", "name"=>"rest 1","phone"=>"0909090090", "email"=>"rest1@gmail.com", "website"=>"", "description"=>"", "direction"=>"", "address"=>"222 nguyen van cu", "short_address"=>"", "district"=>"", "city"=>"hcm", "postcode"=>"", "country"=>"", "lat"=>"10.7969409664976", "lng"=>"106.6462129688949", "filter_ids"=> filter_ids, "halal_status"=>"", "filter_id_shisha"=>filter_shisha, "filter_id_price"=>filter_price, "schedules_attributes"=>{ "0"=>{"day_of_week"=>"1", "time_open"=>"600", "schedule_type"=>"daily", "time_closed"=>"1500", "id"=>"1"}, "3"=>{"day_of_week"=>"2", "time_open"=>"600", "schedule_type"=>"daily", "time_closed"=>"1500", "id"=>"2"}, "5"=>{"day_of_week"=>"3", "time_open"=>"600", "schedule_type"=>"daily", "time_closed"=>"1500", "id"=>"3"}, "6"=>{"day_of_week"=>"4", "time_open"=>"600", "schedule_type"=>"daily", "time_closed"=>"1500", "id"=>"4"}, "8"=>{"day_of_week"=>"5", "time_open"=>"600", "schedule_type"=>"daily", "time_closed"=>"1500", "id"=>"5"}, "10"=>{"day_of_week"=>"6", "time_open"=>"600", "schedule_type"=>"daily", "time_closed"=>"1500", "id"=>"6"}, "12"=>{"day_of_week"=>"7", "time_open"=>"600", "schedule_type"=>"daily", "time_closed"=>"1500", "id"=>"7"}, "15"=>{"day_of_week"=>"1", "time_open"=>"1700", "schedule_type"=>"evening", "time_closed"=>"2300", "id"=>"8"}, "16"=>{"day_of_week"=>"2", "time_open"=>"1700", "schedule_type"=>"evening", "time_closed"=>"2300", "id"=>"9"}, "18"=>{"day_of_week"=>"3", "time_open"=>"1700", "schedule_type"=>"evening", "time_closed"=>"2300", "id"=>"10"}, "21"=>{"day_of_week"=>"4", "time_open"=>"1800", "schedule_type"=>"evening", "time_closed"=>"2300", "id"=>"11"}, "23"=>{"day_of_week"=>"5", "time_open"=>"1730", "schedule_type"=>"evening", "time_closed"=>"2300", "id"=>"12"}, "25"=>{"day_of_week"=>"6", "time_open"=>"1700", "schedule_type"=>"evening", "time_closed"=>"1900", "id"=>"13"}, "27"=>{"day_of_week"=>"7", "time_open"=>"1700", "schedule_type"=>"evening", "time_closed"=>"1900", "id"=>"14"} } } end it "case 1: not login" do put "restaurant_managerment", id: @restaurant.id, restaurant: @params_update response.should redirect_to(new_user_session_path) end it "case 2: login, not owner" do sign_in @user2 put "restaurant_managerment", id: @restaurant.id, restaurant: @params_update response.should redirect_to("/") end it "case 3: login, owner" do sign_in @user1 put "restaurant_managerment", id: @restaurant.id, restaurant: @params_update expect(flash[:notice]).to eq I18n.t('restaurant.update_wait_approve') expect(assigns[:restaurant_temp].restaurant_id).to eq @restaurant.id expect(assigns[:restaurant_temp].schedules.count).to eq 14 expect(assigns[:restaurant_temp].disabled.to_s).to eq @params_update["disabled"] expect(assigns[:restaurant_temp].name.to_s).to eq @params_update["name"] expect(assigns[:restaurant_temp].email.to_s).to eq @params_update["email"] expect(assigns[:restaurant_temp].direction.to_s).to eq @params_update["direction"] expect(assigns[:restaurant_temp].address.to_s).to eq @params_update["address"] expect(assigns[:restaurant_temp].district.to_s).to eq @params_update["district"] expect(assigns[:restaurant_temp].postcode.to_s).to eq @params_update["postcode"] expect(assigns[:restaurant_temp].lat.to_s).to eq @params_update["lat"] expect(assigns[:restaurant_temp].lng.to_s).to eq @params_update["lng"] expect(assigns[:restaurant_temp].filter_ids).to eq (@params_update["filter_ids"] << @params_update["filter_id_shisha"] << @params_update["filter_id_price"]) expect(assigns[:restaurant_temp].halal_status.to_s).to eq @params_update["halal_status"] expect(RestaurantTemp.where(restaurant_id: @restaurant.id).count).to eq 1 response.should redirect_to(edit_user_restaurant_path(@restaurant.slug)) @params_update["name"] = "name update new 2" put "restaurant_managerment", id: @restaurant.id, restaurant: @params_update expect(flash[:notice]).to eq I18n.t('restaurant.update_wait_approve') expect(assigns[:restaurant_temp].restaurant_id).to eq @restaurant.id expect(assigns[:restaurant_temp].schedules.count).to eq 14 expect(assigns[:restaurant_temp].disabled.to_s).to eq @params_update["disabled"] expect(assigns[:restaurant_temp].name.to_s).to eq @params_update["name"] expect(assigns[:restaurant_temp].email.to_s).to eq @params_update["email"] expect(assigns[:restaurant_temp].direction.to_s).to eq @params_update["direction"] expect(assigns[:restaurant_temp].address.to_s).to eq @params_update["address"] expect(assigns[:restaurant_temp].district.to_s).to eq @params_update["district"] expect(assigns[:restaurant_temp].postcode.to_s).to eq @params_update["postcode"] expect(assigns[:restaurant_temp].lat.to_s).to eq @params_update["lat"] expect(assigns[:restaurant_temp].lng.to_s).to eq @params_update["lng"] expect(assigns[:restaurant_temp].filter_ids).to eq (@params_update["filter_ids"] ) expect(assigns[:restaurant_temp].halal_status.to_s).to eq @params_update["halal_status"] expect(RestaurantTemp.where(restaurant_id: @restaurant.id).count).to eq 1 response.should redirect_to(edit_user_restaurant_path(@restaurant.slug)) end end end
class RemovePurchasemethodAndSoldOnFromItems < ActiveRecord::Migration def self.up remove_column :items, :sold_on remove_column :items, :purchasemethod_id remove_column :items, :updated_on # obsoleted by updated_at end def self.down end end
class Emote attr_reader :str def initialize(str) @str = str end def happy " #{str} 😀" end def sad " #{str} 😞" end def laughing " #{str} 🤣" end def angry " #{str} 😡" end end @sentence = Emote.new("This is an okay program") @sentence2 = Emote.new("This is the second sentence") @sentence3 = Emote.new("This is the third") # puts sentence.happy # puts sentence.sad # puts sentence.laughing # puts sentence.angry # puts sentence.inspect
# Demo test for the Watir controller. # # Purpose: to test on the following Launchpad functionality: # * Deposit # * Reload # * and Withdraw # Test will execute transfering of load from one casino to another. #-------------------------------------------------------------# # the Watir controller require "watir" require 'spec' require 'win32ole' require 'test/unit' require 'ci/reporter/rake/test_unit_loader.rb' # set a variable launchpad_site = "http://202.44.100.86:8087/" casino_site ="http://202.44.100.86:8087/home.php" # open the IE browser ie = Watir::IE.new # print some comments puts "Beginning of test: Launchpad" puts "Step 1: go to Launchpad site: " + launchpad_site ie.goto launchpad_site ie.maximize() puts "Step 2: enter username'' in the text field." ie.text_field(:name, "txtuser").set "icsa-tst04" puts "Step 3: click the 'Login' button." ie.button(:value, "Login").click x=1 for x in 1..3 do puts "Step 4: click the 'Vibrant Vegas Casino'." ie.link(:class, "rollover1").click puts "Step 5: click 'YES' button." #ie.div(:text,"Do you want to transfer your balance to Vibrant Vegas?").flash ie.button(:id, "transferbuttonbora").flash ie.button(:id, "transferbuttonbora").click puts "Step 6: click 'OK' button. Game Client will be launched." Watir::Waiter::wait_until { (ie.button(:value,"OK")).exist? } ie.button(:value, "OK").click puts "Step 7: Activate again launchpad window." ie.goto casino_site ie.button(:id, "refrshbtn").click #-------------------------------------------------------------# puts "Step 8: click the 'Magic Macau Casino'." ie.link(:class, "rollover2").click puts " Step 9: click 'YES' button." #ie.div(:text,"Do you want to transfer your balance to Magic Macau?").flash ie.button(:id, "transferbuttonmanila").flash ie.button(:id, "transferbuttonmanila").click puts " Step 10: click 'OK' button. Game Client will be launched." Watir::Waiter::wait_until { (ie.button(:value,"OK")).exist? } ie.button(:value, "OK").click puts "Step 11: Activate again launchpad window." ie.goto casino_site ie.button(:id, "refrshbtn").click puts "======================================" end puts "End of test: Launchpad." $end
class CreateProyects < ActiveRecord::Migration[5.2] def change create_table :proyects do |t| t.string :nombre t.text :desc t.date :fecha_inicio t.date :fecha_termino t.integer :estado, default: 0 t.timestamps end end end
class Board attr_accessor :solution_row, :guesses def initialize @solution_row = Row.new @guesses = [] end def create_solution ( solution ) @solution_row.populate_row ( solution ) end def create_autogenerate_solution solution = [] Row::NUM_PEGS.times do solution << Peg::COLORS.sample end create_solution( solution ) end def add_guess_row( guess_string_arr ) # guess is an array of strings here guess_row = Row.new guess_row.populate_row( guess_string_arr ) new_guess = Guess.new ( guess_row ) @guesses << new_guess end def to_s @guesses.each { | guess | guess.row.to_s } end end
=begin Numbers to Commas Solo Challenge I spent [1.5] hours on this challenge. Complete each step below according to the challenge directions and include it in this file. Also make sure everything that isn't code is commented in the file. 0. Pseudocode What is the input? -->accept an integer What is the output? (i.e. What should the code return?) -->output an integer with pretty commmas What are the steps needed to solve the problem? split integer digits into an array IF array length > 3 create counter var = -4 insert "," at counter position increment counter -3 until counter >= array length END LOOP ELSE return it END IF =end # 1. Initial Solution def separate_comma(my_integer) my_integer = my_integer.to_s.split(//) array_length = my_integer.length if my_integer.length > 3 counter = -4 loop do my_integer.insert(counter, ",") counter = counter - 4 array_length += 1 break if -counter >= array_length + 1 end end return my_integer.join end separate_comma(100040166840000) # 2. Refactored Solution def pretty_numbers_re(my_integer) my_integer = my_integer.to_s.split(//) array_length = my_integer.length add_commas(array_length, my_integer) end def add_commas(integer_array_length, integer_as_array) if integer_array_length > 3 counter = -4 loop do integer_as_array.insert(counter, ",") counter -= 4 integer_array_length += 1 break if -counter >= integer_array_length + 1 end end puts integer_as_array.join end pretty_numbers_re(3010) # 3. Reflection =begin What was your process for breaking the problem down? What different approaches did you consider? I thought of the steps required. First push int into an array. Then test it. Then add the commas. Then put array to string. I didn't have another approach. I just fine-tuned the steps I had. Was your pseudocode effective in helping you build a successful initial solution? Yes, it helps to remember what step you're on, and what you need to do at that step. I think it engenders good practice to proceed step by step, and to test at each step. So once the code breaks, you can stop and re-assess. Then proceed on to next step. Otherwise it's easy to forget what step you were on. What Ruby method(s) did you use when refactoring your solution? What difficulties did you have implementing it/them? Did it/they significantly change the way your code works? If so, how? I found .split and .insert. I struggled with insert at first, because I had argument syntax backwards. These were crucial to my code. I didn't find any more sophisticated methods to use. How did you initially iterate through the data structure? I created a counter variable and incremented it. I don't know of another way to do that with an array. Especially when it calls for jumping three positions at a time. Do you feel your refactored solution is more readable than your initial solution? Why? No. I tried to pull out the method that actually inserts commas, and make it separate from the method that converts integer to array. I know it's good practice to break methods up that way. But I find it more confusing. I still don't understand how to pass the result from the inner method to the surrounding method and have the surrounding method puts it. =end
require 'spec_helper' describe User do it { should have_many(:reviews).order('created_at DESC') } it { should have_many(:queue_items).order('position') } it { should have_secure_password } it { should validate_presence_of :email } it { should validate_presence_of :password } it { should validate_presence_of :full_name } it { should validate_uniqueness_of :email } describe '#has_queue_item(queue_item)' do let(:sarah) { Fabricate(:user) } let(:video) { Fabricate(:video) } it 'returns true if the user has the item queued' do queue_item = Fabricate(:queue_item, user: sarah, video: video) expect(sarah.has_queue_item(queue_item)).to be true end it 'returns false if the user does not have the item queued' do queue_item = Fabricate(:queue_item, user: Fabricate(:user),video: video) expect(sarah.has_queue_item(queue_item)).to be false end end describe '#next_position_available' do it 'returns the next position available in the users queue' do sarah = Fabricate(:user) queue_item = Fabricate(:queue_item, user: sarah, video: Fabricate(:video)) expect(sarah.next_position_available).to eq(2) end end describe '#already_queued?(video)' do let(:sarah) { Fabricate(:user) } let(:video) { Fabricate(:video) } it "returns true if the video is already in the user's queue" do queue_item = Fabricate(:queue_item, user: sarah, video: video) expect(sarah.already_queued?(video)).to be true end it "returns false if the video is not in the user's queue" do expect(sarah.already_queued?(video)).to be false end end end
class Shoe < ActiveRecord::Base belongs_to :brand has_many :results, dependent: :destroy validates :name, presence: true, uniqueness: true validates :brand_id, presence: true validates :description, presence: true has_attached_file :picture, styles: { medium: "300x300>", thumb: "100x100>" } validates_attachment_content_type :picture, content_type: /\Aimage\/.*\z/ end
require 'stax/aws/keypair' module Stax module Keypair def self.included(thor) thor.desc(:keypair, 'Keypair subcommands') thor.subcommand(:keypair, Cmd::Keypair) end def keypair_create Aws::Keypair.create(stack_name).key_material rescue ::Aws::EC2::Errors::InvalidKeyPairDuplicate => e fail_task(e.message) end def keypair_delete Aws::Keypair.delete(stack_name) end end module Cmd class Keypair < SubCommand desc 'ls', 'list keypairs' method_option :all_keys, aliases: '-a', type: :boolean, default: false, desc: 'list all keys' def ls names = options[:all_keys] ? nil : [my.stack_name] print_table Aws::Keypair.describe(names).map { |k| [k.key_name, k.key_fingerprint] } end desc 'create [NAME]', 'create keypair' def create puts my.keypair_create end desc 'delete [NAME]', 'delete keypair' def delete(name = my.stack_name) my.keypair_delete if yes?("Really delete keypair #{name}?", :yellow) end end end end
module Endpoints class Meats < Base namespace "/meats" do before do content_type :html, charset: 'utf-8' end get do @current_meat = Meat.last haml :index end end end end
# frozen_string_literal: true module ObsGithubDeployments module CLI module Commands class ObsCommand < Dry::CLI::Command protected def status_response(status:, reason: "") { status: status, reason: reason }.to_json end def raise_error(message) raise(Dry::CLI::Error, message) end end end end end
require "evil/client/connection/net_http" describe Evil::Client::Connection::NetHTTP do let(:uri) { URI("https://example.com/foo/") } let(:connection) { described_class.new(uri) } let(:env) do { http_method: "post", path: "bar/baz", headers: { "Content-Type": "text/plain", "Accept": "text/plain" }, body_string: "Check!", query_string: "status=new" } end before do stub_request(:post, "https://example.com/foo/bar/baz?status=new") .to_return status: 201, body: "Success!", headers: { "Content-Type" => "text/plain; charset: utf-8" } end subject { connection.call env } it "sends a request" do subject expect(a_request(:post, "https://example.com/foo/bar/baz?status=new")) .to have_been_made end it "returns rack-compatible response" do expect(subject).to eq [ 201, { "content-type" => ["text/plain; charset: utf-8"] }, ["Success!"] ] end end
require 'spec_helper' describe ApplicationHelper do include ApplicationHelper let(:base_title) { "Ruby on Rails Tutorial Sample App" } describe "full_title" do describe "returns just the base title" do it "if the title is nil" do full_title(nil).should == base_title end it "if the title is empty" do full_title("").should == base_title end end it "returns the 'base title | title' if valid title is passed" do full_title("Home").should == "#{base_title} | Home" end end end
require 'rails_helper' describe Api::V1::CustomersController do context '#index' do it 'returns all the customers' do Customer.create(first_name: 'jorge', last_name: 'mexican') Customer.create(first_name: 'horace', last_name: 'hipster') get :index, format: :json expect(response).to have_http_status(:ok) customers = JSON.parse(response.body) expect(customers.count).to eq(2) customer = customers.first customer2 = customers.last expect(customer['first_name']).to eq('jorge') expect(customer['last_name']).to eq('mexican') expect(customer2['first_name']).to eq('horace') expect(customer2['last_name']).to eq('hipster') end end context '#show' do it 'returns a merchant' do customer = Customer.create(first_name: 'jorge', last_name: 'mexican') get :show, id: customer.id, format: :json expect(response).to have_http_status(:ok) customer = JSON.parse(response.body) expect(customer['first_name']).to eq('jorge') expect(customer['last_name']).to eq('mexican') end end context '#random' do it "returns a random customer" do Customer.create(first_name: 'jorge', last_name: 'mexican') get :random, format: :json expect(response).to have_http_status(:ok) customers = JSON.parse(response.body) expect(customers.first["first_name"]).to eq('jorge') end end context '#find' do it "can find by params" do Customer.create(first_name: 'jorge', last_name: 'mexican') get :find, name:'jorge', format: :json expect(response).to have_http_status(:ok) customer = JSON.parse(response.body) expect(customer["first_name"]).to eq('jorge') end it "can find all by params" do Customer.create(first_name: 'jorge', last_name: 'mexican') Customer.create(first_name: 'jorge', last_name: 'tellez') get :find_all, name:'jorge', format: :json expect(response).to have_http_status(:ok) customer = JSON.parse(response.body) expect(customer.first["last_name"]).to eq('mexican') expect(customer.last["last_name"]).to eq('tellez') end end context 'invoices' do xit "can return invoices for a customer" do customer = Customer.create(first_name: 'jorge', last_name: 'mexican') merchant = Merchant.create(name: "Jalapenos", created_at: "2012-03-27 14:54:09", updated_at: "2012-03-27 14:54:09") invoice1 = Invoice.create(customer_id: customer.id, merchant_id: merchant.id, status: "shipped", created_at: "2020-12-12 12:12:12", updated_at: "2020-12-11 12:12:12") invoice2 = Invoice.create(customer_id: customer.id, merchant_id: merchant.id, status: "shipped", created_at: "2020-12-01 12:12:12", updated_at: "2020-12-11 12:12:12") get :invoices, id: customer.id, format: :json expect(response).to have_http_status(:ok) customer = JSON.parse(response.body) binding.pry expect(customer.first["last_name"]).to eq('mexican') expect(customer.last["last_name"]).to eq('tellez') end end context 'invoices' do xit "can return invoices for a customer" do customer = Customer.create(first_name: 'jorge', last_name: 'mexican') merchant = Merchant.create(name: "Jalapenos", created_at: "2012-03-27 14:54:09", updated_at: "2012-03-27 14:54:09") invoice1 = Invoice.create(customer_id: customer.id, merchant_id: merchant.id, status: "shipped", created_at: "2020-12-12 12:12:12", updated_at: "2020-12-11 12:12:12") invoice2 = Invoice.create(customer_id: customer.id, merchant_id: merchant.id, status: "shipped", created_at: "2020-12-01 12:12:12", updated_at: "2020-12-11 12:12:12") get :merchants, id: customer.id, format: :json expect(response).to have_http_status(:ok) customer = JSON.parse(response.body) binding.pry expect(customer.first["last_name"]).to eq('mexican') expect(customer.last["last_name"]).to eq('tellez') end end end
Factory.define :category do |p| p.type 'Category' p.sequence(:title) {|n| "Test Category Title #{n}"} p.body 'Test Category Body' end
Rails.application.routes.draw do get 'registration/new', to: "registration#new" post 'registration/new', to: "registration#check" root to: 'static_pages#home' get 'static_pages/home', to: 'static_pages#home' resources :gossips do resources :comments end resources :users end
# ruby -r "./scheme_automation/android_emulator_link_test.rb" -e "AndroidEmulatorLinkTest.new.execute" require 'rubygems' require 'appium_lib' require 'webdrivers' require 'fileutils' require 'nokogiri' require 'CSV' class AndroidEmulatorLinkTest def initialize @arr = [] end # def execute # session = GoogleDrive::Session.from_service_account_key("sheets.json") # spreadsheet = session.spreadsheet_by_title("android-link-guess") # worksheet = spreadsheet.worksheets.first # worksheet.rows.first(100).each { |row| # # test_link(row) # # @arr << "#{row[0]},#{row[3]},#{row[4]},#{row[10]}" # puts @arr } # add_to_csv # end def execute Dir.chdir("/Users/ericmckinney/desktop/scheme_discovery/") Dir.foreach("./scheme_data") do |f| @csv_name = f next if f == '.' or f == '..' or f.include? '*IOS' or f.include? 'DS_Store' CSV.foreach("./scheme_data/#{f}") do |row| next unless row[0].to_s.include?('intent://') @arr << "#{row[0]}" test_link(row[0]) end end end def test_link(row) desired_caps = { caps: { platformName: 'Android', platformVersion: '11.0', deviceName: 'Pixel_3_API_30', browserName: 'Chrome', } } @appium_driver = Appium::Driver.new(desired_caps) @selenium_driver = @appium_driver.start_driver Appium.promote_appium_methods Object @selenium_driver.get("https://halgatewood.com/deeplink/") sleep 2 @selenium_driver.find_element(css: "body > div.wrap > form > input[type=url]").send_keys row sleep 3 @selenium_driver.find_element(:css, "body > div.wrap > form > div > input[type=submit]").click sleep 5 @selenium_driver.find_element(:xpath, "/html/body/div[1]/div/div[1]/a").click # @selenium_driver.find_element(css: "body > div.wrap > div > div.click > a").click #/html/body/div[1]/div/div[1]/a sleep 10 # TODO: if 'install' is present in button >> click - wait for download ? else ? end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :set_search def set_search q = params[:q] @clientes = Cliente.search(email_cont: q).result @q=Cliente.search(params[:q]) end def search index render :index end end
require 'test_helper' class ProductsControllerTest < ActionDispatch::IntegrationTest test 'should get index' do get products_path assert_response :success end test 'should get show' do get product_path(products(:one)) assert_response :success end test 'should get new' do get new_product_path assert_response :success end test 'should destroy product' do assert_difference('Product.count', -1) do delete product_path(products(:one)) end end test 'should create product' do assert_difference('Product.count', 1) do post "/products", params: { product: { name: 'MyProduct', code: 'myproduct'}} end product = Product.last assert_redirected_to new_product_variant_path(product_id: product.id) follow_redirect! assert_select 'h1', 'New variants for MyProduct' end end
class Quote < ApplicationRecord after_create :send_quote_create_email belongs_to :enquiry belongs_to :accountant validates :message, presence: true validates :invite, inclusion: { in: [true, false] } def send_quote_create_email QuoteMailer.created(self).deliver_now end end
class Fight_System attr_accessor :player, :monster def initialize( player, monster ) @player = player @monster = monster fight end def ui system("clear") puts "HP: #{player.hp}" puts "#{monster.name}: #{monster.hp}" print "a - attack, d - defend" gets.chomp end def fight until someone_won? case ui when "a" attack when "d" defend end monster_turn end puts player.hp > 0 ? "You won!" : "You lost!" end def someone_won? player.hp <= 0 || monster.hp <= 0 end def attack monster.hp -= rand(10) + 1 end def defend end def monster_turn end end
class Unit attr_accessor :level_training, :current_points, :unit_type, :army def initialize(army, unit_type) @unit_type = unit_type @army = army @level_training = 0 calculate_points end def sum_level(level) @level_training += level calculate_points end def calculate_points @current_points = @unit_type.points + ( @unit_type.training_points * level_training ) end def unit_transformation(unit_type) @unit_type = unit_type calculate_points end end
require File.dirname(__FILE__) + '/../spec_helper' describe Order do before(:each) do @customer = FactoryGirl.create(:customer) end it 'has a valid factory' do expect(FactoryGirl.build(:order, customer: @customer)).to be_valid end it 'is invalid without a customer' do expect(FactoryGirl.build(:order, customer: nil)).to_not be_valid end it 'is invalid without a valid status' do expect(FactoryGirl.build(:order, customer: @customer, status: 'pending')).to be_valid expect(FactoryGirl.build(:order, customer: @customer, status: 'cancelled')).to be_valid expect(FactoryGirl.build(:order, customer: @customer, status: 'paid')).to be_valid expect(FactoryGirl.build(:order, customer: @customer, status: 'shipped')).to be_valid expect(FactoryGirl.build(:order, customer: @customer, status: 'returned')).to be_valid expect(FactoryGirl.build(:order, customer: @customer, status: nil)).to_not be_valid expect(FactoryGirl.build(:order, customer: @customer, status: 'abracadabra')).to_not be_valid end describe '.generate new order' do it 'creates a new order when given valid params' do store = create(:store) product = create(:product, store: store) customer = create(:customer) current_session_cart = {"#{product.id}" => '2'} order = Order.generate_new_order(store.id, customer.id, current_session_cart) expect(order).to be_valid end end end
class AddGraduationToStudents < ActiveRecord::Migration def change add_column :refinery_fg_students, :graduation, :boolean, :default => false # true: 毕业, false: 未毕业 end end
class Runner < ActiveRecord::Base has_many :distances, dependent: :destroy def full_name return "#{first_name} #{last_name}" end end
require_relative 'contact' require_relative 'contact_database' user_input = ARGV case user_input[0] when 'help' puts "Here is a list of available commands:\n new - Create a new contact\n list - List all contacts\n show - Show a contact commands:\n find - Find a contact" when 'new' puts 'Enter username' username = $stdin.gets.chomp puts 'Enter email' email = $stdin.gets.chomp if DataBase.check(username) puts "Contact already exists..." else number = [] loop do puts 'Enter Mobile number' mobile_number = $stdin.gets.chomp break if mobile_number == "" number << ["Mobile: #{mobile_number}"] end Contact.create(username, email, number) end when 'list' Contact.all when 'show' Contact.show(user_input[1]) when 'find' Contact.find(user_input[1]) else puts 'Enter a valid command' end
module Fog module Compute class Google class SslCertificates < Fog::Collection model Fog::Compute::Google::SslCertificate def get(identity) if identity ssl_certificate = service.get_ssl_certificate(identity).to_h return new(ssl_certificate) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end def all(_filters = {}) data = service.list_ssl_certificates.to_h[:items] || [] load(data) end end end end end
class User def self.create(email:, password:) # Encrypt the plaintext password encrypted_password = BCrypt::Password.create(password) # Insert the encrypted password into the database sql = "INSERT INTO users (email, password) VALUES('#{email}','#{encrypted_password}') RETURNING id, email" result = DatabaseConnection.query(sql) User.new( id: result[0]['id'], email: result[0]['email'] ) end def self.find(id) return nil unless id sql = "SELECT * FROM users WHERE id = '#{id}'" result = DatabaseConnection.query(sql) User.new(id: result[0]['id'], email: result[0]['email']) end def self.authenticate(email:, password:) sql = "SELECT * FROM users WHERE email = '#{email}';" result = DatabaseConnection.query(sql) # Guard clauses against incorrect email or password return nil unless result.any? return nil unless BCrypt::Password.new(result[0]['password']) == password User.new(id: result[0]['id'], email: result[0]['email']) end attr_reader :id, :email def initialize(id:, email:) @id = id @email = email end end
module Page module Post class NewPost < Page::Base form_resource :post def visit super new_post_path end def submit click_button 'Save' end def has_blank_field_alert? page.has_text? 'blank' end def has_taken_title_alert? page.has_text? 'taken' end end end end
json.array!(@quotations) do |quotation| json.extract! quotation, :id, :file_path, :project_id, :name, :cost, :deadline json.url quotation_url(quotation, format: :json) end
# frozen_string_literal: true step "Are you talking about :name !!!!!" do |name| expect(name).to eq("Kuririn") end step "When you give up, that's when the game is over." do expect(true).to be true end
require 'docopt' require 'vanagon/logger' class Vanagon class CLI class Ship < Vanagon::CLI DOCUMENTATION = <<~DOCOPT.freeze Usage: ship [--help] Options: -h, --help Display help DOCOPT def parse(argv) Docopt.docopt(DOCUMENTATION, { argv: argv }) rescue Docopt::Exit => e VanagonLogger.error e.message exit 1 end def run(_) ENV['PROJECT_ROOT'] = Dir.pwd if Dir['output/**/*'].select { |entry| File.file?(entry) }.empty? VanagonLogger.error 'vanagon: Error: No packages to ship in the "output" directory. Maybe build some first?' exit 1 end require 'packaging' Pkg::Util::RakeUtils.load_packaging_tasks Pkg::Util::RakeUtils.invoke_task('pl:jenkins:ship', 'artifacts', 'output') Pkg::Util::RakeUtils.invoke_task('pl:jenkins:ship_to_artifactory', 'output') end end end end
class Event < ApplicationRecord belongs_to :user has_many :rsvps, -> { includes(:user) } has_many :likes, -> { includes(:user) } default_scope { order('start_time') } attr_accessor :start_date_date, :start_date_time, :end_date_date, :end_date_time after_initialize :get_datetimes before_validation :set_datetimes DATE_FORMAT = "%d %B, %Y" TIME_FORMAT = "%I:%M%p" DATE_AND_TIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT DATE_AND_TIME_FORMAT_SHORT = "%a, %b %d at %I:%M%p" def start_time_display format_display_date(self.start_time) end def end_time_display format_display_date(self.end_time) end def start_time_display_short format_display_date_short(self.start_time) end def end_time_display_short format_display_date_short(self.end_time) end def can_modify(user) (user && ( (user.id == self.user_id) || user.is_admin) ) end def num_rsvps rsvps.length end private def format_display_date(date) date.strftime(DATE_AND_TIME_FORMAT) end def format_display_date_short(date) date.strftime(DATE_AND_TIME_FORMAT_SHORT) end def get_datetimes if (self.start_time) self.start_date_date = self.start_time.strftime(DATE_FORMAT) self.start_date_time = self.start_time.strftime(TIME_FORMAT) end if (self.end_time) self.end_date_date = self.end_time.strftime(DATE_FORMAT) self.end_date_time = self.end_time.strftime(TIME_FORMAT) end end def set_datetimes if (self.start_date_date && self.start_date_time) date_str = self.start_date_date + self.start_date_time Rails.logger.debug("date_str = #{date_str}") new_date = DateTime.parse(date_str) Rails.logger.debug("new date = #{new_date}") self.start_time = new_date end if (self.end_date_date && self.end_date_time) date_str = self.end_date_date + self.end_date_time Rails.logger.debug("date_str = #{date_str}") new_date = DateTime.parse(date_str) Rails.logger.debug("new date = #{new_date}") self.end_time = new_date end end end
Rails.application.routes.draw do get '/gitinfo', to: 'students#gitinfo' root 'api/students#index' get 'api/students/:id/resources', to: 'api/students#resources' namespace :api do resources :students end end
require 'erb' require 'json' require 'nokogiri' require 'open-uri' require 'ostruct' require 'zip' module Tapir module Reports # a template in Word docx format class Template def initialize(template) @template = template # open the template, cache the bits we are interested in, then close template_opened = URI.open(@template) zipfile = Zip::File.open_buffer(template_opened) @relationships = zipfile.read('word/_rels/document.xml.rels') @files = { 'word/document.xml' => zipfile.read('word/document.xml') } @files['docProps/core.xml'] = zipfile.read('docProps/core.xml') unless zipfile.find_entry('docProps/core.xml').nil? zipfile.glob(File.join('**', 'header*.xml')).each { |e| @files[e.name] = zipfile.read(e) } zipfile.glob(File.join('**', 'footer*.xml')).each { |e| @files[e.name] = zipfile.read(e) } zipfile.close end def contents @files['word/document.xml'] end def render(your_binding, key = 'word/document.xml') erb = Template.to_erb(@files[key]) ERB.new(erb, trim_mode: '-').result(your_binding) end def self.to_erb(content) # remove extraneous Word xml tags between erb start and finish # enable anti-nil syntax 'xyz&.attr' content.gsub!(/(&lt;%[^%]*%[^&]*&gt;)/m) do |erb_tag| erb_tag.gsub(/(<[^>]*>)/, '').gsub('&amp;', '&').gsub('‘', "'") end # unescape erb tags content.gsub!('&lt;%', '<%') content.gsub!('%&gt;', '%>') content end # This is still pretty dirty, but you get a Word transformation as html.erb def self.to_bootstrap_erb(content, replacements = []) content = to_erb(content) content.gsub!('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '<!DOCTYPE html>') content.gsub!('w:document', 'html') content.gsub!('w:body', 'body') content.gsub!(/<html(\s[^>]*>|>)/, '<html lang="en-GB"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> </head>') content.gsub!('<body>', '<body><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>') content = strip_tag(content, 'mc:AlternateContent') content = strip_tag(content, 'wps:bodyPr') content = strip_tag(content, 'w:rPr') content = strip_tag(content, 'w:sectPr') content = strip_tag(content, 'w:tblPr') content = strip_tag(content, 'w:trPr') content = strip_tag(content, 'w:tcPr') content = strip_tag(content, 'w:tblGrid') content = replace_tag(content, 'w:drawing', replacements) content = strip_tag(content, 'w:drawing') content = strip_tag(content, 'w:pict') close_div = '</div>'.freeze content.gsub!(/<w:p(\s[^>]*>|>)/, '<w:p>') content.gsub!(/<w:r(\s[^>]*>|>)/, '<w:r>') content.gsub!(/<w:right(\s[^>]*>|>)/, '<w:right>') content.gsub!(/<w:tr(\s[^>]*>|>)/, '<w:tr>') content.gsub!(%r{<w:tcW(\s[^>]*/>)}, '') content.gsub!(%r{<w:proofErr(\s[^>]*/>)}, '') content.gsub!('<w:tbl>', '<div class="container">') content.gsub!('</w:tbl>', close_div) content.gsub!('<w:tbl>', '') content.gsub!('</w:tbl>', '') content.gsub!('<w:tr>', '<div class="row">') content.gsub!('</w:tr>', close_div) content.gsub!(%r{<w:p><w:pPr><w:pStyle w:val="Heading1"/>}, '<p class="h1"><w:pPr>') content.gsub!(%r{<w:p><w:pPr><w:pStyle w:val="Heading2"/>}, '<p class="h2"><w:pPr>') content.gsub!(%r{<w:p><w:pPr><w:pStyle w:val="Heading3"/>}, '<p class="h3"><w:pPr>') content.gsub!(%r{<w:p><w:pPr><w:pStyle w:val="Heading4"/>}, '<p class="h4"><w:pPr>') content.gsub!('<w:p>', '<p>') content.gsub!('</w:p>', '</p>') content = strip_tag(content, 'w:pPr') content.gsub!('<w:r>', '') content.gsub!('</w:r>', '') content.gsub!('<w:tc>', '<div class="col-auto">') content.gsub!('</w:tc>', close_div) content.gsub!(/<w:t(\s[^>]*>|>)/, '') content.gsub!('</w:t>', '') content.gsub!('<w:temporary/>', '') content.gsub!('<w:showingPlcHdr/>', '') content.gsub!('<w:text/>', '') content.gsub!('<w:sdtEndPr/>', '') content.gsub!('<w:br w:type="page"/>', '** page break **') content.gsub!('<w15:appearance w15:val="hidden"/>', '') content.gsub!(%r{<w:id [^>]*/>}, '') content = remove_tag(content, 'w:sdt') content = remove_tag(content, 'w:sdtContent') content = remove_tag(content, 'w:sdtPr') content = remove_tag(content, 'w:placeholder') content.gsub!(%r{<w:docPart [^>]*/>}, '') content end def relationship_id(image_name) xml = Nokogiri::XML(@files['word/document.xml']) xml.root.add_namespace('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main') drawing = xml.at_xpath("//w:drawing[*/wp:docPr[@title='#{image_name}' or @descr='#{image_name}']]") node = drawing.at_xpath('*//a:blip/@r:embed') if drawing # if nil then object is not a picture, it is a border box or something node&.value end def self.replace_tag(content, tag, replacements) open_tag = "<#{tag}" close_tag = "</#{tag}>" while content.index(open_tag) up_to_start_tag = content[0..content.index(open_tag) - 1] between_tags = content[content.index(open_tag)..content.index(close_tag)] after_close_tag = content[content.index(close_tag) + close_tag.size..] found = false replacements.each do |r| look_for = "descr=\"#{r[0]}\"" next unless between_tags.include?(look_for) found = true img_tag = "<img src='#{r[1]}' height=200 alt='#{r[0]}'/>" content = up_to_start_tag + img_tag + after_close_tag end content = up_to_start_tag + after_close_tag unless found end content end # remove <tag>but leave everything between be</tag> def self.remove_tag(content, tag) open_tag = "<#{tag}>" close_tag = "</#{tag}>" while content.index(open_tag) up_to_start_tag = content[0..content.index(open_tag) - 1] after_up_to_start = content[content.index(open_tag) + open_tag.size..] between = after_up_to_start[0..after_up_to_start.index(close_tag) - 1] after_close_tag = after_up_to_start[after_up_to_start.index(close_tag) + close_tag.size..] content = up_to_start_tag + between + after_close_tag end content end # remove <tag>and everything between</tag> def self.strip_tag(content, tag) open_tag = "<#{tag}" close_tag = "</#{tag}>" while content.index(open_tag) up_to_start_tag = content[0..content.index(open_tag) - 1] after_close_tag = content[content.index(close_tag) + close_tag.size..] content = up_to_start_tag + after_close_tag end content end def url(relationship_id) relationships = Nokogiri::XML(@relationships) target = relationships.at_xpath("//*[@Id='#{relationship_id}']/@Target") "word/#{target}" end def url_for(image_name) url(relationship_id(image_name)) # if relationship_id(image_name) end def output(your_binding, image_replacements) image_replacements2 = {} image_replacements.each do |rep| url = url_for(rep[0]) image_replacements2[url] = rep[1] unless url.nil? end buffer = Zip::OutputStream.write_buffer do |out| zipfile = Zip::File.open_buffer(URI.open(@template)) zipfile.entries.each do |entry| if @files.keys.include?(entry.name) rendered_document_xml = render(your_binding, entry.name) out.put_next_entry(entry.name) out.write(rendered_document_xml) elsif image_replacements2.keys.include?(entry.name) # write the alternative image's contents instead of placeholder's out.put_next_entry(entry.name) begin URI.open(image_replacements2[entry.name]) do |f| data = f.read signature = data[0, 3].bytes if [[255, 216, 255], [137, 80, 78]].include?(signature) out.write(data) else URI.open('https://github.com/jnicho02/tapir-reports/raw/master/lib/tapir/reports/image-not-found.png') { |not_found| out.write(not_found.read) } end end rescue URI.open('https://github.com/jnicho02/tapir-reports/raw/master/lib/tapir/reports/image-not-found.png') { |not_found| out.write(not_found.read) } end else out.put_next_entry(entry.name) begin out.write(entry.get_input_stream.read) rescue puts "error. Cannot write #{entry.name} as-is" URI.open('https://github.com/jnicho02/tapir-reports/raw/master/lib/tapir/reports/image-not-found.png') { |not_found| out.write(not_found.read) } end end end zipfile.close end buffer.string end end end end
json.array!(@design_solutions) do |design_solution| json.extract! design_solution, :id json.url design_solution_url(design_solution, format: :json) end
#encoding:utf-8 #22 minutos require_relative 'Sorpresa' require_relative 'TipoSorpresa' require_relative 'Qytetet' module Test class Examen @@MAX=10 #Ejercicio 3 @contador_global=0 def self.contador_global @contador_global end def self.contador_global=(v) @contador_global=v end ################### def initialize(c) @contador=c end def self.constructor1(c) new(c) end def self.constructor2() new(0) end private_class_method :new #También se podría no hacer new privado y añadir solo constructor2 attr_reader :contador def contabilizar @contador=[@contador+1,@@MAX].min end def principal contabilizar #Ejercicio 2 mazo=Array.new mazo<<ModeloQytetet::Sorpresa.new("Te conviertes a especulador", 5000, ModeloQytetet::TipoSorpresa::CONVERTIRME) mazo<<ModeloQytetet::Sorpresa.new("Ganas saldo", 100, ModeloQytetet::TipoSorpresa::PAGARCOBRAR) mazo<<ModeloQytetet::Sorpresa.new("Vas a la casilla 6", 6, ModeloQytetet::TipoSorpresa::IRACASILLA) suma_coste=0 mazo.each do |s| suma_coste+=s.valor end media=suma_coste.to_f/mazo.length puts "La media es "+media.to_s ################### #Ejercicio 3 self.class.contador_global=self.class.contador_global+1 ################### #Ejercicio 4 puts "Les presento el juego:" ModeloQytetet::Qytetet.instance.inicializarJuego(["Alicia","Verónica"]) puts ModeloQytetet::Qytetet.instance.to_s ################### puts "Contador de principal "+@contador.to_s end end end #Programa principal instancia=Test::Examen.constructor1(9) 2.times { instancia.principal } #Probamos el contador global a nivel de clase instancia2=Test::Examen.constructor2 instancia2.principal puts "Ejecuciones globales: "+Test::Examen.contador_global.to_s
require 'rails_helper' RSpec.describe 'deleting account' do it 'destroys user and redirects to login page' do user = User.create(name: "Marco", email: "marco@email.com", password: "password", password_confirmation: "password") visit '/sessions/new' unless current_path == "/sessions/new" fill_in 'email', with: "marco@email.com" fill_in 'password', with: "password" click_button 'Log in' click_link 'Edit Profile' click_button 'Delete Account' expect(current_path).to eq('/sessions/new') end end
require 'orocos/test' require 'fakefs/safe' describe Orocos::TaskConfigurations do include Orocos::Spec attr_reader :conf attr_reader :model def setup super @model = Orocos.default_loader.task_model_from_name('configurations::Task') @conf = Orocos::TaskConfigurations.new(model) end def verify_loaded_conf(conf, name = nil, *base_path) if conf.respond_to?(:sections) assert conf.sections.has_key?(name) @conf_context = conf.sections[name] else @conf_context = conf if name base_path.unshift name end end @conf_getter = method(:get_conf_value) base_path.each do |p| @conf_context = @conf_context[p] end yield end def verify_apply_conf(task, conf, names, *base_path, &block) conf.apply(task, names) verify_applied_conf(task, *base_path, &block) end def verify_applied_conf(task, *base_path) if !base_path.empty? base_property = task.property(base_path.shift) value_path = base_path end @conf_getter = lambda do |*path| property= if base_property then base_property else task.property(path.shift) end result = property.raw_read (base_path + path).inject(result) do |result, field| result.raw_get(field) end end yield end def get_conf_value(*path) path.inject(@conf_context) do |result, field| if result.respond_to?(:raw_get) result.raw_get(field) else result.fetch(field) end end end def assert_conf_value(*path) expected_value = path.pop type = path.pop type_name = path.pop value = @conf_getter[*path] assert_kind_of type, value assert_equal type_name, value.class.name if block_given? value = yield(value) elsif value.kind_of?(Typelib::Type) value = Typelib.to_ruby(value) end assert_equal expected_value, value end it "should be able to load simple configuration structures" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'base_config.yml')) assert_equal %w{compound default simple_container}, conf.sections.keys.sort verify_loaded_conf conf, 'default' do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.1 end verify_loaded_conf conf, 'compound', 'compound' do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test2" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.2 assert_conf_value 'simple_array', 0, "/int32_t", Typelib::NumericType, 1 assert_conf_value 'simple_array', 1, "/int32_t", Typelib::NumericType, 2 assert_conf_value 'simple_array', 2, "/int32_t", Typelib::NumericType, 3 array = get_conf_value 'simple_array' assert_equal 3, array.size end verify_loaded_conf conf, 'simple_container', 'simple_container' do assert_conf_value 0, "/int32_t", Typelib::NumericType, 10 assert_conf_value 1, "/int32_t", Typelib::NumericType, 20 assert_conf_value 2, "/int32_t", Typelib::NumericType, 30 container = get_conf_value assert_equal 3, container.size end end it "should be able to load dynamic configuration structures" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'dynamic_config.yml')) assert_equal %w{compound default simple_container}, conf.sections.keys.sort verify_loaded_conf conf, 'default' do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.1 assert_conf_value 'bl', '/bool', Typelib::NumericType, true end verify_loaded_conf conf, 'compound', 'compound' do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'str', "/std/string", Typelib::ContainerType, ".yml" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.2 assert_conf_value 'simple_array', 0, "/int32_t", Typelib::NumericType, 1 assert_conf_value 'simple_array', 1, "/int32_t", Typelib::NumericType, 2 assert_conf_value 'simple_array', 2, "/int32_t", Typelib::NumericType, 3 array = get_conf_value 'simple_array' assert_equal 3, array.size end verify_loaded_conf conf, 'simple_container', 'simple_container' do assert_conf_value 0, "/int32_t", Typelib::NumericType, 10 assert_conf_value 1, "/int32_t", Typelib::NumericType, 20 assert_conf_value 2, "/int32_t", Typelib::NumericType, 30 container = get_conf_value assert_equal 3, container.size end end describe "the loaded yaml cache" do before do @root_dir = make_tmpdir @cache_dir = FileUtils.mkdir File.join(@root_dir, 'cache') @conf_file = File.join(@root_dir, "conf.yml") write_fixture_conf <<~CONF --- name:default intg: 20 CONF end def write_fixture_conf(content) File.open(@conf_file, 'w') { |io| io.write(content) } end it "auto-saves a marshalled version in the provided cache directory" do @conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) flexmock(YAML).should_receive(:load).never conf = Orocos::TaskConfigurations.new(model) conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) default = conf.conf('default') assert_equal 20, Typelib.to_ruby(default['intg']) end it "ignores the cache if the document changed" do # Generate the cache @conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) write_fixture_conf <<~CONF --- name:default intg: 30 CONF flexmock(YAML).should_receive(:load).at_least.once.pass_thru conf = Orocos::TaskConfigurations.new(model) conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) default = conf.conf('default') assert_equal 30, Typelib.to_ruby(default['intg']) end it "does not use the cache if the dynamic content is different" do write_fixture_conf <<~CONF --- name:default intg: <%= Time.now.tv_usec %> CONF @conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) flexmock(YAML).should_receive(:load).at_least.once.pass_thru conf = Orocos::TaskConfigurations.new(model) conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) end it "properly deals with an invalid cache" do write_fixture_conf <<~CONF --- name:default intg: 20 CONF @conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) Dir.glob(File.join(@cache_dir, "*")) do |file| File.truncate(file, 0) if File.file?(file) end conf = Orocos::TaskConfigurations.new(model) conf.load_from_yaml(@conf_file, cache_dir: @cache_dir) default = conf.conf('default') assert_equal 20, Typelib.to_ruby(default['intg']) end end it "raises if the same section is defined twice in the same file" do assert_raises(ArgumentError) do conf.load_from_yaml( File.join(data_dir, "configurations", "duplicate_sections.yml") ) end end it "raises even if the duplicate section is the implicit default section" do assert_raises(ArgumentError) do conf.load_from_yaml( File.join(data_dir, "configurations", "duplicate_default.yml") ) end end it "ignores a no-op default section at the top of the file" do conf.load_from_yaml( File.join(data_dir, "configurations", "noop_default.yml") ) end it "should be able to load complex structures" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'complex_config.yml')) verify_loaded_conf conf, 'compound_in_compound', 'compound', 'compound' do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test2" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.2 end verify_loaded_conf conf, 'vector_of_compound', 'compound', 'vector_of_compound' do assert_conf_value 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 2, 'intg', "/int32_t", Typelib::NumericType, 30 end verify_loaded_conf conf, 'vector_of_vector_of_compound', 'compound', 'vector_of_vector_of_compound' do assert_conf_value 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 0, 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 0, 2, 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 1, 0, 'intg', "/int32_t", Typelib::NumericType, 11 assert_conf_value 1, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 1, 'intg', "/int32_t", Typelib::NumericType, 21 assert_conf_value 1, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 1, 2, 'intg', "/int32_t", Typelib::NumericType, 31 end verify_loaded_conf conf, 'array_of_compound', 'compound', 'array_of_compound' do assert_conf_value 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 2, 'intg', "/int32_t", Typelib::NumericType, 30 end verify_loaded_conf conf, 'array_of_vector_of_compound', 'compound', 'array_of_vector_of_compound' do assert_conf_value 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 0, 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 0, 2, 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 1, 0, 'intg', "/int32_t", Typelib::NumericType, 11 assert_conf_value 1, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 1, 'intg', "/int32_t", Typelib::NumericType, 21 assert_conf_value 1, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 1, 2, 'intg', "/int32_t", Typelib::NumericType, 31 end end describe "#conf" do it "merges configuration structures" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'merge.yml')) result = conf.conf(['default', 'add'], false) verify_loaded_conf result do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 20 end verify_loaded_conf result, 'compound' do assert_conf_value 'compound', 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'compound', 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'vector_of_compound', 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'vector_of_compound', 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 'vector_of_compound', 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'array_of_vector_of_compound', 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 'array_of_vector_of_compound', 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'array_of_vector_of_compound', 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'array_of_vector_of_compound', 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 1, 0, 'intg', "/int32_t", Typelib::NumericType, 12 assert_conf_value 'array_of_vector_of_compound', 2, 0, 'enm', "/Enumeration", Typelib::EnumType, :Second end end it "merge without overrides should have the same result than with if no conflicts exist" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'merge.yml')) result = conf.conf(['default', 'add'], false) result_with_override = conf.conf(['default', 'add'], true) assert_equal result, result_with_override end it "raises ArgumentError if conflicts exist and override is false" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'merge.yml')) # Make sure that nothing is raised if override is false conf.conf(['default', 'override'], true) assert_raises(ArgumentError) { conf.conf(['default', 'override'], false) } end it "raises SectionNotFound if given an unknown section" do assert_raises(Orocos::TaskConfigurations::SectionNotFound) { conf.conf(['default', 'does_not_exist'], false) } end it "accepts a 'default' section even if it does not exist" do assert_equal Hash.new, conf.conf(['default'], false) end it "accepts a single string as section name" do assert_equal Hash.new, conf.conf('default', false) end it "takes values from the last section if conflicts exist and override is true" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'merge.yml')) result = conf.conf(['default', 'override'], true) verify_loaded_conf result do assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 25 end verify_loaded_conf result, 'compound' do assert_conf_value 'compound', 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'vector_of_compound', 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'vector_of_compound', 0, 'intg', "/int32_t", Typelib::NumericType, 42 assert_conf_value 'vector_of_compound', 1, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'vector_of_compound', 1, 'intg', "/int32_t", Typelib::NumericType, 22 assert_conf_value 'array_of_vector_of_compound', 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 'array_of_vector_of_compound', 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'array_of_vector_of_compound', 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'array_of_vector_of_compound', 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 1, 0, 'intg', "/int32_t", Typelib::NumericType, 11 assert_conf_value 'array_of_vector_of_compound', 2, 0, 'enm', "/Enumeration", Typelib::EnumType, :Second end end end describe "#conf_as_ruby" do it "converts the configuration to a name-to-ruby value mapping" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'merge.yml')) result = conf.conf_as_ruby(['default', 'add'], override: false) assert_same :First, result['enm'] end end describe "#conf_as_typelib" do it "converts the configuration to a name-to-typelib value mapping" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'merge.yml')) result = conf.conf_as_typelib(['default', 'add'], override: false) assert_equal '/Enumeration', result['enm'].class.name assert_equal :First, Typelib.to_ruby(result['enm']) end end it "should be able to apply simple configurations on the task" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'base_config.yml')) start 'configurations::Task' => 'configurations' task = Orocos.get "configurations" assert_equal (0...10).to_a, task.simple_container.to_a assert_equal :First, task.compound.enm simple_array = task.compound.simple_array.to_a simple_container = task.simple_container.to_a conf.apply(task, 'default') assert_equal (0...10).to_a, task.simple_container.to_a assert_equal :First, task.compound.enm verify_applied_conf task do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.1 end conf.apply(task, ['default', 'compound']) verify_applied_conf task do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.1 end simple_array[0, 3] = [1, 2, 3] verify_applied_conf task, 'compound' do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test2" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.2 assert_conf_value 'simple_array', '/int32_t[10]', Typelib::ArrayType, simple_array do |v| v.to_a end end conf.apply(task, ['default', 'compound', 'simple_container']) simple_container = [10, 20, 30] verify_applied_conf task do assert_conf_value 'simple_container', '/std/vector</int32_t>', Typelib::ContainerType, simple_container do |v| v.to_a end end end it "should be able to apply complex configuration on the task" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'complex_config.yml')) Orocos.run "configurations_test" do task = Orocos::TaskContext.get "configurations" verify_apply_conf task, conf, 'compound_in_compound', 'compound', 'compound' do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'str', "/std/string", Typelib::ContainerType, "test2" assert_conf_value 'fp', '/double', Typelib::NumericType, 0.2 end verify_apply_conf task, conf, 'vector_of_compound', 'compound', 'vector_of_compound' do assert_conf_value 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 2, 'intg', "/int32_t", Typelib::NumericType, 30 end verify_apply_conf task, conf, 'vector_of_vector_of_compound', 'compound', 'vector_of_vector_of_compound' do assert_conf_value 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 0, 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 0, 2, 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 1, 0, 'intg', "/int32_t", Typelib::NumericType, 11 assert_conf_value 1, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 1, 'intg', "/int32_t", Typelib::NumericType, 21 assert_conf_value 1, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 1, 2, 'intg', "/int32_t", Typelib::NumericType, 31 end verify_apply_conf task, conf, 'array_of_compound', 'compound', 'array_of_compound' do assert_conf_value 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 2, 'intg', "/int32_t", Typelib::NumericType, 30 end verify_apply_conf task, conf, 'array_of_vector_of_compound', 'compound', 'array_of_vector_of_compound' do assert_conf_value 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 0, 1, 'intg', "/int32_t", Typelib::NumericType, 20 assert_conf_value 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 0, 2, 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 1, 0, 'intg', "/int32_t", Typelib::NumericType, 11 assert_conf_value 1, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 1, 1, 'intg', "/int32_t", Typelib::NumericType, 21 assert_conf_value 1, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 1, 2, 'intg', "/int32_t", Typelib::NumericType, 31 end end end it "zeroes out newly created structures and initializes fields that need to" do conf.load_from_yaml(File.join(data_dir, 'configurations', 'complex_config.yml')) Orocos.run "configurations_test" do task = Orocos::TaskContext.get "configurations" verify_apply_conf task, conf, 'zero_and_init', 'compound', 'vector_of_compound' do assert_conf_value 0, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 0, 'intg', "/int32_t", Typelib::NumericType, 0 assert_conf_value 1, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 1, 'intg', "/int32_t", Typelib::NumericType, 20 end end end it "should be able to load a configuration directory, register configurations on a per-model basis, and report what changed" do manager = Orocos::ConfigurationManager.new manager.load_dir(File.join(data_dir, 'configurations', 'dir')) result = manager.conf['configurations::Task'].conf(['default', 'add'], false) verify_loaded_conf result do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 20 end verify_loaded_conf result, 'compound' do assert_conf_value 'compound', 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'compound', 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'vector_of_compound', 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'vector_of_compound', 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 'vector_of_compound', 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'array_of_vector_of_compound', 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 'array_of_vector_of_compound', 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'array_of_vector_of_compound', 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'array_of_vector_of_compound', 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 1, 0, 'intg', "/int32_t", Typelib::NumericType, 12 assert_conf_value 'array_of_vector_of_compound', 2, 0, 'enm', "/Enumeration", Typelib::EnumType, :Second end assert_equal(Hash.new, manager.load_dir(File.join(data_dir, 'configurations', 'dir'))) assert_equal({'configurations::Task' => ['default']}, manager.load_dir(File.join(data_dir, 'configurations', 'dir_changed'))) result = manager.conf['configurations::Task'].conf(['default', 'add'], false) verify_loaded_conf result do assert_conf_value 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'intg', "/int32_t", Typelib::NumericType, 0 end verify_loaded_conf result, 'compound' do assert_conf_value 'compound', 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'compound', 'intg', "/int32_t", Typelib::NumericType, 30 assert_conf_value 'vector_of_compound', 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'vector_of_compound', 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 'vector_of_compound', 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'array_of_vector_of_compound', 0, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 0, 0, 'intg', "/int32_t", Typelib::NumericType, 10 assert_conf_value 'array_of_vector_of_compound', 0, 1, 'enm', "/Enumeration", Typelib::EnumType, :Second assert_conf_value 'array_of_vector_of_compound', 0, 2, 'enm', "/Enumeration", Typelib::EnumType, :Third assert_conf_value 'array_of_vector_of_compound', 1, 0, 'enm', "/Enumeration", Typelib::EnumType, :First assert_conf_value 'array_of_vector_of_compound', 1, 0, 'intg', "/int32_t", Typelib::NumericType, 12 assert_conf_value 'array_of_vector_of_compound', 2, 0, 'enm', "/Enumeration", Typelib::EnumType, :Second end end describe "#add" do before do manager = Orocos::ConfigurationManager.new manager.load_dir(File.join(data_dir, 'configurations', 'dir')) @conf = manager.conf['configurations::Task'] end describe "merge: true" do it "merges into an existing section" do assert @conf.add 'default', Hash['compound' => Hash['compound' => Hash['intg' => 20]]], merge: true assert_equal 20, @conf.conf('default')['compound']['compound']['intg'].to_ruby assert_equal 10, @conf.conf('default')['compound']['vector_of_compound'][0]['intg'].to_ruby end it "returns false if the updated value is equal to the existing one" do refute @conf.add 'default', Hash['compound' => Hash['compound' => Hash['intg' => 30]]], merge: true end it "updates the cached value returned by #conf" do @conf.conf('default') @conf.add 'default', Hash['compound' => Hash['compound' => Hash['intg' => 20]]], merge: true assert_equal 20, @conf.conf('default')['compound']['compound']['intg'].to_ruby end end describe "merge: false" do it "replaces an existing section" do assert @conf.add 'default', Hash['compound' => Hash['compound' => Hash['intg' => 20]]], merge: false assert_equal 20, @conf.conf('default')['compound']['compound']['intg'].to_ruby assert_nil @conf.conf('default')['compound']['vector_of_compound'] end it "updates the cached value returned by #conf" do @conf.conf('default') @conf.add 'default', Hash['compound' => Hash['compound' => Hash['intg' => 20]]], merge: false assert_equal 20, @conf.conf('default')['compound']['compound']['intg'].to_ruby end end it "adds a new section if the added section does not exist" do assert @conf.add 'does_not_already_exist', Hash['compound' => Hash['compound' => Hash['intg' => 20]]], merge: false assert_equal 20, @conf.conf('does_not_already_exist')['compound']['compound']['intg'].to_ruby end end describe "apply_conf_on_typelib_value" do attr_reader :array_t, :vector_t before do registry = Typelib::CXXRegistry.new @array_t = registry.create_array "/double", 2 @vector_t = registry.create_container "/std/vector", "/double" end it "should resize a smaller container" do vector = vector_t.new Orocos::TaskConfigurations.apply_conf_on_typelib_value(vector, [1, 2, 3]) assert_equal 3, vector.size assert_equal 1, vector[0] assert_equal 2, vector[1] assert_equal 3, vector[2] end it "should keep a bigger container to its current size" do vector = Typelib.from_ruby([1, 2], vector_t) Orocos::TaskConfigurations.apply_conf_on_typelib_value(vector, [-1]) assert_equal 2, vector.size assert_equal -1, vector[0] assert_equal 2, vector[1] end it "should only set the relevant values on a bigger array" do array = Typelib.from_ruby([1, 2], array_t) Orocos::TaskConfigurations.apply_conf_on_typelib_value(array, [-1]) assert_equal -1, array[0] assert_equal 2, array[1] end it "should raise ArgumentError if the array is too small" do array = Typelib.from_ruby([1, 2], array_t) assert_raises(ArgumentError) do Orocos::TaskConfigurations.apply_conf_on_typelib_value(array, [0, 1, 2]) end end end describe "#load_dir" do attr_reader :conf before do FakeFS.activate! @conf = flexmock(Orocos::ConfigurationManager.new) end after do FakeFS.deactivate! FakeFS::FileSystem.clear end it "should raise ArgumentError if the directory does not exist" do assert_raises(ArgumentError) { conf.load_dir "/does/not/exist" } end it "should ignore entries that are not files" do FileUtils.mkdir_p "/conf/entry.yml" conf.should_receive(:load_file).never conf.load_dir "/conf" end it "should ignore entries whose model cannot be found" do FileUtils.mkdir_p "/conf" File.open("/conf/entry.yml", 'w').close conf.should_receive(:load_file).with("/conf/entry.yml").and_raise(OroGen::TaskModelNotFound) # Should not raise conf.load_dir "/conf" end it "should return a hash from model name to section list if some sections got added or modified" do FileUtils.mkdir_p "/conf" File.open("/conf/first.yml", 'w').close File.open("/conf/second.yml", 'w').close conf.should_receive(:load_file).with("/conf/first.yml"). and_return("task::Model" => ['section']) conf.should_receive(:load_file).with("/conf/second.yml"). and_return("task::Model" => ['other_section']) # Should not raise assert_equal Hash["task::Model" => ['section', 'other_section']], conf.load_dir("/conf") end end describe "#load_file" do attr_reader :conf before do FakeFS.activate! FileUtils.mkdir_p "/conf" @conf = flexmock(Orocos::ConfigurationManager.new) end after do FakeFS.deactivate! FakeFS::FileSystem.clear end it "should raise ArgumentError if the file does not exist" do assert_raises(ArgumentError) { conf.load_file "/does/not/exist" } end it "should allow to specify the model name manually" do File.open("/conf/first.yml", 'w').close conf.load_file "/conf/first.yml", "configurations::Task" flexmock(Orocos).should_receive(:task_model_from_name).with("task::Model"). pass_thru end it "should infer the model name if it is not given" do File.open("/conf/configurations::Task.yml", 'w').close conf.load_file "/conf/configurations::Task.yml" flexmock(Orocos).should_receive(:task_model_from_name).with("task::Model"). pass_thru end it "should raise OroGen::TaskModelNotFound if the model does not exist" do File.open("/conf/first.yml", 'w').close assert_raises(OroGen::TaskModelNotFound) { conf.load_file "/conf/first.yml", "does_not::Exist" } end it "should return false if no sections got added or modified" do File.open("/conf/configurations::Task.yml", 'w').close conf.load_file "/conf/configurations::Task.yml" assert !conf.load_file("/conf/configurations::Task.yml") end it "should return a hash from model name to section list if some sections got added or modified" do File.open("/conf/file.yml", 'w') do |io| io.puts "--- name:test" end assert_equal Hash["configurations::Task" => ["test"]], conf.load_file("/conf/file.yml", "configurations::Task") end end describe "evaluate_numeric_field" do attr_reader :float_t, :int_t before do registry = Typelib::CXXRegistry.new @float_t = registry.get '/float' @int_t = registry.get '/int' end describe "plain values" do it "leaves integer values as-is" do assert_equal 10, conf.evaluate_numeric_field(10, int_t) end it "floors integer types, but issues a warning" do flexmock(Orocos::ConfigurationManager).should_receive(:warn).once assert_equal 9, conf.evaluate_numeric_field(9.7, int_t) end it "leaves floating-point values as-is" do assert_in_delta 9.2, conf.evaluate_numeric_field(9.2, float_t), 0.000001 end end describe "plain values represented as strings" do it "leaves integer values as-is" do assert_equal 10, conf.evaluate_numeric_field('10', int_t) end it "floors by default for integer types, but emits a warning" do flexmock(Orocos::ConfigurationManager).should_receive(:warn).once assert_equal 9, conf.evaluate_numeric_field('9.7', int_t) end it "allows to specify the rounding mode for integer types" do assert_equal 9, conf.evaluate_numeric_field('9.7.floor', int_t) assert_equal 10, conf.evaluate_numeric_field('9.2.ceil', int_t) assert_equal 10, conf.evaluate_numeric_field('9.7.round', int_t) end it "leaves floating-point values as-is" do assert_in_delta 9.2, conf.evaluate_numeric_field('9.2', float_t), 0.000001 end it "handles exponent specifications in floating-point values" do assert_in_delta 9.2e-3, conf.evaluate_numeric_field('9.2e-3', float_t), 0.000001 end end describe "values with units" do it "converts a plain unit to the corresponding SI representation" do assert_in_delta 10 * Math::PI / 180, conf.evaluate_numeric_field("10.deg", float_t), 0.0001 end it "handles power-of-units" do assert_in_delta 10 * (Math::PI / 180) ** 2, conf.evaluate_numeric_field("10.deg^2", float_t), 0.0001 end it "handles unit scales" do assert_in_delta 10 * 0.001 * (Math::PI / 180), conf.evaluate_numeric_field("10.mdeg", float_t), 0.0001 end it "handles full specifications" do assert_in_delta 10 / (0.001 * Math::PI / 180) ** 2 * 0.01 ** 3, conf.evaluate_numeric_field("10.mdeg^-2.cm^3", float_t), 0.0001 end end end describe "normalize_conf_value" do attr_reader :registry before do @registry = Typelib::CXXRegistry.new end it "maps the elements of a ruby array if the sizes do not match" do type = registry.build('/int[5]') result = conf.normalize_conf_value([1, 2, 3, 4], type) assert_kind_of Array, result result.each do |e| assert_kind_of type.deference, e end assert_equal [1, 2, 3, 4], result.map { |e| Typelib.to_ruby(e) } end it "maps arrays to a typelib array if the sizes match" do type = registry.build('/int[5]') result = conf.normalize_conf_value([1, 2, 3, 4, 5], type) assert_kind_of type, result assert_equal [1, 2, 3, 4, 5], result.to_a end it "maps hashes passing on the field types" do type = registry.create_compound '/Test' do |c| c.add 'f0', '/int' c.add 'f1', '/std/string' end result = conf.normalize_conf_value(Hash['f0' => 1, 'f1' => 'a_string'], type) result.each do |k, v| assert_kind_of type[k], v end assert_equal Hash['f0' => 1, 'f1' => 'a_string'], Typelib.to_ruby(result) end it "converts numerical values using evaluate_numeric_field" do type = registry.get '/int' flexmock(conf).should_receive(:evaluate_numeric_field). with('42', type).and_return(42).once result = conf.normalize_conf_value('42', type) assert_kind_of type, result assert_equal 42, Typelib.to_ruby(result) end it "converts /std/string as a final value instead of a container" do string_t = registry.get '/std/string' normalized = conf.normalize_conf_value("bla", string_t) assert_kind_of string_t, normalized assert_equal "bla", Typelib.to_ruby(normalized) end it "keeps typelib compound values that match the target value" do compound_t = registry.create_compound('/S') { |c| c.add 'a', '/int' } compound = compound_t.new(a: 10) normalized = conf.normalize_conf_value(compound, compound_t) assert_equal compound, normalized end it "normalizes a compound's field" do compound_t = registry.create_compound('/S') { |c| c.add 'a', '/int' } compound = compound_t.new(a: 10) normalized = conf.normalize_conf_value(Hash['a' => compound.a], compound_t) assert_equal compound.a, normalized['a'] end it "keeps typelib container values" do container_t = registry.create_container('/std/vector', '/int') container = container_t.new container << 0 normalized = conf.normalize_conf_value(container, container_t) assert_kind_of container_t, normalized normalized.raw_each { |v| assert_kind_of(container_t.deference, v) } normalized.raw_each.each_with_index { |v, i| assert_equal(container[i], v) } end it "keeps typelib array values" do array_t = registry.create_array('/int', 3) array = array_t.new normalized = conf.normalize_conf_value(array, array_t) assert_kind_of array_t, normalized normalized.raw_each { |v| assert_kind_of(array_t.deference, v) } normalized.raw_each.each_with_index { |v, i| assert_equal(array[i], v) } end it "properly handles Ruby objects that are converted from a complex Typelib type" do klass = Class.new compound_t = registry.create_compound('/S') { |c| c.add 'a', '/int' } compound_t.convert_from_ruby(klass) { |v| compound_t.new(a: 10) } normalized = conf.normalize_conf_value(klass.new, compound_t) assert_kind_of compound_t, normalized assert_kind_of compound_t['a'], normalized.raw_get('a') assert_equal 10, normalized['a'] end describe "conversion error handling" do attr_reader :type before do registry = Typelib::CXXRegistry.new inner_compound_t = registry.create_compound '/Test' do |c| c.add 'in_f', '/std/string' end array_t = registry.create_array inner_compound_t, 2 @type = registry.create_compound '/OuterTest' do |c| c.add 'out_f', array_t end end it "reports the exact point at which a conversion error occurs" do bad_value = Hash[ 'out_f' => Array[ Hash['in_f' => 'string'], Hash['in_f' => 10] ] ] e = assert_raises(Orocos::TaskConfigurations::ConversionFailed) do conf.normalize_conf_value(bad_value, type) end assert_equal %w{.out_f [1] .in_f}, e.full_path assert(/\.out_f\[1\]\.in_f/ === e.message) end it "reports the exact point at which an unknown field has been found" do bad_value = Hash[ 'out_f' => Array[ Hash['in_f' => 'string'], Hash['f' => 10] ] ] e = assert_raises(Orocos::TaskConfigurations::ConversionFailed) do conf.normalize_conf_value(bad_value, type) end assert_equal %w{.out_f [1]}, e.full_path assert(/\.out_f\[1\]/ === e.message) end it "validates array sizes" do bad_value = Hash[ 'out_f' => Array[ Hash['in_f' => 'string'], Hash['in_f' => 'blo'], Hash['in_f' => 'bla'] ] ] e = assert_raises(Orocos::TaskConfigurations::ConversionFailed) do conf.normalize_conf_value(bad_value, type) end assert_equal %w{.out_f}, e.full_path assert(/\.out_f/ === e.message) end end end describe "#save" do describe "#save(task)" do attr_reader :task before do start 'configurations::Task' => 'task' @task = Orocos.get 'task' # We must load all properties before we activate FakeFS task.each_property do |p| v = p.new_sample v.zero! p.write v end flexmock(conf).should_receive(:save). with(task, FlexMock.any, FlexMock.any). pass_thru end it "warns about deprecation" do flexmock(Orocos).should_receive(:warn).once flexmock(conf).should_receive(:save). with('sec', FlexMock.any, FlexMock.any). once conf.save(task, '/conf.yml', 'sec') end it "extracts the task's configuration and saves it to disk" do flexmock(Orocos).should_receive(:warn) expected_conf = conf.normalize_conf(Orocos::TaskConfigurations.read_task_conf(task)) flexmock(conf).should_receive(:save). with('sec', '/conf.yml', task_model: task.model). once. and_return(ret = flexmock) assert_same ret, conf.save(task, '/conf.yml', 'sec') assert_equal expected_conf, conf.conf('sec') end end describe "#save(name, file)" do attr_reader :section before do @section = Hash['enm' => 'First'] conf.add 'sec', section end it "saves the named configuration to disk" do flexmock(Orocos::TaskConfigurations).should_receive(:save). with(conf.conf('sec'), '/conf.yml', 'sec', task_model: conf.model, replace: false). once conf.save('sec', '/conf.yml') end it "allows to override the model" do task_model = flexmock flexmock(Orocos::TaskConfigurations).should_receive(:save). with(conf.conf('sec'), '/conf.yml', 'sec', task_model: task_model, replace: false). once conf.save('sec', '/conf.yml', task_model: task_model) end end end describe ".save" do describe ".save(task)" do attr_reader :task, :expected before do start 'configurations::Task' => 'task' @task = Orocos.get 'task' # We must load all properties before we activate FakeFS task.each_property do |p| v = p.new_sample v.zero! p.write v end conf = Orocos::TaskConfigurations.new(task.model) @expected = conf.normalize_conf(Orocos::TaskConfigurations.read_task_conf(task)) end it "extracts the configuration from the task and saves it" do flexmock(Orocos::TaskConfigurations). should_receive(:save).once. with(task, '/conf.yml', 'sec', task_model: task.model). pass_thru flexmock(Orocos::TaskConfigurations). should_receive(:save).once. with(expected, '/conf.yml', 'sec', replace: false, task_model: task.model) Orocos::TaskConfigurations.save(task, '/conf.yml', 'sec', task_model: task.model) end end describe ".save(config)" do before do FakeFS.activate! end after do FakeFS.deactivate! FakeFS::FileSystem.clear end it "creates the target directory" do config = Hash['enm' => 'First'] Orocos::TaskConfigurations.save(config, '/config/conf.yml', 'sec') assert File.directory?('/config') end it "saves the task's configuration file into the specified file and section" do config = Hash['enm' => 'First'] Orocos::TaskConfigurations.save(config, '/conf.yml', 'sec') conf.load_from_yaml '/conf.yml' c = conf.conf(['sec']) assert(c.keys == ['enm']) assert(:First == Typelib.to_ruby(c['enm']), "mismatch: #{config} != #{c}") end it "adds the property's documentation to the saved file" do model.find_property('enm').doc('this is a documentation string') config = Hash['enm' => 'First'] Orocos::TaskConfigurations.save(config, '/conf.yml', 'sec', task_model: model) data = File.readlines('/conf.yml') _, idx = data.each_with_index.find { |line, idx| line.strip == "# this is a documentation string" } assert data[idx + 1].strip =~ /^enm:/ end it "appends the documentation to an existing file" do config = Hash['enm' => 'First'] Orocos::TaskConfigurations.save(config, '/conf.yml', 'first') Orocos::TaskConfigurations.save(config, '/conf.yml', 'second') conf.load_from_yaml '/conf.yml' assert conf.has_section?('first') assert conf.has_section?('second') end it "uses the model's name as default file name" do config = Hash['enm' => :First] conf_dir = File.expand_path(File.join('conf', 'dir')) model = OroGen::Spec::TaskContext.blank('model::Name') expected_filename = File.join(conf_dir, "#{model.name}.yml") FileUtils.mkdir_p conf_dir Orocos::TaskConfigurations.save(config, expected_filename, 'sec', task_model: model) conf.load_from_yaml expected_filename enm = Typelib.to_ruby(conf.conf('sec')['enm']) assert(Typelib.to_ruby(enm) == :First) end it "uses #to_yaml to normalize the configuration hash" do config = flexmock conf_dir = File.expand_path(File.join('conf', 'dir')) model = OroGen::Spec::TaskContext.blank('model::Name') expected_filename = File.join(conf_dir, "#{model.name}.yml") FileUtils.mkdir_p conf_dir flexmock(Orocos::TaskConfigurations).should_receive(:to_yaml). with(config).and_return('enm' => :First) Orocos::TaskConfigurations.save(config, expected_filename, 'sec', task_model: model) conf.load_from_yaml expected_filename enm = Typelib.to_ruby(conf.conf('sec')['enm']) assert(Typelib.to_ruby(enm) == :First) end end describe "#to_yaml" do before do @registry = Typelib::Registry.new @numeric_t = @registry.create_numeric '/int', 4, :sint @converted_t = converted_t = @registry.create_compound '/with_convertion' do |c| c.add 'f', '/int' end @converted_ruby_t = converted_ruby_t = Class.new do attr_accessor :value def initialize(v = 0); @value = v end end @converted_t.convert_to_ruby(@converted_ruby_t) { |v| converted_ruby_t.new(v.f) } @converted_t.convert_from_ruby(@converted_ruby_t) { |v| converted_t.new(f: v.value) } end it "applies the conversion from converted types in compounds" do compound_t = @registry.create_compound '/C' do |c| c.add 'f', @converted_t end compound = compound_t.new(f: @converted_t.new(f: 0)) compound.f.value = 42 assert_equal Hash['f' => Hash['f' => 42]], Orocos::TaskConfigurations.to_yaml(compound) end end end end class TC_Orocos_Configurations < Minitest::Test TaskConfigurations = Orocos::TaskConfigurations def test_merge_conf_array assert_raises(ArgumentError) { TaskConfigurations.merge_conf_array([nil, 1], [nil, 2], false) } assert_equal([1, 2], TaskConfigurations.merge_conf_array([1, nil], [nil, 2], false)) assert_equal([nil, 2], TaskConfigurations.merge_conf_array([nil, 1], [nil, 2], true)) assert_equal([1, 2], TaskConfigurations.merge_conf_array([], [1, 2], false)) assert_equal([1, 2], TaskConfigurations.merge_conf_array([], [1, 2], true)) assert_equal([1, 2], TaskConfigurations.merge_conf_array([1], [nil, 2], false)) assert_equal([1, 2], TaskConfigurations.merge_conf_array([1], [nil, 2], true)) assert_equal([1, 4, 3, 5], TaskConfigurations.merge_conf_array([1, 2, 3], [nil, 4, nil, 5], true)) assert_equal([1, 2], TaskConfigurations.merge_conf_array([1, 2], [1, 2], false)) assert_equal([1, 2], TaskConfigurations.merge_conf_array([1, 2], [1, 2], true)) end def test_override_arrays if !Orocos.registry.include?('/base/Vector3d') type_m = Orocos.registry.create_compound('/base/Vector3d') do |t| t.data = '/double[4]' end Orocos.default_loader.register_type_model(type_m) end model = mock_task_context_model do property 'gyrorw', '/base/Vector3d' property 'gyrorrw', '/base/Vector3d' end conf = Orocos::TaskConfigurations.new(model) default_conf = { 'gyrorrw' => { 'data' => [2.65e-06, 4.01e-06, 5.19e-06] }, 'gyrorw' => { 'data' => [6.04E-05, 6.94E-05, 5.96E-05] } } conf.add('default', default_conf) xsens_conf = { 'gyrorw' => { 'data' => [0.0006898864, 0.0007219069, 0.0005708627] } } conf.add('mti_xsens', xsens_conf) result = conf.conf(['default', 'default'], true) assert_equal(default_conf, result) result = conf.conf(['default', 'mti_xsens'], true) assert_equal({ 'gyrorrw' => default_conf['gyrorrw'], 'gyrorw' => xsens_conf['gyrorw'] }, result) end end
class RenameBoardTripsTable < ActiveRecord::Migration[5.2] def change rename_table :boards_trips, :board_trips end end
require 'rake/clean' require_relative 'rakelib/ascii_to_video_utils' require_relative 'rakelib/dodgeball_runner' SP_SCRIPT_TEMPLATE = "ENVIRONMENT/aimaload.lisp" MP_SCRIPT_TEMPLATE = "ENVIRONMENT/aimaload_mp.lisp" MP_SCRIPT = "mp_script.lisp" AGENTS = FileList["*"].exclude(/ENVIRONMENT.*/) .exclude(/sublime/) .exclude(/Rakefile/) .exclude(/output/) .exclude(/mp_script\.lisp/) .exclude(/tags/) .exclude(/images/) .exclude(/result\.mp4/) .exclude(/README\.md/) SP_SCRIPTS = AGENTS.collect { |a| "#{a}/sp_script.lisp" } MP_AGENTS = AGENTS.collect { |a| "#{a}/#{a}_mp.lisp" } CLEAN.include("*/sp_script.lisp") CLEAN.include("*/mp_script.lisp") CLEAN.include("images") CLEAN.include("*/images") CLEAN.include("output") CLEAN.include("*/output") CLEAN.include("*/*.gif") CLEAN.include("result.mp4") CLEAN.include("*/*.mp4") CLEAN.include("**/*.fasl") CLEAN.include("**/*.fas") CLEAN.include(MP_SCRIPT) SP_READY_AGENTS = [:cackolen, :chmelond, :cincuada, :cadekva1, #:fifiksta, :fiserale, :hanafran, :hlusiond, :hrubaeli, :kacurtom, #:kersnmar, :kokorigo, #:kotrbluk, #:ludacrad, :macalkar, :milikjan, #:musilon4, :nohavja1, #:palkoigo, :perutond, #:sembejir, :silhaja6, #:staryvac, :steklmar, :stiplsta, :strnaj11, :temnymar, :valespe3, :vanikjak, :wancavil ] MP_READY_AGENTS = [:cackolen, :chmelond, #:cincuada, #:fifiksta, #:fiserale, #:hanafran, :hlusiond, #:hrubaeli, :kacurtom, #:kersnmar, :kokorigo, #:kotrbluk, #:ludacrad, #:macalkar, #:milikjan, #:musilon4, #:nohavja1, #:palkoigo, #:perutond, #:sembejir, #:silhaja6, #:staryvac, #:steklmar, #:stiplsta, :strnaj11, :temnymar, #:valespe3, :vanikjak, :wancavil ] AGENTS.each do |agent| file "#{agent}/sp_script.lisp" => "#{agent}/#{agent}_sp.lisp" do script_file = "#{agent}/sp_script.lisp" File.open script_file, 'w+' do |f| f.puts single_player_script(agent) end File.chmod 0755, script_file end file "#{agent}/mp_script.lisp" => "#{agent}/#{agent}_mp.lisp" do script_file = "#{agent}/mp_script.lisp" IO.write(script_file, single_player_script(agent)) File.chmod 0755, script_file end file "#{agent}/#{agent}_sp.lisp" file "#{agent}/#{agent}_mp.lisp" desc "single player with agent #{agent}" task "#{agent}_sp" => "#{agent}/sp_script.lisp" do Dodgeball::DodgeballRunner.new("#{agent}/sp_script.lisp", "#{agent}/output").run end desc "single player with multi player agent #{agent}" task "#{agent}_mp" => "#{agent}/mp_script.lisp" do Dodgeball::DodgeballRunner.new("#{agent}/mp_script.lisp", "#{agent}/output").run end desc "generate animation for single player with agent #{agent}" task "#{agent}_sp_mp4" => "#{agent}_sp" do AsciiToVideoUtils.create_animation("#{agent}/output", "#{agent}/images", "#{agent}/#{agent}.mp4", 3) end end file MP_SCRIPT => MP_AGENTS do IO.write(MP_SCRIPT, multi_player_script) File.chmod 0755, MP_SCRIPT end task :default => [:single_player, :multi_player] desc "single player for each sp ready agent" task :single_player => SP_SCRIPTS do SP_READY_AGENTS.each do |agent| Dodgeball::DodgeballRunner.new("#{agent}/sp_script.lisp", "#{agent}/output").run end end desc "single player for sp ready agent, with pause after each run" task :single_player_debug => SP_SCRIPTS do SP_READY_AGENTS.each do |agent| Dodgeball::DodgeballRunner.new("#{agent}/sp_script.lisp", "#{agent}/output").run puts agent puts "Continue?" answer = STDIN.gets.chomp exit if answer != 'y' && answer != '' end end desc "multi player with all mp ready agents" task :multi_player => MP_SCRIPT do Dodgeball::DodgeballRunner.new(MP_SCRIPT, "output").run end task :multi_player_mp4 => :multi_player do AsciiToVideoUtils.create_animation("output", "images", "result.mp4") end def multi_player_script script = IO.read(MP_SCRIPT_TEMPLATE) script .gsub("<AGENT_PATHS>", MP_READY_AGENTS.collect {|a| "(print \"Loading #{a}\")\n(load \"#{a}/#{a}_mp.lisp\")\n(print \"#{a} sucessfully loaded\")" }.join("\n")) .gsub("<AGENT_NAMES>", MP_READY_AGENTS.collect {|a| "'#{a}" }.join(" ")) end def single_player_script(agent) script = IO.read(SP_SCRIPT_TEMPLATE) script.gsub("<AGENT_PATH>", "#{Dir.pwd}/#{agent}/#{agent}_sp.lisp").gsub("<AGENT_NAME>", agent) end
class SystemAPI < Grape::API get '/ping' do "Pong from rollout-service, current time is #{Time.now}" end end
require 'spec_helper' Sec::Firms.configure do |config| config.root_path = 'data' end describe Sec::Firms::Downloader do subject { described_class.new('https://www.google.com/') } describe 'content' do context 'when local file does not exist' do before { `rm #{subject.file_name}` } it 'downloads the file and save its content' do expect(subject.content).to match('Google') end end context 'when local file exists' do before { subject.content } it 'reads file content' do expect(subject.content).to match('Google') end end end describe 'file_name' do it 'generates file name using url and root path' do expect(subject.file_name).to eq('data/downloads/d75277cdffef995a46ae59bdaef1db86.xml') end end end
class BookController < ApplicationController before_action :set_book, only: [:show, :edit, :update, :destroy] def index @books = Book.all end def new @book = Book.new end private # Use callbacks to share common setup or constraints between actions. def set_book @book = Book.find(params[:id]) end end
# Admin Message Serializer class AdminMessageSerializer < ActiveModel::Serializer attributes :title, :message # Relationships belongs_to :user end
class CitiesController < ApplicationController before_action :set_state def index json_response({ :cities => @state.cities }) end def set_state @state = State.find(params[:state_id]) if params[:state_id] end end
# frozen_string_literal: true RSpec.describe "search result pagination", type: :system, clean: true, js: true do before do solr = Blacklight.default_index.connection solr.add([dog, cat, bird]) solr.commit end let(:dog) do { id: '111', title_tesim: 'Handsome Dan is a bull dog.', creator_tesim: 'Eric & Frederick', subjectName_ssim: "this is the subject name", sourceTitle_tesim: "this is the source title", orbisBibId_ssi: '1238901', visibility_ssi: 'Public' } end let(:cat) do { id: '212', title_tesim: 'Handsome Dan is not a cat.', creator_tesim: 'Frederick & Eric', sourceTitle_tesim: "this is the source title", orbisBibId_ssi: '1234567', visibility_ssi: 'Public' } end let(:bird) do { id: '313', title_tesim: 'Handsome Dan is not a bird.', creator_tesim: 'Frederick & Eric', sourceTitle_tesim: "this is the source title", orbisBibId_ssi: '1234567', visibility_ssi: 'Public' } end it "displays no pagination when search results are less than per page cap" do # default per page cap is 10 and there are 3 search results visit '/catalog?search_field=all_fields&view=list' # this double arrow is the last page link in the bottom pagination expect(page).not_to have_link "»" end it 'displays pagination when search results are greater than per page cap"' do # sets per page cap to 2 and there are 3 search results visit '/catalog?per_page=2&q=&search_field=all_fields' # last page link expect(page).to have_link "»" end context "navigating with search context links" do it "has the appropriate context links on the first page of results" do visit '/catalog?per_page=2&q=&search_field=all_fields' expect(page).to have_link "PREVIOUS" # this link is disabled on the first page of results expect(page).not_to have_link "«" expect(page).to have_link "»" expect(page).to have_link "NEXT" end it "jumps to last page of results" do visit '/catalog?per_page=2&q=&search_field=all_fields' click_on "»" within 'ul.pagination' do # next button is disabled on last page so it cannot be found expect(page).not_to have_button("NEXT") end end it "jumps to first page of results" do visit '/catalog?per_page=2&q=&search_field=all_fields' click_on "»" click_on "«" within 'ul.pagination' do # previous button is disabled on first page so it cannot be found expect(page).not_to have_button("PREVIOUS") end end end end
require 'minitest' require 'minitest/autorun' require 'minitest/pride' require_relative 'credit_check' class CreditCheckTest < MiniTest::Test def test_class_exists ccheck = CreditCheck.new assert ccheck end def test_stringify_returns_string ccheck = CreditCheck.new number = 123456789012345 assert_instance_of String, ccheck.stringify(number) end def test_split_string_returns_array_of_elements ccheck = CreditCheck.new string = "123" assert_equal ccheck.split_string(string), ["1","2","3"] end def test_sum_array_of_numbers ccheck = CreditCheck.new numbers = [1,2,3] assert_equal ccheck.sum_array(numbers), 6 end def test_reverse_the_number ccheck = CreditCheck.new number = "0123456789012345" reversed_number = "5432109876543210" assert ccheck.reverse_number(number), reversed_number end def test_combine_large ccheck = CreditCheck.new number = 11 assert_equal 2, ccheck.combine_large(number) end def test_doubles_every_second_digit_after_reverse ccheck = CreditCheck.new number = %w(5 4 3 2 1 0 9 8) new_number = [5,8,3,4,1,0,9,16] assert_equal ccheck.collect_doubled_numbers(number), new_number end def test_validate_returns_true ccheck = CreditCheck.new number1 = "5541808923795240" number2 = "4024007136512380" number3 = "6011797668867828" assert ccheck.validate(number1) assert ccheck.validate(number2) assert ccheck.validate(number3) end def test_validate_returns_false ccheck = CreditCheck.new number1 = "5541801923795240" number2 = "4024007106512380" number3 = "6011797668868728" refute ccheck.validate(number1) refute ccheck.validate(number2) refute ccheck.validate(number3) end def test_american_express_true ccheck = CreditCheck.new number1 = "342804633855673" #passing assert ccheck.validate(number1) end def test_american_express_false ccheck = CreditCheck.new number2 = "342801633855673" #failing refute ccheck.validate(number2) end end
class RenameAssetsTable < ActiveRecord::Migration[4.2] def change rename_table :assets, :resource_assets end end
require 'spec_helper' describe "The app" do it "should display version number" do Lmpm.version.should eq Lmpm::VERSION end describe "Configure" do before :each do @uri = "https://github.com/TheNotary/the_notarys_linux_mint_postinstall_configuration" end it "should be able to configure LM based on a config file (link)" do Lmpm.configure(@uri).should eq Lmpm.data[:successful_configure_message] end end end
class DropDrinksIngredients < ActiveRecord::Migration def change drop_table :drinks_ingredients end end
#To render plain text from a Rails controller, you specify plain:, followed by the text you want to display: # class BirdsController < ApplicationController # def index # @birds = Bird.all # render plain: "Hello #{@birds[3].name}" # end # end #To render JSON from a Rails controller, you specify json: followed something can be converted to valid JSON: # class BirdsController < ApplicationController # def index # @birds = Bird.all # render json: 'Remember that JSON is just object notation converted to string data, so strings also work here' # end # end #We can pass strings as we see above, as well as hashes, arrays, and other data types: # class BirdsController < ApplicationController # def index # @birds = Bird.all # render json: { message: 'Hashes of data will get converted to JSON' } # end # end # class BirdsController < ApplicationController # def index # @birds = Bird.all # render json: ['As','well','as','arrays'] # end # end #In our bird watching case, we actually already have a collection of data, @birds, so we can write: # class BirdsController < ApplicationController # def index # @birds = Bird.all # render json: @birds # end # end # We can choose to explicitly convert our array or hash, without any problem by adding to_json to the end: # class BirdsController < ApplicationController # def index # @birds = Bird.all # render json: { birds: @birds, messages: ['Hello Birds', 'Goodbye Birds'] } # end # end # We can choose to explicitly convert our array or hash, without any problem by adding to_json to the end: class BirdsController < ApplicationController def index @birds = Bird.all render json: { birds: @birds, messages: ['Hello Birds', 'Goodbye Birds'] }.to_json end end
class Post < ActiveRecord::Base validates :url,presence:true validates :image,presence:true validates :post,presence:true validates :title,presence:true validates :category,presence:true validates :url, uniqueness: {message: "already exist"},if: "url.present?" end
class Expense include Mongoid::Document include Mongoid::Timestamps include Mongoid::Includes field :name, type: String field :description, type: String field :value, type: Float field :status, type: Integer field :date, type: Date field :tags, type: Array belongs_to :clan belongs_to :user scope :filter_month, ->(date_filter, current_clan) {where date:( date_filter.beginning_of_month .. date_filter.end_of_month), clan: current_clan} end
class Team < ApplicationRecord has_and_belongs_to_many :players has_many :organizations has_many :leagues, through: :organizations validates_presence_of :name end
module Spree module Admin class LabelsController < Spree::Admin::BaseController def index @labels = Spree::ProductLabel.page(params[:page]) end def new @label = Spree::ProductLabel.new end def edit @label = Spree::ProductLabel.find(params[:id]) end def create @label = Spree::ProductLabel.new(params[:product_label]) if @label.save redirect_to spree.admin_labels_path, :notice => 'DONE!' else render :new end end def update @label = Spree::ProductLabel.find(params[:id]) if @label.update_attributes(params[:product_label]) redirect_to :back, :notice => 'DONE!' else render :edit end end def destroy @label = Spree::ProductLabel.find(params[:id]) @label.destroy redirect_to :back, :notice => 'DONE!' end # for product def available @labels = Spree::ProductLabel.all @product = Spree::Product.find_by_permalink!(params[:product_id]) end def select @product = Spree::Product.find_by_permalink!(params[:product_id]) @label = Spree::ProductLabel.find(params[:id]) @product.labels << @label respond_to do |format| format.html { redirect_to :back } format.js { render :text => 'Ok' } end end def remove @product = Spree::Product.find_by_permalink!(params[:product_id]) @label = Spree::ProductLabel.find(params[:id]) @product.labels.delete(@label) respond_to do |format| format.html { redirect_to :back } format.js { render :text => 'Ok' } end end def update_positions params[:positions].each do |id, index| Spree::ProductLabel.where(:id => id).update_all(:position => index) end respond_to do |format| format.html { redirect_to admin_labels_url() } format.js { render :text => 'Ok' } end end end end end
# ============================================================================= # # MODULE : lib/dispatch_queue_rb/mixins/dispatch_sync_impl.rb # PROJECT : DispatchQueue # DESCRIPTION : # # Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved. # ============================================================================= module DispatchQueue module DispatchSyncImpl def dispatch_sync( group:nil, &task ) mutex, condition = ConditionVariablePool.acquire() result = nil mutex.synchronize do dispatch_async( group:group ) do result = task.call() mutex.synchronize { condition.signal() } end condition.wait( mutex ) end ConditionVariablePool.release( mutex, condition ) result end def dispatch_barrier_sync( group:nil, &task ) mutex, condition = ConditionVariablePool.acquire() result = nil mutex.synchronize do dispatch_barrier_async( group:group ) do result = task.call() mutex.synchronize { condition.signal() } end condition.wait( mutex ) end ConditionVariablePool.release( mutex, condition ) result end end # class DispatchSyncImpl end # module DispatchQueue
class AddFoodIdToFoodOrders < ActiveRecord::Migration def change add_column :food_orders, :food_id, :integer end end
# frozen_string_literal: true class Category include Mongoid::Document belongs_to :parent_category, class_name: 'Category' end
RSpec.feature "Users can view reports" do include HideFromBullet def expect_to_see_relevant_table_headings(headings: []) within "thead tr" do headings.each_with_index do |heading, heading_index| expect(page).to have_xpath("th[#{heading_index + 1}]", text: heading) end end end context "as a BEIS user" do let(:beis_user) { create(:beis_user) } before do authenticate!(user: beis_user) end after { logout } def expect_to_see_a_table_of_reports_grouped_by_organisation(selector:, reports:, organisations:) within selector do expect(page.find_all("th[scope=rowgroup]").count).to eq(organisations.count) expect(page.find_all("tbody tr").count).to eq(reports.count) headings = ["Organisation", "Financial quarter"] headings.concat(["Deadline", "Status"]) if selector == "#current" headings.concat(["Fund (level A)", "Description"]) expect_to_see_relevant_table_headings(headings: headings) organisations.each do |organisation| expect_to_see_grouped_rows_of_reports_for_an_organisation( organisation: organisation, expected_reports: reports.select { |r| r.organisation == organisation }, selector: selector ) end end end def expect_to_see_grouped_rows_of_reports_for_an_organisation(organisation:, expected_reports:, selector:) expected_heading_id = [organisation.id, selector[1, selector.length - 1]].join("-") expect(page).to have_selector("th[id='#{expected_heading_id}']") expect(page).to have_content organisation.name expected_reports.each do |report| within "##{report.id}" do expect(page).to have_content report.description expect(page).to have_content report.financial_quarter_and_year end end end scenario "they can see a list of all active and approved reports" do organisations = create_list(:partner_organisation, 2) unapproved_reports = [ create_list(:report, 2, :active, organisation: organisations.first), create_list(:report, 3, :active, organisation: organisations.last), create_list(:report, 3, :awaiting_changes, organisation: organisations.first), create_list(:report, 2, :in_review, organisation: organisations.last) ].flatten approved_reports = [ create_list(:report, 3, :approved, organisation: organisations.first), create_list(:report, 1, :approved, organisation: organisations.last) ].flatten visit reports_path expect(page).to have_content t("page_title.report.index") expect_to_see_a_table_of_reports_grouped_by_organisation( selector: "#current", reports: unapproved_reports, organisations: organisations ) expect_to_see_a_table_of_reports_grouped_by_organisation( selector: "#approved", reports: approved_reports, organisations: organisations ) end scenario "they can see a list of active and approved reports for a single organisation" do organisation = create(:partner_organisation) current = [ create_list(:report, 2, :active, organisation: organisation), create_list(:report, 3, :awaiting_changes, organisation: organisation), create_list(:report, 2, :in_review, organisation: organisation) ].flatten approved = create_list(:report, 3, :approved, organisation: organisation) skip_bullet do visit organisation_reports_path(organisation) end expect(page).to have_content t("page_title.report.index") state_groups = ["current", "approved"] state_groups.each do |state_group| within "##{state_group}" do headings = ["Financial quarter"] headings.concat(["Deadline", "Status"]) if state_group == "current" headings.concat(["Fund (level A)", "Description"]) expect_to_see_relevant_table_headings(headings: headings) reports = binding.local_variable_get(state_group) expect(page.find_all("tbody tr").count).to eq(reports.count) end end end scenario "can view a report belonging to any partner organisation" do report = create(:report, :active) visit reports_path within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_content report.financial_quarter expect(page).to have_content report.fund.source_fund.name end scenario "the report includes a summary" do report = create(:report, :active, organisation: build(:partner_organisation)) visit reports_path within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_content report.description expect(page).to have_content l(report.deadline) expect(page).not_to have_content t("page_content.report.summary.editable.#{report.editable?}") expect(page).to have_content report.organisation.name expect(page).to have_content t("page_content.tab_content.summary.activities_added") expect(page).to have_content t("page_content.tab_content.summary.activities_updated") expect(page).to have_content t("page_content.tab_content.summary.actuals_total") expect(page).to have_content t("page_content.tab_content.summary.forecasts_total") expect(page).to have_content t("page_content.tab_content.summary.refunds_total") end scenario "the report includes a list of newly created and updated activities" do partner_organisation = create(:partner_organisation) fund = create(:fund_activity) programme = create(:programme_activity, parent: fund) project = create(:project_activity, parent: programme) report = create(:report, :active, fund: fund, organisation: partner_organisation, financial_quarter: 1, financial_year: 2021) new_activity = create(:third_party_project_activity, organisation: partner_organisation, parent: project, originating_report: report) updated_activity = create(:third_party_project_activity, organisation: partner_organisation, parent: project) _history_event = create(:historical_event, activity: updated_activity, report: report) visit reports_path within "##{report.id}" do click_on t("default.link.show") end within ".govuk-tabs" do click_on "Activities" end expect(page).to have_content new_activity.title expect(page).to have_content updated_activity.title end context "when there is no report description" do scenario "the summary does not include the empty value" do report = create(:report, :active, organisation: build(:partner_organisation), description: nil) visit report_path(report.id) expect(page).not_to have_content t("form.label.report.description") end end scenario "they can view budgets in a report" do report = create(:report, :active) budget = create(:budget, report: report) visit report_budgets_path(report) within "##{budget.id}" do expect(page).to have_content budget.parent_activity.roda_identifier expect(page).to have_content budget.value end end scenario "they see helpful guidance about and can download a CSV of a report" do report = create(:report, :active) visit reports_path within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_content("Download a CSV file to review offline.") expect(page).to have_link("guidance in the help centre (opens in new tab)") click_link t("action.report.download.button") expect(page.response_headers["Content-Type"]).to include("text/csv") expect(page).to have_http_status(:ok) end context "when the report has an export_filename" do scenario "the link to download the report is the download path instead of the show path" do report = create(:report, :approved, export_filename: "FQ4 2020-2021_GCRF_BA_report-20230111184653.csv") visit reports_path within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_link(t("action.report.download.button"), href: download_report_path(report)) end end context "if the report description is empty" do scenario "the report csv has a filename made up of the fund name & report financial year & quarter" do report = create(:report, :active, description: "", financial_quarter: 4, financial_year: 2019) visit reports_path within "##{report.id}" do click_on t("default.link.show") end click_on t("action.report.download.button") expect(page.response_headers["Content-Type"]).to include("text/csv") header = page.response_headers["Content-Disposition"] expect(header).to match(/#{ERB::Util.url_encode("FQ4 2019-2020")}/) expect(header).to match(/#{ERB::Util.url_encode(report.fund.roda_identifier)}/) end end context "when there are no active reports" do scenario "they see an empty state on the current tab" do visit reports_path within("#current") do expect(page).to have_content t("table.body.report.no_current_reports") end end end context "when there are no approved reports" do scenario "they see an empty state on the approved tab" do visit reports_path within("#approved") do expect(page).to have_content t("table.body.report.no_approved_reports") end end end context "when there are legacy ingested reports" do let(:activity) { create(:project_activity) } let!(:report) { create(:report, :active, fund: activity.associated_fund, organisation: activity.organisation, financial_quarter: nil, financial_year: nil) } before do visit reports_path within "##{report.id}" do click_on t("default.link.show") end end it "they can be viewed" do expect(page).to have_content "Variance" visit report_budgets_path(report) expect(page).to have_content "Budgets" end it "they canont be downloaded as CSV" do expect(page).not_to have_content "Download report as CSV file" end end scenario "they can view all comments made during a reporting period" do report = create(:report) activities = create_list(:project_activity, 2, organisation: report.organisation, source_fund_code: report.fund.source_fund_code) comments_for_report = [ create_list(:comment, 3, commentable: activities[0], report: report), create_list(:comment, 1, commentable: activities[1], report: report) ].flatten page = ReportPage.new(report) page.visit_comments_page expect(page).to have_comments_grouped_by_activity( activities: activities, comments: comments_for_report ) expect(page).to_not have_edit_buttons_for_comments(comments_for_report) end end context "as a partner organisation user" do let(:partner_org_user) { create(:partner_organisation_user) } def expect_to_see_a_table_of_reports(selector:, reports:) within selector do expect(page.find_all("tbody tr").count).to eq(reports.count) headings = ["Financial quarter"] headings.concat(["Deadline", "Status"]) if selector == "#current" headings.concat(["Fund (level A)", "Description"]) headings << "Can edit?" if selector == "#current" expect_to_see_relevant_table_headings(headings: headings) reports.each do |report| within "##{report.id}" do expect(page).to have_content report.description expect(page).to have_content report.financial_quarter_and_year end end end end before do authenticate!(user: partner_org_user) end after { logout } scenario "they can see a list of all their active and approved reports" do reports_awaiting_changes = create_list(:report, 2, organisation: partner_org_user.organisation, state: :awaiting_changes) approved_reports = create_list(:report, 3, :approved, organisation: partner_org_user.organisation) visit reports_path expect(page).to have_content t("page_title.report.index") expect_to_see_a_table_of_reports(selector: "#current", reports: reports_awaiting_changes) expect_to_see_a_table_of_reports(selector: "#approved", reports: approved_reports) end context "when there is an active report" do scenario "can view their own report" do report = create(:report, :active, organisation: partner_org_user.organisation) visit reports_path expect_to_see_a_table_of_reports(selector: "#current", reports: [report]) within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_content report.financial_quarter expect(page).to have_content report.fund.source_fund.name end scenario "their own report includes a summary" do report = create(:report, :active, organisation: partner_org_user.organisation) visit reports_path within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_content report.description expect(page).to have_content l(report.deadline) expect(page).to have_content t("page_content.report.summary.editable.#{report.editable?}") expect(page).not_to have_content report.organisation.name expect(page).to have_content t("page_content.tab_content.summary.activities_added") expect(page).to have_content t("page_content.tab_content.summary.activities_updated") expect(page).to have_content t("page_content.tab_content.summary.actuals_total") expect(page).to have_content t("page_content.tab_content.summary.forecasts_total") expect(page).to have_content t("page_content.tab_content.summary.refunds_total") end scenario "the report shows the total forecasted and actual spend and the variance" do quarter_two_2019 = Date.parse("2019-7-1") activity = create(:project_activity, organisation: partner_org_user.organisation) reporting_cycle = ReportingCycle.new(activity, 4, 2018) forecast = ForecastHistory.new(activity, financial_quarter: 1, financial_year: 2019) reporting_cycle.tick forecast.set_value(1000) reporting_cycle.tick report = Report.for_activity(activity).in_historical_order.first report_quarter = report.own_financial_quarter _actual_value = create(:actual, parent_activity: activity, report: report, value: 1100, **report_quarter) travel_to quarter_two_2019 do visit reports_path within "##{report.id}" do click_on t("default.link.show") end click_on t("tabs.report.variance.heading") expect(page).to have_content t("table.header.activity.identifier") expect(page).to have_content t("table.header.activity.forecasted_spend") within "##{activity.id}" do expect(page).to have_content "£1,000.00" expect(page).to have_content "£1,100.00" expect(page).to have_content "£100.00" end within "tfoot tr:first-child td" do expect(page).to have_content "£100.00" end end end scenario "they see helpful content about uploading activities data on the activities tab" do report = create(:report, :active, organisation: partner_org_user.organisation) visit report_activities_path(report) expect(page).to have_text("Ensure you use the correct template when uploading activities data.") expect(page).to have_text("Large numbers of activities can be added via the activities upload.") expect(page).to have_text("For guidance on uploading activities data, see the") expect(page).to have_text("To get implementing organisation names, you can refer to the") expect(page).to have_link( "Upload activity data", href: new_report_activities_upload_path(report) ) expect(page).to have_link( "guidance in the help centre (opens in new tab)", href: "https://beisodahelp.zendesk.com/hc/en-gb/articles/1500005510061-Understanding-the-Bulk-Upload-Functionality-to-Report-your-Data" ) expect(page).to have_link( "Implementing organisations section (opens in new tab)", href: organisations_path ) end scenario "they see helpful content about uploading actuals spend data and a link to the template on the actuals tab" do report = create(:report, :active, organisation: partner_org_user.organisation) visit report_actuals_path(report) expect(page).to have_text("Ensure you use the correct template (available below) when uploading the actuals and refunds.") expect(page).to have_text("Large numbers of actuals and refunds can be added via the actuals upload.") expect(page).to have_text("For guidance on uploading actuals and refunds, see") expect(page).to have_text("If you need to upload comments about why there are no actuals/refunds, add an activity comment rather than uploading a blank actuals template.") expect(page).to have_link( "Download actuals and refunds data template", href: report_actuals_upload_path(report, format: :csv) ) expect(page).to have_link( "guidance in the help centre (opens in new tab)", href: "https://beisodahelp.zendesk.com/hc/en-gb/articles/1500005601882-Downloading-the-Actuals-Template-in-order-to-Bulk-Upload" ) end scenario "they can view and edit budgets in a report" do activity = create(:project_activity, organisation: partner_org_user.organisation) report = create(:report, :active, organisation: partner_org_user.organisation, fund: activity.associated_fund) budget = create(:budget, report: report, parent_activity: activity) visit report_budgets_path(report) within "##{budget.id}" do expect(page).to have_content budget.parent_activity.roda_identifier expect(page).to have_content budget.value expect(page).to have_link t("default.link.edit"), href: edit_activity_budget_path(budget.parent_activity, budget) end end scenario "they can view their own submitted reports" do report = create(:report, state: :submitted, organisation: partner_org_user.organisation) visit reports_path expect(page).to have_content report.description end scenario "they do not see the name of the associated organisation" do report = create(:report) visit reports_path expect(page).not_to have_content report.organisation.name end scenario "cannot view a report belonging to another partner organisation" do another_report = create(:report, organisation: create(:partner_organisation)) visit report_path(another_report) expect(page).to have_http_status(:unauthorized) end scenario "they see helpful guidance about and can download a CSV of their own report" do report = create(:report, :active, organisation: partner_org_user.organisation) visit reports_path within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_content("Download a CSV file to review offline.") expect(page).to have_link("guidance in the help centre (opens in new tab)") click_link t("action.report.download.button") expect(page.response_headers["Content-Type"]).to include("text/csv") expect(page.response_headers["Content-Type"]).to include("text/csv") expect(page).to have_http_status(:ok) end end context "when the report has an export_filename" do scenario "the link to download the report is the download path instead of the show path" do report = create(:report, :approved, export_filename: "FQ4 2020-2021_GCRF_BA_report-20230111184653.csv", organisation: partner_org_user.organisation) visit reports_path within "##{report.id}" do click_on t("default.link.show") end expect(page).to have_link(t("action.report.download.button"), href: download_report_path(report)) end end scenario "they can view all comments made during a reporting period" do report = create(:report, :active, organisation: partner_org_user.organisation, fund: create(:fund_activity, :newton)) activities = create_list(:project_activity, 2, :newton_funded, organisation: partner_org_user.organisation) activity_comments = [ create_list(:comment, 3, commentable: activities[0], report: report, owner: partner_org_user), create_list(:comment, 1, commentable: activities[1], report: report, owner: partner_org_user) ].flatten actual_comments = [ create_list(:comment, 1, commentable: create(:actual, parent_activity: activities[0]), report: report), create_list(:comment, 1, commentable: create(:actual, parent_activity: activities[1]), report: report) ].flatten refund_comments = [ create_list(:comment, 2, commentable: create(:refund, parent_activity: activities[0]), report: report), create_list(:comment, 1, commentable: create(:refund, parent_activity: activities[1]), report: report) ].flatten adjustment_comments = create_list(:comment, 2, commentable: create(:adjustment, parent_activity: activities[0]), report: report) comments_for_report = activity_comments + actual_comments + refund_comments + adjustment_comments page = ReportPage.new(report) page.visit_comments_page expect(page).to have_comments_grouped_by_activity( activities: activities, comments: comments_for_report ) expect(page).to have_edit_buttons_for_comments(activity_comments) expect(page).to_not have_edit_buttons_for_comments(adjustment_comments) expect(page).to_not have_edit_buttons_for_comments(comments_for_report) end context "when there are no active reports" do scenario "they see an empty state on the current tab" do report = create(:report, :approved, organisation: partner_org_user.organisation) visit reports_path within("#current") do expect(page).not_to have_content report.description expect(page).to have_content t("table.body.report.no_current_reports") end end end context "when there are no approved reports" do scenario "they see an empty state on the approved tab" do report = create(:report, organisation: partner_org_user.organisation) visit reports_path within("#approved") do expect(page).not_to have_content report.description expect(page).to have_content t("table.body.report.no_approved_reports") end end end end end
module Pajama class Forecast include Term::ANSIColor SIMULATION_COUNT = 10000 PRINT_DOT_EVERY = SIMULATION_COUNT / 50 def initialize(db, task_weights) @db = db @task_weights = task_weights @now = DateTime.now @owners = Array.new @ship_date_counts = Hash.new { |h,k| h[k] = Hash.new(0) } end def simulate @db.each_owner do |owner| $stderr.print green("Simulating #{owner}") @owners << owner v = Velocities.new(@db, @task_weights, owner) SIMULATION_COUNT.times do |iteration| $stderr.print '.' if (iteration % PRINT_DOT_EVERY == 0) total_duration = 0 @db.in_progress_cards_for(owner) do |info, tasks, work_duration| size = Velocities.combined_size(tasks, @task_weights) total_duration += (size.fdiv(v.sample) - work_duration) / 24.0 end completion_date = (@now + (total_duration / v.at_work_ratio)).to_date @ship_date_counts[completion_date][owner] += 1 end $stderr.puts "Done" end end def write(output) output.puts "Date\t" + @owners.join("\t") probability_by_owner = Hash.new(0) @ship_date_counts.keys.sort.each do |date| @owners.each do |owner| probability_by_owner[owner] += @ship_date_counts[date][owner] end row = [date.strftime('%m/%d/%Y')] row.concat(probability_by_owner.values_at(*@owners).map { |p| (p * (100.0 / SIMULATION_COUNT)).round }) output.puts row.join("\t") end end end end
RSpec.describe "operation with http_method" do # see Test::Client definition in `/spec/support/test_client.rb` before do class Test::Client < Evil::Client operation do |settings| http_method settings.version > 1 ? :post : :get path { "data" } response :success, 200 end operation :clear_data do http_method :delete end operation :find_data operation :reset_data do |settings| http_method settings.version > 2 ? :patch : :put end end stub_request(:any, //) end let(:path) { "https://foo.example.com/api/v3/data" } let(:client) { Test::Client.new("foo", version: 3, user: "bar") } it "uses default value" do client.operations[:find_data].call expect(a_request(:post, path)).to have_been_made end it "reloads default value with operation-specific one" do client.operations[:clear_data].call expect(a_request(:delete, path)).to have_been_made end it "is customizeable by settings" do client.operations[:reset_data].call expect(a_request(:patch, path)).to have_been_made end end
class AddStateToLecture < ActiveRecord::Migration def change add_column :lectures, :state, :string, default: 'unstart' end end
require_relative 'test_helper.rb' require './lib/macaction.rb' require './lib/board.rb' require './lib/ship.rb' require './lib/player.rb' class MacActionTest < MiniTest::Test attr_reader :board, :mac, :ship, :mac_board, :me include Message def setup @board = Board.new @mac = MacAction.new @ship = Ship.new @mac_board = board.computer_board @me = Player.new end def test_place_ships_changes_computer_board mac.place_ships(mac_board, ship.destroyer) refute board.player_board.eql?(mac_board) end def test_place_destroyer_adds_two_ds_to_computer_board mac.place_ships(mac_board, ship.destroyer) assert 16, mac_board.count assert 16, mac_board.flatten.bsearch{|e| e.to_i == 0} assert 2, mac_board.flatten.bsearch {|e| e == 'd'} end def test_placing_destroyer_adds_three_ss_to_board mac.place_ships(mac_board, ship.submarine) assert 3, mac_board.flatten.bsearch {|e| e == 's'} end def test_two_ships_do_not_intersect_when_added_to_board mac.place_ships(mac_board, ship.submarine) mac.place_ships(mac_board, ship.destroyer) assert 2, mac_board.flatten.bsearch {|e| e == 'd'} assert 3, mac_board.flatten.bsearch {|e| e == 's'} end def test_computer_can_shoot_and_will_output_miss_message mac.place_ships(mac_board, ship.submarine) assert Message.computer_miss, mac.shoot(mac_board) end def test_computer_can_win assert mac.win?(mac_board) end def test_computer_can_also_not_win mac.place_ships(mac_board, ship.submarine) mac.place_ships(mac_board, ship.destroyer) refute mac.win?(mac_board) end def test_choose_spot_alters_a_and_b_values a = mac.a b = mac.b mac.choose_spot refute mac.a == a refute mac.b == b end end
class CreateIncidents < ActiveRecord::Migration[5.1] def change create_table :incidents do |t| t.string :content t.integer :recordnumberclient t.integer :recordnumber t.string :group t.string :module t.string :dms t.date :dateexe t.timestamps end end end
# == Schema Information # # Table name: tasks # # id :integer not null, primary key # user_id :integer # task_name :string(255) # description :string(255) # status :string(255) # created_at :datetime # updated_at :datetime # # require 'httparty' class Task < ActiveRecord::Base belongs_to :user validates_presence_of :importance geocoded_by :address reverse_geocoded_by :latitude, :longitude do |obj, results| if geo = results.first obj.street_number = geo.street_number obj.route = geo.route obj.state = geo.state obj.city = geo.city # obj.street_address = geo.street_address obj.zipcode = geo.postal_code obj.street_address = geo.street_address end end after_validation :geocode, :if => :address_changed? after_validation :reverse_geocode def set_bing_address_from_bing bing_data = get_bing_data address = bing_data["resourceSets"][0]["resources"][0]["address"]["formattedAddress"] self[:bing_address] = address self.save end def get_bing_data HTTParty.get('http://dev.virtualearth.net/REST/v1/Locations/@task.latitude.to_i,@task.longitude.to_i?key=Ah_f4EtXujIKRwM2DMfcrhaL_XJ0G_Ob_Yyy1nlDf0X_LYGhJilPBjWSfI91E3MV') end def location [latitude, longitude] end end
require 'spec_helper' describe RobotVim::Runner do describe "specifying which vim to use" do it "uses the vim passed in during initialization if provided" do vim = "/usr/local/bin/vim" runner = RobotVim::Runner.new(:vim => vim) runner.vim_binary.should == vim end it "defaults to vim in user's path" do vim = "vim" runner = RobotVim::Runner.new() runner.vim_binary.should == vim end end describe "running commands in vim" do let(:vim_path){"/usr/local/bin/vim"} let(:runner){RobotVim::Runner.new(:vim => vim_path)} let(:commands){"some vim commands\n"} let(:input_file){"some/path/to/a/file"} before do Kernel.stub(:`) runner.stub(:read_output_file_contents) RobotVim::InputFile.stub(:path_for).and_yield(input_file) end def run_robot runner.run(:commands => commands, :input_file => input_file) end it "invokes the correct vim" do Kernel.should_receive(:`).with(/#{vim_path}/) run_robot end it "runs against the requested input file" do Kernel.should_receive(:`).with(/#{input_file}$/) run_robot end it "runs vim without swap files so vim doesn't show swap warnings" do Kernel.should_receive(:`).with(/-n/) run_robot end it "invokes vim with a script file" do script_file_path = "path/to/script/file" RobotVim::ScriptFile.stub(:open).and_yield(script_file_path) Kernel.should_receive(:`).with(/-s #{script_file_path}/) run_robot end it "adds a write command to the user supplied commands" do RobotVim::ScriptFile.should_receive(:open).with(/\n\:w/) run_robot end it "generates a unique filename for the output file on each run" do files = [] RobotVim::ScriptFile.should_receive(:open) do |msg| files << msg.match(/:w (.*)/)[1] end.twice run_robot run_robot files[0].should_not == files[1] end it "adds vim closing commands to the user supplied commands" do RobotVim::ScriptFile.should_receive(:open).with(/:%bd!\n:q!/) run_robot end describe "output file management" do let(:output_file_name){"output_file_name"} before do RobotVim::FileNameGenerator.stub(:generate).and_return(output_file_name) end it "returns the contents of the output file" do expected_result = "awesome buffer" runner.stub(:read_output_file_contents).with(output_file_name).and_return(expected_result) result = run_robot result.should == expected_result end it "deletes the output file" do run_robot File.exists?(output_file_name).should be_false end end end end
module MarsExplorer class Robot def initialize(args = {}) @x = args.fetch(:x, MarsExplorer::Axis.new) @y = args.fetch(:y, MarsExplorer::Axis.new) @nose = args.fetch(:nose, 'N') end def move can_move? ? axis.value += increment_value : false end def turn(direction) @nose = directions[direction.to_sym][@nose.to_sym] end def position "(#{@x.value}, #{@y.value}, #{nose})" end private attr_reader :nose def can_move? axis.value.abs < axis.limit end def increment_value axis_selector[nose.to_sym][:value] end def axis axis_selector[nose.to_sym][:axis] end def directions { R: { N: 'E', E: 'S', S: 'W', W: 'N'}, L: { N: 'W', W: 'S', S: 'E', E: 'N' } } end def axis_selector { N: { axis: @y, value: 1 }, E: { axis: @x, value: 1 }, S: { axis: @y, value: -1 }, W: { axis: @x, value: -1 } } end end end
class Link < Media include PenderData validates :url, presence: true, on: :create validate :validate_pender_result_and_retry, on: :create validate :url_is_unique, on: :create after_create :set_pender_result_as_annotation, :set_account def domain host = Addressable::URI.encode(self.url, Addressable::URI).host unless self.url.nil? host.nil? ? nil : host.gsub(/^(www|m)\./, '') end def provider domain = self.domain domain.nil? ? nil : domain.gsub(/\..*/, '').capitalize end def picture path = '' begin pender_data = self.get_saved_pender_data path = pender_data['picture'] rescue path = '' end path.to_s end def get_saved_pender_data begin JSON.parse(self.annotations.where(annotation_type: 'metadata').last.load.get_field_value('metadata_value')) rescue {} end end def text self.get_saved_pender_data['description'].to_s end def original_published_time published_time = self.metadata['published_at'] return '' if published_time.to_i.zero? published_time.is_a?(Numeric) ? Time.at(published_time) : Time.parse(published_time) end def media_type self.get_saved_pender_data['provider'] end def self.normalized(url, pender_key = nil) l = Link.new url: url, pender_key: pender_key l.valid? l.url end private def set_account if !self.pender_data.nil? && !self.pender_data['author_url'].blank? self.account = Account.create_for_source(self.pender_data['author_url'], nil, false, false, self.pender_data[:pender_key]) self.save! end end def url_is_unique unless self.url.nil? existing = Media.where(url: self.url).first errors.add(:base, "Media with this URL exists and has id #{existing.id}") unless existing.nil? end end def validate_pender_result_and_retry self.validate_pender_result(false, true) # raise error for invalid links raise self.handle_pender_error(self.pender_error_code) if self.pender_error end end
require "test_helper" class UsersControllerTest < ActionDispatch::IntegrationTest def setup @admin = users :admin @normal_user = users :normal_user @michael = users :michael end test "should get new" do get signup_url assert_response :success end test "only logged in users can see list of users" do get users_path assert_redirected_to login_path end test "should not allow the admin attribute to be edited via the web" do login_as @normal_user assert_not @normal_user.admin? update_user @normal_user, admin: true assert_not @normal_user.admin? end test "non-admin users can't delete other users" do login_as @normal_user assert_no_difference "User.count" do delete user_path(@michael) end assert_redirected_to root_url assert_not_empty flash[:danger] end test "admin successfully delete normal users" do login_as @admin assert_difference "User.count", -1 do delete user_path(@michael) end assert_redirected_to users_path assert_not_empty flash[:success] end end
module ScorchedEarth module Subscribers module MouseMoved def setup super event_runner.subscribe(Events::MouseMoved) do |event| @mouse = Mouse.new event.x, event.y, mouse.pressed_at end end end end end
class User < ActiveRecord::Base has_many :teams # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, #, :confirmable, authentication_keys: [:email] # before_validation :team_key_to_id, if: :has_team_key? # def self.find_first_by_auth_conditions(warden_conditions) # conditions = warden_conditions.dup # team_key = conditions.delete(:team_key) # team_id = Team.where(key: team_key).first # email = conditions.delete(:email) # if team_id && email # where(conditions).where(["team_id = :team_id AND email = :email", # { team_id: team_id, email: email }]).first # elsif conditions.has_key?(:confirmation_token) # where(conditions).first # else # false # end # end # private # def has_team_key? # team_key.present? # end # def team_key_to_id # team = Team.where(key: team_key).first_or_create # self.team_id = team.id # end end
class Admin::ProductionsController < Admin::ApplicationController before_action :set_production, only: [:show, :edit,:update] def index end def new @production = Production.new @production_detail = @production.production_details.build end def create pr = produciton_params.merge(brand: params[:brand].to_i) @production = Production.new pr if @production.save! flash[:success] = "production create" redirect_to admin_productions_path end end def show end def edit end def update pr = produciton_params.merge(brand: params[:brand].to_i) if @production.update! pr redirect_to @production end end private def set_production @production = Production.find_by id: params[:id] end def produciton_params params.require(:production).permit(:name,:image,:description ,:brand, :url, production_details_attributes: [:color, :rom,:ram, :product_id, :_destroy,:price, :quantity]) end end
Vagrant.configure("2") do |config| config.vm.define :saucy64 do |saucy64| saucy64.omnibus.chef_version = :latest saucy64.vbguest.auto_update = true saucy64.ssh.forward_agent = true saucy64.cache.auto_detect = true #saucy64.cache.enable_nfs = true saucy64.vm.box = "skylab-saucy64" saucy64.vm.box_url = "http://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_ubuntu-13.10_chef-provisionerless.box" saucy64.vm.network :private_network, ip: "33.33.33.33" saucy64.vm.network :forwarded_port, guest: 80, host: 8080 saucy64.vm.hostname = 'saucy64.kunstmaan.be' saucy64.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--memory", "1024"] vb.customize ["modifyvm", :id, "--cpus", 2] end saucy64.vm.provision :chef_solo do |chef| chef.cookbooks_path = "cookbooks" chef.add_recipe "skylab::default" chef.log_level = :info end end end
require 'active_support/core_ext/hash/indifferent_access' require 'active_support/json' require 'aws-sdk-resources' require 'shoryuken' require 'ehonda/version' require 'ehonda/logging' require 'ehonda/configuration' require 'ehonda/railtie' if defined? Rails module Ehonda class << self def configure @config ||= Configuration.new yield @config if block_given? @config.validate! unless (ENV['RAILS_ENV'] || ENV['RACK_ENV']) == 'test' end def configuration fail 'You must call Ehonda.configure before you can access any config.' unless @config @config end def sns_client ::Aws::SNS::Client.new configuration.sns_options end def sqs_client ::Aws::SQS::Client.new configuration.sqs_options end end end
Puppet::Type.newtype(:f5_rule) do @doc = "Manage F5 rule." apply_to_device ensurable do desc "F5 rule resource state. Valid values are present, absent." defaultto(:present) newvalue(:present) do provider.create end newvalue(:absent) do provider.destroy end end newparam(:name, :namevar=>true) do desc "The rule name." end newproperty(:definition) do desc "The rule definition." end end
# frozen_string_literal: true require "open-uri" # Wrapper for Invoice that supplies all the data needed for invoice. class Pdf::Finance::InvoiceReportData LINE_ITEMS_HEADING = %w[Name Quantity Cost Charged].freeze DATE_FORMAT = "%e %B, %Y" delegate :name, :cost, :to => :@invoice def initialize(invoice) @invoice = invoice end def buyer person_data(@invoice.to, @invoice.fiscal_code, @invoice.vat_code, po_number) end def provider person_data(@invoice.from, @invoice.provider.fiscal_code, @invoice.provider.vat_code, nil) end def issued_on format_date(@invoice.issued_on) end def due_on format_date(@invoice.due_on) end def period_start format_date(@invoice.period.begin) end def period_end format_date(@invoice.period.end) end def filename date = @invoice.created_at.strftime('%B-%Y').downcase "invoice-#{date}.pdf" end def email provider.finance_support_email end def plan @invoice.buyer_account.bought_plan.name end def logo @logo_stream ||= open(@invoice.provider_account.profile.logo.url(:invoice)) rescue StandardError => e # TODO: - uncomment complete exception! # rescue OpenURI::HTTPError => e Rails.logger.error "Failed to retrieve logo from: #{e.message}" nil end def logo? @invoice.provider_account.profile.logo.file? && logo end def line_items line_items = @invoice.line_items.map do |item| [CGI.escapeHTML(item.name || ""), item.quantity || '', item.cost.round(LineItem::DECIMALS), ''] end line_items.push(*total_invoice_label) end def vat_rate @invoice.vat_rate end def friendly_id @invoice.friendly_id end def invoice_footnote CGI.escapeHTML(@invoice.provider_account.invoice_footnote || "") end def vat_zero_text CGI.escapeHTML(@invoice.provider_account.vat_zero_text || "") end def po_number CGI.escapeHTML(@invoice.buyer_account.po_number || "") end private def person_data(address, fiscal_code, vat_code, po_number) pd = [['Name', CGI.escapeHTML(address.name || '')], ['Address', CGI.escapeHTML(location_text(address))], ['Country', CGI.escapeHTML(address.country || '')]] pd << ['Fiscal code', CGI.escapeHTML(fiscal_code)] if fiscal_code.present? pd << [@invoice.buyer_account.field_label('vat_code'), CGI.escapeHTML(vat_code)] if vat_code.present? pd << ['PO num', CGI.escapeHTML(po_number)] if po_number.present? pd end def location_text(address) location = [] location << [address.line1, address.line2].compact.join(' ') location << [address.city, [address.state, address.zip].compact.join(' ')].compact.join(', ') location.join("\n") || '' end def format_date(date) date ? date.strftime(DATE_FORMAT) : '-' end def total_invoice_label if @invoice.vat_rate.nil? total = ['Total cost', '', @invoice.exact_cost_without_vat, @invoice.charge_cost] [total] else vat_rate_label = @invoice.buyer_account.field_label('vat_rate') total_without_vat = ["Total cost (without #{vat_rate_label})", '', @invoice.exact_cost_without_vat, @invoice.charge_cost_without_vat] total_vat = ["Total #{vat_rate_label} Amount", '', @invoice.vat_amount, @invoice.charge_cost_vat_amount] total = ["Total cost (#{vat_rate_label} #{@invoice.vat_rate}% included)", '', '', @invoice.charge_cost] [total_without_vat, total_vat, total] end end end
class Fluentd module Setting class FormatterHash include Fluentd::Setting::Plugin register_plugin("formatter", "hash") def self.initial_params {} end def common_options [ :add_newline ] end end end end
class LandingPageRelationshipsCreate < ActiveRecord::Migration def self.up create_table :landing_page_relationships do |t| t.column :parent_id, :integer, :null => false t.column :child_id, :integer, :null => false t.column :position, :integer, :null => false t.column :title_phrase, :string, :limit => 128 t.column :view_more_phrase, :string, :limit => 128 t.column :seo_snippet, :string, :limit => 512 t.column :created_at, :datetime t.column :updated_at, :datetime end end def self.down drop_table :landing_page_relationships end end
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2019-2022, by Samuel Williams. require 'io/console' module Console # Styled terminal output. module Terminal class Text def initialize(output) @output = output @styles = {reset: self.reset} end def [] key @styles[key] end def []= key, value @styles[key] = value end def colors? false end def style(foreground, background = nil, *attributes) end def reset end def write(*arguments, style: nil) if style and prefix = self[style] @output.write(prefix) @output.write(*arguments) @output.write(self.reset) else @output.write(*arguments) end end def puts(*arguments, style: nil) if style and prefix = self[style] @output.write(prefix) @output.puts(*arguments) @output.write(self.reset) else @output.puts(*arguments) end end # Print out the given arguments. # When the argument is a symbol, look up the style and inject it into the output stream. # When the argument is a proc/lambda, call it with self as the argument. # When the argument is anything else, write it directly to the output. def print(*arguments) arguments.each do |argument| case argument when Symbol @output.write(self[argument]) when Proc argument.call(self) else @output.write(argument) end end end # Print out the arguments as per {#print}, followed by the reset sequence and a newline. def print_line(*arguments) print(*arguments) @output.puts(self.reset) end end end end
# frozen_string_literal: true ROM::SQL.migration do change do create_table :coin_insertions do primary_key :id column :coin_id, Integer, null: false, index: true end alter_table :coin_insertions do add_foreign_key [:coin_id], :coins end end end