text
stringlengths
10
2.61M
require 'sinatra/base' require 'sinatra/activerecord' require 'date' require './models/event.rb' # your models # require 'json' #json support require './models/score.rb' # your models # require 'json' #json support require './models/user.rb' # your models # require 'json' #json support class MyApplication < Sinatra::Base register Sinatra::ActiveRecordExtension enable :sessions #:nocov: configure :production,:staging do set :database, ENV['DATABASE_URL'] end configure :development do set :database, 'sqlite:///dev.db' end #:nocov: configure :test do set :database, 'sqlite:///dev.db' end get '/' do session[:user] = nil erb :login end get '/new' do erb :event_new end get '/event/:id/rate' do |id| begin event = Event.find(id) rescue ActiveRecord::RecordNotFound @message = "PAGE NOT FOUND" erb :operation_result else @event = event.name erb:rating_form end end get '/home' do user = session[:user] if !user.nil? @user_name = User.find(user).name end erb:home end get '/signup' do erb:signup end post '/new' do user = session[:user] #id del usuario actual name = params[:name] date = Date.parse(params[:date]) event = Event.new event.name = name event.date = date event.user = user event.save @message = "Event created" @event_link = "http://rate-me-2012.herokuapp.com/event/#{event.id}/rate" erb :event_new end get '/events' do @message = "Events" @list = Event.find_all_by_user(session[:user]) erb :event_list end get '/recoverPassword' do erb :recover_password end get '/users' do @list = User.all erb :user_list end get '/send_Password/:mail/' do |mail| @mail = mail erb :send_password end get '/edit/:id/rate' do |id| event = Event.find(id) @event_id = id @event_date = event.date @event_name = event.name scores = Score.where(:event_id => id).count if scores > 0 @message = "This event has been rated, you can not edit" erb :error_edit else event = Event.find(id) @event_name = event.name erb :edit_page end end get '/event/:id/details' do |id| event = Event.find(id) @event_date = event.date @event_name = event.name @event_link = "http://rate-me-2012.herokuapp.com/event/#{event.id}/rate" erb :event_details end get '/delete/:id/rate' do |id| event = Event.find(id) @event_name = event.name erb :delete_event end get '/viewstats/:id/rate' do |id| begin event = Event.find(id) event_id = event.id.to_s() user = session[:user] rescue ActiveRecord::RecordNotFound @message = "PAGE NOT FOUND" erb :operation_result else @message = "View stats event #{event.name}" @awfully = Score.where(:event_id => id, :option => 'awfully good').count @nice = Score.where(:event_id => id, :option => 'nice').count @bad = Score.where(:event_id => id, :option => 'I did not like').count erb :event_stats end end get '/event/:id/comments' do |id| begin event = Event.find(id) event_id = event.id user = session[:user] rescue ActiveRecord::RecordNotFound @message = "PAGE NOT FOUND" erb :operation_result else @message = "View comments event #{event.name}" @list = Score.find_all_by_event_id(event_id) erb :comments_list end end get '/globalstats/rate' do user = session[:user] @message = "Global stats event" @awfully = Event.where(:user => user, :scores => {:option => 'awfully good'}).joins("INNER JOIN scores ON scores.event_id = events.id").count @nice = Event.where(:user => user, :scores => {:option => 'nice'}).joins("INNER JOIN scores ON scores.event_id = events.id").count @bad = Event.where(:user => user, :scores => {:option => 'I did not like'}).joins("INNER JOIN scores ON scores.event_id = events.id").count erb :event_stats end post '/event/:id/rate' do |id| begin id_calif = params[:option] event = Event.find(params[:id]) score = Score.new score.option = id_calif score.event_id = id score.comment = params[:comments] score.save! rescue ActiveRecord::RecordInvalid @message = "you must choose an option" erb :rating_form else @message = "Thank,your score was sent" erb :score_result end end post '/login' do mail = params[:mail] password = params[:password] password_confirmation = params[:password_confirmation] user = User.find(:first, :conditions => ['mail = ? AND password = ?', mail, password]) if user.nil? @message = "user does not exists" erb :login else session[:user] = user.id @user_name = User.find(session[:user]).name erb :home end end post '/signup' do name = params[:name] mail = params[:mail] password = params[:password] password_confirmation= params[:password_confirmation] begin if password != password_confirmation raise PasswordError end @user = User.new @user.name = name @user.mail = mail @user.password = password @user.save! rescue PasswordError @message = "error confirmation password" erb :signup rescue ActiveRecord::RecordInvalid @message = "the user already exists" erb :signup else session[:user] = @user.id u = User.find(session[:user]) @user_name = u.name @user_id = u.id erb :home end end post '/events' do @message = "Events" user = session[:user] event_search = "%#{params[:search_by_name]}%" @list = Event.where(:user => user).where("name LIKE ?", event_search) erb :event_list end post '/edit/:id/edit' do |id| begin Event.update(id, :name => params[:name], :date => Date.parse(params[:date])) event = Event.find(id) @event_id = id @event_date = event.date @event_name = event.name rescue @error = "invalid date" erb :edit_page else @message = "The event was successfully updated" erb :edit_page end end post '/delete/:id/delete' do |id| event = Event.find(id) @event_name = event.name Score.delete_all(:event_id => id) event.delete @message = "The event was deleted" erb :delete_event end post '/recover' do mail = params[:mail] user = User.find_by_mail(mail) if user.nil? @message = "Email not found" erb :recover_password else @password = user.password @message = "We have sent your password to your email" erb :operation_result end end class PasswordError < StandardError end class EventNotFoundError < StandardError end end
require_relative 'property_utilities' module AnimalQuiz class Animal include PropertyUtilities attr_reader :name, :properties def initialize(name, props = []) @name = name @properties = props end end end
# # Copyright 2011 National Institute of Informatics. # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. require 'test_helper' class ComponentConfigDefaultTest < ActiveSupport::TestCase # Replace this with your real tests. # called before every single test def setup @ccd = ComponentConfigDefault.new(:path => Dir.pwd, :content => 'contents', :component => Component.find_by_name("nova_compute")) end # called after every single test def teardown end test "should not save ComponentConfigDefault without path" do @ccd.path = nil assert !@ccd.save end test "should not save ComponentConfigDefault without content" do @ccd.content = nil assert !@ccd.save end test "should not save ComponentConfigDefault without component" do @ccd.component = nil assert !@ccd.save end test "should not save ComponentConfigDefault with the same path and component" do @ccd.save ccd_new = ComponentConfigDefault.new(:path => Dir.pwd, :content => 'contents', :component => Component.find_by_name("nova_compute")) assert !ccd_new.save end test "should save ComponentConfigDefault" do assert @ccd.save end end
module ProductHelper def cart_count count = current_user.products.count count > 0 ? pluralize(count, 'item') : 'Empty' end def cart_link_for(product) if product.in_cart? link_to 'Remove From Cart', product_remove_path(product), method: :delete, class: 'btn btn-danger', role: 'button' else link_to "$#{product.price} - Add to Cart", products_users_path(:product_id => product.id), method: :post, class: 'btn btn-primary', role: 'button' end end end
Given(/^I login to the "([^"]*)" application$/) do |application| begin visit env sleep 8 arg = getCredentialInfo fill_in "Username",:with => arg["Username"] fill_in "Password",:with => arg["Password"] sleep 5 find("#Login").click sleep 10 puts "Successfully entered the #{application} user credentials" sleep 3 rescue Exception => ex raise "Error occurred while entering #{application} user credentials" end end Then(/^I able to see the logged in to "([^"]*)" application$/) do |app| sleep 5 if page.has_css?("#userNav") puts "Successfully logged in to #{app} application" else raise "Failed to logged in to #{app} application" end end And(/^I click on the "([^"]*)" button$/) do |button_text| begin sleep 3 if page.has_button?(button_text) click_on button_text sleep 2 puts "Successfully click the #{button_text} button" else putstr "Failed to see the #{button_text} button" end rescue Exception => ex putstr "Error occurred while clicking on #{button_text} button" end end When(/^I click on the "([^"]*)" tab$/) do |tab| begin sleep 5 first(:link, tab).click sleep 10 puts "Successfully navigated to #{tab} tab" rescue Exception => ex putstr "Error occurred while navigate to the #{tab} tab" end end When(/^I click on "([^"]*)" link$/) do |name| begin sleep 3 if page.has_content? name puts "Successfully see the the #{name} link" click_on name else raise "Failed to see the #{name} link" end rescue Exception => ex putstr "Error occurred while clicking the #{name} link" end end When(/^I click on "([^"]*)" button from "([^"]*)" page$/) do |name, currency| begin sleep 3 if page.has_button? name puts "Successfully see the #{name} button" find(:xpath,"//input[@title='#{name}']").click sleep 2 puts "Successfully click the #{name} button" else putstr "Failed to see the #{name} button" end rescue Exception => ex putstr "Error occurred while clicking on #{name} button from #{currency} page" end end When(/^I select the "([^"]*)" from "([^"]*)" pickList field$/) do |option, field| sleep 3 if page.has_content?(field) puts "Successfully see the #{field} field" if page.has_css?("#p3") puts "Successfully see the #{field} pickList" sleep 2 result = false find("#p3").all('option').each do |record_type| if record_type.text.to_s == option.to_s puts "Successfully see the #{field} pickList value: #{option}" result = true sleep 3 find("#p3").send_keys option end end raise "Failed to see the #{field} pickList value: #{option}" unless result sleep 3 else putstr "Failed to see the #{field} pickList" end else putstr "Failed to see the #{field} field" end end When(/^I click on "([^"]*)" link from user menu$/) do |setup| begin sleep 2 find("#userNavButton").click sleep 2 within("#userNav-menuItems") do click_on setup end rescue Exception => ex putstr "Error occurred while clicking the #{setup} link" end end And(/^I click on "([^"]*)" button from new "([^"]*)" page$/) do |save, context| begin sleep 3 within("#topButtonRow") do if page.has_button? save puts "Successfully see the #{save} button from #{context} page" click_on save else putstr "Failed to see the #{save} button from #{context} page" end end rescue Exception => ex putstr "Error occurred while clicking the #{save} button from #{context} page" end end Then(/^I able to see the "([^"]*)" page$/) do |content| begin sleep 4 if page.has_content? content puts "Successfully see the the #{content} page" else putstr "Failed to see the #{content} page" end rescue Exception => ex putstr "Error occurred while verifying the #{content} page" end end Then(/^I able to see the "([^"]*)" name$/) do |name| begin sleep 3 if page.has_content? name puts "Successfully see the the #{name} name" else putstr "Failed to see the #{name} name" end rescue Exception => ex putstr "Error occurred while verifying the #{name} name" end end Then(/^I able to see the "([^"]*)" home page$/) do |name| begin sleep 2 if page.has_content? name puts "Successfully see the the #{name} page" else raise "Failed to see the #{name} page" end rescue Exception => ex putstr "Error occurred while verifying the #{name} page" end end And(/^I fill the "([^"]*)" required fields$/) do |location_address| begin sleep 3 arg = getDetails 'NewCasesInformation' $location_address = "#{arg["LocationAddressName"]}#{Time.now.strftime('%m%d_%H%M_%S')}" if page.has_css?("#Name") puts "Successfully see the #{location_address} Name field" fill_in "Location Address Name",:with => $location_address puts "Successfully fill the the #{location_address} required fields" sleep 3 else raise "Failed to see the #{location_address} Name field" end rescue Exception => ex putstr "Error occurred while filling the #{location_address} required fields" end end Then(/^I able to see the created "([^"]*)"$/) do |location_address| begin sleep 3 if page.has_css?(".pageDescription") if find(".pageDescription").text == $location_address puts "Successfully created the #{location_address}: #{$location_address}" else putstr "Failed to created the #{location_address}: #{$location_address}" end within(".pbSubsection") do if find("#Name_ileinner").text == $location_address puts "Successfully created the #{location_address}: #{$location_address}" else putstr "Failed to created the #{location_address}: #{$location_address}" end end else putstr "Failed to created the #{location_address}: #{$location_address}" end rescue Exception => ex putstr "Error occurred while verifying the created #{location_address} record: #{$location_address}" end end And(/^I fill the all lead required fields$/) do begin sleep 2 arg = getDetails 'NewLeadInformation' $lead_name = "#{arg["LastName"]}#{Time.now.strftime('%m%d_%H%M_%S')}" if page.has_css?("#lea13") puts "Successfully see the Lead Status field" find("#lea13").send_keys arg["LeadStatus"] else putstr "Failed to find the Lead Status field" end if page.has_css?("#name_lastlea2") puts "Successfully see the Last Name field" find("#name_lastlea2").send_keys $lead_name else putstr "Failed to find the Last Name field" end if page.has_css?("#lea3") puts "Successfully see the company field" find("#lea3").send_keys arg["Company"] else putstr "Failed to find the company field" end sleep 3 fill_in "Estimated Amount",:with => arg["LeadEstimatedAmount"] fill_in "Estimated Close Date",:with => arg["LeadEstimatedCloseDate"] if page.has_css?("#lea5") puts "Successfully see the Lead Source PickList" find("#lea5").select arg["LeadSource"] else putstr "Failed to find the Lead Source PickList" end sleep 4 select(arg["LeadType"], :from => "Lead Type") select(arg["LeadSubType"], :from => "Lead Sub-Type") sleep 4 puts "Successfully fill the all lead required fields" rescue Exception => ex putstr "Error occurred while filling the all lead required fields" end end And(/^I able to see the lead created successfully$/) do begin sleep 3 if page.has_css?(".topName") if find(".topName").text == $lead_name puts "Successfully created the Lead: #{$lead_name}" else putstr "Failed to created the Lead: #{$lead_name}" end within all(".pbSubsection")[0] do if find("#lea2_ileinner").text == $lead_name puts "Successfully created the Lead: #{$lead_name}" else putstr "Failed to created the Lead: #{$lead_name}" end end else putstr "Failed to created the Lead: #{$lead_name}" end rescue Exception => ex putstr "Error occurred while verifying the created Lead record: #{$lead_name}" end end When(/^I fill the asset required fields$/) do begin sleep 2 arg = getDetails 'OpportunityAssets' $asset_name = "#{arg["AssetName"]}#{Time.now.strftime('%m%d_%H%M_%S')}" if page.has_css?("#Name") puts "Successfully see the Asset Name field" find("#Name").send_keys $asset_name else putstr "Failed to find the Asset Name field" end if page.has_css?("#Product2") puts "Successfully see the Product Lookup field" main = page.driver.browser.window_handles.first find(:xpath,"//a[@title='Product Lookup (New Window)']").click sleep 3 page.driver.browser.switch_to.window(page.driver.browser.window_handles.last) lookup = page.driver.browser.window_handles.last page.driver.browser.switch_to.frame("searchFrame") fill_in("lksrch",:with=> arg["AssetProductName"]) sleep 3 find_button('Go!').click sleep 4 page.driver.browser.switch_to.window(lookup) page.driver.browser.switch_to.frame("resultsFrame") within('.pbBody') do all("tbody")[0].all('tr')[1].all('th')[0].find('a').click end page.driver.browser.switch_to.window(main) sleep 6 else putstr "Failed to find the Product Lookup field" end #if page.has_css?("#Account") # puts "Successfully see the Account field" # main = page.driver.browser.window_handles.first # find(:xpath,"//a[@title='Account Lookup (New Window)']").click # sleep 3 # page.driver.browser.switch_to.window(page.driver.browser.window_handles.last) # lookup = page.driver.browser.window_handles.last # page.driver.browser.switch_to.frame("searchFrame") # fill_in("lksrch",:with=> arg["AssetAccountName"]) # sleep 3 # find_button('Go!').click # sleep 4 # page.driver.browser.switch_to.window(lookup) # page.driver.browser.switch_to.frame("resultsFrame") # within('.pbBody') do # all("tbody")[0].all('tr')[1].all('th')[0].find('a').click # end # page.driver.browser.switch_to.window(main) # sleep 6 #else # putstr "Failed to find the Account field" #end if page.has_css?("#Contact") puts "Successfully see the Contact field" main = page.driver.browser.window_handles.first find(:xpath,"//a[@title='Contact Lookup (New Window)']").click sleep 3 page.driver.browser.switch_to.window(page.driver.browser.window_handles.last) lookup = page.driver.browser.window_handles.last page.driver.browser.switch_to.frame("searchFrame") fill_in("lksrch",:with=> arg["AssetContactName"]) sleep 3 find_button('Go!').click sleep 4 page.driver.browser.switch_to.window(lookup) page.driver.browser.switch_to.frame("resultsFrame") within('.pbBody') do all("tbody")[0].all('tr')[1].all('th')[0].find('a').click end page.driver.browser.switch_to.window(main) sleep 6 else putstr "Failed to find the Contact field" end if page.has_css?("#SerialNumber") puts "Successfully see the Serial Number field" find("#SerialNumber").send_keys arg["AssetSerialNumber"] else putstr "Failed to find the Serial Number field" end puts "Successfully fill the asset required fields" rescue Exception => ex putstr "Error occurred while filling the asset required fields" end end Then(/^I able to see the asset created successfully$/) do begin sleep 3 arg = getDetails 'OpportunityAssets' if page.has_content? arg["AssetDetailsPage"] puts "Successfully see the #{arg["AssetDetailsPage"]} page" if find(".pageDescription").text == $asset_name puts "Successfully created the Asset: #{$asset_name}" else putstr "Failed to created the Asset: #{$asset_name}" end within all(".pbSubsection")[0] do if find("#Name_ileinner").text.include? $asset_name puts "Successfully created the Asset: #{$asset_name}" else putstr "Failed to created the Asset: #{$asset_name}" end end else putstr "Failed to create the New Asset" end rescue Exception => ex putstr "Error occurred while creating the Asset: #{$asset_name}" end end When(/^I select the "([^"]*)" filter$/) do |filter_name| begin sleep 4 if page.has_css?("#fcf") find('#fcf').select filter_name sleep 4 puts "Successfully selected the opportunity filter: #{filter_name}" else putstr "Failed to selected the opportunity filter: #{filter_name}" end if page.has_css?(".fBody") within (".fBody") do click_button 'Go!' end end sleep 4 rescue Exception => ex putstr "Error occurred while selecting the opportunity filter: #{filter_name}" end end When(/^I fill the service contract required fields$/) do begin sleep 2 arg = getDetails 'NewAccountInformation' $service_contract_name = "#{arg["ServiceContractName"]}#{Time.now.strftime('%m%d_%H%M_%S')}" if page.has_css?("#Name") puts "Successfully see the Service Contract Name field" find("#Name").send_keys $service_contract_name else putstr "Failed to find the Service Contract Name field" end puts "Successfully fill the service contract required fields" rescue Exception => ex putstr "Error occurred while filling the service contract required fields" end end Then(/^I able to see the service contract created successfully$/) do begin sleep 3 arg = getDetails 'NewAccountInformation' if page.has_content? arg["ServiceContractDetailPage"] puts "Successfully see the #{arg["ServiceContractDetailPage"]} page" if find(".pageDescription").text == $service_contract_name puts "Successfully created the Service Contract: #{$service_contract_name}" else putstr "Failed to created the Service Contract: #{$service_contract_name}" end within all(".pbSubsection")[0] do if find("#Name_ileinner").text.include? $service_contract_name puts "Successfully created the Service Contract: #{$service_contract_name}" else putstr "Failed to created the Service Contract: #{$service_contract_name}" end end else putstr "Failed to create the New Service Contract" end rescue Exception => ex putstr "Error occurred while creating the Service Contract: #{$service_contract_name}" end end And(/^I should not able to see the "([^"]*)" field$/) do |field| begin sleep 3 unless page.has_content?(field) puts "Unable to see the #{field} field" else putstr "Able to see the #{field} field" end rescue Exception => ex putstr "Error occurred while verifying the #{field} field" end end When(/^I click on "([^"]*)" from "([^"]*)" page$/) do |tab, context| begin sleep 3 if page.has_css?(".allTabsArrow") puts "Successfully find the #{context} plus icon" find(".allTabsArrow").click sleep 3 if page.has_content? context first(:link, tab).click sleep 3 puts "Successfully navigated to the #{tab} page" else putstr "Failed to navigated to the #{tab} page" end else putstr "Failed to find the #{context} plus icon" end rescue Exception => ex putstr "Error occurred while navigate to the #{tab} tab" end end When(/^I click on the "([^"]*)" button from "([^"]*)" page$/) do |save, product_edit| begin sleep 3 within("#topButtonRow") do if page.has_button? save puts "Successfully see the #{save} button from #{product_edit} page" click_on save else putstr "Failed to see the #{save} button from #{product_edit} page" end end rescue Exception => ex putstr "Error occurred while clicking the #{save} button from #{product_edit} page" end end Then(/^I able to see the "([^"]*)" section$/) do |content| begin sleep 4 if page.has_content? content puts "Successfully see the the #{content} section" else putstr "Failed to see the #{content} section" end rescue Exception => ex putstr "Error occurred while verifying the #{content} section" end end And(/^I should not able to see the quote "([^"]*)" field$/) do |field| begin sleep 3 unless page.has_content?(field) puts "Unable to see the #{field} field" else putstr "Able to see the #{field} field" end rescue Exception => ex putstr "Error occurred while verifying the #{field} fields" end end When(/^I search the "([^"]*)" name$/) do |opportunity| begin sleep 5 arg = getDetails 'NewQuotesDetails' if page.has_css?("#phSearchInput") puts "Successfully see the search text box" sleep 4 find("#phSearchInput").send_keys arg["NewOpportunityName"] sleep 4 puts "Successfully fill the Opportunity name: #{arg["NewOpportunityName"]}" within("#searchButtonContainer") do first("#phSearchButton").click puts "Successfully clicked the Search button" end else putstr "Failed to see the search text box" end rescue Exception => ex putstr "Error occurred while searching the #{opportunity} name" end end Then(/^I able to see the "([^"]*)" search results$/) do |opportunity| begin sleep 3 arg = getDetails 'NewQuotesDetails' unless page.has_content? arg["NoOpportunityResults"] if page.has_css?("#secondSearchButton") puts "Successfully see the #{opportunity} search button" sleep 3 if page.has_css?("#Opportunity") puts "Successfully see the #{opportunity} search results" sleep 3 else putstr "Failed to see the #{opportunity} search results" end else putstr "Failed to see the #{opportunity} search button" end else putstr "No #{opportunity} results records found" end rescue Exception => ex putstr "Error occurred while clicking the #{opportunity} record" end end When(/^I click the "([^"]*)" record$/) do |opportunity| begin sleep 5 arg = getDetails 'NewQuotesDetails' unless page.has_content? arg["NoOpportunityResults"] if page.has_css?("#Opportunity") puts "Successfully see the #{opportunity} search results" sleep 4 within(".listRelatedObject.opportunityBlock") do within("#Opportunity_body") do tr = first("tbody").all(".dataRow") sleep 3 result = false tr.each do |row| if row.first("th").first("a").text.include? arg["NewOpportunityName"] puts "Successfully see the #{opportunity} record" row.first("th").first("a").click sleep 5 puts "Successfully clicked the #{opportunity} record" result = true break end end putstr "Failed to see the #{opportunity} record" unless result sleep 3 end end else putstr "Failed to see the #{opportunity} search record" end else putstr "No #{opportunity} results records found" end rescue Exception => ex putstr "Error occurred while clicking the #{opportunity} record" end end When(/^I click on "([^"]*)" link under "([^"]*)" section$/) do |opportunities, customize| begin sleep 3 if page.has_content? customize puts "Successfully see the the #{customize} section" if page.has_css?("#Opportunity_font") puts "Successfully see the #{opportunities} link under #{customize} section" find("#Opportunity_font").click sleep 4 puts "Successfully clicked the #{opportunities} link under #{customize} section" else putstr "Failed to see the #{opportunities} link under #{customize} section" end else putstr "Failed to see the #{customize} section" end rescue Exception => ex putstr "Error occurred while verifying the #{opportunities} link under #{customize} section" end end Then(/^I verify the "([^"]*)" rule should be visible and active$/) do |rule| begin sleep 3 if page.has_content? rule puts "Successfully see the the #{rule} role" within(".listRelatedObject.setupBlock") do within(".list") do tr = first("tbody").all(".dataRow") sleep 3 result = false tr.each do |row| if row.first("th").first("a").text == rule if row.all("td")[5].first("img")[:title] == "Checked" puts "#{rule} rule is active" result = true break else putstr "#{rule} rule is not active" end end end putstr "Failed to see the #{rule} rule" unless result sleep 3 end end else putstr "Failed to see the #{rule} rule" end rescue Exception => ex putstr "Error occurred while verifying the #{rule} rule" end end Then(/^I verify the specific users with "([^"]*)" permission$/) do |permission_set_name| begin sleep 3 if page.has_content? permission_set_name puts "Successfully see the the #{permission_set_name} permission" else putstr "Failed to see the #{permission_set_name} permission" end rescue Exception => ex putstr "Error occurred while verifying the #{permission_set_name} permission" end end And(/^I fill the account required fields$/) do begin sleep 2 arg = getDetails 'NewAccountInformation' $account_name = "#{arg["AccountRequiredName"]}#{Time.now.strftime('%m%d_%H%M_%S')}" if page.has_css?("#acc2") puts "Successfully see the Account Name field" find("#acc2").send_keys $account_name else putstr "Failed to find the Account Name field" end if page.has_css?("#acc3") puts "Successfully see the Parent Account Lookup field" main = page.driver.browser.window_handles.first find(:xpath,"//a[@title='Parent Account Lookup (New Window)']").click sleep 3 page.driver.browser.switch_to.window(page.driver.browser.window_handles.last) lookup = page.driver.browser.window_handles.last page.driver.browser.switch_to.frame("searchFrame") fill_in("lksrch",:with=> arg["ParentAccountName"]) sleep 3 find_button('Go!').click sleep 4 page.driver.browser.switch_to.window(lookup) page.driver.browser.switch_to.frame("resultsFrame") within('.pbBody') do all("tbody")[0].all('tr')[1].all('th')[0].find('a').click end page.driver.browser.switch_to.window(main) sleep 6 else putstr "Failed to find the Parent Account Lookup field" end puts "Successfully fill the account required fields" rescue Exception => ex putstr "Error occurred while filling the account required fields" end end Then(/^I able to see the account created successfully$/) do begin sleep 3 if page.has_css?(".topName") if find(".topName").text == $account_name puts "Successfully created the Account: #{$account_name}" else putstr "Failed to created the Account: #{$account_name}" end within all(".pbSubsection")[0] do if find("#acc2_ileinner").text.include? $account_name puts "Successfully created the Account: #{$account_name}" else putstr "Failed to created the Account: #{$account_name}" end end else putstr "Failed to created the Account: #{$account_name}" end rescue Exception => ex putstr "Error occurred while verifying the created Account record: #{$account_name}" end end When(/^I select the "([^"]*)" pickList value$/) do |risk_assessment_overall| begin sleep 2 arg = getDetails 'NewAccountInformation' if page.has_select?(risk_assessment_overall) puts "Successfully see the #{risk_assessment_overall} field" select(arg["RiskAssessmentOverallValue"], :from => risk_assessment_overall) puts "Successfully selected the #{risk_assessment_overall} value: #{arg["RiskAssessmentOverallValue"]}" end puts "Successfully selected the #{risk_assessment_overall} field" rescue Exception => ex putstr "Error occurred while selecting the #{risk_assessment_overall} field" end end When(/^I verify the "([^"]*)" should be current system date and time$/) do |overall_risk_status_last_changed| begin sleep 3 $current_date_time = "#{(Time.now.utc + Time.zone_offset('PDT')).strftime("%-m/%e/%Y %l:%M %p")}" within all(".pbSubsection")[0] do tr = first("tbody").all("tr") sleep 3 result = false tr.each do |row| if row.all("td")[0].text == overall_risk_status_last_changed if row.all("td")[1].first("div").text.delete(' ').include? $current_date_time.delete(' ') puts "Successfully updated the #{overall_risk_status_last_changed} field with current system date and time" result = true break else putstr "Failed to updated the #{overall_risk_status_last_changed} field with current system date and time" result = true break end end end putstr "Failed to see the #{overall_risk_status_last_changed} field" unless result sleep 3 end rescue Exception => ex putstr "Error occurred while verifying the #{overall_risk_status_last_changed} should be current system date and time" end end And(/^I able to see the "([^"]*)" cases pickList fields$/) do |field| begin sleep 2 arg = getDetails 'NewCasesInformation' if page.has_css?("#p3") puts "Successfully see the #{field} pickList" $case_types = [] all(:xpath,"//select[@id='p3']/option").each do |options| $case_types << options.text end if $case_types.include?arg["CaseTypeQuoteRequest"] puts "Successfully see the #{field} pickList value: #{arg["CaseTypeQuoteRequest"]}" else putstr "Failed to see the #{field} pickList value: #{arg["CaseTypeQuoteRequest"]}" end if $case_types.include?arg["CaseTypeBookingRequest"] puts "Successfully see the #{field} pickList value: #{arg["CaseTypeBookingRequest"]}" else putstr "Failed to see the #{field} pickList value: #{arg["CaseTypeBookingRequest"]}" end if $case_types.include?arg["CaseTypeDataProcessing"] puts "Successfully see the #{field} pickList value: #{arg["CaseTypeDataProcessing"]}" else putstr "Failed to see the #{field} pickList value: #{arg["CaseTypeDataProcessing"]}" end if $case_types.include?arg["CasesTypeReviewRequest"] puts "Successfully see the #{field} pickList value: #{arg["CasesTypeReviewRequest"]}" else putstr "Failed to see the #{field} pickList value: #{arg["CasesTypeReviewRequest"]}" end if $case_types.include?arg["CaseTypeReportingRequest"] puts "Successfully see the #{field} pickList value: #{arg["CaseTypeReportingRequest"]}" else putstr "Failed to see the #{field} pickList value: #{arg["CaseTypeReportingRequest"]}" end if $case_types.include?arg["CaseTypeDataUpdateRequest"] puts "Successfully see the #{field} pickList value: #{arg["CaseTypeDataUpdateRequest"]}" else putstr "Failed to see the #{field} pickList value: #{arg["CaseTypeDataUpdateRequest"]}" end if $case_types.include?arg["CaseTypeLeadSubmission"] puts "Successfully see the #{field} pickList value: #{arg["CaseTypeLeadSubmission"]}" else putstr "Failed to see the #{field} pickList value: #{arg["CaseTypeLeadSubmission"]}" end else putstr "Failed to see the #{field} pickList" end rescue Exception => ex putstr "Error occurred while verifying the #{field} pickList values" end end
require 'rails_helper' RSpec.describe DoctorSpecialty, type: :model do it "Doctor cant have equal specialties" do specialties = Specialty.create([{name: "Test Specialty 1"}]) doctor = Doctor.new(name: "Doctor Test", crm:"crm test", phone: "phone_test", specialty_ids:[specialties[0].id,specialties[0].id]) doctor.save specialty_with_error = doctor.doctor_specialties.select{|specialty| specialty.errors.full_messages.any? }.first expect(specialty_with_error.errors[:doctor_id]).to include('has already been taken') end end
RSpec.describe "Announcements" do it "lists the announcements" do visit announcements_path expect(page).to have_current_path(announcements_path) end it "lists items on the page" do announcement = create :announcement visit announcements_path expect(page).to have_text announcement.title end it "goes to log in page when not logged in" do visit new_announcement_path expect(page).to have_current_path(new_user_session_path) end it "tells if there are no announcements to show" do visit announcements_path expect(page).to have_text("No announcements to show") end end
require 'cucumber/formatter/html' module VagrantPlugins module Cucumber module Formatter class Html < ::Cucumber::Formatter::Html def puts(message) # TODO Strip ansi escape codes @delayed_messages << message end end end end end
class Topic < ApplicationRecord extend FriendlyId friendly_id :title, use: :slugged belongs_to :user has_many :questions belongs_to :parent_topic, class_name: 'Topic', foreign_key: :parent_topic_id has_many :subtopics, class_name: 'Topic', foreign_key: :parent_topic_id has_many :followings scope 'parent_topics', -> { where(parent_topic: nil) } scope 'most_questions', -> { order(recursive_questions_count: :desc) } after_commit :update_recursive_subtopic_ids, on: [:create, :destroy] after_update :update_recursive_subtopic_ids def all_questions topic_ids = [id].concat(recursive_subtopic_ids.try(:split, ',') || []) Question.for_topics(topic_ids) end def parent_path return [] if (p = parent_topic).nil? parents = [] loop do parents << p p = p.parent_topic break if p.nil? end return parents end def path(include_self=true) all = parent_path.reverse all << self if include_self all.map(&:title).join('/') end def update_recursive_questions_count count = subtopics.inject(questions_count) do |total, subtopic| total += subtopic.recursive_questions_count end update_column(:recursive_questions_count, count) if parent_topic.present? parent_topic.update_recursive_questions_count end end def update_recursive_subtopic_ids ids = [] subtopics.each do |st| ids << st.id if st.recursive_subtopic_ids.present? ids.concat st.recursive_subtopic_ids.split(',').map(&:to_i) end end ids_string = ids.uniq.sort.join(',') if recursive_subtopic_ids != ids_string update_column :recursive_subtopic_ids, ids_string rescue nil end if parent_topic.present? || parent_topic_id_was.present? if parent_topic_id_was.present? && parent_topic_id != parent_topic_id_was previous_parent = Topic.find_by(id: parent_topic_id_was) end self.reload rescue nil parent_topic.update_recursive_subtopic_ids if parent_topic.present? previous_parent.update_recursive_subtopic_ids if previous_parent.present? end end end
require 'rails_helper' describe "Beer" do let!(:brewery) { FactoryGirl.create :brewery, name:"Koff" } let!(:style) { FactoryGirl.create :style, name:"Lager" } let!(:user) { FactoryGirl.create :user } before :each do visit signin_path fill_in('username', with:'Pekka') fill_in('password', with:'Foobar1') click_button('Log in') end it "when name is empty, beer is not registered" do visit new_beer_path select('Koff', from:'beer[brewery_id]') select('Lager', from:'beer[style_id]') click_button "Create Beer" expect(Beer.count).to eq(0) expect(page).to have_content "Errors when creating new beer" end end
json.array! @images.each do |image| json.partial! "image.json.jbuilder", images: image end
# app/models/post.rb class Post < ApplicationRecord # friendly url extend FriendlyId friendly_id :title, use: :slugged # validations validates_presence_of :title # callbacks before_save :anti_spam def to_s return "#{self.title}" end def anti_spam doc = Nokogiri::HTML::DocumentFragment.parse(self.content) doc.css('a').each do |a| a[:rel] = 'nofollow' a[:target] = '_blank' end self.content = doc.to_s end end
class ControllerAircraft include Mongoid::Document field :original_id, type: Integer field :created_at, type: Time field :content, type: Hash after_create :store_standardized_version def self.parse_zipfile `unzip -o controller.zip` `ls controller`.split("\n").each do |file| listings = JSON.parse(File.read("controller/"+file)) listings["BodyComponent"]["Props"]["ListPageAjaxModel"]["Listings"].each do |listing| ca = ControllerAircraft.where(original_id: listing["Id"]).first if ca.nil? ca = ControllerAircraft.new(original_id: listing["Id"], content: listing, created_at: Time.parse(listing["FormattedUpdatedOnTime"])) ca.save! end end end end def avionics_package avionics = self.content["Specs"].select{|x| x["Key"] == "Avionics/Radios"}.first avionics && avionics["Value"].split(/[(\r\n)\n,.;\/]/) || [] end def self.store_standardized_versions while true set = Hash[StandardizedAircraft.where(original_source: "controller", likely_avionics_ids: nil).all.shuffle.first(500).collect{|x| [x.original_id, x]}] rp_slice = ControllerAircraft.where(:id.in => set.values.collect(&:original_id)) likely_avionics_id_set = AvionicsModel.new.analyze(rp_slice.collect(&:avionics_package)) rp_slice.zip(likely_avionics_id_set).each do |rp, avionics| next if set[rp.id].nil? set[rp.id].likely_avionics_ids = avionics set[rp.id].save! end end while true set = StandardizedAircraft.where(original_source: "controller", likely_avionics_ids: nil).all.shuffle.first(500) rp_slice = ControllerAircraft.where(:id.in => set.collect(&:original_id)) likely_avionics_id_set = AvionicsModel.new.analyze(rp_slice.collect(&:avionics_package)) rp_slice.zip(likely_avionics_id_set).each do |rp, avionics| next if sas[rp.id].nil? sas[rp.id].likely_avionics_ids = avionics sas[rp.id].save! end end ControllerAircraft.all.to_a.shuffle.each_slice(500) do |rp_slice| likely_avionics_id_set = AvionicsModel.new.analyze(rp_slice.collect(&:avionics_package)) sas = Hash[StandardizedAircraft.where(:original_id.in => rp_slice.collect(&:id), original_source: "controller").collect{|x| [x.original_id, x]}] rp_slice.zip(likely_avionics_id_set).each do |rp, avionics| next if sas[rp.id].nil? sas[rp.id].likely_avionics_ids = avionics sas[rp.id].save! end end ControllerAircraft.all.to_a.select{|x| StandardizedAircraft.where(original_id: x.id, original_source: "controller").first.nil?}.each_slice(100) do |rp_slice| puts "slice" likely_avionics_id_set = AvionicsModel.new.analyze(rp_slice.collect(&:avionics_package)) rp_slice.zip(likely_avionics_id_set).each do |rp, avionics| puts rp.id rp.store_standardized_version(avionics) rescue nil end end end def year self.content["ListingTitle"][0..3].to_i end def total_time tt = self.content["Specs"].select{|x| x["Key"] == "Total Time"}.first tt && tt["Value"].to_i end def engine_1_time tt = self.content["Specs"].select{|x| x["Key"] == "Engine 1 Time"}.first tt && tt["Value"].gsub(/[^0-9.]/, "") end def engine_2_time tt = self.content["Specs"].select{|x| x["Key"] == "Engine 2 Time"}.first tt && tt["Value"].gsub(/[^0-9.]/, "") end def interior_year exts = self.content["Specs"].select{|x| ["Year Interior", "Interior Notes", "Interior"].include?(x["Key"])} vals = exts.collect{|x| x["Value"].gsub(/[^0-9 ]/, "").split(" ").select{|x| x.length == 4}.collect(&:to_i)}.flatten.compact.reject{|x| x==0} vals.empty? ? nil : vals.average end def year_painted exts = self.content["Specs"].select{|x| ["Year Painted", "Exterior Notes", "Exterior"].include?(x["Key"])} vals = exts.collect{|x| x["Value"].gsub(/[^0-9 ]/, "").split(" ").select{|x| x.length == 4}.collect(&:to_i)}.flatten.compact.reject{|x| x==0} vals.empty? ? nil : vals.average end def num_of_seats tt = self.content["Specs"].select{|x| x["Key"] == "Number of Seats"}.first tt && tt["Value"].gsub(/[^0-9.]/, "") end def reg_number tt = self.content["Specs"].select{|x| x["Key"] == "Registration #"}.first tt && tt["Value"] end def serial_no tt = self.content["Specs"].select{|x| x["Key"] == "Serial Number"}.first tt && tt["Value"] end def category_level category_map = { "Piston Helicopters" => "Piston+Helicopters", "Turboprop Aircraft" => "Turboprop", "Piston Twin Aircraft" => "Multi+Engine+Piston", "Turbine Helicopters" => "Turbine+Helicopters", "Light Sport Aircraft" => "Ultralight", "Jet Aircraft" => "Jets", "Piston Single Aircraft" => "Single+Engine+Piston" } category_map[self.content["CategoryName"]] end def full_address self.content["ListingLocation"]["FormattedLocation"].to_s+" "+self.content["ListingLocation"]["PostalCode"].to_s end def price self.content["RetailPrice"].gsub(/[^0-9.]/, "").to_i end def airframe self.content["Description"] end def get_make_model_response MakeModelModel.new.analyze([self.content["ListingTitle"]]) end def similar_planes ControllerAircraft.where("content.Model" => self.content["Model"], "content.ManufacturerName" => self.content["ManufacturerName"]) end def store_standardized_version(likely_avionics_ids=nil) response = self.get_make_model_response.select{|x| x["success"] == true} mm = MakeModel.where("make.id" => AircraftSpecRecord.find(response.first["ids"].first).aircraft['make']['id']).first rescue nil sa = StandardizedAircraft.where(original_id: self.id, original_source: "controller").first_or_create sa.make_model_id = mm.id rescue nil sa.year = self.year sa.aftt = self.total_time sa.smoh_1 = self.engine_1_time.split("_").first.to_i rescue nil sa.smoh_2 = self.engine_2_time.split("_").first.to_i rescue nil sa.smoh_3 = nil sa.smoh_4 = nil sa.tbo = AircraftSpecRecord.where("aircraft.make.id" => mm.make["id"]).collect{|x| x.aircraft_engines.flatten.collect{|x| x["tbo"]}}.flatten.average rescue nil sa.interior_quality = self.interior_year ? 1-(self.created_at.year-self.interior_year.to_i).abs/44.0 : 0.5 #magic number from RawPlane.where(:interior_year.ne => nil).collect{|x| x.created_at.year-x.interior_year.to_i}.sort.percentile(0.95) sa.exterior_quality = self.year_painted ? 1-(self.created_at.year-self.year_painted.to_i).abs/45.0 : 0.5 #magic number from RawPlane.where(:year_painted.ne => nil).collect{|x| x.created_at.year-x.year_painted.to_i}.sort.percentile(0.95) sa.num_seats = self.num_of_seats if likely_avionics_ids sa.likely_avionics_ids = likely_avionics_ids else sa.likely_avionics_ids = AvionicsModel.new.analyze([self.avionics_package])[0] end sa.reg_no = self.reg_number sa.serial_no = self.serial_no sa.category = self.category_level sa.location = self.full_address sa.price = self.price sa.airframe_description = self.airframe sa.avionics_description = self.avionics_package sa.list_date = self.list_date sa.save! end def list_date Time.parse(self.content["FormattedUpdatedOnTime"]) rescue nil end end
require 'spec_helper' describe command('ufw status verbose') do its(:stdout) { should match /^Status: active$/ } its(:stdout) { should match /^Default: deny \(incoming\), allow \(outgoing\), deny \(routed\)$/ } its(:exit_status) { should eq 0 } end
# The rules of tic-tac-toe are as follows # There are two players in the game (X and O) # Players take turns until the game is over # A player can claim a field if it is not already taken # A turn ends when a player claims a field # A player wins if they claim all the fields in a row, column or diagonal # A game is over if a player wins # A game is over when all fields are taken # TODO: computer player should only be called if player's previous move was valid - game over variable? # computer player should probably be player 2, so initialise done by game runner, and input handled by player class? class Tic_tac_toe_game attr_reader :board, :active_player, :inactive_player, :game_over def initialize(num_players) @board = [ [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '] ] if num_players == 2 @player_1 = Player.new(:x, 1) @player_2 = Player.new(:o, 2) elsif num_players == 1 @player_1 = Player.new(:x, 1) @player_2 = Computer_player.new(:o, 2) else return nil end @game_over = false @active_player = @player_1 @inactive_player = @player_2 end def input(input) input_arr = input.split(',') return invalid_input_message unless validate_input(input_arr) input_arr.map!{ |input_val| input_val.strip.to_i } move(input_arr[0], input_arr[1]) end def move(row, column) return position_filled_message(row, column) if position_filled?(row, column) @board[row][column] = @active_player unless update_game_over switch_current_player unless update_game_over return game_state end def game_state output = "Current state of the board:\n" + board_state if @game_over output += game_over_message else output += "#{@active_player.info} goes next.\n" end output end private def board_state output = " 0 1 2 \n" @board.each.with_index do |row, index| output += " #{index} " row.each do |place| output += "[ #{place} ] " end output += "\n" end return output end def update_game_over @game_over = true if row_claimed? || column_claimed? || diagonal_claimed? || board_full? return @game_over end def switch_current_player @active_player, @inactive_player = @inactive_player, @active_player end def row_claimed? @board.any? { |row| row.uniq == [@player_1] || row.uniq == [@player_2] } end def column_claimed? @board.transpose.any? { |row| row.uniq == [@player_1] || row.uniq == [@player_2] } end def diagonal_claimed? center = @board[1][1] claimed = false if center != ' ' top_left = @board[0][0] top_right = @board[0][2] bottom_left = @board[2][0] bottom_right = @board[2][2] if top_left == center claimed = true if bottom_right == center end if top_right == center claimed = true if bottom_left == center end end claimed end def board_full? @board.none? { |row| row.include?(' ') } end def position_filled?(row, column) @board[row][column] != ' ' end def position_filled_message(row, column) filled_by = @board[row][column] return "Sorry, that position has already been filled by #{filled_by.info}" end def game_over_message return "Game over! #{@active_player.info} wins!" if row_claimed? || column_claimed? || diagonal_claimed? return "Game over! Noone wins!" if board_full? end def validate_input(arr) arr.length == 2 && arr.none? { |item| item.strip.to_i > 2 || item.strip.to_i < 0 } end def invalid_input_message return "You didn't input a valid move. Try again!" end end class Player attr_reader :symbol, :number, :player_type def initialize(symbol, number) @symbol = symbol @number = number @player_type = :human end def to_s return @symbol.to_s end def info return "Player #{@number} (#{@symbol.to_s})" end end class Tic_tac_toe_game_runner def initialize end def run loop do puts "Enter 1 for single player, 2 for two player" input = gets.chomp single_player if input == '1' two_player if input == '2' end end def two_player @game = Tic_tac_toe_game.new(2) puts @game.game_state loop do puts "Enter the row and column where you want to go, separated by a comma" unless @game.game_over puts @game.input(gets.chomp) end end def single_player @game = Tic_tac_toe_game.new(1) puts @game.game_state loop do puts "Enter the row and column where you want to go, separated by a comma" puts @game.input(gets.chomp) puts @game.input(@game.active_player.move(@game.board)) if @game.active_player.player_type == :computer end end end class Computer_player attr_reader :symbol, :number, :player_type def initialize(symbol, number) @player_type = :computer @symbol = symbol @number = number end def to_s return @symbol.to_s end def info return "Computer player #{@number} (#{@symbol.to_s})" end def move(board) # return "0, 1" # return pick_move_at_random(board) if block_if_threatens_win(board) return block_if_threatens_win(board) else return pick_move_at_random(board) end end def block_if_threatens_win(board) return block_horizontal_win(board) if block_horizontal_win(board) return pick_move_at_random(board) return block_vertical_win(board) if block_vertical_win(board) return block_diagonal_win(board) if block_diagonal_win(board) return nil end def pick_move_at_random(board) valid_moves = [] board.each.with_index do |row, row_index| row.each.with_index { |piece, column_index| valid_moves.push([row_index, column_index]) if piece == ' ' } end return valid_moves.sample.join(', ') end def block_horizontal_win(board) block_position = [] board.each.with_index do |row, row_index| if enemy(row[1]) && not_full(row) block_position.push([row_index, [0]]) if enemy(row[2]) block_position.push([row_index, [2]]) if enemy(row[0]) end block_position.push end block_position[0] ? block_position.sample.join(', ') : nil end def block_vertical_win(board) block_position = [] board.transpose.each.with_index do |row, row_index| if enemy(row[1]) && not_full(row) block_position.push([row_index, [0]]) if enemy(row[2]) block_position.push([row_index, [2]]) if enemy(row[0]) end block_position.push end block_position[0] ? block_position.sample.join(', ') : nil end def block_diagonal_win(board) end def enemy(position) position != ' ' && position != self end def not_full(row) row.include? ' ' end end runner = Tic_tac_toe_game_runner.new runner.run # game = Tic_tac_toe_game.new # puts game.move(0, 2) # player = Computer_player.new # puts game.input(player.move(game.board)) # game = Tic_tac_toe_game.new # puts game.move(1,2) # puts game.move(0,1) # puts game.move(1,1) # puts game.move(0,2) # puts game.move(2,1) # puts game.move(0,0) # puts game.move(2,2) # computer player needs to know
class AddInitialAmountToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :initial_amount, :decimal, precision: 8, scale: 2, default: 0 end end
# Write your code here. katz_deli = [] def line(deli_line) if deli_line.length == 0 puts "The line is currently empty." else beginning_sentence = "The line is currently:" list_of_names = [] deli_line.each_with_index do |item, index| list_of_names.push("#{index+1}. #{item}") end puts "#{beginning_sentence} #{list_of_names.join(" ")}" end end def take_a_number(deli_line, name) if deli_line.length == 0 puts "Welcome, #{name}. You are number 1 in line." else puts "Welcome, #{name}. You are number #{deli_line.length+1} in line." end deli_line.push(name) end def now_serving(deli_line) if deli_line.length == 0 puts "There is nobody waiting to be served!" else puts "Currently serving #{deli_line[0]}." deli_line.shift end end
require 'rubygems' require 'oauth' require 'json' class Twitter def initialize(user, count) baseurl = "https://api.twitter.com" path = "/1.1/statuses/user_timeline.json" query = URI.encode_www_form( "screen_name" => "#{user}", "count" => count, ) address = URI("#{baseurl}#{path}?#{query}") @request = Net::HTTP::Get.new address.request_uri @http = Net::HTTP.new address.host, address.port @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_PEER end def get_connection http = @http consumer_key = OAuth::Consumer.new( "Qo4x9IByYdEdNIJeNK67KsLQ2", "S0AZDgDHLezBq2OqwDbpA2zp3yzXFaljNEc5lYyHK98ffSM0nr") access_token = OAuth::Token.new( "50933451-GgTiu4AZXo2lB91dqXMq7xmYeiGxXIkiuSnfOEvp5", "4Kmk4AESfSsbod578fOeoYNGCWp0XlwzosHO3rBDxZjlQ") # Issue the request. @request.oauth! http, consumer_key, access_token http.start @response = http.request @request end def grab_tweets tweets = nil response = @response # Parse and print the Tweet if the response code was 200 if response.code == '200' then tweets = JSON.parse(response.body) tweets = JSON.pretty_generate(tweets) file = File.open('./data/tweets.json', 'w+') file.write(tweets) file.close end end end
class Contact < ActiveRecord::Base attr_accessible :contact_us acts_as_gmappable :check_process => false def gmaps4rails_address #describe how to retrieve the address from your model, if you use directly a db column, you can dry your code, see wiki "#{self.contact_us}" end end
module Account class UsersController < ApplicationController def show @user = current_user end def edit @user = current_user end def update @user = current_user # authorize @user @user.update(user_params) redirect_to account_dashboard_path end private def user_params params.require(:user).permit(:name, :picture, :age, :crew, :phone_number) end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require "cases/helper" require 'models/contact' class SerializationTest < ActiveRecord::TestCase FORMATS = [ :xml, :json ] def setup @contact_attributes = { :name => 'aaron stack', :age => 25, :avatar => 'binarydata', :created_at => Time.utc(2006, 8, 1), :awesome => false, :preferences => { :gem => '<strong>ruby</strong>' } } @contact = Contact.new(@contact_attributes) end def test_serialize_should_be_reversible for format in FORMATS @serialized = Contact.new.send("to_#{format}") contact = Contact.new.send("from_#{format}", @serialized) assert_equal @contact_attributes.keys.collect(&:to_s).sort, contact.attributes.keys.collect(&:to_s).sort, "For #{format}" end end def test_serialize_should_allow_attribute_only_filtering for format in FORMATS @serialized = Contact.new(@contact_attributes).send("to_#{format}", :only => [ :age, :name ]) contact = Contact.new.send("from_#{format}", @serialized) assert_equal @contact_attributes[:name], contact.name, "For #{format}" assert_nil contact.avatar, "For #{format}" end end def test_serialize_should_allow_attribute_except_filtering for format in FORMATS @serialized = Contact.new(@contact_attributes).send("to_#{format}", :except => [ :age, :name ]) contact = Contact.new.send("from_#{format}", @serialized) assert_nil contact.name, "For #{format}" assert_nil contact.age, "For #{format}" assert_equal @contact_attributes[:awesome], contact.awesome, "For #{format}" end end end
require 'spec_helper' describe TagsController do describe 'GET #index' do it "populates an array of tags" it "renders the :index view" end describe 'GET #show' do context "when the tag exists by name" do it "assigns the requested tag to @tag" it "renders the :show view" end context "when the tag exists by id" do it "assigns the requested tag to @tag" it "renders the :show view" end context "when the tag does not exist by name or id" do it "redirects to the tags index page" end end end
# encoding: utf-8 pages_names = { home: 'ГЛАВНАЯ', concept: 'КОНЦЕПЦИЯ', place: 'РАСПОЛОЖЕНИЕ', floor_plans: 'ПЛАНИРОВКА', service: 'СЕРВИС', gallery: 'ГАЛЕРЕЯ', contacts: 'КОНТАКТЫ', main: 'ГЛАВНАЯ', } Page.reset_column_information pages_names.each do |page_slug, page_name| parent_page = Page.create! slug: page_slug, name: page_name, title: page_name, content: '' end # По всему сайту ужаснейший говнокод, но мне уже пофигу (: =begin pages_names = { 'Home' => [], 'Best' => ['Place', 'Service', 'Engineering', 'Design'], 'Aparts' => ['Gallery', 'Floor Plans'] } Page.reset_column_information pages_names.each do |parent_page_name, subpages_names| parent_page = Page.create!(name: parent_page_name, title: parent_page_name, content: '') parent_page.subpages << subpages_names.map do |subpage_name| Page.create!(name: subpage_name, title: subpage_name, content: '') end end =end
require 'spec_helper' require 'email_spec' describe PayslipNotifier do before(:each) do period = FactoryGirl.build(:periodJan2013) payroll_tags = PayTagGateway.new payroll_concepts = PayConceptGateway.new @payroll_process = PayrollProcess.new(payroll_tags, payroll_concepts, period) end it 'Should create Email Payroll' do empty_value = {} tag_employee_numb = '00010' tag_employee_dept = 'IT crowd' tag_employee_name = 'Ladislav Lisy' tag_employer_name = 'Hrave Mzdy - effortlessly, promptly, clearly Ltd.' tag_employee_mail = 'ladislav.lisy@seznam.cz' PayslipNotifier.send_payslip(tag_employee_mail, tag_employee_name, tag_employer_name, tag_employee_numb) test_email = find_email!(tag_employee_mail) test_email.subject.should include(tag_employer_name) end end
Rails.application.routes.draw do #post "cart_products/update_quantity" => "cart_products#update_quantity" resources :products do collection do get :choose_new_type get :new_books get :new_cloth get :new_snacks get :category_products post :create_books post :create_snacks post :create_cloth end member do get :buy get :put_in_cart end end resources :cart_products do collection do get :show_cart get :update_quantity end member do get :destory end end resources :orders do collection do get :show_order post :new_cart_orders post :create_cart_orders get :pay_for_orders get :request_manager end member do get :purchase get :check_out get :pay delete :destroy get :approval get :update_reject_status patch :reject get :refund get :confirm get :ship end end devise_for :users # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end root to: 'homepage#home' match '/help', to: 'homepage#help', via: 'get' match '/about', to: 'homepage#about', via: 'get' match '/contact', to: 'homepage#contact', via: 'get' end
module Closeio class Client module OpportunityStatus def list_opportunity_statuses get(opportunity_status_path) end def create_opportunity_status(options = {}) post(opportunity_status_path, options) end def update_opportunity_status(id, options = {}) put(opportunity_status_path(id), options) end def delete_opportunity_status(id) delete(opportunity_status_path(id)) end private def opportunity_status_path(id = nil) id ? "status/opportunity/#{id}/" : 'status/opportunity/' end end end end
# == Schema Information # # Table name: gifts # # id :integer not null, primary key # name :string # description :text # event_id :integer # created_at :datetime not null # updated_at :datetime not null # photo :string # # Indexes # # index_gifts_on_event_id (event_id) # # Foreign Keys # # fk_rails_... (event_id => events.id) # FactoryBot.define do # frozen_string_literal: true. factory :gift do name "MyString" description "MyText" event nil end end
class UserSession < Authlogic::Session::Base generalize_credentials_error_messages true single_access_allowed_request_types :all params_key "api_key" end
require File.expand_path '../../spec_helper.rb', __FILE__ require './src/services/location_counts_by_date_importer.rb' describe "Services::LocationCountsByDateImporter" do klass = Services::LocationCountsByDateImporter it "should be defined" do expect(klass).not_to be nil end it "should have an API for pulling location counts by date" do subject = klass.new data = subject.pull(["UNITED+STATES", "US", "UNITED+KINGDOM", "JAPAN"]) expect(data.size).to_not be 0 end it "should be able to return data in csv format" do subject = klass.new data = subject.pull(["UNITED+STATES", "US", "UNITED+KINGDOM", "JAPAN"]) expect(data.to_csv).to_not be nil end end
module OSMLib module Element # OpenStreetMap Way. # # To create a new OSMLib::Element::Way object: # way = OSMLib::Element::Way.new(1743, 'user', '2007-10-31T23:51:17Z') # # To get a way from the API: # way = OSMLib::Element::Way.from_api(17) # class Way < OSMLib::Element::Object # Array of node IDs in this way. attr_reader :nodes # Create new Way object. # # id:: ID of this way. If +nil+ a new unique negative ID will be # allocated. # user:: Username # timestamp:: Timestamp of last change # nodes:: Array of Node objects and/or node IDs def initialize(id=nil, user=nil, timestamp=nil, nodes=[], uid=-1, version=1, visible=nil) @nodes = nodes.collect{ |node| node.kind_of?(OSMLib::Element::Node) ? node.id : node } super(id, user, timestamp, uid, version, visible) end def type 'way' end # Add one or more tags or nodes to this way. # # The argument can be one of the following: # # * If the argument is a Hash or an OSMLib::Element::Tags object, those tags # * are added. If the argument is an OSMLib::Element::Node object, its ID # * is added to the list of node IDs. If the argument is an # * Integer or String containing an Integer, this ID is added # * to the list of node IDs. If the argument is an Array the # * function is called recursively, i.e. all items in the # * Array are added. # # Returns the way to allow chaining. # # call-seq: way << something -> Way # def <<(stuff) case stuff when Array # call this method recursively stuff.each do |item| self << item end when OSMLib::Element::Node nodes << stuff.id when String nodes << stuff.to_i when Integer nodes << stuff else tags.merge!(stuff) end self # return self to allow chaining end # Is this way closed, i.e. are the first and last nodes the same? # # Returns false if the way doesn't contain any nodes or only one node. # # call-seq: is_closed? -> true or false # def is_closed? return false if nodes.size < 2 nodes[0] == nodes[-1] end # Return an Array with all the node objects that are part of this way. # # Only works if the way and nodes are part of an OSMLib::Database. # # call-seq: node_objects -> Array of OSMLib::Element::Node objects # def node_objects raise OSMLib::Error::NoDatabaseError.new("can't get node objects if the way is not in a OSMLib::Database") if @db.nil? nodes.collect do |id| @db.get_node(id) end end # Create object of class GeoRuby::SimpleFeatures::LineString with the # coordinates of the node in this way. # Raises a OSMLib::Error::GeometryError exception if the way contain less than # two nodes. Raises an OSMLib::Error::NoDatabaseError exception if this way # is not associated with an OSMLib::Database. # # Only works if the GeoRuby library is loaded. # # call-seq: linestring -> GeoRuby::SimpleFeatures::LineString or nil # def linestring raise OSMLib::Error::GeometryError.new("way with less then two nodes can't be turned into a linestring") if nodes.size < 2 raise OSMLib::Error::NoDatabaseError.new("can't create LineString from way if the way is not in a OSMLib::Database") if @db.nil? GeoRuby::SimpleFeatures::LineString.from_coordinates(node_objects.collect{ |node| [node.lon.to_f, node.lat.to_f] }) end # Create object of class GeoRuby::SimpleFeatures::Polygon with # the coordinates of the node in this way. # Raises a OSMLib::Error::GeometryError exception if the way contain less # than three nodes. # Raises an OSMLib::Error::NoDatabaseError exception if this way is not # associated with an OSMLib::Database. # Raises an OSMLib::Error::NotClosedError exception if this way is not closed. # # Only works if the GeoRuby library is loaded. # # call-seq: polygon -> GeoRuby::SimpleFeatures::Polygon or nil # def polygon raise OSMLib::Error::GeometryError.new("way with less then three nodes can't be turned into a polygon") if nodes.size < 3 raise OSMLib::Error::NoDatabaseError.new("can't create Polygon from way if the way is not in a OSMLib::Database") if @db.nil? raise OSMLib::Error::NotClosedError.new("way is not closed so it can't be represented as Polygon") unless is_closed? GeoRuby::SimpleFeatures::Polygon.from_coordinates([node_objects.collect{ |node| [node.lon.to_f, node.lat.to_f] }]) end # Currently the same as the linestring method. This might change in # the future to return a Polygon in some cases. # # Only works if the GeoRuby library is loaded. # # call-seq: geometry -> GeoRuby::SimpleFeatures::LineString or nil # def geometry linestring end # Return string version of this Way object. # # call-seq: to_s -> String # def to_s if @visible == nil "#<OSMLib::Element::Way id=\"#{@id}\" user=\"#{@user}\" timestamp=\"#{@timestamp}\">" else "#<OSMLib::Element::Way id=\"#{@id}\" user=\"#{@user}\" timestamp=\"#{@timestamp}\" visible=\"#{@visible}\">" end end # Return XML for this way. This method uses the Builder library. # The only parameter ist the builder object. def to_xml(xml) xml.way(attributes) do nodes.each do |node| xml.nd(:ref => node) end tags.to_xml(xml) end end end end end
class DevicesController < ApplicationController before_action :set_device, only: [:show, :edit, :update, :destroy] #, :new_point, :new_point1] before_filter :authenticate_user!, :except => [:new_point, :new_point1] # GET /devices # GET /devices.json def index #@devices = Device.all @devices = Device.where("user_id = ?",current_user.id ).includes(:user) end # GET /devices/1 # GET /devices/1.json def show end # GET /devices/new def new @device = Device.new end # GET /devices/1/edit def edit end # POST /devices # POST /devices.json def create @device = Device.new(device_params) @device.user = current_user respond_to do |format| if @device.save format.html { redirect_to @device, notice: 'Device was successfully created.' } format.json { render action: 'show', status: :created, location: @device } else format.html { render action: 'new' } format.json { render json: @device.errors, status: :unprocessable_entity } end end end # PATCH/PUT /devices/1 # PATCH/PUT /devices/1.json def update #el imei NUNCA debe ser modificable. respond_to do |format| if @device.update(device_params) format.html { redirect_to @device, notice: 'Device was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @device.errors, status: :unprocessable_entity } end end end # DELETE /devices/1 # DELETE /devices/1.json def destroy @device.destroy #$redis.srem("u:" + self.user.id.to_s, self.imei.to_s) respond_to do |format| format.html { redirect_to devices_url } format.json { head :no_content } end end def new_point if params[:imei].present? && params[:datetime].present? && params[:latitude].present? && params[:longitude].present? && params[:speed].present? && params[:altitude].present? && params[:course].present? && params[:extended].present? if Device.new_point(params[:imei], params[:datetime], params[:latitude], params[:longitude], params[:speed], params[:altitude], params[:course], params[:extended]) render :text => ("OK") else render :text => ("KO") end else render :text => ("KO") end end def new_ack end private # Use callbacks to share common setup or constraints between actions. def set_device @device = Device.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def device_params params.require(:device).permit(:name, :user_id, :type_id, :last_lat, :last_lon, :last_fix, :active, :available, :imei) end end
require 'spree_core' require "spree_reports/engine" require "chartkick" require "groupdate" module SpreeReports # list of visible reports mattr_accessor :reports # time zone mattr_accessor :time_zone # start of week mattr_accessor :week_start # export mattr_accessor :csv_export # available months to select in reports mattr_accessor :report_months # default months selection in reports mattr_accessor :default_months # check if the api user has this role mattr_accessor :api_user_role # date formats for different group_by settings mattr_accessor :date_formats # these user roles are exluded from all reports mattr_accessor :excluded_roles # these user accounts are exluded from all reports mattr_accessor :excluded_users end # default configuration, overrideable in config/initializer spree_reports.rb SpreeReports.reports = [ :orders_by_period, :sold_products ] SpreeReports.time_zone = "Pacific Time (US & Canada)" SpreeReports.week_start = :mon SpreeReports.csv_export = true SpreeReports.report_months = %w{1 3 6 12 24 36 48 all} SpreeReports.default_months = 6 SpreeReports.api_user_role = "admin" SpreeReports.date_formats = { year: "%Y", month: "%m.%Y", week: "%W/%Y", day: "%m.%d.%y" } SpreeReports.excluded_roles = %w{admin} SpreeReports.excluded_users = []
require ('minitest/autorun') require ('minitest/rg') require_relative ('../models/members') class TestMember < MiniTest::Test def setup @member1 = Member.new({ 'first_name' => 'Ricky', 'last_name' => 'Corrigan', 'membership_type' => 'Basic' }) end def test_member_first_name assert_equal("Ricky", @member1.first_name) end def test_member_last_name assert_equal("Corrigan", @member1.last_name) end def test_member_membership_type assert_equal("Basic", @member1.membership_type) end end
require 'pry' class Person attr_accessor :hair_color, :top_color, :height attr_reader :height # Instance Variables def initialize(height = 0.0) @height = height @top_color = 'Black' @hair_color = 'Blue' end def to_s "Your hair color is #{@hair_color}. Your height is #{@height.to_s}. Your top colour is #{@top_color}." end #Instance methods def dance 'I am Dancing' end def sleep 'I am Sleeping' end end class Baby < Person attr_accessor :smells def initialize(height = 0.0) @smells= true super end def cry if @smells ";-;" else "^_^" end end def dance "*This is a baby, it can't dance*" end end binding.pry
class Mytodo < ActiveRecord::Base attr_accessible :description, :done, :due, :priority validates :description, presence: true belongs_to :user end
module TransferAccountService def self.call(source_account_id, destination_account_id, amount) account = Account.find_by_account_id(source_account_id) raise StandardError, 'Source Account not found' unless account recipient = Account.find_by_account_id(destination_account_id) raise StandardError, 'Destination Account not found' unless recipient Account.transfer(account, recipient, amount) end end
class Public::ArticlesController < PublicController def index @page = params.has_key?(:page) ? params[:page] : 1 @limit = limit = APP_CONFIG[:articles_per_page] @offset = offset = (@page.to_i - 1) * limit; @articles = Article.all_public(nil, offset, limit) @page_count = (Article.count_all_public.to_f / limit).ceil @authors = Employee.all_authors @content = Content.get_hash_by_slug([:articles_meta_title, :articles_meta_description]) end def index_by_user @author = Employee.find_by_slug(params[:author_slug]) @page = params.has_key?(:page) ? params[:page] : 1 limit = APP_CONFIG[:articles_per_page] offset = (@page.to_i - 1) * limit; @articles = Article.all_public(@author.user_id, offset, limit) @page_count = (Article.count_all_public(@author.user_id).to_f / limit).ceil @authors = Employee.all_authors end def show @article = Article.find_by_slug(params[:article_slug]) @article_comment = ArticleComment.new @comments = ArticleComment.all_public_for_article(@article.id) end def show_preview @article = params[:article] end def create_comment @article_comment = ArticleComment.new(params[:article_comment]) @article = Article.find(params[:id]) # If the user is logged in add it if user_signed_in? @article_comment.author_id = current_user.id # Remove the exiting name, email, website values params[:article_comment].delete(:name) params[:article_comment].delete(:email) params[:article_comment].delete(:website) params[:article_comment].delete(:image) # Add the user's name, email, website values @article_comment.name = current_user.userable.name @article_comment.email = current_user.email @article_comment.website = current_user.userable.class.to_s == 'Employee' ? agent_path(current_user.userable.slug) : '' @article_comment.image = current_user.userable.image_url(:thumb).nil? ? '' :view_context.image_path(current_user.userable.image_url(:thumb)); end # Add the article_id @article_comment.article_id = @article.id # Add the status to default as not approved if the author is different then the current authenticated user if user_signed_in? and current_user.id == @article.author_id @article_comment.is_approved = true else @article_comment.is_approved = false end if @article_comment.valid? @article_comment.save render :json => {status: true} else render :json => {status: false, errors: @article_comment.errors} end end def old_blog_post article = Article.find_by_old_slug(URI::encode(params[:slug]).downcase) redirect_to article_path(article.author_slug, article.globbing_slug, article.slug), :status => 301 end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # USERS u1 = User.create!(name: 'Pat Flyin', nick: 'test1', email: 'test1@example.com', anon: false) u2 = User.create!(name: 'Fred Kimble', nick: 'test2', email: 'test2@example.com', anon: false) u3 = User.create!(name: 'Furiously', anon: true) u4 = User.create!(name: 'Not chatting', anon: true) # CHATS c1 = Chat.create!(user: u1, name: 'Common chat 1', chat_type: 'common', last_activity: Time.now) c2 = Chat.create!(user: u2, name: 'Common chat 2 with password', chat_type: 'common', password: 'pepe', last_activity: Time.now) c3 = Chat.create!(user: u3, name: 'Anon chat 1', chat_type: 'anon', last_activity: Time.now) # MEMBERS Member.create!(user: u1, chat: c1) Member.create!(user: u2, chat: c1) Member.create!(user: u3, chat: c1) Member.create!(user: u4, chat: c1) Member.create!(user: u1, chat: c2) Member.create!(user: u2, chat: c2) Member.create!(user: u3, chat: c2) Member.create!(user: u4, chat: c2) Member.create!(user: u1, chat: c3) Member.create!(user: u2, chat: c3) Member.create!(user: u3, chat: c3) Member.create!(user: u4, chat: c3) # MESSAGES Message.create!(user: u3, chat: c3, message: "This is a test message.") Message.create!(user: u1, chat: c1, message: "This is a test message.") Message.create!(user: u2, chat: c2, message: "This is a test message.") Message.create!(user: u1, chat: c2, message: "This is a test message.") Message.create!(user: u1, chat: c1, message: "This is a test message.") Message.create!(user: u2, chat: c1, message: "This is a test message.") Message.create!(user: u3, chat: c1, message: "This is a test message.") Message.create!(user: u1, chat: c2, message: "This is a test message.") Message.create!(user: u2, chat: c3, message: "This is a test message.") Message.create!(user: u3, chat: c3, message: "This is a test message.") Message.create!(user: u3, chat: c2, message: "This is a test message.") Message.create!(user: u2, chat: c2, message: "This is a test message.") Message.create!(user: u1, chat: c1, message: "This is a test message.")
require 'spec_helper' class MoonPresenterSpec < TarotSpec let(:options) do { :phase => phase, :illumination => illumination, :is_waxing => is_waxing, :is_waning => is_waning } end let(:moon) { OpenStruct.new(options) } let(:phase) { :new } let(:illumination) { 0 } let(:is_waxing) { false } let(:is_waning) { false } let(:presenter) { MoonPresenter.new(moon) } it 'gives access to phase' do assert_equal phase, presenter.phase end it 'gives access to percent_illuminated' do assert_equal illumination * 100, presenter.percent_illuminated end it 'gives access to is_waxing' do assert_equal is_waxing, presenter.waxing? end it 'gives access to is_waning' do assert_equal is_waning, presenter.waning? end describe 'image_path' do it 'returns the correct image path' do assert_equal '/images/luna/0.png', presenter.image_path end describe '23% waxing'do let(:phase) { :crescent } let(:illumination) { 0.23 } let(:is_waxing) { true } it 'returns the correct image path' do assert_equal '/images/luna/3.png', presenter.image_path end end describe '23% waning' do let(:phase) { :balsamic } let(:illumination) { 0.23 } let(:is_waning) { true } it 'returns the correct image path' do assert_equal '/images/luna/24.png', presenter.image_path end end end end
# frozen_string_literal: true class Api::ServicePlansController < Api::PlansBaseController before_action :authorize_service_plans! before_action :activate_sidebar_menu activate_menu :serviceadmin, :subscriptions, :service_plans sublayout 'api/service' def index @new_plan = ServicePlan end def new @plan = collection.build params[:service_plan] end def edit @plan || raise(ActiveRecord::RecordNotFound) end # class super metod which is Api::PlansBaseController#create # to create plan same way as all plans # def create super params[:service_plan] end def update super params[:service_plan] do redirect_to plans_index_path, :notice => "Service plan updated." end end def destroy super end def masterize generic_masterize_plan(@service, :default_service_plan) end protected def activate_sidebar_menu activate_menu :sidebar => :service_plans end def collection(service_id = params[:service_id].presence) # start of our scope is current_account scope = current_account # if we have :service_id, then lookup service first scope = scope.accessible_services.find(service_id) if service_id # then return all service plans of current scope scope.service_plans end def authorize_service_plans! authorize! :manage, :service_plans end end
#Blackjack #Tealeaf Academy SUITS = ["Hearts", "Diamonds", "Spades", "Clubs"] CARDS = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "ACE", "KING", "QUEEN", "JESTER"] BLACKJACK = 21 DEALER_HIT_LIMIT = 17 #calculates score for respective hand def calculate_score(hand_of_cards) card_values = hand_of_cards.map{|card_value| card_value[1]} total = 0 card_values.each do |card_value| if card_value == "ACE" total+= 11 elsif card_value.to_i == 0 #For suits ie Jester, Queen total+= 10 else total+= card_value.to_i end end #adjust for Aces card_values.select{|card| card == "ACE"}.count.times do total-=10 if total > 21 end total end #format cards def format_card(card) card[1] +" of "+ card[0] end def deal_first_cards(user_hand, dealer_hand, deck) 2.times do user_hand<< deck.pop dealer_hand<< deck.pop end end def insert_blank_line puts "" end def output_cards(hand_of_cards) card_list = [] hand_of_cards.each do |card| card_list<< format_card(card) end formatted_cards = card_list.join(", ") end def compare_hands(user_hand, dealer_hand, name) user_total = calculate_score(user_hand) dealer_total = calculate_score(dealer_hand) puts "#{name} has #{output_cards(user_hand)} with a total of #{user_total}" puts "Dealer has #{output_cards(dealer_hand)} with a total of #{dealer_total}" if user_total > dealer_total puts "#{name} wins!!!" insert_blank_line elsif dealer_total > user_total puts "Dealer wins, you lose.." insert_blank_line else puts "OMG..it's a tie!!!!!" insert_blank_line end end #Our game begin user_hand = [] dealer_hand = [] win_or_bust = false #make deck of cards and shuffle deck = SUITS.product(CARDS) deck.shuffle! puts "What is your name?" name = gets.chomp insert_blank_line puts "Let's play #{name}" insert_blank_line deal_first_cards(user_hand, dealer_hand, deck) insert_blank_line user_total = calculate_score(user_hand) dealer_total = calculate_score(dealer_hand) puts "#{name} has #{output_cards(user_hand)} with a total of #{user_total}" puts "Dealer has a total of #{dealer_total}" insert_blank_line if user_total == BLACKJACK puts "#{name} hit blackjack! #{name} wins!!!" insert_blank_line win_or_bust = true end #User turn while user_total < BLACKJACK && win_or_bust == false puts "#{name}, enter 1 to hit or 2 to stay:" choice = gets.chomp if !['1','2'].include?(choice) next end if choice == '1' puts "#{name} has chosen to hit" user_hand<< deck.pop user_total = calculate_score(user_hand) puts "#{name} has the following cards: #{output_cards(user_hand)}" puts "with a total of #{user_total}" end if user_total == BLACKJACK puts "#{name} hit blackjack! #{name} wins!!!" insert_blank_line win_or_bust = true break elsif user_total > BLACKJACK puts "#{name} has busted. Dealer wins, you lose..." insert_blank_line win_or_bust = true break end if choice == "2" puts "#{name} has chosen to stay" insert_blank_line break end end #Dealer turn if dealer_total == BLACKJACK puts "Dealer has hit blackjack. #{name} has lost.." insert_blank_line win_or_bust = true elsif win_or_bust == false while dealer_total < DEALER_HIT_LIMIT #keep hitting dealer_hand<<deck.pop dealer_total = calculate_score(dealer_hand) puts "Dealer has a total of #{dealer_total}" insert_blank_line if dealer_total == BLACKJACK puts "Dealer has hit blackjack. #{name} has lost.." insert_blank_line win_or_bust = true break elsif dealer_total > BLACKJACK puts "Dealer has busted. #{name} wins!" insert_blank_line win_or_bust = true break end end end if win_or_bust == false compare_hands(user_hand, dealer_hand, name) end puts "Play again? (y/n):" again = gets.chomp.downcase end while again == 'y'
FactoryGirl.define do factory :user do name "username" password "password" email "sample@example.com" factory :admin_user do admin true end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) ActiveRecord::Base.transaction do # Clear all tables and reset id value [User, Artwork, ArtworkShare, Comment, Like].each do |c| ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{c.table_name} RESTART IDENTITY;") end users = %w[Bojangles Frodo Pickles] # Create Users (username) users.each { |u_name| User.create(username: u_name) } # Create Artworks (title, image_url, artist_id) users.each_with_index do |name, idx| Artwork.create(title: "#{name} Made This", image_url: "#{name}.com", artist_id: idx + 1) end # Create ArtworkShares (artwork_id, viewer_id) ArtworkShare.create(artwork_id: 1, viewer_id: 2) ArtworkShare.create(artwork_id: 1, viewer_id: 3) ArtworkShare.create(artwork_id: 2, viewer_id: 3) ArtworkShare.create(artwork_id: 3, viewer_id: 1) # Create Comments (artwork_id, user_id, body) Comment.create(artwork_id: 1, user_id: 2, body: 'Comment on art 1 by user 2') Comment.create(artwork_id: 1, user_id: 3, body: 'Comment on art 1 by user 3') Comment.create(artwork_id: 2, user_id: 1, body: 'Comment on art 2 by user 1') # Create Likes (user_id, likeable_id, likeable_type) Like.create(user_id: 1, likeable_id: 1, likeable_type: 'Artwork') Like.create(user_id: 2, likeable_id: 1, likeable_type: 'Comment') Like.create(user_id: 1, likeable_id: 1, likeable_type: 'Comment') end
class League class Roster class CommentEdit < ApplicationRecord default_scope { order(created_at: :desc) } belongs_to :created_by, class_name: 'User' belongs_to :comment, class_name: 'Comment' validates :content, presence: true end end end
class Price include Comparable attr_accessor :money attr_accessor :tax def initialize(cents, currency, &block) @currency = currency @money = Money.new(cents, @currency) @tax = Money.new(0, @currency) yield self if block_given? end def tax_cents=(cents) @tax = Money.new(cents, @currency) end def take_tax_from_money(percentage) tmp = @money.cents.to_f / (100.0 + percentage) @money = Money.new(tmp * 100, @currency) @tax = Money.new(tmp * percentage, @currency) end def apply_tax(percentage) @tax = Money.new(@money.cents.to_f / 100 * percentage, @currency) end def ==(other_price) raise "Cannot perform comparison between prices of different currency" unless self.currency == other_price.currency self.with_tax == other_price.with_tax end def <=>(other_price) raise "Cannot perform comparison between prices of different currency" unless self.currency == other_price.currency self.with_tax <=> other_price.with_tax end def +(other_price) raise "Cannot perform arithmetic between prices of different currency" unless self.currency == other_price.currency Price.new(self.money.cents + other_price.money.cents, @currency) do |price| price.tax_cents = self.tax.cents + other_price.tax.cents end end def -(other_price) raise "Cannot perform arithmetic between prices of different currency" unless self.currency == other_price.currency Price.new(self.money.cents - other_price.money.cents, @currency) do |price| price.tax_cents = self.tax.cents - other_price.tax.cents end end def *(fixnum) Price.new(self.money.cents * fixnum, @currency) do |price| price.tax_cents = self.tax.cents.to_f * fixnum end end def /(fixnum) Price.new(self.money.cents / fixnum, @currency) do |price| price.tax_cents = self.tax.cents.to_f / fixnum end end def with_tax self.money + self.tax end def without_tax self.money end def to_f self.money.to_f end def to_s self.money.to_s end def method_missing(method, *args) if self.money.send(:respond_to?, method) self.money.send(method, *args) else super end end end
module Byebug class Breakpoint def inspect values = %w{id pos source expr hit_condition hit_count hit_value enabled?}.map do |field| "#{field}: #{send(field)}" end.join(", ") "#<Byebug::Breakpoint #{values}>" end end end
json.array! @organization_types do |org_type| json.id org_type.id json.title org_type.title end
# == Schema Information # # Table name: comunicado_archivos # # id :integer not null, primary key # comunicado_id :integer # nombre :string # ruta :string # created_at :datetime not null # updated_at :datetime not null # class ComunicadoArchivo < ApplicationRecord belongs_to :comunicado end
require 'spec_helper' describe Season do it { should allow_mass_assignment_of(:name) } it { should allow_mass_assignment_of(:rounds_attributes) } it { should validate_presence_of(:name).with_message("Name can't be blank") } it { should have_many(:rounds).dependent(:destroy) } it { should accept_nested_attributes_for(:rounds).allow_destroy(true) } end
# -*- coding: utf-8 -*- class TopPage < ActiveRecord::Base # Relation belongs_to :person # Validations validates :planed_value, :numericality => true validates :erned_value, :numericality => true def rate self.erned_value / planed_value end end
class Review < ActiveRecord::Base belongs_to :user has_attached_file :photo, styles: { thumbnail: "50x50>" } validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/ end
#!/usr/bin/env ruby # frozen_string_literal: true class Score attr_reader :frame_score def initialize score = ARGV[0] # @resultscore = score.split(',').map{|s| s == 'X'? 10, 0 : s.to_i} 折りたたみ演算で記述したかったのですができず。 @frame_score = score.split(',').each_with_object([]) do |s, result| if s == 'X' # strike result << 10 # ここでXのときの返り値が10と0の2つ数字が欲しい為injectで実装が出来ませんでした。 result << 0 else result << s.to_i end end end end class Frame attr_accessor :shot_one, :shot_two, :last_shot def initialize(frame) @shot_one = frame[0] @shot_two = frame[1] @last_shot = 0 end def adjust_last_frame @shot_one + @shot_two + @last_shot end end input_score = Score.new unless ARGV[0].nil? game = input_score.frame_score.each_slice(2).to_a frame_scores = game.map { |frame| Frame.new(frame) }.to_a result_score = 0 if frame_scores[9].shot_one == 10 && frame_scores[10].shot_one == 10 # 10フレーム目の一投目と二投目がストライクのとき last_two_frames = frame_scores.pop(2) # ストライクであれば末尾配列2つが必要無くなる。 frame_scores[9].last_shot = last_two_frames.last.shot_one frame_scores[9].shot_two = last_two_frames.first.shot_one elsif frame_scores[9].shot_one == 10 && frame_scores[10].shot_one != 10 # 10フレーム目の一投目のみストライクの時 last_frame = frame_scores.pop frame_scores[9].last_shot = last_frame.shot_two frame_scores[9].shot_two = last_frame.shot_one # ストライクでなければ3等目を入れている配列を消す elsif frame_scores[9].shot_one + frame_scores[9].shot_two == 10 # 10フレーム目がスペアのとき last_frame = frame_scores.pop frame_scores[9].last_shot = last_frame.shot_one end frame_scores.each_with_index do |score, i| case i when 0..8 result_score += score.shot_one + score.shot_two if i == 8 && score.shot_one == 10 result_score += frame_scores[9].shot_one + frame_scores[9].shot_two elsif score.shot_one == 10 && frame_scores[i + 1].shot_one == 10 # 一投目がストラクかつ次のフレームもストライク result_score += frame_scores[i + 1].shot_one + frame_scores[i + 2].shot_one elsif score.shot_one == 10 # 一投目のみストライク result_score += frame_scores[i + 1].shot_one + frame_scores[i + 1].shot_two elsif score.shot_one + score.shot_two == 10 # スペア result_score += frame_scores[i + 1].shot_one end when 9 result_score += frame_scores[9].adjust_last_frame end end puts result_score
class InfoQuery < ApplicationQuery def initialize(options = {}) @current_user = options[:current_user] @query = SqlQuery.new(:info_query) end private attr_accessor :current_user, :query end
require "UnitTest" class Board_Manual_Key < UnitTest private ##################################### # DEFAULT PARAMETERS # ##################################### @@DEFAULT_EXECUTION_TIMEOUT = 30; ##################################### # TEST DESCRIPTION # ##################################### @@TEST_NAME = "Key Test"; @@VERSION = "1.0" @@ENVIRONEMENT = "BOARD"; @@TYPE = "MANUAL"; @@PREREQUISITE = "NONE" @@DESCRIPTION = "The user is invited to press in order the key 1,2,3,4,5,6,7,8,9,*,0,#. Timeout after 20s" @@PARAMETERS=[ ["timeout","#{@@DEFAULT_EXECUTION_TIMEOUT}s","Timeout for the test execution"] ] @@RESULTS ="" @@EXAMPLE ="" @@AUTHOR ="Lilian" TestsHelp.addTestHelpEntry( @@TEST_NAME, @@VERSION, @@ENVIRONEMENT, @@TYPE, @@PREREQUISITE, @@PARAMETERS, @@DESCRIPTION, @@RESULTS, @@EXAMPLE, @@AUTHOR ) ##################################### # TEST DESCRIPTION END # ##################################### @@TEST_RETURN_CODE = CH__gtes_test_board_manual_key_globals; public def initialize(params) super(params[:timeout] || @@DEFAULT_EXECUTION_TIMEOUT ,"BOARD_MANUAL_KEY") end def process puts("Press key in order 1, 2, 3, 4, 5, 6, 7, 8, 9, *, 0, #"); start(); results(); end def results super @test_succeeded = 1; if(@results_available) @html_report << "<UL>" if(@results.result.R == @@TEST_RETURN_CODE::GTES_TEST_BOARD_MANUAL_KEY_OK) @html_report << "<LI><TABLE BORDER=0 WIDTH=100%><TR><TD WIDTH=50%>Key test</TD><TD>" @html_report << "<font color='black'><B>Test successed !</B></font></TD></TR></TABLE>" else @html_report << "<LI><TABLE BORDER=0 WIDTH=100%><TR><TD WIDTH=50%>Key test</TD><TD>" @html_report << "<font color='red'><B>Test failed !</B></font></TD></TR></TABLE>" @test_succeeded = 0; end @html_report << "</UL>" end return @html_report end end
require File.dirname(__FILE__) + '/../spec_helper' ### # CONVIENENCE METHODS ### def build_valid_endeca_dimension_value(opts=nil, create=false) opts ||= {} unless opts.key?(:endeca_dimension) opts[:endeca_dimension] = mock_model(EndecaDimension) end unless opts.key?(:name) opts[:name] = 'name-123456789' end unless opts.key?(:dim_value_id) opts[:dim_value_id] = "123456789" end f = EndecaDimensionValue.new opts dump_model_errors(f) unless f.valid? f.should be_valid f.save.should be_true if create f end def expect_invalid_model(ar, attribute=nil, message=nil) ar.valid?.should be_false ar.errors[attribute.to_sym].should_not be_blank unless attribute.blank? ar.errors[attribute.to_sym].should eql(message) unless message.blank? end def expect_invalid_ar_on_blank_string_attribute(ar, attribute) [nil, '', " "].each do |v| ar.send("#{attribute.to_s}=", v) expect_invalid_model(ar, attribute.to_sym) end end ### # SHARED BEHAVIORS ### describe "A valid EndecaDimensionValue", :shared => true do it "should be invalid when endeca_dimension is blank" do @endeca_dimension_value.endeca_dimension = nil expect_invalid_model(@endeca_dimension_value, :endeca_dimension) end end ### # BEHAVIOURS ### describe EndecaDimensionValue do before(:each) do @endeca_dimension_value = build_valid_endeca_dimension_value end it_should_behave_like "A valid EndecaDimensionValue" end
module VCAP::CloudController module AnnotationsUpdate class TooManyAnnotations < StandardError; end class << self def update(resource, annotations, annotation_klass) annotations ||= {} starting_size = annotation_klass.where(resource_guid: resource.guid).count annotations.each do |key, value| key = key.to_s if value.nil? annotation_klass.find(resource_guid: resource.guid, key: key).try(:destroy) next end annotation = annotation_klass.find_or_create(resource_guid: resource.guid, key: key) annotation.update(value: value.to_s) end max_annotations = VCAP::CloudController::Config.config.get(:max_annotations_per_resource) current_size = resource.class.find(guid: resource.guid).annotations.size if starting_size < current_size && current_size > max_annotations raise TooManyAnnotations.new("Failed to add #{annotations.size} annotations because it would exceed maximum of #{max_annotations}") end end end end end
class Sqlite3BTree attr_accessor :header, :cells, :file @@types = {2 => 'Interior Index', 5 => 'Interior Table', 10 => 'Leaf Index', 13 => 'Leaf Table'} def initialize(f) @file = f old = @file.pos self.header = parse_header self.cells = parse_cells(self.header[:cells]) @file.pos = old end def parse_header f = @file old = f.pos header = { :type => f.read(1).unpack('C')[0], :ffree => f.read(2).unpack('n')[0], :cells => f.read(2).unpack('n')[0], :content => f.read(2).unpack('n')[0], :fragmented_free_bytes => f.read(1).unpack('C')[0] } if header[:type] == 5 #p "reading rightmost at #{f.pos}" header[:rightmost_pointer] = f.read(4).unpack('N')[0] - 1 end header[:type_string] = @@types[header[:type]] return header end # jimmy data out of the cell pointer array def parse_cells(count) cells = [] 1.upto(count) do |x| cells << @file.read(2).unpack('n')[0] end return cells end end
RSpec.describe ContactsController, type: :controller do describe 'GET #index' do it_behaves_like 'Unauthorized' context 'When user logged in' do sign_in_user it 'renders main contacts page' do get :index expect(response).to render_template :index end end def do_request(options = {}) get :index end end end
require File.join(File.expand_path(File.dirname(__FILE__)), '../integration_test_helper') class EditCollectionsTest < ActionDispatch::IntegrationTest setup do @collection = Collection::SKOS::Unordered.new.publish.tap { |c| c.save } end test 'create a new collection version' do login('administrator') visit collection_path(@collection, lang: 'de', format: 'html') assert page.has_button?('Neue Version erstellen'), "Button 'Neue Version erstellen' is missing on concepts#show" click_link_or_button('Neue Version erstellen') assert_equal edit_collection_url(@collection, published: 0, lang: 'de', format: 'html'), current_url visit collection_path(@collection, lang: 'de', format: 'html') assert page.has_no_button?('Neue Version erstellen'), "Button 'Neue Version erstellen' although there already is a new version" assert page.has_link?('Vorschau der Version in Bearbeitung'), "Link 'Vorschau der Version in Bearbeitung' is missing" click_link('Vorschau der Version in Bearbeitung') assert_equal collection_url(@collection, published: 0, lang: 'de', format: 'html'), current_url end end
# == Schema Information # # Table name: documents # # id :integer not null, primary key # title :text not null # filename :text not null # date :date not null # type :string(255) not null # is_public :boolean default(FALSE), not null # event_id :integer # language_id :integer # legacy_id :integer # created_by_id :integer # updated_by_id :integer # created_at :datetime not null # updated_at :datetime not null # number :string(255) # require 'spec_helper' describe Document do describe :create do context "when date is blank" do let(:document){ build( :document, :date => nil ) } specify { expect(document).to be_invalid } specify { expect(document).to have(1).error_on(:date) } end context "setting title from filename" do let(:document){ create(:document) } specify{ expect(document.title).to eq('Annual report upload exporter') } end end end
class Company < ActiveRecord::Base attr_accessible :company_url, :image_url, :name, :featured validates :company_url, presence: true validates :image_url, presence: true validates :name, presence: true has_many :sponsorships has_many :events, through: :sponsorships scope :featured, where(featured: true).limit(4) end
class CreateArenas < ActiveRecord::Migration[6.0] def change create_table :arenas do |t| t.string :arena_name t.text :arena_description t.timestamps end end end
class ClassChangesController < ApplicationController before_action :user_signed_in before_action :user_has_profile before_action :find_clazz before_action :owns_clazz before_action :not_in_the_past before_action :not_canceled, only: :cancel before_action :canceled, only: :uncancel before_action :not_substituted, only: :substitute before_action :substituted, only: :unsubstitute def cancel if @clazz.update_attributes canceled: true flash[:success] = "Class canceled" else flash[:danger] = "Unable to cancel class" end redirect_to class_path(@clazz) end def uncancel if @clazz.update_attributes canceled: false flash[:success] = "Class un-canceled" else flash[:danger] = "Unable to un-cancel class" end redirect_to class_path(@clazz) end def substitute if @clazz.update_attributes substituted: true flash[:success] = "Class substituted" else flash[:danger] = "Unable to substitute class" end redirect_to class_path(@clazz) end def unsubstitute if @clazz.update_attributes substituted: false flash[:success] = "Class un-substituted" else flash[:danger] = "Unable to un-substitute class" end redirect_to class_path(@clazz) end def delete if @clazz.destroy flash[:success] = "Class deleted" else flash[:danger] = "Unable to delete class" end redirect_to profile_path(@clazz.instructor_profile.profile_path) end def delete_and_future_weeks if @clazz.recurring_class.delete_from! @clazz flash[:success] = "Recurring class deleted" else flash[:danger] = "Unable to delete recurring class" end redirect_to profile_path(@clazz.instructor_profile.profile_path) end private def find_clazz @clazz = Clazz.confirmed.find_by id: params[:class_id] if @clazz.nil? flash[:danger] = "Could not find class" redirect_to profile_path(current_user.instructor_profile.profile_path) end end def owns_clazz unless current_user.id == @clazz.instructor_profile.user_id flash[:danger] = "Unauthorized access" redirect_to root_path end end def not_canceled if @clazz.canceled? flash[:danger] = "Class already canceled" redirect_to root_path end end def canceled unless @clazz.canceled? flash[:danger] = "Class not canceled" redirect_to root_path end end def not_substituted if @clazz.substituted? flash[:danger] = "Class already substituted" redirect_to root_path end end def substituted unless @clazz.substituted? flash[:danger] = "Class not substituted" redirect_to root_path end end def not_in_the_past if @clazz.in_the_past? flash[:danger] = "Class in the past" redirect_to root_path end end end
# encoding: utf-8 class Omniauth def initialize(omniauth) @omniauth = omniauth end def provider @omniauth[:provider].to_s.downcase end def uid @omniauth[:uid] end def email @omniauth[:info][:email].to_s.downcase end def avatar @omniauth[:info][:image] end def name @omniauth[:info][:name] end def oauth_token @omniauth[:credentials][:token] end def oauth_expires_at Time.at(@omniauth[:credentials][:expires_at]) end end
class AbstractTaskWrapper def call catch(:done) do loop do ActiveSupport::Notifications.instrument('pipeline.task_wrapper.loop', name: name) do do_work rescue ApplicationError => e Rails.logger.error "#{e.message}\n#{e.backtrace}" next end end end end private attr_accessor :task, :name end
class Label < ApplicationRecord has_many :task_labels, dependent: :destroy has_many :tasks, through: :task_labels, source: :task validates :name, presence: true, length: { maximum: 20 }, uniqueness: true end
class TripSeparator include GeocodeUtil STOP_TIME_THRESHOLD_S = 15 * 60 attr_accessor :visited_regions, :region, :locs def initialize(user) @user = user @visited_regions = [] end def calc_and_save_trips until (locs = unprocessed_locations).empty? Rails.logger.debug "Separating trips based on locations #{locs.inspect}" locs.each { |l| add_location l } @user.save end end def unprocessed_locations if @user.current_region @user.locations.where('recorded_time > ?', @user.current_region.last_time) .order(:recorded_time) else @user.locations.order(:recorded_time) end end def add_location(loc) if @user.current_region in_region = @user.current_region.add_loc_if_within_region loc if in_region create_new_trip if is_stop?(@user.current_region) && @user.last_stop_region != @user.current_region else add_location_in_new_region loc end else add_location_in_new_region loc @user.last_stop_region = @user.current_region end end def is_stop?(region) region.anchor.last_time - region.anchor.first_time > STOP_TIME_THRESHOLD_S end def add_location_in_new_region(loc) @user.current_region.save if @user.current_region @user.current_region = TripSeparatorRegion.new_with_center loc @user.current_region.user = @user end def create_new_trip create_trip_from_origin_and_dest @user.last_stop_region.anchor, @user.current_region.anchor @user.last_stop_region = @user.current_region end def create_trip_from_origin_and_dest(origin, dest) origin.calc_latitude_longitude dest.calc_latitude_longitude Trip.create user: @user, from_phone: true, start_time: origin.last_time, end_time: dest.first_time, start_place: @user.place_for_location(origin), end_place: @user.place_for_location(dest), distance: TripSeparator.driving_distance(origin, dest) end def self.driving_distance(from, to) MapQuestApi.distance("#{from.latitude},#{from.longitude}", "#{to.latitude},#{to.longitude}") end end
require 'rails_helper' describe User do it { expect(subject).to have_many(:users_groups) } it { expect(subject).to have_many(:groups).through(:users_groups) } it { expect(subject).to have_many(:expenses) } it { expect(subject).to have_many(:users_expenses) } it { expect(subject).to have_many(:owned_expenses).through(:users_expenses) } let!(:user) { create(:user) } let!(:expense) { create(:expense, status: 'unresolved', cost: 100, owners: [user1, user2], user: user, group: group) } let!(:user1) { create(:user) } let!(:user2) { create(:user) } let!(:group) { create(:group, users: [user, user1, user2]) } describe "#create_personal_group" do let(:test_user) { build(:user) } let(:test_group) { test_user.groups.last } it "creates default group for personal expenses" do expect{ test_user.save }.to change(test_user.groups, :count).by 1 expect(test_group.name).to eq "My Personal Expenses" end end describe "#name" do let(:user) { create(:user, first_name: "first", last_name: "last") } it 'returns user full name' do expect(user.name).to eq "first last" end end describe "#current_debt_for(group, user)" do it 'returns current total debt of current_user' do expect(user1.current_debt_for(group, user)).to eq 50 expect(user2.current_debt_for(group, user)).to eq 50 end end describe "#current_loan_for(group, user)" do it 'returns current total debt of current_user' do expect(user.current_loan_for(group, user1)).to eq 50 expect(user.current_loan_for(group, user2)).to eq 50 end end describe "#confirm_debts_paid_with(group, user)" do it 'marks all user_expense_share_values as resolved' do expect{ user.confirm_debts_paid_with(group, user1) }.not_to change(user1.user_expense_share_values.first, :status) expect{ user.confirm_debts_paid_with(group, user2) }.not_to change(user2.user_expense_share_values.first, :status) end end end
# == Schema Information # # Table name: lists # # id :integer not null, primary key # title :string(255) # created_at :datetime not null # updated_at :datetime not null # description :string(255) # user_id :integer default(0), not null # require 'spec_helper' describe List do before { @list = List.new(title: "example", description: "example descr") } subject { @list } it { should respond_to(:title) } it { should respond_to(:description) } it { should be_valid } describe "when title is not present" do before { @list.title = "" } it { should_not be_valid } end describe "when description is not present" do before { @list.description = "" } it { should be_valid } end end
class NoteItem include Listable attr_reader :description @@note_items = [] def initialize(description) @description = description @@note_items << self end def self.note_items unless @@note_items == 0 @@note_items else puts "There are no notes in this list" end end def details "Note - " + format_description(@description) end end
class Question < ActiveRecord::Base ANSWER_KEYS = { 0 => 'no', 1 => 'yes', 2 => 'partially'} belongs_to :control def answer ANSWER_KEYS[self.answer_id] end end
class Api::FollowingsController < ApplicationController def create new_follow = Following.new new_follow.followee_id = params[:user_id] new_follow.follower_id = current_user.id if new_follow.save @user = current_user render 'api/users/show' else render json: new_follow.errors.full_messages, status: 422 end end def destroy unfollowing = Following.find_by(followee_id: params[:id], follower_id: current_user.id) unless unfollowing return render status: 404 end if unfollowing.destroy @user = current_user render 'api/users/show' else render status: 422 end end end
class Product < ActiveRecord::Base belongs_to :merchant has_many :orders has_many :sales, through: :orders, source: :merchant end
require 'rails_helper' RSpec.describe User, type: :model do it { should have_many :questions } it { should have_many :badges } it { should have_many :likes } it { should have_many(:authorizations).dependent(:destroy) } it { should have_many(:subscriptions).dependent(:destroy) } it { should validate_presence_of :email } it { should validate_presence_of :password } describe '#author?' do let(:user) { create(:user) } let(:any_user) { create(:user) } it 'current user is author' do question = create(:question, user: user) expect(user).to be_author(question) end it 'current user not an author' do question = create(:question, user: any_user) expect(user).to_not be_author(question) end end describe '#award_badge!' do let(:user) { create(:user) } let(:question) { create(:question, user: user) } let(:badge) { create(:badge, question: question) } it 'user awarding the badge' do user.award_badge!(badge) expect(badge).to eq user.badges.last end end describe '#liked?' do let(:user) { create(:user) } let(:liker) { create(:user) } let(:question) { create(:question, user: user) } before { question.vote_up(liker) } it 'user already liked the resource' do expect(liker).to be_liked(question) end it 'user has not liked the resource' do expect(user).to_not be_liked(question) end end describe '.find_for_oauth' do let!(:user) { create(:user) } let(:auth) { OmniAuth::AuthHash.new(provider: 'facebook', uid: '123456') } let(:service) { double('Services::FindForOauth') } it 'calls Services::FindForOauth' do expect(Services::FindForOauth).to receive(:new).with(auth).and_return(service) expect(service).to receive(:call) User.find_for_oauth(auth) end end describe '#create_authorization' do let!(:user) { create(:user) } let(:auth) { OmniAuth::AuthHash.new(provider: 'facebook', uid: '123456') } it 'add authorization to user' do expect(user.create_authorization(auth)).to eq user.authorizations.last end end describe '#email_temporary?' do let(:user) { create(:user) } let(:user_with_temp_email) { create(:user, email: User::TEMPORARY_EMAIL) } it 'user have a real email' do expect(user.email_temporary?).to be_falsey end it 'user email is temporary' do expect(user_with_temp_email.email_temporary?).to be_truthy end end end
#This is assignment 23 # load 'a23_InvoiceItemClass.rb' load 'a23_Invoiceclass.rb' require 'active_support' require 'active_support/all' b = Invoice.new loop do puts ' ' puts "Enter a product name:" product_name = gets.chomp break if product_name == '\q'.downcase puts ' ' puts "Enter a sales price:" sale_price = gets.chomp puts ' ' puts "Enter a quantity:" quantity = gets.chomp puts ' ' puts "Enter a tax percent:" tax_percentage = gets.chomp # Enter items name, sale price, quantity and tax percentage a = Invoiceitem.new() a.product_name = product_name a.sale_price = sale_price a.quantity = quantity a.tax_percentage = tax_percentage b.items.push a end # Select only the items with quantity > 0 b.items.select! {|x| (x.quantity > "0")} puts "" b.items.each do |item| puts "Item Name / Sales Price / Quantity / Tax Percentage " print item.product_name + " / " + item.sale_price + " / " + item.quantity + " / " + item.tax_percentage puts " " end puts "There have been #{b.total_items} items created for this invoice" # Calculations for totals total_item_price = b.items.sum {|x| (x.sale_price.to_f * x.quantity.to_i).to_f } total_item_tax = b.items.sum {|x| (x.sale_price.to_f * x.quantity.to_f) * (x.tax_percentage.to_f/100)} total_price = total_item_price.to_f + total_item_tax.to_f # Display the total cost of items, total tax and the final price puts "The total price of just the items in the invoice is - $ #{total_item_price.to_f}" puts "The total tax is $ #{total_item_tax.to_f}" puts "The total price plus tax is $ #{total_price.to_f}"
require 'rails_helper' describe User do it "can be a shopper" do user = create :user, :shopper expect( user.shopper? ).to eq true end it "can be a seller" do user = create :user, :seller expect( user.seller? ).to eq true end it "is a shopper by default" do user = create :user, role=nil expect( user.shopper? ).to eq true end end
class ProjectUpdatesController < ApplicationController breadcrumb "Project Updates", :project_updates_path, match: :exact before_action :get_project_update, except: [:index, :new, :create] def index @project_updates = ProjectUpdate.paginate(page: params[:page], per_page: 15) end def show breadcrumb @project_update.source_headline, project_update_path(@project_update) end def new head(404) and return unless can?(current_user, :create) breadcrumb "New Project Update", new_project_update_path @project_update = ProjectUpdate.new end def edit head(404) and return unless can?(current_user, :edit) breadcrumb @project_update.source_headline, project_update_path(@project_update), match: :exact breadcrumb 'Edit', edit_project_update_path(@project_update) end def create head(404) and return unless can?(current_user, :create) @project_update = ProjectUpdate.new(project_update_params) respond_to do |format| if @project_update.save format.html {redirect_to @project_update, flash: {success: 'Project Update Created Successfully'}} else format.json {render json: @project_update.errors, status: :unprocessable_entity} end end end def update head(404) and return unless can?(current_user, :edit) respond_to do |format| if @project_update.update(project_update_params) format.html {redirect_to @project_update, flash: {success: 'Project Update Updated Successfully'}} else format.json {render json: @project_update.errors, status: :unprocessable_entity} end end end def destroy head(404) and return unless can?(current_user, :destroy) @project_update.destroy respond_to do |format| format.html {redirect_to project_updates_url, notice: 'Project Update was successfully destroyed.'} format.json {head :ok} end end private def project_update params.require(:project_update).permit(:source_headline, :date, :link, :sector, :project_update_type, :status, :project_update_type) end def get_project_update @project_update = ProjectUpdate.find(params[:id]) end end
# frozen_string_literal: true class AddDefaultImageToReviews < ActiveRecord::Migration[5.1] def change change_column :reviews, :image, :string, default: 'https://www.eaglenewsonline.com/wp-content/uploads/2018/12/paws-tongue.jpg' end end
require "test_helper" require "minitest/spec" module ActiveRecord::Snapshot class ImportTest < ActiveSupport::TestCase extend MiniTest::Spec::DSL let(:rake_task) { stub("Rake Task", invoke: true) } before do Object.any_instance.stubs(:puts) end describe "::call" do describe "given no version" do let(:version) { nil } before do Stepper.stubs(:call) end it "selects a snapshot" do SelectSnapshot.expects(:call).with(version) Import.call(version: version) end end describe "given a numbered version" do let(:version) { "5" } before do Stepper.stubs(:call) end it "selects a snapshot" do SelectSnapshot.expects(:call).with(version) Import.call(version: version) end end describe "given a string version" do let(:version) { "foo" } before do Stepper.stubs(:call) end it "takes the version verbatim" do SelectSnapshot.expects(:call).never Import.call(version: version) end end describe "when the version has been downloaded" do let(:version) { 15 } before do Version.expects(current: version, write: true).once SelectSnapshot.stubs(:call) Rake::Task.stubs(:[]).returns(rake_task) run_steps end it "skips the download and extraction" do Snapshot.any_instance.expects(:download).never OpenSSL.expects(:decrypt).never Bzip2.expects(:decompress).never Import.call(version: version) end end describe "given no tables" do it "resets the database" do run_steps Rake::Task.expects(:[]).with("db:drop").returns(rake_task).once Rake::Task.expects(:[]).with("db:create").returns(rake_task).once Import.call(version: "foo") end end describe "given tables" do it "filters the database" do run_steps FilterTables.expects(call: true).once Import.call(version: "foo", tables: %w[foo bar]) end end def run_steps Snapshot.any_instance.expects(download: true).once OpenSSL.expects(decrypt: true).once FileUtils.expects(rm: true).once Bzip2.expects(decompress: true).once MySQL.expects(import: true).once Rake::Task.expects(:[]).with("db:schema:dump").returns(rake_task).once Rake::Task.expects(:[]).with("db:environment:set").returns(rake_task).once end end end end
# frozen_string_literal: true require "cbor" require "uri" require "openssl" require "webauthn/authenticator_data" require "webauthn/authenticator_response" require "webauthn/attestation_statement" require "webauthn/client_data" require "webauthn/encoder" module WebAuthn class AttestationStatementVerificationError < VerificationError; end class AttestedCredentialVerificationError < VerificationError; end class AuthenticatorAttestationResponse < AuthenticatorResponse def self.from_client(response) encoder = WebAuthn.configuration.encoder new( attestation_object: encoder.decode(response["attestationObject"]), client_data_json: encoder.decode(response["clientDataJSON"]) ) end attr_reader :attestation_type, :attestation_trust_path def initialize(attestation_object:, **options) super(options) @attestation_object = attestation_object end def verify(expected_challenge, expected_origin = nil, user_verification: nil, rp_id: nil) super verify_item(:attested_credential) verify_item(:attestation_statement) if WebAuthn.configuration.verify_attestation_statement true end def credential authenticator_data.credential end def attestation_statement @attestation_statement ||= WebAuthn::AttestationStatement.from(attestation["fmt"], attestation["attStmt"]) end def authenticator_data @authenticator_data ||= WebAuthn::AuthenticatorData.new(attestation["authData"]) end def attestation_format attestation["fmt"] end def attestation @attestation ||= CBOR.decode(attestation_object) end def aaguid raw_aaguid = authenticator_data.attested_credential_data.raw_aaguid unless raw_aaguid == WebAuthn::AuthenticatorData::AttestedCredentialData::ZEROED_AAGUID authenticator_data.attested_credential_data.aaguid end end def attestation_certificate_key raw_subject_key_identifier(attestation_statement.attestation_certificate)&.unpack("H*")&.[](0) end private attr_reader :attestation_object def type WebAuthn::TYPES[:create] end def valid_attested_credential? authenticator_data.attested_credential_data_included? && authenticator_data.attested_credential_data.valid? end def valid_attestation_statement? @attestation_type, @attestation_trust_path = attestation_statement.valid?(authenticator_data, client_data.hash) end def raw_subject_key_identifier(certificate) extension = certificate.extensions.detect { |ext| ext.oid == "subjectKeyIdentifier" } return unless extension ext_asn1 = OpenSSL::ASN1.decode(extension.to_der) ext_value = ext_asn1.value.last OpenSSL::ASN1.decode(ext_value.value).value end end end
module Httpotemkin class Client attr_reader :out, :err, :exit_code def initialize(containers) @containers = containers end def execute(cmd, working_directory: nil) @out, @err, @exit_code = @containers.exec_client(cmd, working_directory: working_directory) end def inject_tarball(filename) Cheetah.run(["cat", filename], ["docker", "cp", "-", "client:/"]) end def install_gem_from_spec(specfile) Dir.chdir(File.dirname(specfile)) do out = Cheetah.run(["gem", "build", File.basename(specfile)], stdout: :capture) gemfile = out[/File: (.*)\n/, 1] @containers.run_docker(["cp", gemfile, "client:/tmp"]) @containers.run_docker(["exec", "client", "gem", "install", "--local", File.join("/tmp", gemfile)]) end end end end
#------------------------------------------------------------------------------ # Copyright (c) 2013 The University of Manchester, UK. # # BSD Licenced. See LICENCE.rdoc for details. # # Taverna Player was developed in the BioVeL project, funded by the European # Commission 7th Framework Programme (FP7), through grant agreement # number 283359. # # Author: Robert Haines #------------------------------------------------------------------------------ require 'test_helper' module TavernaPlayer class RunIoTest < ActiveSupport::TestCase setup do @port1 = taverna_player_run_ports(:one) @port2 = taverna_player_run_ports(:two) @port3 = taverna_player_run_ports(:three) @port5 = taverna_player_run_ports(:five) @port6 = taverna_player_run_ports(:six) end test "run port inheritance types" do in_port = RunPort::Input.new assert_equal "TavernaPlayer::RunPort::Input", in_port.port_type, "Input does not inherit as TavernaPlayer::RunPort::Input" out_port = RunPort::Output.new assert_equal "TavernaPlayer::RunPort::Output", out_port.port_type, "Output does not inherit as TavernaPlayer::RunPort::Output" end test "should not save run ports without name" do in_port = RunPort::Input.new assert !in_port.save, "Saved the run input port without a name" out_port = RunPort::Output.new assert !out_port.save, "Saved the run output port without a name" end test "should not save small input values in a file" do test_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" port = RunPort::Input.create(:name => "test_port") port.value = test_value assert port.save, "Port did not save" assert_equal port.value_preview, port.value, "Value and preview differ" assert_nil port.file.path, "File present" assert_equal test_value, port.value, "Saved value does not match test" end test "should not save small output values in a file" do test_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" port = RunPort::Output.create(:name => "test_port") port.value = test_value assert port.save, "Port did not save" assert_equal port.value_preview, port.value, "Value and preview differ" assert_nil port.file.path, "File present" assert_equal test_value, port.value, "Saved value does not match test" end test "should save large input values in a file" do test_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" port = RunPort::Input.create(:name => "test_port") port.value = test_value assert port.save, "Port did not save" assert_not_nil port.file.path, "File not present" assert port.read_attribute(:value).size == 255, "Port value size != 255" assert_equal test_value, port.value, "Saved value does not match test" assert_not_equal port.value_preview, port.value, "Value and preview same" port.value = "small" assert port.save, "Port did not save" assert_nil port.file.path, "File present" end test "should save large output values in a file" do test_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" port = RunPort::Output.create(:name => "test_port") port.value = test_value assert port.save, "Port did not save" assert_not_nil port.file.path, "File not present" assert port.read_attribute(:value).size == 255, "Port value size != 255" assert_equal test_value, port.value, "Saved value does not match test" assert_not_equal port.value_preview, port.value, "Value and preview same" port.value = "small" assert port.save, "Port did not save" assert_nil port.file.path, "File present" end test "should handle non ascii/utf-8 characters in large input values" do test_value = "\xC2"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "\xC2" port = RunPort::Input.create(:name => "test_port") port.value = test_value assert port.save, "Port did not save" assert_not_nil port.file.path, "File not present" assert_equal test_value, port.value, "Saved value does not match test" assert_not_equal port.value_preview, port.value, "Value and preview same" end test "should handle non ascii/utf-8 characters in large output values" do test_value = "\xC2"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "\xC2" port = RunPort::Output.create(:name => "test_port") port.value = test_value assert port.save, "Port did not save" assert_not_nil port.file.path, "File not present" assert_equal test_value, port.value, "Saved value does not match test" assert_not_equal port.value_preview, port.value, "Value and preview same" end test "should display port names correctly" do assert_equal @port1.name, @port1.display_name, "Name with no spaces should not be changed" assert_equal @port2.name, @port2.display_name, "Name with no spaces should not be changed" assert_not_equal @port3.name, @port3.display_name, "Name with spaces should not be unchanged" refute @port3.display_name.include?('_'), "Display name should not have any underscores" refute @port5.display_name.include?('_'), "Display name should not have any underscores" assert_equal @port3.name.gsub('_', ' '), @port3.display_name, "Only underscores should be changed" assert_equal @port5.name.gsub('_', ' '), @port5.display_name, "Only underscores should be changed" end test "should not allow both file and value on create input" do file = fixture_file_upload "/files/crassostrea_gigas.csv" port = RunPort::Input.create(:name => "test_port", :value => "test", :file => file) assert port[:value].blank?, "Value should be blank" refute port.file.blank?, "File should be present" end test "should not allow both file and value on create output" do file = fixture_file_upload "/files/crassostrea_gigas.csv" port = RunPort::Output.create(:name => "test_port", :value => "test", :file => file) assert port[:value].blank?, "Value should be blank" refute port.file.blank?, "File should be present" end test "should not allow both file and value on update input" do file = fixture_file_upload "/files/crassostrea_gigas.csv" port = RunPort::Input.create(:name => "test_port") port.file = file port.value = "test" port.save assert port[:value].blank?, "Value should be blank" refute port.file.blank?, "File should be present" end test "should not allow both file and value on update output" do file = fixture_file_upload "/files/crassostrea_gigas.csv" port = RunPort::Output.create(:name => "test_port") port.file = file port.value = "test" port.save assert port[:value].blank?, "Value should be blank" refute port.file.blank?, "File should be present" end test "should change large input value correctly" do orig_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" new_value = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" port = RunPort::Input.create(:name => "test_port", :value => orig_value) refute port.value.blank?, "Value is empty" refute port.file.blank?, "File not present" port.value = new_value port.save refute port.value.blank?, "Value is empty" refute port.file.blank?, "File not present" assert_not_equal orig_value, port.value, "Port still has old value" end test "should change large output value correctly" do orig_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" new_value = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" port = RunPort::Output.create(:name => "test_port", :value => orig_value) refute port.value.blank?, "Value is empty" refute port.file.blank?, "File not present" port.value = new_value port.save refute port.value.blank?, "Value is empty" refute port.file.blank?, "File not present" assert_not_equal orig_value, port.value, "Port still has old value" end test "should blank out large value if file changed" do orig_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" port = RunPort::Input.create(:name => "test_port", :value => orig_value) refute port.value.blank?, "Value is empty" refute port.file.blank?, "File not present" port.file = fixture_file_upload "/files/crassostrea_gigas.csv" port.save assert_nil port[:value], "Port value not nil" refute port.file.blank?, "File not present" end test "should blank out large value if file removed" do orig_value = "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789"\ "01234567890123456789012345678901234567890123456789" port = RunPort::Input.create(:name => "test_port", :value => orig_value) refute port.value.blank?, "Value is empty" refute port.file.blank?, "File not present" port.file = nil port.save assert_nil port.value, "Port value not nil" assert port.file.blank?, "File not present" end test "get value types" do assert_equal "text/plain", @port1.value_type, "Type not text/plain" assert_equal "text/plain", @port2.value_type(1), "Type not text/plain" assert_equal "application/x-error", @port2.value_type(2), "Type not application/x-error" assert_equal "text/plain", @port3.value_type, "Type not text/plain" assert_equal "text/plain", @port6.value_type(0, 0), "Type not text/plain" assert_equal "text/plain", @port6.value_type([2, 1]), "Type not text/plain" # Test when there is no metadata port = RunPort::Input.create(:name => "test_port", :value => "Test") assert_equal "text/plain", port.value_type, "Unspecified type should return \"text/plain\"" assert port.value_is_text?, "Unspecified type should be text" assert_nil port.value_size, "Unspecified size should return nil" end test "detecting text values" do assert @port1.value_is_text?, "Value not detected as text" assert @port2.value_is_text?(0), "Value not detected as text" assert @port3.value_is_text?, "Value not detected as text" assert @port6.value_is_text?(0, 0), "Value not detected as text" assert @port6.value_is_text?([1, 1]), "Value not detected as text" refute @port2.value_is_text?(2), "Value detected as text" end test "get value sizes" do assert_equal 13, @port1.value_size, "Value size not 13" assert_equal 974, @port2.value_size(2), "Value size not 974" assert_equal 3, @port3.value_size, "Value size not 3" assert_equal 15, @port6.value_size([0, 0]), "Value size not 15" assert_equal 24, @port6.value_size([2, 1]), "Value size not 24" end test "value methods should not alter input parameters" do index = [1, 1] index_saved = index.dup @port6.value_type(index) assert_equal index_saved, index, "Parameter index was altered" @port6.value_is_text?(index) assert_equal index_saved, index, "Parameter index was altered" @port6.value_size(index) assert_equal index_saved, index, "Parameter index was altered" end end end
Rails.application.routes.draw do resources :ai_books # Home root to: 'landing#index' # Oauth2 use_doorkeeper do skip_controllers :authorizations, :applications, :authorized_applications end # RESTful API scope '/api' do scope '/v1' do post '/register' => 'auth#register' post '/login' => 'doorkeeper/tokens#create' scope '/author' do get '/' => 'authors#index' post '/' => 'authors#create' scope '/:id' do get '/' => 'authors#show' put '/' => 'authors#update' delete '/' => 'authors#destroy' end end scope '/book' do get '/' => 'books#index' post '/' => 'books#create' scope '/:id' do get '/' => 'books#show' put '/' => 'books#update' delete '/' => 'books#destroy' get '/authors' => 'books#authors' end end end end end
require_relative '../../../../test_helper' require 'ehonda/middleware/server/active_record/transaction' middleware_class = Ehonda::Middleware::Server::ActiveRecord::Transaction retrier_class = Ehonda::Middleware::Server::ActiveRecord::Retrier describe middleware_class do let(:error) { nil } let(:worker) { Object.new } before do ::ActiveRecord::Base.expects(:transaction).at_least_once.with do |*args| @transaction_args = args true end.yields begin middleware_class.new(options).call(worker, nil, nil, nil) do fail error if error @called = true end rescue => e @error_raised = e end end describe 'active record transaction options' do describe "options are passed that are accepted by ActiveRecord's transaction method" do let(:options) { { requires_new: true, joinable: true, isolation: :repeatable_read } } it 'passes the accepted options' do @transaction_args.count.must_equal 1 @transaction_args.first.must_equal options end it 'invokes the block supplied to the middleware' do @called.must_equal true end end describe "options are passed that are not accepted by ActiveRecord's transaction method" do let(:options) { { foo: 1, bar: 2 } } it 'does not pass the unaccepted options' do @transaction_args.count.must_equal 1 @transaction_args.first.must_equal Hash.new end it 'invokes the block supplied to the middleware' do @called.must_equal true end end end describe 'retryable errors' do let(:worker) do Class.new do def log_retry(error) @log_retry_called = true end attr_reader :log_retry_called end.new end describe 'a retry callback method is named' do let(:options) { { on_retriable_error: :log_retry } } it 'invokes the block supplied to the middleware' do @called.must_equal true end describe 'the block supplied to the middleware raises an error' do describe 'the error is a record not unique error' do let(:error) { ::ActiveRecord::RecordNotUnique.new } it 'calls the callback' do worker.log_retry_called.must_equal true end end describe 'the error refers to a deadlock' do let(:error) do ActiveRecord::StatementInvalid.new 'PG::TRDeadlockDetected: '\ 'ERROR: deadlock detected '\ 'DETAIL: Process 1105 waits for ShareLock on transaction 1197700; blocked b.... '\ 'Process 1043 waits for ShareLock on transaction 1197560; blocked by process 1105. '\ 'HINT: See server log for query details.' end it 'calls the callback' do worker.log_retry_called.must_equal true end end describe 'the error refers to a serializable isolation level error' do let(:error) do ActiveRecord::StatementInvalid.new 'PG::TRSerializationFailure: '\ 'ERROR: could not serialize access due to read/write dependencies among transactions '\ 'DETAIL: Reason code: Canceled on identification as a pivot, during conflict in checking. '\ 'HINT: The transaction might succeed if retried.' end it 'calls the callback' do worker.log_retry_called.must_equal true end end describe 'the error refers to something else' do let(:error) { ActiveRecord::StatementInvalid.new 'TRFoobar' } it 'does not call the callback' do (!!worker.log_retry_called).must_equal false end end describe 'the error is not retriable' do let(:error) { StandardError.new } it 'does not call the callback' do (!!worker.log_retry_called).must_equal false end end end end end end
# frozen_string_literal: true class CreateTransactions < ActiveRecord::Migration[6.0] def change create_table :transactions do |t| t.references :store, null: false, foreign_key: true t.datetime :transacted_at, null: false t.references :transaction_type, null: false, foreign_key: true t.integer :value t.string :cpf t.string :card t.timestamps end end end
require 'test_helper' class PostsControllerTest < ActionController::TestCase def setup login_as(users(:admin)) end test 'index' do get :index assert_redirected_to posts(:base) end test 'new' do get :new assert_response :success end test 'create invalid' do Post.stub_any_instance :save, false do post :create, params: { post: valid_attributes } end assert_response :success end test 'create valid' do Post.stub_any_instance :save, true do post :create, params: { post: valid_attributes } end assert_redirected_to :posts end private def valid_attributes { at: Time.zone.now, body: 'Body', } end end
require_relative 'gratter_class.rb' require_relative 'prepare.rb' base_url = "http://www.tinymixtapes.com/music-reviews?page=0" base_xpath = { :links => "//section[@class='tile-panel tile-panel--archive view view-TMT7-Music-Reviews view-id-TMT7_Music_Reviews view-display-id-page_1 view--musicreview view-dom-id-1']//a[@class='tile__link']/@href" } instance = Gratter.new( {:url => base_url, :xpaths => base_xpath} ) data = instance.use data.prepare_gratter!("http://www.tinymixtapes.com", 2) xpaths = { artist: "//span[@class='entry__main-title']/span[@itemprop='name']/text()", title: "//span[@class='entry__subtitle']/cite/i/text()", year: "//p[@class='meta']/text()", record_label: "//p[@class='meta']/text()", tinymixtapes_rating: "//div[@class='review-heading__details-middle']//img/@title", tinymixtapes_cover: "//header[@class='review-heading']//img[@class='art__img']/@src" } scrapped = [] data.each do |h| to_be_added = { :tinymixtapes_url => h[:links], :tinymixtapes_review_date => Date.today.to_s } options = { :url => h[:links], :xpaths => xpaths, :to_be_added => to_be_added, :trans_pattern => { :artist => Proc.new { |node| node.strip }, :title => Proc.new { |node| node.strip }, :year => Proc.new { |node| node.gsub(/.+;|\]|\s/, "") }, :record_label => Proc.new { |node| node.gsub(/;.+|\[/, "") }, :tinymixtapes_rating => Proc.new { |node| node.gsub(/Rating:\s|\/5/, "") } } } instance = Gratter.new(options) album_data = instance.use puts album_data.inspect scrapped << album_data end #puts scrapped.inspect
class GrumblersController < ApplicationController def index @grumblers = GrumblerModel.all render json: @grumblers.to_json end def show @grumbler = GrumblerModel.find(params[:id]) render json: @grumbler.to_json end def new @grumbler = Grumbler.new end def create @grumbler = GrumblerModel.new(grumbler_params) if @grumbler.save render json: @grumbler.to_json end def update @grumbler = GrumblerModel.find(params[:id]) if @grumbler.update(grumbler_params) render json: @grumbler.to_json end end def destroy @grumbler = GrumblerModel.find(params[:id]) if @grumbler.destroy render json: @grumbler.to_json end end private def grumbler_params params.require(:grumbler).permit(:body, :author, :title, :avatar_url) end end
# frozen_string_literal: true module ActiveStorage class InvariableError < StandardError; end class UnpreviewableError < StandardError; end class UnrepresentableError < StandardError; end end
require 'rails_helper' describe 'Routing' do example 'Staff page top' do expect(get: 'http://baukis.example.com').to route_to( host: 'baukis.example.com', controller: 'staff/top', action: 'index' ) end example "Admin login form" do expect(get: 'http://baukis.example.com/admin/login').to route_to( host: 'baukis.example.com', controller: 'admin/sessions', action: 'new' ) end it 'should redirect to error/not_found if host name is invalid' do expect(get: 'http://foo.example.jp').to route_to( controller: 'errors', action: 'routing_error' ) end it 'should redirect to error/not_found if the path does not exists' do expect(get: 'http://baukis.example.com/jfklsj').to route_to( controller: 'errors', action: 'routing_error', anything: 'jfklsj' ) end example 'Customer page top' do expect(get: 'http://example.com/mypage').to route_to( host: 'example.com', controller: 'customer/top', action: 'index' ) end end
class LinksController < ApplicationController before_filter :require_user, except: [:index, :show] expose(:reference) { Reference.find params[:reference_id] } expose(:links) { reference.links } expose(:link) def index index!(link) end def new new!(link) end def show redirect_to reference end def edit edit!(link) end def create link.user = current_user create!(link, :link) { reference_path(reference) } end def update update!(link, :link) { reference_links_path(reference) } end def destroy destroy!(link, :link) { reference_links_path(reference) } end end
class JudgingController < ApplicationController before_filter :authenticate_user! def outstanding_reviews @scorecards = Judging.outstanding_reviews(current_user.username) end def scorecard @participant = Participant.find(params[:participant_id]) @submissions = @participant.current_submissions(@participant.challenge.challenge_id) scorecard_questions = Judging.participant_scorecard(params[:participant_id], current_user.username) @scorecard = JSON.parse(scorecard_questions.keys.first) gon.scorecard = scorecard_questions.values.first end def scorecard_save results = Judging.save_scorecard(params[:participant_id], params[:answers], { :scored => params[:set_as_scored].to_bool, :delete_scorecard => params[:delete_participant_submission].try(:to_bool), :judge_membername => current_user.username }) puts results.to_yaml if results.success flash[:notice] = results.message else flash[:error] = results.message end redirect_to outstanding_reviews_path end def judging_queue @no_challenges_message = 'There are currently no challenges that are in need of judges. Please check back later.' @member = Member.find(current_user.username, { fields: 'id,total_wins,can_judge' }) @member.can_judge = '' if !@member.can_judge @challenges = Judging.judging_queue if @member.total_wins < 10 && !@member.can_judge.include?('Override Minimum Wins') @challenges = [] @no_challenges_message = 'Sorry... you must have won at least ten CloudSpokes challenges before you are eligible to judge.' elsif @member.can_judge.include?('Banned') @challenges = [] @no_challenges_message = 'Sorry... you are not able to judge challenges are this time.' end end def add_judge render :text => Judging.add_judge(params[:challenge_id], current_user.username) end end
module Sluggable extend ActiveSupport::Concern included do before_save :call_slug end def to_param self.slug end def generate_slug(column) the_slug = to_slug(column) obj = self.class.find_by(slug: the_slug) count = 2 while obj && obj != self the_slug = append_suffix(the_slug, count) obj = self.class.find_by(slug: the_slug) count += 1 end self.slug = the_slug end def to_slug(column) column.strip.gsub(/\W/, '-').gsub(/-+/, '-').gsub(/^-|-$/, '').downcase end def append_suffix(the_slug, count) if the_slug.split('-').last.to_i != 0 str.split('-').slice(0...-1).join('-') + '-' + count.to_s else the_slug + '-' + count.to_s end end end
# Write a method reverse_array to reverse the order of elements in an array. You will take in an array as a parameter, and will return the reversed array. You may not use the .reverse method def reverse_array(n) newArr=[] n.each do |i| newArr.push(n[-i]) end return newArr end p reverse_array([1,2,3,4,5,6,7,8,9])
feature 'testing a user can sign up' do scenario 'a user signs up with a username, email and password' do visit '/users/new' expect(page).to have_css("input[type=text][name='username']") expect(page).to have_css("input[type=email][name='email']") expect(page).to have_css("input[type=password][name='password']") end end
class Fluentd module Setting class InMonitorAgent include Fluentd::Setting::Plugin register_plugin("input", "monitor_agent") def self.initial_params { bind: "0.0.0.0", port: 24220, emit_interval: 60, include_config: true, include_retry: true } end def common_options [ :label, :bind, :port, :tag ] end end end end
# frozen_string_literal: true # Used for creating exceptions with the Ldap connections and configuration module LdapQuery class Error < StandardError; end class AttributeError < Error; end class ConnectionError < Error; end class CredentialsError < Error; end class ConfigError < Error; end end
# frozen_string_literal: true module Sentry class DummyTransport < Transport attr_accessor :events, :envelopes def initialize(*) super @events = [] @envelopes = [] end def send_event(event) @events << event end def send_envelope(envelope) @envelopes << envelope end end end
class ItemOutputsController < ApplicationController before_action :set_item_output, only: [:show, :edit, :update, :destroy] # GET /item_outputs # GET /item_outputs.json def index @item_outputs = ItemOutput.order(departure_date: :desc).page(params[:page]) end # GET /item_outputs/1 # GET /item_outputs/1.json def show end # GET /item_outputs/new def new @item_output = ItemOutput.new respond_to do |f| f.html f.js end end # GET /item_outputs/1/edit def edit end # POST /item_outputs # POST /item_outputs.json def create @item_output = ItemOutput.new(item_output_params) respond_to do |format| if @item_output.save format.html { redirect_to @item_output, notice: 'Item output was successfully created.' } format.json { render :show, status: :created, location: @item_output } format.js else format.html { render :new } format.json { render json: @item_output.errors, status: :unprocessable_entity } format.js end end end # PATCH/PUT /item_outputs/1 # PATCH/PUT /item_outputs/1.json def update respond_to do |format| if @item_output.update(item_output_params) format.html { redirect_to @item_output, notice: 'Item output was successfully updated.' } format.json { render :show, status: :ok, location: @item_output } else format.html { render :edit } format.json { render json: @item_output.errors, status: :unprocessable_entity } end end end # DELETE /item_outputs/1 # DELETE /item_outputs/1.json def destroy @item_output.destroy respond_to do |format| format.html { redirect_to item_outputs_url, notice: 'Item output was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_item_output @item_output = ItemOutput.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def item_output_params params.require(:item_output).permit(:equipment_id, :departure_date, :quantity, :point_id, :fixed_asset) end end
# frozen_string_literal: true module IndieLand module Response # List of future events RangeEvents = Struct.new(:range_events) end end