text
stringlengths
10
2.61M
require 'tty-prompt' require 'artii' class Game < ActiveRecord::Base attr_reader :our_team_id has_many :finishing_positions @our_team_id = nil # CONTROL FLOW FUNCTIONS def wait_for_any_key require 'io/console' puts ' ' puts 'Press any key to continue' puts '' STDIN.getch end def show_current_standings puts '' puts "after this event let's have a look where we stand.." wait_for_any_key end def points_per_position(position) case position when 1 25 when 2 18 when 3 12 when 4 10 when 5 8 when 6 4 when 7 2 when 8..10 1 else 0 end end def credits_per_position(position) case position when 1 10 when 2 8 when 3 6 when 4 4 when 5 2 when 6 1 else 0 end end #PREPARE SEASON # Output Text def welcome_screen puts `clear` a = Artii::Base.new :font => 'slant' puts a.asciify('FORMULA 1') end def require_team_name puts 'Please enter your team name:' gets.strip end def require_team_nationality puts 'Please enter the country your team has originated from:' gets.strip end def prompt_user_select_first_driver puts 'Now its time to hire some drivers for your season!' puts 'Every drivers desperate to be on your books, but watch out,' puts 'that lottery fund of £100m will only take you so far' puts 'and once a drivers signed that contract hes in for the season!' puts 'You have a starting budget of £100 but be careful not to spend it all on your drivers.' puts "You wont have anything left for spending throughout the season!" puts '' end # def prompt_user_select_second_driver # puts ' ' # puts 'Great choice!' # puts ' ' # puts "#{our_team.drivers[0].first_name} has been on fire pre-season." # puts "You have #{our_team.budget} left for your next driver:" # puts ' ' # end # Functions def setup_game_data seed_data(id) end def create_team team_name = require_team_name team_nationality = require_team_nationality our_team = Constructor.create( name: team_name, nationality: team_nationality, tech_factor: 4.0, budget: 100, game_id: self.id ) self.users_team = team_name @our_team_id = our_team.id end def game_constructors Constructor.all.select { |constructor| constructor.game_id == id } # returns an array of constructor instances end def our_team game_constructors.select { |constructor| constructor.id == @our_team_id }[0] # returns an instance end def drivers_in_game Driver.all.select { |driver| driver.game_id == id } # returns an array of driver instances end def selectable_drivers array = drivers_in_game.reject do |driver| driver.constructor_id == nil end array1 = array.reject do |driver| driver.price > our_team.budget || driver.first_name == our_team.drivers[0].first_name if our_team.drivers!=[] # driver.first_name == 'Lance' || driver.first_name == 'Sergio' || driver.price > our_team.budget || driver.first_name == our_team.drivers[0].first_name if our_team.drivers!=[] end return array1 end def list_selectable_drivers selectable_drivers.map { |d| "Price: #{d.price} | #{d.name}" } end def select_driver prompt = TTY::Prompt.new prompt_user_select_first_driver example = prompt.select("Please select the driver you would like to join your team", list_selectable_drivers, per_page: 16) selectable_drivers.each_with_index do |d, i| if example == list_selectable_drivers[i] our_team.pick_driver(d) balance = our_team.budget - d.price update_team_budget(balance) end end end # def select_drivers_for_team # prompt_user_select_first_driver # sleep(1) # list_selectable_drivers # select_driver # prompt_user_select_second_driver # list_selectable_drivers # select_driver def update_team_budget(balance) our_team.update(budget: balance) end # def select_drivers_for_team # prompt_user_select_first_driver # sleep(1) # list_selectable_drivers # select_driver # prompt_user_select_second_driver # list_selectable_drivers # select_driver # end def teams_not_full_staffed game_constructors.select { |team| team.drivers.size < 2 } # returns an array of size 2 end def fill_teams # teams not fully staffed teams_needing_drivers = teams_not_full_staffed # replacement drivers stroll = Driver.find_by(second_name: "Stroll", game_id: id) perez = Driver.find_by(second_name: "Perez", game_id: id) # fill it up if teams_needing_drivers.size == 2 stroll.update(constructor_id: teams_needing_drivers[0].id) perez.update(constructor_id: teams_needing_drivers[1].id) else stroll.update(constructor_id: teams_needing_drivers[0].id) perez.update(constructor_id: teams_needing_drivers[0].id) end end def present_lineup puts ' ' puts "And there it is, the lineup for '#{our_team.name}':" puts ' ' puts our_team.drivers[0].name.to_s puts our_team.drivers[1].name.to_s puts ' ' end def present_teams puts ' ' puts 'The teams are ready to roll for the new season' puts ' ' puts ' Team | Driver 1 | Driver 2 ' puts '------------------------------------------------' game_constructors.map do |team| print "#{team.name}" print " | #{team.drivers[0].name}" print " | #{team.drivers[1].name}" puts '' end end # RUN A RACE def create_race_results(race) race.run_race(drivers_in_game) end def show_race_ranking(race) race.show_ranking(drivers_in_game) end # RUN SEASON def show_season_intro_text puts '..' puts '..prepare season..' puts '..' end def races_in_game Race.all.select { |race| race.game_id == id } end def driver_finishingpositions_all_races(driver) FinishingPosition.all.select do |fp| fp.game_id == id && fp.driver_id == driver.id end # returns an array of instances [,,,] end def driver_positions_all_races(driver) driver_finishingpositions_all_races(driver).map{ |fp| fp.final_position } # returns an array of integers [,,,] end def driver_points_all_races(driver) # sums all points a driver has earned driver_positions_all_races(driver).map { |pos| points_per_position(pos) } # return total points > integer end def driver_total_points(driver) # sums all points a driver has earned driver_points_all_races(driver).reduce { |sum, point| sum + point } # return total points > integer end def drivers_total_points drivers_in_game.map do |driver| [driver_total_points(driver), driver] end end def driver_wins(driver) driver_positions_all_races(driver).select { |pos| pos == 1 }.size # returns an integer end def ranked_drivers_total_points drivers_total_points.sort { |a, b| a[0] <=> b[0] }.reverse # returns an sorted (desc) array of arrays [points, driver] end def show_standing_for_game puts ' Rank | Driver | Points' puts '-----------------------------------' ranked_drivers_total_points.each_with_index do |standing, index| puts "#{index + 1} | #{standing[1].name} | #{standing[0]} "#| #{standing[1].wins}" end puts ' ' end ## Team Rankings def team_scoreboard game_constructors.map do |team| [driver_total_points(team.drivers[0]) + driver_total_points(team.drivers[1]), team.name] end end def sorted_team_scoreboard team_scoreboard.sort { |a, b| b[0] <=> a[0] } # returns an array of arrays end def show_constructor_standings puts 'Points | Team ' puts '-----------------------' sorted_team_scoreboard.each do |standing| puts "#{standing[0]} | #{standing[1]}" end end def show_winning_constructor puts '' puts "This season's winning team was #{sorted_team_scoreboard[0][1]}" puts '' end def changes_introduction puts "Improving your team is vital throughout the season! Keep winning races and you'll have more to spend!" puts "Would you like to make changes to your car or to your driver?" end def mid_season_changes prompt = TTY::Prompt.new example3 = prompt.select("Would you like to make any changes to the team? You have a budget of £#{our_team.budget}", cycle:true) do |menu| menu.choice "No", 0 menu.choice "Car", 1 menu.choice "Drivers", 2 end if example3 == 0 puts "Confident in your team, lets push on to the next race" elsif example3 == 1 select_car_part elsif driver_improvements end end def select_car_part prompt = TTY::Prompt.new example = prompt.select("Scroll through the car elements and select the part you would like to improve", cycle:true) do |menu| menu.choice "Engine: £3", 0 menu.choice "Front Wing: £1", 1 menu.choice "Tyres: £1", 2 menu.choice "Suspension: £2", 3 end if example == 0 if our_team.budget >= 3 puts "Engine Upgraded!" self.our_team.update(tech_factor: self.our_team.tech_factor += 0.5) self.our_team.update(budget: our_team.budget -=3) else puts "You cant afford this! you only have £#{our_team.budget} left" end elsif example == 1 if our_team.budget >= 1 puts "Front Wing Upgraded!" self.our_team.update(tech_factor: self.our_team.tech_factor += 0.1) self.our_team.update(budget: our_team.budget -=1) else puts "You cant afford this! you only have £#{our_team.budget} left" end elsif example == 2 if our_team.budget >= 1 puts "Tyres Upgraded!" self.our_team.update(tech_factor: self.our_team.tech_factor += 0.2) self.our_team.update(budget: our_team.budget -=1) else puts "You cant afford this! you only have £#{our_team.budget} left" end elsif example == 3 if our_team.budget >= 2 puts "Suspension Upgraded!" self.our_team.update(tech_factor: self.our_team.tech_factor += 0.3) self.our_team.update(budget: our_team.budget -=2) else puts "You cant afford this! you only have £#{our_team.budget} left" end end end def drivers_names ["#{self.our_team.drivers[0].first_name} #{self.our_team.drivers[0].second_name}", "#{self.our_team.drivers[1].first_name} #{self.our_team.drivers[1].second_name}"] end def driver_improvements prompt = TTY::Prompt.new example2 = prompt.select("Which driver would you like to improve? Each Training session costs £3", cycle:true) do |menu| menu.choice "#{self.drivers_names[0]}", 0 menu.choice "#{self.drivers_names[1]}", 1 end if example2 == 0 if our_team.budget >= 3 puts "Driver Upgraded!" our_team.drivers[0].update(skill_factor: our_team.drivers[0].skill_factor += 0.5) self.our_team.update(budget: our_team.budget -=3) else puts "You cant afford this! you only have £#{our_team.budget} left" end elsif example2 == 1 if our_team.budget >= 3 puts "Driver Upgraded!" our_team.drivers[1].update(skill_factor: our_team.drivers[1].skill_factor += 0.5) self.our_team.update(budget: our_team.budget -=3) else puts "You cant afford this! you only have £#{our_team.budget} left" end end end def end_season_stats races_in_game.map do |race| [race.circuit, FinishingPosition.all.find_by(race_id: race.id, driver_id: our_team.drivers[0].id).final_position, FinishingPosition.all.find_by(race_id: race.id, driver_id: our_team.drivers[1].id).final_position] end end def show_winning_constructor puts '' puts "This season's winning team was #{sorted_team_scoreboard[0][1]}" puts '' end def show_end_season_stats puts ' ' a = Artii::Base.new :font => 'slant' puts a.asciify('Le Fin') puts '' puts 'Well, done! What an eventful season!' puts '' show_winning_constructor puts '' show_constructor_standings puts '' wait_for_any_key puts "Let's see how you did." puts '' puts 'Circuit | Driver 1 Position | Driver 2 Position ' puts '---------------------------------------------------' end_season_stats.each do |stat| puts "#{stat[0]} | #{stat[1]} | #{stat[2]}" end puts '--------------------------------------' puts "Total | #{driver_total_points(our_team.drivers[0])} | #{driver_total_points(our_team.drivers[1])} " puts '' puts "Congrats again and see you next season!" end end
# frozen_string_literal: true require 'rails_helper' describe 'teachers', type: :request do let(:headers) do { 'Accept' => 'application/vnd.api+json', 'Content-Type' => 'application/vnd.api+json' } end let(:params) { { teacher: teacher }.to_json } subject do request! response end describe 'GET index' do before do teachers end let(:request!) { get teachers_path, headers: headers } context 'when there are no teachers' do let(:teachers) {} it { is_expected.to have_http_status(:ok) } it 'should return an empty array' do body = JSON.parse(subject.body) expect(body).to be_empty end end context 'when there are teachers' do let(:teachers) { create_list(:teacher, 2) } it { is_expected.to have_http_status(:ok) } it 'should return a list of teachers' do body = JSON.parse(subject.body) expect(body.size).to eq(teachers.size) body.each_with_index do |teacher, index| expect(teacher['id']).to eq(teachers[index].id) expect(teacher['first_name']).to eq(teachers[index].first_name) expect(teacher['grade']).to eq(teachers[index].grade.to_s) expect(teacher['is_active']).to eq(teachers[index].is_active) expect(teacher['last_name']).to eq(teachers[index].last_name) end end end end describe 'GET show' do before do teacher_id end let(:request!) { get teacher_path(teacher_id) } context 'when the teacher can be found' do let(:teacher) { create(:teacher) } let(:teacher_id) { teacher.id } it { is_expected.to have_http_status(:ok) } it 'should return a teacher' do body = JSON.parse(subject.body) expect(body['id']).to eq(teacher.id) expect(body['first_name']).to eq(teacher.first_name) expect(body['grade']).to eq(teacher.grade.to_s) expect(body['is_active']).to eq(teacher.is_active) expect(body['last_name']).to eq(teacher.last_name) end end context 'when the teacher can not be found' do let(:teacher_id) { SecureRandom.uuid } it { is_expected.to have_http_status(:not_found) } it 'should return an error message' do body = JSON.parse(subject.body) expect(body).to eq("Couldn't find Teacher with 'id'=#{teacher_id}") end end end describe 'POST create' do let(:request!) do post teachers_path, params: params, headers: headers end context 'when the teacher attributes are valid' do let(:teacher) { attributes_for(:teacher) } it { is_expected.to have_http_status(:ok) } it 'should return a success message' do message = JSON.parse(subject.body)['message'] expect(message).to eq(I18n.t('teachers.create.success')) end end context 'when the teacher attributes are not valid' do let(:teacher) { attributes_for(:teacher, first_name: nil) } it { is_expected.to have_http_status(:unprocessable_entity) } it 'should return a success message' do message = JSON.parse(subject.body)['message'] expect(message).to eq(I18n.t('teachers.create.failure')) end end end describe 'PATCH update' do let(:request!) do patch teacher_path(teacher_id), params: params, headers: headers end context 'when the teacher is valid' do let(:params) do { teacher: { last_name: teacher.first_name } }.to_json end let(:teacher) { create(:teacher) } let(:teacher_id) { teacher.id } it { is_expected.to have_http_status(:ok) } it 'they see a success message' do body = JSON.parse(subject.body) expect(body['message']).to eq(I18n.t('teachers.update.success')) expect(body['resource']['last_name']).to eq(teacher.first_name) end end context 'when the teacher is not valid' do let(:params) do { teacher: { is_active: 'test' } }.to_json end let(:teacher) { create(:teacher) } let(:teacher_id) { teacher.id } it { is_expected.to have_http_status(:unprocessable_entity) } it 'should return a success message' do message = JSON.parse(subject.body)['message'] expect(message).to eq(I18n.t('teachers.update.failure')) end end context 'when the teacher is not found' do let(:params) do { teacher: { last_name: teacher.first_name } }.to_json end let(:teacher) { create(:teacher) } let(:teacher_id) { SecureRandom.uuid } it { is_expected.to have_http_status(:not_found) } it 'should return an error message' do body = JSON.parse(subject.body) expect(body).to eq("Couldn't find Teacher with 'id'=#{teacher_id}") end end end end
describe "Command" do before(:each) do @game = Game.new end context "PLACE command" do it "Report command: Unplace robot" do expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output(/Unplaced/).to_stdout end it "Place command: wrong number of arguments" do expect do result = @game.execute_command("PLACE 0,0") expect(result).to eq(true) end.to output(/Wrong number of arguments/).to_stdout # The robot shouldn't be placed after invalid command expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output(/Unplaced/).to_stdout end it "Place command: invalid x param" do expect do result = @game.execute_command("PLACE -1,0,NORTH") expect(result).to eq(true) end.to output(/Invalid position/).to_stdout # The robot shouldn't be placed after invalid command expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output(/Unplaced/).to_stdout end it "Place command: invalid y param" do expect do result = @game.execute_command("PLACE 0,5,NORTH") expect(result).to eq(true) end.to output(/Invalid position/).to_stdout # The robot shouldn't be placed after invalid command expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output(/Unplaced/).to_stdout end it "Place command: invalid direction" do expect do result = @game.execute_command("PLACE 1,4,NORTH-EAST") expect(result).to eq(true) end.to output(/Invalid direction/).to_stdout # The robot shouldn't be placed after invalid command expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output(/Unplaced/).to_stdout end it "Place command: valid" do expect do result = @game.execute_command("PLACE 1,4,NORTH") expect(result).to eq(true) end.to_not output.to_stdout # The robot should be placed expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output("1,4,NORTH\n").to_stdout end end it "Sequence of valid commands" do expect do result = @game.execute_command("PLACE 4,1,NORTH") expect(result).to eq(true) end.to_not output.to_stdout expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output("4,1,NORTH\n").to_stdout expect do result = @game.execute_command("MOVE") expect(result).to eq(true) end.to_not output.to_stdout expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output("4,2,NORTH\n").to_stdout expect do result = @game.execute_command("LEFT") expect(result).to eq(true) end.to_not output.to_stdout expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output("4,2,WEST\n").to_stdout expect do result = @game.execute_command("MOVE") expect(result).to eq(true) end.to_not output.to_stdout expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output("3,2,WEST\n").to_stdout expect do result = @game.execute_command("RIGHT") expect(result).to eq(true) end.to_not output.to_stdout expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output("3,2,NORTH\n").to_stdout result = @game.execute_command("EXIT") expect(result).to eq(false) end end
class PapersController < ApplicationController def index if params[:year].nil? == false @papers = Paper.published_in(params[:year]) else @papers = Paper.all end end def show @paper = Paper.find(params[:id]) end def new @paper = Paper.new end def edit @paper = Paper.find(params[:id]) end def create @paper = Paper.new(paper_params) if @paper.save redirect_to @paper else render 'new' end end def update @paper = Paper.find(params[:id]) if @paper.update(paper_params) redirect_to @paper else render 'edit' end end def destroy @paper = Paper.find(params[:id]) @paper.destroy redirect_to papers_path end private def paper_params params.require(:paper).permit(:title, :venue, :year, { author_ids: []}) end end
require 'rails_helper' describe ResourceAssetPolicy do subject { ResourceAssetPolicy.new(user, resource_asset) } context 'visitante não pode ver material do participante' do let(:user) { nil } let(:resource_asset) { create(:asset_event_participant_material) } it { should_not permit(:show) } it { should_not permit(:create) } it { should_not permit(:new) } it { should_not permit(:update) } it { should_not permit(:edit) } it { should_not permit(:destroy) } end context 'visitante não pode ver material do docente' do let(:user) { nil } let(:resource_asset) { create(:asset_event_instructor_material) } it { should_not permit(:show) } it { should_not permit(:create) } it { should_not permit(:new) } it { should_not permit(:update) } it { should_not permit(:edit) } it { should_not permit(:destroy) } end context 'usuário participante em evento pode ver material do participante' do let(:resource_asset) { create(:asset_event_participant_material) } let(:user) { user = create(:user) user.add_role(:participant, resource_asset.assetable) user } it { should permit(:show) } it { should_not permit(:create) } it { should_not permit(:new) } it { should_not permit(:update) } it { should_not permit(:edit) } it { should_not permit(:destroy) } end context 'usuário participante em evento NÃO pode ver material do docente' do let(:resource_asset) { create(:asset_event_instructor_material) } let(:user) { user = create(:user) user.add_role(:participant, resource_asset.assetable) user } it { should_not permit(:show) } it { should_not permit(:create) } it { should_not permit(:new) } it { should_not permit(:update) } it { should_not permit(:edit) } it { should_not permit(:destroy) } end context 'usuário docente em evento pode administrar material do docente' do let(:resource_asset) { create(:asset_event_instructor_material) } let(:user) { user = create(:user) user.add_role(:instructor, resource_asset.assetable) user } it { should permit(:show) } it { should permit(:create) } it { should permit(:new) } it { should permit(:update) } it { should permit(:edit) } it { should permit(:destroy) } end context 'usuário docente GLOBAL só pode ver (não editar) material do docente' do let(:resource_asset) { create(:asset_event_instructor_material) } let(:user) { user = create(:user) user.add_role(:instructor) user } it { should permit(:show) } it { should_not permit(:create) } it { should_not permit(:new) } it { should_not permit(:update) } it { should_not permit(:edit) } it { should_not permit(:destroy) } end context 'usuário admin de evento pode administrar material do docente' do let(:resource_asset) { create(:asset_event_instructor_material) } let(:user) { user = create(:user) user.add_role(:event_admin) user } it { should permit(:show) } it { should permit(:create) } it { should permit(:new) } it { should permit(:update) } it { should permit(:edit) } it { should permit(:destroy) } end end
=begin puts 1 + 1 This is a multiline comment section. They are not used as often as just including a # at the beginning of every line. =end puts "Multi line comments in the section above."
module MixpanelTest class Analysis def initialize(options = {}) @events_count = {} @events_properties_counts = {} @events_properties_values_counts = {} @properties_counts = {} @properties_values_counts = {} @super_properties_counts = {} @super_properties_values_counts = {} end def initialize_for_event(ev) name = ev["event"] initialize_for_event_property_list(name, ev["properties"].keys) ev["properties"].each do |k, v| # Initialize property counters @events_properties_values_counts[name][k][v] ||= 0 @properties_values_counts[k][v] ||= 0 end end def initialize_for_event_property_list(name, props) # Initialize counters @events_count[name] ||= 0 @events_properties_counts[name] ||= {} @events_properties_values_counts[name] ||= {} props.each do |k| # Initialize property counters @events_properties_counts[name][k] ||= 0 @events_properties_values_counts[name][k] ||= {} @properties_counts[k] ||= 0 @properties_values_counts[k] ||= {} end end def add_documentation_object(obj) # Each event and property counts for an undefined number > 0. # Discard notes # Only useful for merging two documentation objects obj["events"].each do |name, props| initialize_for_event_property_list(name, props) @events_count[name] += 1 props.each do |p_name| @events_properties_counts[name][p_name] += 1 @properies_count[p_name] += 1 end end obj["properties"].each do |p| @properties_count[p["name"]] ||= 0 @properties_count[p["name"]] += 1 p["values"].each do |v| @properties_values_count[p["name"]][v] ||= 0 @properties_values_count[p["name"]][v] += 1 end end end def add_events(arr) arr.each do |ev| add_event(ev) end end def add_event(ev) initialize_for_event(ev) name = ev["event"] ev["properties"].each do |k, v| # Increment property counters @properties_counts[k] += 1 @events_properties_counts[name][k] += 1 @events_properties_values_counts[name][k][v] += 1 @properties_values_counts[k][v] += 1 end end def format_verbose puts "Mixpanel events caught:" pp @events_count puts "Mixpanel properties caught for each event:" pp @events_properties_counts puts "All Mixpanel properties caught:" pp @properties_counts puts "Mixpanel values frequency by property:" pp @properties_values_counts puts "Mixpanel values frequency by property and event:" pp @events_properties_values_counts end def format_documentation pp documentation_object end def documentation_object default_notes = "Undocumented" { "events" => @events_count.keys.map do |k| { k => { "notes" => default_notes, "properties" => @events_properties_counts[k].keys } } end, "properties" => @properties_counts.keys.map do |k| { "name" => k, "notes" => default_notes, "values" => @properties_values_counts[k].keys } end } end end end
# == Schema Information # # Table name: customers # # id :integer not null, primary key # name :string(255) # description :text(65535) # created_at :datetime not null # updated_at :datetime not null # phone :string(255) # qq_number :string(255) # class Customer < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable has_many :attachments, as: :attachable accepts_nested_attributes_for :attachments, allow_destroy: true has_many :admin_users accepts_nested_attributes_for :admin_users, allow_destroy: true has_many :products has_many :orders end
class AddVideoToVirtualTourisms < ActiveRecord::Migration def change add_attachment :virtual_tourisms, :video end end
require 'redmine' Redmine::Plugin.register :redmine_graph_activities do name 'Redmine Graph Activities plugin' author '@me_umacha' description "The plugin to generate a graph for visualizing members' activities." version '0.0.3' # This plugin works as a project module and can be enabled/disabled at project level project_module :graph_activities do # All actions are public permission permission :graph_activities_view, {:graph_activities => [:view]}, :public => true permission :graph_activities_graph, {:graph_activities => [:graph]}, :public => true permission :graph_activities_graph_issue_per_day, {:graph_activities => [:graph_issue_per_day]}, :public => true permission :graph_activities_graph_repos_per_day, {:graph_activities => [:graph_repos_per_day]}, :public => true end # Add an item in project menu menu :project_menu, :graph_activities, {:controller=>'graph_activities', :action=>'view', :user_id=>'', :from=>'', :to=>''}, :caption => :graph_activities_name # Settings settings :default => {'include_subproject' => '1'}, :partial => 'settings/redmine_graph_activities_settings' end
module Moped class Indexes include Enumerable private def database @database end def collection_name @collection_name end def namespace @namespace end def initialize(database, collection_name) @database = database @collection_name = collection_name @namespace = "#{database.name}.#{collection_name}" end public # Retrive an index by its definition. # # @param [Hash] key an index key definition # @return [Hash, nil] the index with the provided key, or nil. # # @example # session[:users].indexes[id: 1] # # => {"v"=>1, "key"=>{"_id"=>1}, "ns"=>"moped_test.users", "name"=>"_id_" } def [](key) database[:"system.indexes"].find(ns: namespace, key: key).one end # Create an index unless it already exists. # # @param [Hash] key the index spec # @param [Hash] options the options for the index. # @see http://www.mongodb.org/display/DOCS/Indexes#Indexes-CreationOptions # # @example Without options # session[:users].indexes.create(name: 1) # session[:users].indexes[name: 1] # # => {"v"=>1, "key"=>{"name"=>1}, "ns"=>"moped_test.users", "name"=>"name_1" } # # @example With options # session[:users].indexes.create( # { location: "2d", name: 1 }, # { unique: true, dropDups: true } # ) # session[:users][location: "2d", name: 1] # {"v"=>1, # "key"=>{"location"=>"2d", "name"=>1}, # "unique"=>true, # "ns"=>"moped_test.users", # "dropDups"=>true, # "name"=>"location_2d_name_1"} def create(key, options = {}) spec = options.merge(ns: namespace, key: key) spec[:name] ||= key.to_a.join("_") database[:"system.indexes"].insert(spec) end # Drop an index, or all indexes. # # @param [Hash] key the index's key # @return [Boolean] whether the indexes were dropped. # # @example Drop all indexes # session[:users].indexes.count # => 3 # # Does not drop the _id index # session[:users].indexes.drop # session[:users].indexes.count # => 1 # # @example Drop a particular index # session[:users].indexes.drop(name: 1) # session[:users].indexes[name: 1] # => nil def drop(key = nil) if key index = self[key] or return false name = index["name"] else name = "*" end result = database.command deleteIndexes: collection_name, index: name result["ok"] == 1 end # @yield [Hash] each index for the collection. def each(&block) database[:"system.indexes"].find(ns: namespace).each(&block) end end end
module SuckerPunch class << self attr_accessor :queues def reset! self.queues = {} end end SuckerPunch.reset! class Queue attr_reader :name def initialize(name) @name = name SuckerPunch.queues[name] ||= [] end def self.[](name) new(name) end def register(klass, size, args=nil) nil end def workers raise "Not implemented" end def jobs SuckerPunch.queues[@name] end def async self end def method_missing(name, *args, &block) SuckerPunch.queues[@name] << { method: name, args: Array(args) } end end end
p 10 != 5 # true p 10 != 10 # false puts p "Hello" != "Goodbye" # true p "Hello" != "Hello" # false p "Hello" != "hello" # true (not the same case) puts # good to settle on a common method like .downcase capital_hello = "HeLLo" lower_hello = "hello" p capital_hello == lower_hello p capital_hello.downcase == lower_hello.downcase puts p "123" != 123 # true b/c different data types
class CreatePosts < ActiveRecord::Migration def self.up create_table :posts, :force => true do |t| t.integer :user_id t.string :content,:limit=>210 t.string :logo,:limit=>50 t.integer :forward_posts_count,:default=>0 t.integer :favorite_posts_count,:default=>0 t.boolean :is_hide,:default=>false t.integer :article_id t.integer :forward_post_id t.integer :forward_user_id t.integer :category_id t.timestamps end add_index :posts, :user_id add_index :posts, :article_id add_index :posts, :created_at add_index :posts, :category_id add_index :posts, :is_hide add_index :posts, :forward_posts_count add_index :posts, :favorite_posts_count add_index :posts, :forward_post_id add_index :posts, :forward_user_id end def self.down drop_table :posts end end
class State < FlactiveRecord::Base end class Programmer < FlactiveRecord::Base end describe "Metaprogrammed Amazingness" do DBConnection.instance.dbname = 'dynamic_orm_test' CONN = DBConnection.instance.connection context "superclass" do it "exists" do expect{FlactiveRecord::Base}.to_not raise_error end it "returns the connection to the database" do expect(FlactiveRecord::Base.connection).to be_a PG::Connection end it "connects to localhost" do connection = FlactiveRecord::Base.connection expect(connection.host).to eq("localhost") end it "connects to the test database" do connection = FlactiveRecord::Base.connection expect(connection.db).to eq("dynamic_orm_test") end end context "Programmers" do before do seed_data = File.read('spec/db/programmer_seed.sql') CONN.exec(seed_data) end after do CONN.exec("DROP TABLE programmers;") end context "About the Table" do it "knows its table" do expect(Programmer.table_name).to eq('programmers') end it "knows its columns" do expect(Programmer.column_names).to eq(["id", "name", "language"]) end end context "Instances" do it "defines methods based on the columns" do steven_nunez = Programmer.new steven_nunez.name = "Steven Nunez" steven_nunez.language = "Loves teh rubiez" expect(steven_nunez.name) expect(steven_nunez.language) end it "can create instances with a hash" do john_mcarthy = Programmer.new(name: "John McCarthy", language: 'lisp') expect(john_mcarthy.name).to eq("John McCarthy") expect(john_mcarthy.language).to eq('lisp') end it "initializes without an id" do john_mcarthy = Programmer.new(name: "John McCarthy", language: 'lisp') expect(john_mcarthy.id).to be_nil end end context "finders" do it "returns all programmers" do programmers = Programmer.all # From the seed file expect(programmers.count).to eq(3) expect(programmers.first).to be_a Programmer end it "finds a single programmer by id" do programmer = Programmer.find(1) expect(programmer.name).to eq("Yukihiro Matzumoto") end it "returns nil if a programmer isn't found" do programmer = Programmer.find(9001) expect(programmer).to be_nil end end context "saving and updating a programmer" do it "saves an non existent programmer" do programmer = Programmer.new(name: "Steven", language: "Ruby") programmer.save expect(programmer.id).to_not be_nil end it "updates a programmers name" do programmer = Programmer.find(1) programmer.name = "Tenderlove" programmer.save found_programmer = Programmer.find(1) expect(found_programmer.name).to eq('Tenderlove') end end end context "States" do before do seed_data = File.read('spec/db/state_seed.sql') CONN.exec(seed_data) end after do CONN.exec("DROP TABLE states;") end context "About the Table" do it "knows its table" do expect(State.table_name).to eq('states') end it "knows its columns" do expect(State.column_names).to eq(["id", "name", "rank", "density_per_square_mile"]) end end context "Instances" do it "defines methods based on the columns" do new_york = State.new new_york.name = "New York" new_york.rank = 1 new_york.density_per_square_mile = 90000000 expect(new_york.name).to eq('New York') expect(new_york.rank).to eq(1) expect(new_york.density_per_square_mile).to eq 90000000 end it "can create instances with a hash" do new_york = State.new(name: "New York", rank: 1, density_per_square_mile: 90000000) expect(new_york.name).to eq("New York") expect(new_york.rank).to eq(1) expect(new_york.density_per_square_mile).to eq(90000000) end it "initializes without an id" do new_york = State.new(name: "New York", rank: 1, density_per_square_mile: 90000000) expect(new_york.id).to be_nil end end context "finders" do it "returns all programmers" do state = State.all # From the seed file expect(state.count).to eq(10) expect(state.first).to be_a State end it "finds a single programmer by id" do state = State.find(1) expect(state.name).to eq("New Jersey") end it "returns nil if a programmer isn't found" do state = State.find(9001) expect(state).to be_nil end end context "saving and updating a programmer" do it "saves an non existent programmer" do new_york = State.new(name: "Steven", rank: 1, density_per_square_mile: 9000000) new_york.save expect(new_york.id).to_not be_nil end it "updates a programmers name" do new_york = State.find(1) new_york.name = "New York" new_york.save found_state = State.find(1) expect(found_state.name).to eq('New York') end end end end
class UsersController < ApplicationController skip_before_action :verify_authenticity_token before_action :require_user, only: [:show] before_action :require_admin, only: [:index, :destroy] def index @trainer = User.find_by(id: 1) @users = User.where(admin: false) end def show @trainer = User.find_by(id: 1) @user = User.find_by(id: params[:id]) @phases = phases(@user) if @user @phases.sort! if @user.nil? if current_user.admin? flash[:error] = "User doesn't exist!" redirect_to users_path else flash[:error] = "You don't have access!" redirect_to user_path(session[:user_id]) end elsif current_user.admin? @admin = current_user if @user.workouts && @user @workouts = @user.workouts render 'users/show', :locals => {:phases => @phases, workouts: @workouts } end else # Prevents clients to see other client's data################### unless session[:user_id] == @user.id flash[:error] = "You don't have access!" redirect_to user_path(session[:user_id]) return end ################################################# @workouts = current_user.workouts @user.body_fat = find_body_fat render 'users/show', :locals => {phases: @phases, workouts: @workouts } end end def new @user = User.new end def create if @user = User.new(user_params) measurement = Measurement.new( weight: params[:user][:weight], wrist: params[:user][:wrist], waist: params[:user][:waist], forearm: params[:user][:forearm], height: params[:user][:height], neck: params[:user][:neck], hips: params[:user][:hips], chest: params[:user][:chest], body_fat: @user.body_fat, user_id: @user.id) if @user.save && measurement.save # need to save data before we can calculate body fat session[:user_id] = @user.id # @user.body_fat = find_body_fat redirect_to @user else redirect_to new_user_path end else redirect_to new_user_path end end def edit @user = User.find_by(id: params[:id]) end def update @user = User.find_by(id: params[:id]) measurement = Measurement.new( weight: params[:user][:weight], wrist: params[:user][:wrist], waist: params[:user][:waist], forearm: params[:user][:forearm], height: params[:user][:height], neck: params[:user][:neck], hips: params[:user][:hips], chest: params[:user][:chest], body_fat: find_body_fat, user_id: @user.id) if @user.update(user_params) && measurement.save flash[:success] = "User successfully updated!" if current_user.admin? redirect_to users_path else redirect_to user_path end else p @users.errors.full_messages redirect_to edit_user_path(@user) end end def destroy client = User.find_by(id: params[:id]) if current_user.admin? if client.destroy flash[:success] = "User successfully deleted!" redirect_to users_path else redirect_to users_path end else redirect_to root_path end end private def user_params params.require(:user).permit( :first_name, :last_name, :email, :password, :password_confirmation, :avatar, :age, :gender, :weight, :age, :waist, :height, :body_fat, :neck, :forearm, :hips, :chest, :wrist) end def phases(user) phase_collection = [] user.workouts.each do |workout| phase_collection.push(workout.phase) phase_collection = phase_collection.uniq end return phase_collection end # copied over from measurements controller def user_age user = User.find_by(id: params[:id]) return user.age end def user_waist user = User.find_by(id: params[:id]) return user.waist end def user_wrist user = User.find_by(id: params[:id]) return user.wrist end def user_forearm user = User.find_by(id: params[:id]) return user.forearm end def user_weight user = User.find_by(id: params[:id]) return user.weight end def user_height user = User.find_by(id: params[:id]) return user.height end def user_neck user = User.find_by(id: params[:id]) return user.neck end def user_hips user = User.find_by(id: params[:id]) return user.hips end def user_chest user = User.find_by(id: params[:id]) return user.chest end def user_body_fat user = User.find_by(id: params[:id]) return user.body_fat end def user_id user = User.find_by(id: params[:id]) return user.id end def user_gender user = User.find_by(id: params[:id]) return user.gender end def max_hr 220 - user_age end def find_low_int_target_hr max_hr.to_f * 0.70 end def find_high_int_target_hr max_hr.to_f * 0.85 end def in_to_m(inches=0) inches.to_f / 39.370 end def in_to_cm(inches=0) inches.to_f * 2.54 end def lbs_to_kg(lbs=0) lbs.to_f / 2.2046226218 end def find_BMI ( ( lbs_to_kg(user_weight) / in_to_m(user_height) ) / in_to_m(user_height) ) end def user_height user = User.find_by(id: params[:id]) return user.height end def bmr_data converted_weight = 10 * lbs_to_kg(user_weight) converted_height = 6.25 * in_to_cm(user_height) converted_age = 5 * user_age return converted_weight + converted_height - converted_age end def find_BMR if user_gender == "male" bmr = bmr_data + 5 return bmr else bmr = bmr_data - 161 return bmr end end # calculation is slightly off def male_body_fat converted_weight = 1.082 * user_weight converted_waist = 4.15 * user_waist added_converted_weight = 94.42 + converted_weight lean_body_weight = added_converted_weight - converted_waist lean_diff = user_weight - lean_body_weight lean_diff_times_100 = lean_diff * 100 body_fat = lean_diff_times_100 / user_weight return body_fat end # calculation is slightly off def female_body_fat weight_kg = user_weight / 2.2 multipy_weight = 0.732 * weight_kg wrist_cm = user_wrist / 0.394 multipy_wrist = 3.786 * wrist_cm forearm_circumference = user_forearm / 3.14 multipy_forearm = 0.434 * forearm_circumference lean_body_weight = 8.987 + multipy_weight + multipy_wrist + multipy_forearm lean_diff = user_weight - lean_body_weight lean_diff_times_100 = lean_diff * 100 body_fat = lean_diff_times_100 / user_weight return body_fat end # calculation is slightly off def find_body_fat user_gender == "male" ? male_body_fat : female_body_fat end end
require "rails_helper" RSpec.describe BulkApiImport::FhirObservationImporter do before { create(:facility) } let(:import_user) { ImportUser.find_or_create } let(:facility) { import_user.facility } let(:facility_identifier) do create(:facility_business_identifier, facility: facility, identifier_type: :external_org_facility_id) end let(:identifier) { SecureRandom.uuid } let(:patient) { build_stubbed(:patient, id: Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, identifier)) } let(:patient_identifier) do build_stubbed(:patient_business_identifier, patient: patient, identifier: identifier, identifier_type: :external_import_id) end describe "#import" do it "imports a blood pressure observation" do expect { described_class.new( build_observation_import_resource(:blood_pressure) .merge(performer: [{identifier: facility_identifier.identifier}], subject: {identifier: patient_identifier.identifier}) ).import }.to change(BloodPressure, :count).by(1) .and change(Encounter, :count).by(1) .and change(Observation, :count).by(1) end it "imports a blood sugar observation" do expect { described_class.new( build_observation_import_resource(:blood_sugar) .merge(performer: [{identifier: facility_identifier.identifier}], subject: {identifier: patient_identifier.identifier}) ).import }.to change(BloodSugar, :count).by(1) .and change(Encounter, :count).by(1) .and change(Observation, :count).by(1) end end describe "#build_blood_pressure_attributes" do it "correctly builds valid attributes across different blood pressure resources" do 10.times.map { build_observation_import_resource(:blood_pressure) }.each do |resource| bp_resource = resource .merge(performer: [{identifier: facility_identifier.identifier}], subject: {identifier: patient_identifier.identifier}) attributes = described_class.new(bp_resource).build_blood_pressure_attributes expect(Api::V3::BloodPressurePayloadValidator.new(attributes)).to be_valid expect(attributes[:patient_id]).to eq(patient.id) end end end describe "#build_blood_sugar_attributes" do it "correctly builds valid attributes across different blood sugar resources" do 10.times.map { build_observation_import_resource(:blood_sugar) }.each do |resource| bs_resource = resource .merge(performer: [{identifier: facility_identifier.identifier}], subject: {identifier: patient_identifier.identifier}) attributes = described_class.new(bs_resource).build_blood_sugar_attributes expect(Api::V4::BloodSugarPayloadValidator.new(attributes)).to be_valid expect(attributes[:patient_id]).to eq(patient.id) end end end describe "#dig_blood_pressure" do it "extracts systolic and diastolic readings" do expect( described_class.new({ component: [ {code: {coding: [system: "http://loinc.org", code: "8480-6"]}, valueQuantity: {value: 120}}, {code: {coding: [system: "http://loinc.org", code: "8462-4"]}, valueQuantity: {value: 80}} ] }).dig_blood_pressure ).to eq({systolic: 120, diastolic: 80}) end end describe "#dig_blood_sugar" do it "extracts blood sugar types and values" do [ {code: "88365-2", value: 80, expected_type: :fasting, expected_value: 80}, {code: "87422-2", value: 130, expected_type: :post_prandial, expected_value: 130}, {code: "2339-0", value: 100, expected_type: :random, expected_value: 100}, {code: "4548-4", value: 4, expected_type: :hba1c, expected_value: 4} ].each do |code:, value:, expected_type:, expected_value:| expect(described_class.new( { component: [{code: {coding: [system: "http://loinc.org", code: code]}, valueQuantity: {value: value}}] } ).dig_blood_sugar).to eq({blood_sugar_type: expected_type, blood_sugar_value: expected_value}) end end end end
module Fastlane module Actions # Adds a git tag to the current commit class EmailApnsCertsAction < Action def self.run(options) end def self.description "This will email all the APNS Push Certs to Backend" end def self.available_options [ FastlaneCore::ConfigItem.new(key: :html_template, env_name: "APNS_CERTS_HTML_TEMPLATE", description: "The Template", optional: true) ] end def self.author "Rahul Katariya" end def self.is_supported?(platform) true end end end end
class TranslateMultipleForm include ActiveModel::Model FIELDS = %i[column_name from_locale to_locale].freeze attr_accessor :records, *FIELDS attr_reader :message validates(*FIELDS, presence: true) def save # rubocop:todo Metrics/MethodLength already_exists = 0 blank_source = 0 successfully_translated = 0 records.each do |record| current_value = record.send("#{column_name}_backend").read(to_locale, fallback: false) if current_value.present? already_exists += 1 next end from_value = record.send("#{column_name}_backend").read(from_locale, fallback: false) if from_value.blank? blank_source += 1 next end translation = GoogleTranslate.new(from_value, from_locale: from_locale, to_locale: to_locale).perform translate_form = TranslateForm.new(record: record, column_name: column_name, locale: to_locale, column_value: translation) successfully_translated += 1 if translate_form.save end @message = I18n.t( 'already_exists_count_blank_source_count_successfully_translated_count', already_exists_count: already_exists, blank_source_count: blank_source, successfully_translated_count: successfully_translated ) end end
require 'meta-spotify' # meta-spotify gem: Ruby wrapper for the spotify API require_relative 'ArtistSearch' require_relative 'AlbumsByArtistSearch' class Game def initialize @artist_search_term = nil @artist_search_result = nil @artist_index = nil @album_search_result = nil @album_index = nil @is_running = false end def run welcome_user show_description start_game end def start_game @is_running = true while is_running? puts puts "------------------------------" start_new_search @is_running = continue_to_run? end puts puts "Goodbye." puts end def start_new_search @artist_search_term = get_artist_search_term @artist_search_result = ArtistSearch.new(MetaSpotify::Artist.search(@artist_search_term)) if show_artist_search_results @artist_index = get_artist_index artist_uri = @artist_search_result.get_artist_uri_by_index(@artist_index) @album_search_result = AlbumsByArtistSearch.new(MetaSpotify::Artist.lookup(artist_uri, :extras => 'album')) if show_album_search_results @album_index = get_album_index album_uri = @album_search_result.get_album_uri_by_index(@album_index) launch_spotify_with_album(album_uri, @artist_search_result.get_artist_name_by_index(@artist_index), @album_search_result.get_album_name_by_index(@album_index)) end end end def show_artist_search_results puts puts "Your search for '#{@artist_search_term}' returned #{@artist_search_result.total_results} results." if @artist_search_result.total_results > 0 @artist_search_result.to_s else false end end def show_album_search_results puts puts "#{@artist_search_result.get_artist_name_by_index(@artist_index)} has #{@album_search_result.total_results} albums on Spotify. " if @album_search_result.total_results > 0 @album_search_result.to_s else false end end def launch_spotify_with_album(album_uri, artist_name, album_name) puts "Now playing #{album_name} by #{artist_name} on Spotify!" system("open #{album_uri}") end def get_artist_search_term puts print "Please enter an artist's name: " get_user_input.to_s end def get_artist_index puts print "Enter the number of the artist listed above (1 - #{@artist_search_result.total_results}) whose albums you'd like to view: " index = get_user_input.to_i if index > 0 && index <= @artist_search_result.total_results index-=1 else puts puts 'Unexpected input. ' get_artist_index end end def get_album_index puts print "Select the number of the album listed above (1 - #{@album_search_result.total_results}) that you'd like to play in the Spotify client: " index = get_user_input.to_i if index > 0 && index <= @artist_search_result.total_results index-=1 else puts puts 'Unexpected input. ' get_album_index end end def get_user_input gets.chomp end def continue_to_run? puts print "Would you like to search again? 'yes' or 'no': " input = gets.chomp case input when 'yes' true when 'no' false else puts puts 'Unexpected input.' continue_to_run? end end def welcome_user puts "\e[H\e[2J" puts "Welcome to the super simple Spotify browser!" puts "Author: Buster Kapila" puts puts "------------------------------" end def show_description puts puts "Browse albums on Spotify by artist." puts "Select an album and launch the Spotify player." puts "You must have the Spotify client installed to hear your music." puts "Let's get started!" end def is_running? @is_running end end
=begin We are going to create a BankAccount class. This class will recreate some of the common account transactions that normally occur for a bank account such as displaying your account number, checking and savings amount, total amount. Of course, there are also methods to invoke such as depositing a check, checking your balance, withdrawing money =end class BankAccount @@num_of_accounts = 0 def initialize account_number @checking = 0 @savings = 0 @interest_rate = 0.01 end =begin BankAccount should have a method that returns a user's account number, account number should be generated by a private method, account number should be random =end def ret_account_number puts @account_number self end =begin BankAccount should have a method that returns the user's checking account balance =end def checking_balance puts @checking self end =begin BankAccount should have a method that returns the user's saving account balance =end def savings_balance puts @savings self end =begin BankAccount should allow a user to deposit money into either their checking or saving account =end def deposit_checking(amt) @checking += amt self end def deposit_savings(amt) @savings += amt self end =begin BankAccount should allow a user to withdraw money from one of their accounts, return an error if there are insufficient funds =end def withdraw_checking(amt) if @checking < amt puts "Insufficient funds for checking account" else @checking -= amt end self end def withdraw_savings(amt) if @savings < amt puts "Insufficient funds for savings account" else @savings -= amt end self end =begin BankAccount should allow the user to view the total amount of money they have at the bank =end def total_amount puts @savings + @checking self end =begin BankAccount should track how many accounts the bank currently has =end =begin Add an interest_rate attribute that is not accessible by the user. Set it to 0.01 =end =begin BankAccount should have a method called account_information that displays the users account number, total money, checking account balance, saving account balance and interest rate =end def account_information puts " Account Number: #{@account_number}. Total Money: #{@checking + @savings}. Checking Account Balance: #{@checking} . Savings Account Balance: #{@savings}. Interest rate: #{@interest_rate}" self end =begin A user should not be able to set any attributes from the BankAccount class =end private def account_number @account_number = rand(100000..999999) end end myAccount = BankAccount.new myAccount.deposit_savings(1000).deposit_checking(2000).withdraw_savings(50).account_information
require 'test_helper' class PhoneVerificationsControllerTest < ActionController::TestCase setup do @phone_verification = phone_verifications(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:phone_verifications) end test "should get new" do get :new assert_response :success end test "should create phone_verification" do assert_difference('PhoneVerification.count') do post :create, phone_verification: { number: @phone_verification.number, user_id: @phone_verification.user_id } end assert_redirected_to phone_verification_path(assigns(:phone_verification)) end test "should show phone_verification" do get :show, id: @phone_verification assert_response :success end test "should get edit" do get :edit, id: @phone_verification assert_response :success end test "should update phone_verification" do patch :update, id: @phone_verification, phone_verification: { number: @phone_verification.number, user_id: @phone_verification.user_id } assert_redirected_to phone_verification_path(assigns(:phone_verification)) end test "should destroy phone_verification" do assert_difference('PhoneVerification.count', -1) do delete :destroy, id: @phone_verification end assert_redirected_to phone_verifications_path end end
class LikesController < ApplicationController before_action :authenticate_user! before_action :find_picture def create @like = current_user.likes.create!(like_params) end def destroy Like.find(params[:id]).destroy end private def like_params params.permit(:picture_id) end def find_picture @picture = Picture.find(params[:picture_id]) end end
class SessionsController < ApplicationController # GET login form def new end # POST create new def create @user = User.find_by(email: params[:session][:email].downcase) # because we're working with the Session resource, the params hash has a [:session] key that holds our form data if @user && @user.authenticate(params[:session][:password]) # if we found a user by their email, now we check their password. authenticate is a method provided by adding "has_secure_password" to the User model/ if @user.activated? log_in @user params[:session][:remember_me] == '1' ? remember(@user) : forget(@user) # if the use checked the "remember me" box, we stick a cookie in their browser with remember(@user) redirect_back_or @user # redirect_back_or will redirect to whatever you pass in as a param, which is @user in this case. @user will redirect us to the user's show view. else message = 'Account not activated.' message += 'Check your email for the activation link.' flash[:warning] = message redirect_to root_url end else flash.now[:danger] = 'Invalid email/password combination' render 'new' # if authentication fails (due to an invalid username or password for example), re-render the login form end end # DESTROY def destroy log_out if logged_in? redirect_to root_url end end
require('spec_helper') describe(Company) do describe(".all") do it("starts with an empty array of stops") do expect(Company.all()).to(eq([])) end end # describe(".find_category_expenses") do # it("return a list of expenses for a category") do # test_category = Category.new({:name => "Bills", :id => nil}) # test_category.save() # test_expense1 = Expense.new({:amount => 32.50, :id => nil, :date => 20150105}) # test_expense1.save() # test_expense2 = Expense.new({:amount => 100.99, :id => nil, :date => 20150104}) # test_expense2.save() # test_expense3 = Expense.new({:amount => 522.44, :id => nil, :date => 22150104}) # test_expense3.save() # test_category.add_expense(test_expense1.id()) # test_category.add_expense(test_expense3.id()) # expect(Company.find_category_expenses(test_category.id())).to(eq([test_expense1.amount(), test_expense3.amount()])) # end # end describe("#save") do it("pairs a categories ID to a expenses ID") do test_category = Category.new({:name => "Food", :id => nil}) test_category.save() test_expense = Expense.new({:amount => 32.50, :id => nil, :date => 20150119}) test_expense.save() test_company = Company.new({:id => nil, :category_id => test_category.id(), :expense_id => test_expense.id()}) test_company.save() expect(Company.all()).to(eq([test_company])) end end describe("#==") do it("makes sure company is equal if they share a category_id and expense_id") do company1 = Company.new({:category_id => 1, :expense_id => 1}) company2 = Company.new({:category_id => 1, :expense_id => 1}) expect(company1).to(eq(company2)) end end end
require 'spec_helper' describe Visualization::Boxplot, :database_integration => true do let(:account) { GpdbIntegration.real_gpdb_account } let(:database) { GpdbDatabase.find_by_name_and_gpdb_instance_id(GpdbIntegration.database_name, GpdbIntegration.real_gpdb_instance) } let(:dataset) { database.find_dataset_in_schema('base_table1', 'test_schema') } let(:visualization) do Visualization::Boxplot.new(dataset, { :x_axis => "category", :y_axis => "column2", :bins => 20, :filters => filters }) end describe "#fetch!" do let(:filters) { nil } before do visualization.fetch!(account, 12345) end context "dataset is a table" do it "returns the boxplot data" do visualization.rows.should == [ {:bucket => "papaya", :min => 5.0, :median => 6.5, :max => 8.0, :first_quartile => 5.5, :third_quartile => 7.5, :percentage => "44.44%", :count => 4}, {:bucket => "orange", :min => 2.0, :median => 3.0, :max => 4.0, :first_quartile => 2.5, :third_quartile => 3.5, :percentage => "33.33%", :count => 3}, {:bucket => "apple", :min => 0.0, :median => 0.5, :max => 1.0, :first_quartile => 0.25, :third_quartile => 0.75, :percentage => "22.22%", :count => 2} ] end context "with filters" do let(:filters) { ["category != 'apple'"] } it "returns the boxplot data based on the filtered dataset" do visualization.rows.should == [ {:bucket => "papaya", :min => 5.0, :median => 6.5, :max => 8.0, :first_quartile => 5.5, :third_quartile => 7.5, :percentage => "57.14%", :count => 4}, {:bucket => "orange", :min => 2.0, :median => 3.0, :max => 4.0, :first_quartile => 2.5, :third_quartile => 3.5, :percentage => "42.86%", :count => 3} ] end end context "with allcaps column names" do let(:dataset) { database.find_dataset_in_schema('allcaps_candy', 'test_schema') } let(:filters) { nil } let(:visualization) do Visualization::Boxplot.new(dataset, { :x_axis => "KITKAT", :y_axis => "STUFF", :bins => 20, :filters => filters }) end it "fetches the rows correctly" do visualization.rows.should_not be_nil end end end context "dataset is a chorus view" do let(:dataset) { datasets(:executable_chorus_view) } it "returns the boxplot data" do visualization.rows.should == [ {:bucket => "papaya", :min => 5.0, :median => 6.5, :max => 8.0, :first_quartile => 5.5, :third_quartile => 7.5, :percentage => "44.44%", :count => 4}, {:bucket => "orange", :min => 2.0, :median => 3.0, :max => 4.0, :first_quartile => 2.5, :third_quartile => 3.5, :percentage => "33.33%", :count => 3}, {:bucket => "apple", :min => 0.0, :median => 0.5, :max => 1.0, :first_quartile => 0.25, :third_quartile => 0.75, :percentage => "22.22%", :count => 2} ] end context "with filters" do let(:filters) { ["category != 'apple'"] } it "returns the boxplot data based on the filtered dataset" do visualization.rows.should == [ {:bucket => "papaya", :min => 5.0, :median => 6.5, :max => 8.0, :first_quartile => 5.5, :third_quartile => 7.5, :percentage => "57.14%", :count => 4}, {:bucket => "orange", :min => 2.0, :median => 3.0, :max => 4.0, :first_quartile => 2.5, :third_quartile => 3.5, :percentage => "42.86%", :count => 3} ] end end end end end
class CreateStats < ActiveRecord::Migration def change create_table :stats do |t| t.string :surname, null: false t.string :given_name, null: false t.string :position, null: false t.string :league, null: false t.string :division, null: false t.string :team_name, null: false t.string :team_city, null: false t.string :throws t.integer :year, null: false t.integer :games, default: 0 t.integer :games_started, default: 0 t.integer :at_bats, default: 0 t.integer :runs, default: 0 t.integer :hits, default: 0 t.integer :doubles, default: 0 t.integer :triples, default: 0 t.integer :home_runs, default: 0 t.integer :rbi, default: 0 t.integer :steals, default: 0 t.integer :caught_stealing, default: 0 t.integer :sacrifice_hits, default: 0 t.integer :sacrifice_flies, default: 0 t.integer :f_errors, default: 0 t.integer :pb, default: 0 t.integer :walks, default: 0 t.integer :struck_out, default: 0 t.integer :hit_by_pitch, default: 0 t.integer :wins, default: 0 t.integer :losses, default: 0 t.integer :saves, default: 0 t.integer :complete_games, default: 0 t.integer :shut_outs, default: 0 t.integer :earned_runs, default: 0 t.integer :hit_batter, default: 0 t.integer :wild_pitches, default: 0 t.integer :balk, default: 0 t.integer :walked_batter, default: 0 t.integer :struck_out_batter, default: 0 t.integer :tb, default: 0 t.decimal :era, default: 0.0, precision: 10, scale: 3 t.decimal :innings, default: 0.0, precision: 10, scale: 3 t.decimal :slg, default: 0.0, precision: 10, scale: 3 t.decimal :obp, default: 0.0, precision: 10, scale: 3 t.decimal :ops, default: 0.0, precision: 10, scale: 3 t.decimal :avg, default: 0.0, precision: 10, scale: 3 t.timestamps null: false end end end
class User < ActiveRecord::Base has_and_belongs_to_many :permissions acts_as_authentic :logged_in_timeout => 60.minutes, :password_field_validates_presence_of_options => { :on => :update, :if => :update_password? } attr_accessor :dont_update_password def current_or_last_ip current_login_ip || last_login_ip end def current_or_last_at current_login_at || last_login_at end def has_permission?(permission) return true if self.permissions.find( :first, :conditions => { :identifier => permission.to_s } ) return false end def deliver_password_reset_instructions! reset_perishable_token! Notifier.deliver_password_reset_instructions( self ) end def deliver_email_with_password!( password ) Notifier.deliver_email_with_password( self, password ) end def self.generate_password Base64.encode64( Digest::SHA1.digest( "#{rand(1<<64)}/#{Time.now.to_f}/#{Process.pid}" ) )[0..8] end private def update_password? not @dont_update_password end end
module Rockauth class MigrationsGenerator < Rails::Generators::Base def install_migrations Dir[File.expand_path("../../../../db/migrate/*.rb", __FILE__)].each do |file| copy_file file, "db/migrate/#{File.basename(file)}" end end end end
require 'rails_helper' require 'platforms/yammer/client' module Platforms module Yammer RSpec.shared_examples "API module" do |mod| let(:klass) { Api.const_get(mod.camelize) } it { expect(client.send(mod)).to be_a klass } describe "constructor" do before(:each) do allow(klass).to receive(:new).with(client.connection) client.send(mod) end it "received #new with Faraday::Connection" do expect(klass).to have_received(:new). once. with(client.connection) end end end RSpec.shared_examples "generic GET request" do before(:each) do stub_request(:get, "#{api_base}/nonexist/current.json?a=b"). with( headers: { 'Authorization' => "Bearer #{token}", 'Custom' => "headings" } ). to_return( body: body.to_json, headers: { "CONTENT-TYPE" => "application/json" } ) end it "response" do response = client.request :get, "nonexist/current.json", { a: "b" }, headers expect(response.body).to match(body) end end # Test this in the context of a controller, with env RSpec.describe Client do let(:token) { "shakenn0tst1rr3d" } let(:client) { Client.new token } describe "#new" do it { expect(client).to be_a Platforms::Yammer::Client } it { expect(client.connection).to be_a Faraday::Connection } end describe "#request" do let(:headers) { { "custom" => "headings" } } let(:body) { { hello: "world" }.with_indifferent_access } let(:api_base) { "https://www.yammer.com/api/v1" } describe "with client block" do let(:client) do Client.new token do |f| f.use Faraday::Response::RaiseError end end before(:each) do stub_request(:get, "#{api_base}/nonexist/current.json"). with( headers: { 'Authorization' => "Bearer #{token}", } ). to_return( status: 401, body: "Not Authorized" ) end it do expect { client.request :get, "nonexist/current.json" }. to raise_error Faraday::UnauthorizedError end end describe "GET with endpoint and query string" do it_behaves_like "generic GET request" end describe "POST with endpoint and body" do let(:params) { {"a" => "b"}.to_json } before(:each) do stub_request(:post, "#{api_base}/nonexist/current.json"). with( headers: { 'Authorization' => "Bearer #{token}", 'Custom' => "headings" }, body: params ). to_return( body: body.to_json, headers: { "CONTENT-TYPE" => "application/json" } ) end it "response" do response = client.request :post, "nonexist/current.json", params, headers expect(response.body).to match(body) end end describe "GET with alternative endpoint" do let(:api_base) { "https://www.yammer.com/api/v2" } before(:each) do Platforms::Yammer.configure do |c| c.api_base = api_base end end after(:each) do Platforms::Yammer.configure do |c| c.api_base = "https://www.yammer.com/api/v1" end end it_behaves_like "generic GET request" end end it_behaves_like "API module", "messages" it_behaves_like "API module", "pending_attachments" it_behaves_like "API module", "uploaded_files" it_behaves_like "API module", "threads" it_behaves_like "API module", "topics" it_behaves_like "API module", "group_memberships" it_behaves_like "API module", "groups" it_behaves_like "API module", "users" it_behaves_like "API module", "relationships" it_behaves_like "API module", "streams" it_behaves_like "API module", "suggestions" it_behaves_like "API module", "subscriptions" it_behaves_like "API module", "invitations" it_behaves_like "API module", "search" it_behaves_like "API module", "networks" it_behaves_like "API module", "open_graph_objects" it_behaves_like "API module", "supervisor_mode" it_behaves_like "API module", "oauth" end end end
class BackgroundsController < ApplicationController def index list render("list") end def list @backgrounds = Background.all end def show @background = Background.find(params[:id]) end def new @background = Background.new end def create @background = Background.new(background_params) if @background.save flash[:notice] = "Background created." redirect_to(:action => 'list') else render('new') end end def edit @background = Background.find(params[:id]) end def update @background = Background.find(params[:id]) if @background.update_attributes(background_params) flash[:notice] = "Background updated." redirect_to(:action => 'list') else render('new') end end def delete @background = Background.find(params[:id]) end def destroy @background = Background.find(params[:id]) @background.destroy flash[:notice] = "Background deleted." redirect_to(:action => 'list') end private def background_params params.require(:background).permit(:name, :file_url) end end
require 'codily/elements/service_belongging_base' module Codily module Elements class Condition < ServiceBelonggingBase def_attr *%i( comment priority statement ) def setup delete_if_empty! *%i( comment ) force_integer! *%i( priority ) end def type(obj = nil) getset :type, obj.to_s.upcase end def fastly_class Fastly::Condition end end end end
require 'rails_helper' RSpec.describe 'タスク管理機能', type: :system do let!(:basic_user) { FactoryBot.create(:basic_user) } let!(:task) { FactoryBot.create(:task, user:basic_user) } let!(:second_task) { FactoryBot.create(:second_task, user: basic_user) } before do visit new_session_path fill_in 'session[email]', with: 'basic_email@gmail.com' fill_in 'session[password]', with:'basicuser' click_button 'ログイン' end describe '新規作成機能' do context 'タスクを新規作成した場合' do it '作成したタスクが表示される' do visit new_task_path fill_in 'task[title]', with: 'test_title' fill_in 'task[content]', with: 'test_content' fill_in 'task[expired_at]', with: '2021-08-11 00:00:00'.to_date find('.field_status').set('着手中') find('.field_priority').set('中') click_button '送信' expect(page).to have_content 'test_title' expect(page).to have_content 'test_content' expect(page).to have_content '着手中' expect(page).to have_content '中' end end end describe '一覧表示機能' do context '一覧画面に遷移した場合' do it '作成済みのタスク一覧が表示される' do visit tasks_path expect(page).to have_content 'test_title' end end context 'タスクが作成日時の降順に並んでいる場合' do it '新しいタスクが一番上に表示される' do task = FactoryBot.create(:task, user:basic_user, title: 'new') visit tasks_path task_list = all('.task_row') expect(task_list[0]).to have_content 'new' end end context 'タスクが終了期限の降順に並んでいる場合' do it '終了期限が遠いタスクが一番上に表示される' do task = FactoryBot.create(:task, user:basic_user, title: 'limit_far', expired_at:'2021-09-12 00:00:00') visit tasks_path task_list = all('.task_row') expect(task_list[0]).to have_content 'limit_far' end end context '優先順位ソートというリンクを押した場合' do it '優先順位の高い順に並び替えられたタスク一覧が表示される' do task = FactoryBot.create(:task, user:basic_user, title: 'priority_high', priority:'高') visit tasks_path task_list = all('.task_row') expect(task_list[0]).to have_content 'priority_high' end end end describe '詳細表示機能' do context '任意のタスク詳細画面に遷移した場合' do it '該当タスクの内容が表示される' do visit task_path(task.id) expect(page).to have_content 'test_title' end end end describe '検索機能' do before do FactoryBot.create(:task, user:basic_user, title: 'task') FactoryBot.create(:second_task, user:basic_user, title: 'sample') visit tasks_path end context 'タイトルであいまい検索をした場合' do it "検索キーワードを含むタスクで絞り込まれる" do fill_in 'search_title', with: 'task' click_button '検索' expect(page).to have_content 'task' end end context 'ステータス検索をした場合' do it "ステータスに完全一致するタスクが絞り込まれる" do select '未着手', from: 'search_status' click_button '検索' expect(page).to have_content '未着手' end end context 'タイトルのあいまい検索とステータス検索をした場合' do it "検索キーワードをタイトルに含み、かつステータスに完全一致するタスク絞り込まれる" do fill_in 'search_title', with: 'task' select '未着手', from: 'search_status' click_button '検索' expect(page).to have_content 'task' expect(page).to have_content '未着手' end end end end
require "administrate/base_dashboard" class BarcodeDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages throughout the dashboard. ATTRIBUTE_TYPES = { discount_card: Field::BelongsTo, barcode_type: Field::BelongsTo, id: Field::Number, barcode: Field::String, discount_percentage: Field::Number.with_options(decimals: 2), extra_info: Field::String, created_at: Field::DateTime, updated_at: Field::DateTime, }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. COLLECTION_ATTRIBUTES = [ :discount_card, :barcode_type, :id, :barcode, ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. SHOW_PAGE_ATTRIBUTES = [ :discount_card, :barcode_type, :id, :barcode, :discount_percentage, :extra_info, :created_at, :updated_at, ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. FORM_ATTRIBUTES = [ :discount_card, :barcode_type, :barcode, :discount_percentage, :extra_info, ].freeze # Overwrite this method to customize how barcodes are displayed # across all pages of the admin dashboard. # # def display_resource(barcode) # "Barcode ##{barcode.id}" # end end
# Write a Producer thread and a Consumer thread that share a fixed-size buffer # and an index to access the buffer. The Producer should place numbers into the # buffer, while the Consumer should remove the numbers. The order in which the # numbers are added or removed is not important. class IntBuffer require 'thread' BUFFER_SIZE = 8 def initialize @index = 0 @buffer = Array.new(BUFFER_SIZE) @mutex = Mutex.new @resource = ConditionVariable.new end def add num @mutex.synchronize do while @index == (@buffer.size - 1) do begin @resource.wait(@mutex) rescue => e puts "Error in IntBuffer class: #{e.message}" end end @buffer[@index] = num @index += 1 @resource.signal end end def remove @mutex.synchronize do while @index == 0 do begin @resource.wait(@mutex) rescue => e puts "Error in IntBuffer class: #{e.message}" end end @index -= 1 ret = @buffer[@index] @resource.signal return ret end end end class Producer require 'thread' def initialize buffer @buffer = buffer @semaphore = Mutex.new end def run p = Thread.new do @semaphore.synchronize do while true do begin num = rand(1000) @buffer.add num puts "Produced #{num}" rescue => e puts "Error in Producer class: #{e.message}" end end end end #p.join end end class Consumer require 'thread' def initialize buffer @buffer = buffer @semaphore = Mutex.new end def run c = Thread.new do @semaphore.synchronize do while true do begin num = @buffer.remove puts "Consumer #{num}" rescue => e puts "Error in Consumer class: #{e.message}" end end end end #c.join end end # Trying some examples if __FILE__ == $0 b = IntBuffer.new p = Producer.new b c = Consumer.new b p.run c.run end
class Tekka < Formula desc "Individual-based simulator of pacific bluefin tuna" homepage "https://github.com/heavywatal/tekka" url "https://github.com/heavywatal/tekka/archive/v0.7.1.tar.gz" sha256 "cba04ddd16815ac653a875e1153429d9fce43cd73b1ffbde263bdee9ceb5be28" head "https://github.com/heavywatal/tekka.git" depends_on "cmake" => :build depends_on "clippson" depends_on "cxxwtl" def install mkdir "build" do cmake_args = std_cmake_args cmake_args << "-DBUILD_TESTING=OFF" << ".." system "cmake", *cmake_args system "make", "install" end end test do system bin/"tekka" (testpath/"test.cpp").write <<~EOS #include <tekka/program.hpp> int main(int argc, char* argv[]) { std::vector<std::string> args(argv + 1, argv + argc); pbf::Program program(args); program.run(); return 0; } EOS system ENV.cxx, "test.cpp", "-std=c++11", "-I#{include}", "-L#{lib}", "-ltekka", "-o", "test" system "./test" end end
namespace :db do desc "Load default contacts for users" task :analyze => :environment do puts '' puts 'Running database analysis task...' puts "\tThis task will scan the database for errors and log them to a file" load_user_default_emails end end # See if this user has default email contacts information to enter def load_user_default_emails template_data = YAML::load(File.open("#{Rails.root}/config/user_default_emails.yml")) user_data = nil user_data = template_data['users'][self.email] if template_data['users'].has_key?(self.email) if not user_data.nil? user_data.each do |f| next if f['email']== self.email if not(self.has_finalizer? and f['role_id'].to_i == 3) ude = self.user_default_emails.build(:email=>f['email'],:role_id=>f['role_id']) ude.save! end end end end
class Article < ApplicationRecord include PermissionsConcern has_many :has_categories, dependent: :delete_all has_many :categories, through: :has_categories has_many :comments after_create :categories belongs_to :user validates :title, uniqueness: true validates :title, :body, presence: true #validate :validate_categories scope :ultimos, -> {order("created_at DESC")} scope :otro, -> {where(title: "Fotografía historica")} scope :titulo, -> (search){where("title like ?","%#{search}%")} def categories=(value) @categories = value save_categories end def getCategories @categories end private def save_categories @categories.each do |category_id| HasCategory.create(category_id: category_id, article_id: self.id) end end def validate_categories if self.getCategories.blank? errors.add(:categories, "debe agregar una categoría...") end end end
namespace :db do desc "Fill database with sample data" task populate: :environment do make_users make_microposts make_relationships make_subjects make_topics make_grades make_user_groups make_items #make_sub_items make_test_sheets make_schedule end end def make_users admin = User.create!(name: "Admin", email: "admin@ad.min", password: "foobar", password_confirmation: "foobar") admin.toggle!(:admin) test_admin = User.create!(name: "Test Admin", email: "test@ad.min", password: "foobar", password_confirmation: "foobar") test_admin.toggle!(:test_admin) test_admin.toggle!(:scorer) test_admin.toggle!(:super_user) 10.times do |n| name = Faker::Name.name email = "test#{n+1}@test.com" password = "foobar" user = User.create!(name: name, email: email, password: password, password_confirmation: password) user.relate!(test_admin) end end def make_microposts users = User.all(limit: 6) 10.times do content = Faker::Lorem.sentence(5) users.each { |user| user.microposts.create!(content: content) } end end def make_relationships users = User.all user = users.first followed_users = users[2..10] followers = users[3..8] followed_users.each { |followed| user.follow!(followed) } followers.each { |follower| follower.follow!(user) } end def make_subjects subjects = [ "Physics", "Chemical", "Mathematics", "Art", "Astronomy", "Geography", "Genocide", "Science", "Computer science", "Information technology", "Engineering", "Business", "Economics" ] subjects.each{|s| subject = Subject.create!(name: s) } end def make_topics topics = [ [1, "Acceleration"], [1, "Concepts in physics"], [1, "Friction"], [1, "Interaction"], [1, "Waves"], [2, "Gas laws"], [2, "Solubility"], [2, "Chemical kinetics"], [2, "Thermodynamics"], [2, "Electrochemistry"], [2, "Conservation of mass"], [2, "Conservation of energy"], [3, "Algebra"], [3, "Arithmetic"], [3, "Geometry"], [3, "Exponentials"], [3, "Logarithms"] ] topics.each{|t| topic = Topic.create!(subject_id: t[0], name: t[1]) } end def make_grades grades = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ] grades.each{|g| grade = Grade.create!(name: g) } end def make_user_groups groups = [ "MIT", "CIA", "MIB" ] groups.each{|g| group = UserGroup.create!(name: g) } end def make_items ta = User.find(2) 3.times do |i| item = ta.items.create!(title: "Test Item #{i+1}", subject_id: 1, topic_id: 1, grade_from: 1, grade_to: 12, printable: true, succession: true, item_stem: Faker::Lorem.sentence(5), rational: Faker::Lorem.sentence(3), public: true ) make_sub_items(item) end end def make_sub_items(item) #item = Item.find(1) item_id = item.id # best answer subitem = item.si_best_answers.build( item_id: item_id, question: Faker::Lorem.sentence(5) ) subitem.save 5.times do |i| ans = i == 2 ? true : false option = subitem.si_best_answer_options.build( text: Faker::Lorem.sentence(5), best_answer: ans ) option.save end ct = subitem.coding_tables.build(title: Faker::Lorem.word) ct.save ctd = ct.coding_table_data.build(code: '1', definition: '2') ctd.save # tf choices subitem = item.si_tf_choices.build( item_id: item_id, question: Faker::Lorem.sentence(5) ) subitem.save 5.times do |i| ans = i >= 2 ? true : false option = subitem.si_tf_choice_options.build( text: Faker::Lorem.sentence(5), true_answer: ans ) option.save end ct = subitem.coding_tables.build(title: Faker::Lorem.word) ct.save ctd = ct.coding_table_data.build(code: '2', definition: '2,3,4') ctd.save ctd = ct.coding_table_data.build(code: '1', definition: '2,3') ctd.save # essay subitem = item.si_essays.build( item_id: item_id, question: Faker::Lorem.sentence(5) ) subitem.save ct = subitem.coding_tables.build(title: Faker::Lorem.word) ct.save 3.times do |i| ctd = ct.coding_table_data.build( code: (2-i).to_s, definition: Faker::Lorem.sentence(5), criterion: Faker::Lorem.sentence(5), example: Faker::Lorem.sentence(5) ) ctd.save end # fill_table subitem = item.si_fill_tables.build( item_id: item_id, question: Faker::Lorem.sentence(5), table_content: Faker::Lorem.sentence(5) ) subitem.save ct = subitem.coding_tables.build(title: Faker::Lorem.word) ct.save 3.times do |i| ctd = ct.coding_table_data.build( code: (2-i).to_s, definition: Faker::Lorem.sentence(5), criterion: Faker::Lorem.sentence(5), example: Faker::Lorem.sentence(5) ) ctd.save end end def make_test_sheets ta = User.find(2) sheet = ta.test_sheets.create!(title: 'Test 1', subject_id: 1, topic_id: 1, grade_from: 1, grade_to: 12, description: "This is Test 1.", public: true ) items = Item.all items.each do |item| sheet.add_item!(item.id) end end def make_schedule ta = User.find(2) schedule = ta.schedules.create!( title: 'Test schedule 1', time: 60, date_from: '2013/1/1', date_to: '2013/12/31', test_sheet_id: TestSheet.first.id ) group = schedule.test_groups.build( name: 'Test group alpha', username: 'test', password: 'test', ) group.save end
class Puppy def initialize puts "Initializing new puppy instance..." end def fetch(toy) puts "I brought back the #{toy}!" toy end def speak(number_of_barks) i = 0 while i < number_of_barks puts "woof" i += 1 end end def roll_over puts "roll over" end def dog_years(human_years) dog_age = human_years * 7 puts dog_age return dog_age end def play_dead puts "play dead" end end #Driver Code kody = Puppy.new kody.fetch("ball") kody.speak(5) kody.roll_over kody.dog_years(6) kody.play_dead class Dancer def initialize puts "Initializing new dancer instance.." end def jump puts "Jumping..." end def twirl puts "Twirling..." end end dance_team = [] until dance_team.length >= 50 dancer = Dancer.new dance_team.push dancer end dance_team.each do |x| x.jump x.twirl end
# frozen_string_literal: true class CreateChallenges < ActiveRecord::Migration[5.1] def change create_table :challenges do |t| t.belongs_to :record_book, null: false t.string :name, null: false t.integer :challenge_type, null: false t.boolean :repeatable, default: false, null: false t.jsonb :points, default: {}, null: false t.timestamps end end end
begin_registration_time = Time.parse '2012-09-10 11:13:02 UTC' Fabricator(:voter) do # legacy_id is a eight hex symbols legacy_id { (rand(16 ** 8) + (16 * 7 + 1)).to_s(16) } registered_at do sequence(:registered_at) { |i| begin_registration_time + i.minutes } end phone_number { '...' + rand(999).to_s } status { Voter::STATUSES.keys.sample } mmm false end
describe IGMarkets::PayloadFormatter do class PayloadModel < IGMarkets::Model attribute :the_string attribute :the_symbol, Symbol, allowed_values: [:two_three] attribute :the_date, DateTime, format: '%Y/%m/%d' end it 'formats payloads correctly' do model = PayloadModel.new the_string: 'string', the_symbol: :two_three, the_date: '2010/10/20' expect(IGMarkets::PayloadFormatter.format(model)).to eq( theString: 'string', theSymbol: 'TWO_THREE', theDate: '2010/10/20') end it 'camel cases snake case strings' do expect(IGMarkets::PayloadFormatter.snake_case_to_camel_case('one')).to eq(:one) expect(IGMarkets::PayloadFormatter.snake_case_to_camel_case('one_two_three')).to eq(:oneTwoThree) end end
require 'spec_helper' # Tests for RobotView describe RobotView do # Create a new instance for each test before :each do @view = RobotView.new end # Test initialize describe "#new" do it "is an instance of RobotView" do expect(@view).to be_an_instance_of(RobotView) end end # Test displayOutput # Expect displayOutput to display input parameters as in. describe "#displayOutput" do it "when x, y or face is nil" do expect{@view.displayOutput(nil, nil, nil)}.to raise_error(ArgumentError) expect{@view.displayOutput(nil, 0, Direction::N)}.to raise_error(ArgumentError) expect{@view.displayOutput(0, nil, Direction::N)}.to raise_error(ArgumentError) expect{@view.displayOutput(0, 0, nil)}.to raise_error(ArgumentError) end it "when x, y and face are supplied" do expect{@view.displayOutput(0, 0, "unknown")}.to output(/^.*0,0,unknown.*$/).to_stdout expect{@view.displayOutput(2, 3, Direction::N)}.to output(/^.*2,3,NORTH.*$/).to_stdout end end # Test captureInput # Expect captureInput to return input as in. describe "#captureInput" do it "when input is empty" do expect(@view).to receive(:gets).and_return("") expect(@view.captureInput()).to eq("") end it "when input is a string" do expect(@view).to receive(:gets).and_return("testing") expect(@view.captureInput()).to eq("testing") end end end
class GlobalTemplatesQuery < Types::BaseResolver description "Gets all the global templates" type Outputs::TemplateType.connection_type, null: false policy ApplicationPolicy, :logged_in? def authorized_resolve Template.global end end
class LocationHelper # merge the specified set of locations, keeping the first location in the collection def self.merge_locations(locations) return nil if locations.blank? return locations.first if locations.size == 1 location = locations.delete_at(0) company = location.company add_tags = [] # puts "*** keeping location: #{location.company_name}:#{location.id}" locations.each do |remove_location| # puts "*** removing location: #{remove_location.name}:#{remove_location.id}" remove_location.companies.each do |remove_company| # merge tags if !remove_company.tag_list.blank? company.tag_list.add(remove_company.tag_list) company.save end # remove company remove_company.destroy end # merge location phone numbers remove_location.phone_numbers.each do |lp| # destroy phone before merging it lp.destroy location.phone_numbers.push(PhoneNumber.new(:name => lp.name, :address => lp.address)) end # merge location sources remove_location.location_sources.each do |ls| location.location_sources.push(LocationSource.new(:location => @location, :source_id => ls.source_id, :source_type => ls.source_type)) ls.destroy end # remove location remove_location.destroy end end end
class Chapter < ApplicationRecord belongs_to :user belongs_to :learning has_one_attached :video end
# frozen_string_literal: true require 'stannum/contracts/parameters_contract' require 'support/examples/constraint_examples' require 'support/examples/contract_builder_examples' require 'support/examples/contract_examples' RSpec.describe Stannum::Contracts::ParametersContract do include Spec::Support::Examples::ConstraintExamples include Spec::Support::Examples::ContractExamples shared_context 'when the contract has many argument constraints' do let(:constraints) do [ { constraint: Stannum::Constraints::Presence.new, options: { argument: 'name' } }, { constraint: Stannum::Constraints::Presence.new, options: { argument: 'size' } }, { constraint: Stannum::Constraints::Type.new(Integer), options: { argument: 'mass' } } ] end before(:example) do constraints.each do |definition| argument = definition[:options][:argument] constraint = definition[:constraint] contract.add_argument_constraint( nil, constraint, property_name: argument ) end end end shared_context 'when the contract has a variadic arguments constraint' do before(:example) do contract.set_arguments_item_constraint(:values, String) end end shared_context 'when the contract has many keyword constraints' do let(:constraints) do [ { constraint: Stannum::Constraints::Presence.new, options: { keyword: :payload } }, { constraint: Stannum::Constraints::Presence.new, options: { keyword: :propellant } }, { constraint: Stannum::Constraints::Type.new(Integer), options: { keyword: :fuel } } ] end before(:example) do constraints.each do |definition| keyword = definition[:options][:keyword] constraint = definition[:constraint] contract.add_keyword_constraint(keyword, constraint) end end end shared_context 'when the contract has a variadic keywords constraint' do before(:example) do contract.set_keywords_value_constraint(:options, String) end end shared_context 'when the contract has a block constraint' do before(:example) { contract.set_block_constraint(true) } end subject(:contract) do described_class.new(**constructor_options, &constructor_block) end let(:constructor_block) { -> {} } let(:constructor_options) { {} } let(:expected_options) do { allow_extra_keys: false, key_type: nil, value_type: nil } end describe '::Builder' do include Spec::Support::Examples::ContractBuilderExamples subject(:builder) { described_class.new(contract) } let(:described_class) { super()::Builder } let(:contract) do Stannum::Contracts::ParametersContract.new # rubocop:disable RSpec/DescribedClass end describe '.new' do it { expect(described_class).to be_constructible.with(1).argument } end describe '#argument' do let(:options) { {} } let(:name) { :description } before(:example) do allow(contract).to receive(:add_argument_constraint) end it { expect(builder.argument name, String).to be builder } it 'should define the method' do expect(builder) .to respond_to(:argument) .with(1..2).arguments .and_any_keywords .and_a_block end describe 'with nil' do let(:error_message) do 'invalid constraint nil' end it 'should raise an error' do expect { builder.argument(name, nil) } .to raise_error ArgumentError, error_message end end describe 'with an object' do let(:object) { Object.new.freeze } let(:error_message) do "invalid constraint #{object.inspect}" end it 'should raise an error' do expect { builder.argument(name, object) } .to raise_error ArgumentError, error_message end end describe 'with a block' do let(:implementation) { -> {} } it 'should delegate to #add_argument_constraint' do builder.argument(name, &implementation) expect(contract) .to have_received(:add_argument_constraint) .with(nil, an_instance_of(Stannum::Constraint), property_name: name) end it 'should pass the implementation' do allow(contract).to receive(:add_argument_constraint) \ do |_index, constraint, _options| constraint.matches?(nil) end expect { |block| builder.argument(name, &block) }.to yield_control end end describe 'with a block and options' do let(:implementation) { -> {} } let(:options) { { key: 'value' } } it 'should delegate to #add_argument_constraint' do builder.argument(name, **options, &implementation) expect(contract) .to have_received(:add_argument_constraint) .with( nil, an_instance_of(Stannum::Constraint), property_name: name, **options ) end end describe 'with a block and a constraint' do let(:constraint) { Stannum::Constraints::Type.new(String) } let(:implementation) { -> {} } let(:error_message) do 'expected either a block or a constraint instance, but received ' \ "both a block and #{constraint.inspect}" end it 'should raise an error' do expect { builder.argument(name, constraint, &implementation) } .to raise_error ArgumentError, error_message end end describe 'with a class' do let(:type) { String } it 'should delegate to #add_argument_constraint' do builder.argument(name, type) expect(contract) .to have_received(:add_argument_constraint) .with(nil, type, property_name: name) end end describe 'with a class and options' do let(:type) { String } let(:options) { { key: 'value' } } it 'should delegate to #add_argument_constraint' do builder.argument(name, type, **options) expect(contract) .to have_received(:add_argument_constraint) .with(nil, type, property_name: name, **options) end end describe 'with a constraint' do let(:constraint) { Stannum::Constraints::Type.new(String) } it 'should delegate to #add_argument_constraint' do builder.argument(name, constraint) expect(contract) .to have_received(:add_argument_constraint) .with(nil, constraint, property_name: name) end end describe 'with a constraint and options' do let(:constraint) { Stannum::Constraints::Type.new(String) } let(:options) { { key: 'value' } } it 'should delegate to #add_argument_constraint' do builder.argument(name, constraint, **options) expect(contract) .to have_received(:add_argument_constraint) .with(nil, constraint, property_name: name, **options) end end end describe '#arguments' do let(:name) { :args } let(:type) { String } before(:example) do allow(contract).to receive(:set_arguments_item_constraint) end it { expect(builder).to respond_to(:arguments).with(2).arguments } it 'should delegate to #set_arguments_item_constraint' do builder.arguments(name, type) expect(contract) .to have_received(:set_arguments_item_constraint) .with(name, type) end it { expect(builder.arguments(name, type)).to be builder } end describe '#block' do let(:present) { true } before(:example) do allow(contract).to receive(:set_block_constraint) end it { expect(builder).to respond_to(:block).with(1).argument } it 'should delegate to #set_block_constraint' do builder.block(present) expect(contract).to have_received(:set_block_constraint).with(present) end it { expect(builder.block(true)).to be builder } end describe '#contract' do include_examples 'should define reader', :contract, -> { contract } end describe '#keyword' do let(:options) { {} } let(:name) { :format } before(:example) do allow(contract).to receive(:add_keyword_constraint) end it 'should define the method' do expect(builder) .to respond_to(:keyword) .with(1..2).arguments .and_any_keywords .and_a_block end it { expect(builder.keyword(name, String)).to be builder } describe 'with nil' do let(:error_message) do 'invalid constraint nil' end it 'should raise an error' do expect { builder.keyword(name, nil) } .to raise_error ArgumentError, error_message end end describe 'with an object' do let(:object) { Object.new.freeze } let(:error_message) do "invalid constraint #{object.inspect}" end it 'should raise an error' do expect { builder.keyword(name, object) } .to raise_error ArgumentError, error_message end end describe 'with a block' do let(:implementation) { -> {} } let(:expected) do ary = [name, an_instance_of(Stannum::Constraint)] RUBY_VERSION < '3.0' ? ary << {} : ary end it 'should delegate to #add_keyword_constraint' do builder.keyword(name, &implementation) expect(contract) .to have_received(:add_keyword_constraint) .with(*expected) end it 'should pass the implementation' do allow(contract).to receive(:add_keyword_constraint) \ do |_name, constraint, _options| constraint.matches?(nil) end expect { |block| builder.keyword(name, &block) }.to yield_control end end describe 'with a block and options' do let(:implementation) { -> {} } let(:options) { { key: 'value' } } it 'should delegate to #add_keyword_constraint' do builder.keyword(name, **options, &implementation) expect(contract) .to have_received(:add_keyword_constraint) .with( name, an_instance_of(Stannum::Constraint), **options ) end end describe 'with a block and a constraint' do let(:constraint) { Stannum::Constraints::Type.new(String) } let(:implementation) { -> {} } let(:error_message) do 'expected either a block or a constraint instance, but received ' \ "both a block and #{constraint.inspect}" end it 'should raise an error' do expect { builder.keyword(name, constraint, &implementation) } .to raise_error ArgumentError, error_message end end describe 'with a class' do let(:type) { String } let(:expected) do ary = [name, type] RUBY_VERSION < '3.0' ? ary << {} : ary end it 'should delegate to #add_keyword_constraint' do builder.keyword(name, type) expect(contract) .to have_received(:add_keyword_constraint) .with(*expected) end end describe 'with a class and options' do let(:type) { String } let(:options) { { key: 'value' } } it 'should delegate to #add_keyword_constraint' do builder.keyword(name, type, **options) expect(contract) .to have_received(:add_keyword_constraint) .with(name, type, **options) end end describe 'with a constraint' do let(:constraint) { Stannum::Constraints::Type.new(String) } let(:expected) do ary = [name, constraint] RUBY_VERSION < '3.0' ? ary << {} : ary end it 'should delegate to #add_keyword_constraint' do builder.keyword(name, constraint) expect(contract) .to have_received(:add_keyword_constraint) .with(*expected) end end describe 'with a constraint and options' do let(:constraint) { Stannum::Constraints::Type.new(String) } let(:options) { { key: 'value' } } it 'should delegate to #add_keyword_constraint' do builder.keyword(name, constraint, **options) expect(contract) .to have_received(:add_keyword_constraint) .with(name, constraint, **options) end end end describe '#keywords' do let(:name) { :kwargs } let(:type) { String } before(:example) do allow(contract).to receive(:set_keywords_value_constraint) end it { expect(builder).to respond_to(:keywords).with(2).arguments } it 'should delegate to #set_keywords_value_constraint' do builder.keywords(name, type) expect(contract) .to have_received(:set_keywords_value_constraint) .with(name, type) end it { expect(builder.keywords(name, String)).to be builder } end end describe '.new' do it 'should define the constructor' do expect(described_class) .to be_constructible .with(0).arguments .and_any_keywords .and_a_block end describe 'with a block' do let(:constructor_block) do lambda do argument :name, String keyword :payload, String end end let(:builder) do instance_double( described_class::Builder, argument: nil, keyword: nil ) end before(:example) do allow(described_class::Builder).to receive(:new).and_return(builder) end it 'should call the builder with the block', :aggregate_failures do described_class.new(&constructor_block) expect(builder).to have_received(:argument).with(:name, String) expect(builder).to have_received(:keyword).with(:payload, String) end end end include_examples 'should implement the Constraint interface' include_examples 'should implement the Constraint methods' include_examples 'should implement the Contract methods' describe '#add_argument_constraint' do let(:arguments_contract) { contract.send(:arguments_contract) } let(:expected) do ary = [nil, String] RUBY_VERSION < '3.0' ? ary << {} : ary end before(:example) do allow(arguments_contract).to receive(:add_argument_constraint) end it 'should define the method' do expect(contract) .to respond_to(:add_argument_constraint) .with(2).arguments .and_any_keywords end it { expect(contract.add_argument_constraint(nil, String)).to be contract } it 'should delegate to the arguments contract' do contract.add_argument_constraint(nil, String) expect(arguments_contract) .to have_received(:add_argument_constraint) .with(*expected) end describe 'with options' do let(:options) { { key: :value } } let(:expected) { [nil, String] } it 'should delegate to the arguments contract' do contract.add_argument_constraint(nil, String, **options) expect(arguments_contract) .to have_received(:add_argument_constraint) .with(*expected, **options) end end end describe '#add_keyword_constraint' do let(:keyword) { :option } let(:keywords_contract) { contract.send(:keywords_contract) } let(:expected) do ary = [keyword, String] RUBY_VERSION < '3.0' ? ary << {} : ary end before(:example) do allow(keywords_contract).to receive(:add_keyword_constraint) end it 'should define the method' do expect(contract) .to respond_to(:add_keyword_constraint) .with(2).arguments .and_any_keywords end it 'should return the contract' do expect(contract.add_keyword_constraint(keyword, String)) .to be contract end it 'should delegate to the keywords_contract contract' do contract.add_keyword_constraint(keyword, String) expect(keywords_contract) .to have_received(:add_keyword_constraint) .with(*expected) end describe 'with options' do let(:options) { { key: :value } } let(:expected) { [keyword, String] } it 'should delegate to the keywords contract' do contract.add_keyword_constraint(keyword, String, **options) expect(keywords_contract) .to have_received(:add_keyword_constraint) .with(*expected, **options) end end end describe '#arguments_contract' do let(:arguments_contract) { contract.send :arguments_contract } include_examples 'should have private reader', :arguments_contract, -> { be_a Stannum::Contracts::Parameters::ArgumentsContract } it { expect(arguments_contract.each_constraint.count).to be 2 } wrap_context 'when the contract has many argument constraints' do it { expect(arguments_contract.each_constraint.count).to be 5 } end end describe '#each_constraint' do let(:builtin_definitions) do [ be_a_constraint_definition( constraint: be_a_constraint( Stannum::Contracts::Parameters::SignatureContract ), contract: contract, options: { property: nil, sanity: true } ), be_a_constraint_definition( constraint: be_a_constraint( Stannum::Contracts::Parameters::ArgumentsContract ), contract: contract, options: { property: :arguments, property_type: :key, sanity: false } ), be_a_constraint_definition( constraint: be_a_constraint( Stannum::Contracts::Parameters::KeywordsContract ), contract: contract, options: { property: :keywords, property_type: :key, sanity: false } ) ] end let(:expected) { builtin_definitions } it { expect(contract).to respond_to(:each_constraint).with(0).arguments } it { expect(contract.each_constraint).to be_a Enumerator } it { expect(contract.each_constraint.count).to be 3 } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end wrap_context 'when the contract has a block constraint' do let(:block_definition) do be_a_constraint_definition( constraint: be_a_constraint(Stannum::Constraints::Types::ProcType), contract: contract, options: { property: :block, property_type: :key, sanity: false } ) end let(:expected) { builtin_definitions + [block_definition] } it { expect(contract.each_constraint.count).to be 4 } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end end end describe '#each_pair' do let(:actual) do { arguments: %w[ichi ni san], keywords: { foo: :bar }, block: -> {} } end let(:builtin_definitions) do [ be_a_constraint_definition( constraint: be_a_constraint( Stannum::Contracts::Parameters::SignatureContract ), contract: contract, options: { property: nil, sanity: true } ), be_a_constraint_definition( constraint: be_a_constraint( Stannum::Contracts::Parameters::ArgumentsContract ), contract: contract, options: { property: :arguments, property_type: :key, sanity: false } ), be_a_constraint_definition( constraint: be_a_constraint( Stannum::Contracts::Parameters::KeywordsContract ), contract: contract, options: { property: :keywords, property_type: :key, sanity: false } ) ] end let(:values) { [actual, actual[:arguments], actual[:keywords]] } let(:expected) { builtin_definitions.zip(values) } it { expect(contract).to respond_to(:each_pair).with(1).argument } it { expect(contract.each_pair(actual)).to be_a Enumerator } it { expect(contract.each_pair(actual).count).to be 3 } it 'should yield each definition' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end wrap_context 'when the contract has a block constraint' do let(:block_definition) do be_a_constraint_definition( constraint: be_a_constraint(Stannum::Constraints::Types::ProcType), contract: contract, options: { property: :block, property_type: :key, sanity: false } ) end let(:values) { super() + [actual[:block]] } let(:expected) { (builtin_definitions + [block_definition]).zip(values) } it { expect(contract.each_pair(actual).count).to be 4 } it 'should yield each definition' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end end end describe '#keywords_contract' do let(:keywords_contract) { contract.send(:keywords_contract) } include_examples 'should have private reader', :keywords_contract, -> { be_a Stannum::Contracts::Parameters::KeywordsContract } it { expect(keywords_contract.each_constraint.count).to be 2 } wrap_context 'when the contract has many keyword constraints' do it { expect(keywords_contract.each_constraint.count).to be 5 } end end describe '#set_arguments_item_constraint' do let(:arguments_contract) { contract.send(:arguments_contract) } before(:example) do allow(arguments_contract).to( receive(:set_variadic_item_constraint) .and_wrap_original { |fn, type, options| fn.call(type, **options) } ) end it 'should define the method' do expect(contract) .to respond_to(:set_arguments_item_constraint) .with(2).arguments end it 'should delegate to #set_variadic_item_constraint' do contract.set_arguments_item_constraint(:args, String) expect(arguments_contract) .to have_received(:set_variadic_item_constraint) .with(String, as: :args) end it 'should return the contract' do expect(contract.set_arguments_item_constraint(:args, String)) .to be contract end wrap_context 'when the contract has a variadic arguments constraint' do let(:error_message) { 'variadic arguments constraint is already set' } it 'should raise an error' do expect { contract.set_arguments_item_constraint(:args, String) } .to raise_error error_message end end end describe '#set_block_constraint' do it 'should define the method' do expect(contract).to respond_to(:set_block_constraint).with(1).argument end it 'should return the contract' do expect(contract.set_block_constraint(true)).to be contract end describe 'with nil' do let(:error_message) do 'present must be true or false or a constraint' end it 'should raise an error' do expect { contract.set_block_constraint(nil) } .to raise_error ArgumentError, error_message end end describe 'with an object' do let(:error_message) do 'present must be true or false or a constraint' end it 'should raise an error' do expect { contract.set_block_constraint(Object.new.freeze) } .to raise_error ArgumentError, error_message end end describe 'with false' do it 'should add a constraint' do expect { contract.set_block_constraint(false) } .to(change { contract.each_constraint.to_a.size }.by(1)) end it 'should set the block constraint', :aggregate_failures do contract.set_block_constraint(false) definition = contract.each_constraint.to_a.last expect(definition.constraint) .to be_a_constraint(Stannum::Constraints::Types::NilType) expect(definition.property).to be :block expect(definition.options[:property_type]).to be :key end end describe 'with true' do it 'should add a constraint' do expect { contract.set_block_constraint(true) } .to(change { contract.each_constraint.to_a.size }.by(1)) end it 'should set the block constraint', :aggregate_failures do contract.set_block_constraint(true) definition = contract.each_constraint.to_a.last expect(definition.constraint) .to be_a_constraint(Stannum::Constraints::Types::ProcType) .with_options(expected_type: Proc, required: true) expect(definition.property).to be :block expect(definition.options[:property_type]).to be :key end end describe 'with a constraint' do let(:constraint) { Stannum::Constraint.new(type: 'spec.type') } it 'should add a constraint' do expect { contract.set_block_constraint(constraint) } .to(change { contract.each_constraint.to_a.size }.by(1)) end it 'should set the block constraint', :aggregate_failures do contract.set_block_constraint(constraint) definition = contract.each_constraint.to_a.last expect(definition.constraint) .to be_a_constraint(Stannum::Constraint) .with_options(type: 'spec.type') expect(definition.property).to be :block expect(definition.options[:property_type]).to be :key end end wrap_context 'when the contract has a block constraint' do let(:error_message) { 'block constraint is already set' } it 'should raise an error' do expect { contract.set_block_constraint(true) } .to raise_error error_message end end end describe '#set_keywords_value_constraint' do let(:keywords_contract) { contract.send(:keywords_contract) } before(:example) do allow(keywords_contract).to( receive(:set_variadic_value_constraint) .and_wrap_original { |fn, type, options| fn.call(type, **options) } ) end it 'should define the method' do expect(contract) .to respond_to(:set_keywords_value_constraint) .with(2).arguments end it 'should delegate to #set_variadic_value_constraint' do contract.set_keywords_value_constraint(:kwargs, String) expect(keywords_contract) .to have_received(:set_variadic_value_constraint) .with(String, as: :kwargs) end it 'should return the contract' do expect(contract.set_keywords_value_constraint(:kwargs, String)) .to be contract end wrap_context 'when the contract has a variadic keywords constraint' do let(:error_message) { 'variadic keywords constraint is already set' } it 'should raise an error' do expect { contract.set_keywords_value_constraint(:kwargs, String) } .to raise_error error_message end end end end
# A line of people at an amusement park ride # There is a front to the line, as well as a back. # People may leave the line whenever they see fit and those behind them take their place. class Line attr_accessor :members attr_accessor :front, :back, :middle def initialize self.members = [] end def join(person) self.members[self.members.length] = person end def leave(person) self.members.delete(person) end def front self.front = self.members[0] end def middle self.middle = self.members[self.members.length / 2] end def back self.back = self.members[self.members.length - 1] end def search(person) self.members.each do |i| if i == person return i end end return nil end private def index(person) self.members.each_with_index do |i, index| if i == person return index end end end end
class AddYearIndexToPopulations < ActiveRecord::Migration[5.2] def change add_index :populations, :year end end
require 'sorting_strategy' require 'binary_heap' class HeapSort # Important Characteristics # 1. One of the best sorting methods being in-place and with no quadratic worst-case scenarios # 2. Involves two basic parts: # - Creating a Heap of the unsorted list # - Then a sorted array is created by repeatedly removing the largest/smallest element # from the heap and inserting it into the array. The heap is reconstructed after each removal. # Example: # array = [3, 2, 4, 5, 6, 1] # array = HeapSort.order(array) # puts array # Output: [1, 2, 3, 4, 5, 6] # Example: # array = [3, 2, 4, 5, 6, 1] # array = HeapSort.order(array, :desc => true) # puts array # Output: [6, 5, 4, 3, 2, 1] # # OR # # Example: # array = [3, 2, 4, 5, 6, 1] # heap_sort = HeapSort.new(array) # puts heap.array # Output: [1, 2, 3, 4, 5, 6] # # Example: # array = [3, 2, 4, 5, 6, 1] # insertion = HeapSort.new(array, :desc => true) # puts insertion.array # Output: [6, 5, 4, 3, 2, 1] # # # ### Get Time Complexity: # Example: # best = HeapSort::TIME_COMPLEXITY_BEST # worst = HeapSort::TIME_COMPLEXITY_WORST # average = HeapSort::TIME_COMPLEXITY_AVERAGE include SortingStrategy include BinaryHeap TIME_COMPLEXITY_WORST = "O(n log n)" TIME_COMPLEXITY_AVERAGE = "O(n log n)" TIME_COMPLEXITY_BEST = "O(n log n)" SPACE_COMPLEXITY = "O(n)" attr_reader :array, :desc def initialize array, desc=false unless array.is_a? Enumerable raise "Please provide an array or other Enumerable" end unless (array.all? {|item| item.is_a? Comparable}) raise "All objects must implement Comparable" end @array = array @desc = !!desc # sort as min heap if it wants it as descending order # sort as max heap otherwise @is_min_heap = @desc self.sort end def self.order array, desc=false instance = HeapSort.new array, desc=desc instance.array end protected def sort heap_sort array end def is_desc? @desc end def heap_sort array build_heap(array) n = array.length - 1 for heapsize in n.downto 1 swap array, 0, heapsize heapify array, 0, heapsize end end end
# frozen_string_literal: true require_relative 'transaction' require_relative 'transaction_history' require_relative 'bank_statement' class BankAccount def initialize(transaction_history = TransactionHistory.new, bank_statement = BankStatement.new) @balance = 0.00 @transaction_history = transaction_history @balance_logs = [] @bank_statement = bank_statement end def deposit(amount) transaction = Transaction.new('Credit', amount) @transaction_history.add_transaction(transaction.complete_transaction) end def withdraw(amount) transaction = Transaction.new('Debit', amount) @transaction_history.add_transaction(transaction.complete_transaction) end def calculate_balance @transaction_history.transaction_logs.each do |trnsaction| value = trnsaction[:value].to_f trnsaction[:type] == "Credit" ? @balance += value : @balance -= value add_to_balance_logs(trnsaction) end end def print_statement @bank_statement.print_statement(@balance_logs) end private def add_to_balance_logs(trnsaction) @balance_logs.push( date: trnsaction[:date], type: trnsaction[:type], amount: trnsaction[:value], balance: @balance ) end end
require('minitest/rg') require('minitest/autorun') require_relative('./sports_team') class TestSportsTeam < MiniTest::Test def setup @edinburgh = SportsTeam.new("Edinburgh Rugby", ["Grieg", "Jo"], "Vern") end def test_update_coach @edinburgh.update_coach("Jimmy") assert_equal("Jimmy", @edinburgh.coach) end def test_add_new_player @edinburgh.add_player("Howard") assert_equal("Howard", @edinburgh.players.pop) end def test_find_player found_player = @edinburgh.find_player("Grieg") assert_equal( "Grieg" , found_player ) end def test_update_points @edinburgh.update_points(true) assert_equal( 3 , @edinburgh.points ) end end
class CovidCase::Scraper def self.scrape_states doc = Nokogiri::HTML(open("https://coronavirus.jhu.edu/region")) states = doc.css("div.RegionMenu_items__3D_d2 a.Button_base__2nEBG.Button_style-filled-light__14tVT.Button_shape-square__31KW9.has-icon.null") states.collect do |state| name = state.text state_url = state.attribute("href").value CovidCase::States.new(name, state_url) end end def self.scrape_covid_stat(state) options = Selenium::WebDriver::Chrome::Options.new options.add_argument('--headless') driver = Selenium::WebDriver.for :chrome, options: options driver.navigate.to "https://coronavirus.jhu.edu#{state.state_url}" driver.manage.window.resize_to(800, 800) driver.save_screenshot "intoli-screenshot.png" ele = driver.find_element(css: '.RegionOverview_mainSections__3DQD7.RegionOverview_noBorder__1yP6L') state.stats << ele.text end end
module Decogator module Decoration module ClassMethods [:before, :around, :after, :tap].each do |advice| module_eval <<-EOS def #{advice}(*args, &block) __process_advice__(#{advice.inspect}, *args, &block) end EOS end def __process_advice__(advice, *args, &block) opts = args.last.is_a?(Hash) ? args.pop : {} decorator = block || opts[:call] || raise(ArgumentError, "no advice implementation specified") raise ArgumentError, "#{advice} advice cannot be implemented with a block" if [:tap, :around].include?(advice) && block_given? args.each { |meth| __advise_method__(meth, advice, decorator) } end def __advice_chain__ unless @__decogator_chain__ @__decogator_chain__ = Hash.new do |hash, key| prior = ancestors.detect { |a| a.respond_to?(:__advice_chain__) && a.__advice_chain__.has_key?(key) } init_with = prior ? prior.__advice_chain__[key] : instance_method(key) hash[key] = Decogator::Advice::Chain.new(init_with) end end @__decogator_chain__ end def __advise_method__(meth, advice, decorator) meth = meth.to_sym __advice_chain__[meth].send("add_#{advice}", decorator) module_eval <<-EOS def #{meth}(*args, &block) #{self}.__advice_chain__[#{meth.inspect}].call(self, *args, &block) end EOS end def method_added(meth) unless __advice_chain__.has_key?(meth) if ancestors.detect { |a| a.respond_to?(:__advice_chain__) && a.__advice_chain__.has_key?(meth) } __advice_chain__[meth]= Decogator::Advice::Chain.new(instance_method(meth)) end end end end def self.included(base) base.extend(ClassMethods) end end end
class CommentsController < ApplicationController def create @commentable = find_commentable @comment = @commentable.comments.new(comment_params) if @comment.save redirect_to :back else flash[:errors] = @comment.errors.full_messages redirect_to :back end end def find_commentable params.each do |name, value| capture = /(.+)_id$/.match(name) if capture return capture[1].classify.constantize.find(value) end end nil end def comment_params params.require(:comment).permit(:body) end end
class Changestatustenantstostring < ActiveRecord::Migration def change remove_column :tenants, :status, :boolean add_column :tenants, :status, :string end end
require 'faker' FactoryGirl.define do sec = Faker::Number.number(5) factory :timer do title { Faker::Lorem.word } kind { Timer.kind.values.sample } active { [true, false].sample } amount { sec } start_at { Time.zone.now } end_at { Time.zone.now + sec.to_i.seconds } association :user, :factory => :user end end
module ReverseMarkdown class Mapper attr_accessor :raise_errors attr_accessor :log_enabled, :log_level attr_accessor :li_counter attr_accessor :github_style_code_blocks def initialize(opts={}) self.log_level = :info self.log_enabled = true self.li_counter = 0 self.github_style_code_blocks = opts[:github_style_code_blocks] || false end def process_element(element) output = '' output << if element.text? process_text(element) else opening(element) end element.children.each do |child| output << process_element(child) end output << ending(element) unless element.text? output end private def opening(element) parent = element.parent ? element.parent.name.to_sym : nil case element.name.to_sym when :html, :body "" when :li indent = ' ' * [(element.ancestors('ol').count + element.ancestors('ul').count - 1), 0].max if parent == :ol "#{indent}#{self.li_counter += 1}. " else "#{indent}- " end when :pre "\n" when :ol self.li_counter = 0 "\n" when :ul, :root#, :p "\n" when :p if element.ancestors.map(&:name).include?('blockquote') "\n\n> " elsif [nil, :body].include? parent is_first = true previous = element.previous while is_first == true and previous do is_first = false unless previous.content.strip == "" || previous.text? previous = previous.previous end is_first ? "" : "\n\n" else "\n\n" end when :h1, :h2, :h3, :h4 # /h(\d)/ for 1.9 element.name =~ /h(\d)/ '#' * $1.to_i + ' ' when :em "*" when :strong "**" when :blockquote "> " when :code if parent == :pre self.github_style_code_blocks ? "\n```\n" : "\n " else " `" end when :a "[" when :img "![" when :hr "----------\n\n" else handle_error "unknown start tag: #{element.name.to_s}" "" end end def ending(element) parent = element.parent ? element.parent.name.to_sym : nil case element.name.to_sym when :html, :body, :pre, :hr, :p "" when :h1, :h2, :h3, :h4 # /h(\d)/ for 1.9 "\n" when :em '*' when :strong '**' when :li, :blockquote, :root, :ol, :ul "\n" when :code if parent == :pre self.github_style_code_blocks ? "\n```" : "\n" else '` ' end when :a "](#{element.attribute('href').to_s}) " when :img if element.has_attribute?('alt') "#{element.attribute('alt')}][#{element.attribute('src')}] " else "#{element.attribute('src')}] " end else handle_error "unknown end tag: #{element.name}" "" end end def process_text(element) parent = element.parent ? element.parent.name.to_sym : nil case when parent == :code && !self.github_style_code_blocks element.text.strip.gsub(/\n/,"\n ") else element.text.strip end end def handle_error(message) if raise_errors raise ReverseMarkdown::ParserError, message elsif log_enabled && defined?(Rails) Rails.logger.__send__(log_level, message) end end end end
# http://www.mudynamics.com # http://labs.mudynamics.com # http://www.pcapr.net require 'find' require 'set' require 'fileutils' require 'tempfile' require 'digest/md5' module PcaprLocal class Scanner # Creates scanner instance and starts it. def self.start config scanner = Scanner.new config scanner.start scanner end # Runs scanner loop in separate thread. def start Logger.info "Starting scanner thread" Thread.new do loop do begin scan @db.compact! rescue Exception => e Logger.error "Exception during scanning: #{e.message}\n" + e.backtrace.join("\n") end sleep @scan_interval end end end def initialize config @db = config.fetch('db') @xtractr = config.fetch('xtractr') @pcap_dir = File.expand_path(config.fetch('pcap_dir')) @index_dir = File.expand_path(config.fetch('index_dir')) @queue_delay = config.fetch('queue_delay') @scan_interval = config.fetch('interval') end # Removes doc from database and corresponding index file. # Does _not_ remove original pcap. def remove_doc doc @db.delete_doc(doc) if filename = doc['filename'] FileUtils.rm_f pcap_path(filename) remove_index_for(filename) end end def scan # Get list of all pcaps pcaps = self.find_pcaps # Cleanup db and queue new pcaps reconcile_with_db pcaps # Index queued pcaps. self.index end RE_PCAP = /\.p?cap\Z/ # Returns a set of pcap files (relative paths) def find_pcaps if not File.directory?(@pcap_dir) or not File.readable?(@pcap_dir) return Set.new end pcaps = Set.new pcap_prefix_size = @pcap_dir.size + 1 # / Find.find @pcap_dir do |path| # Don't recurse into ".pcapr_local" or other "." dirs if File.basename(path) =~ /^\./ Find.prune end # Should be a file ending in .cap or .pcap next unless path =~ RE_PCAP and File.file?(path) rel_path = path[pcap_prefix_size..-1] pcaps << rel_path end pcaps end def requeue_pcap rel_path res = @db.view("pcaps/by_filename", :key => rel_path) return nil if res['rows'].empty? id = res['rows'][0]["id"] @db.update_doc id do |doc| doc['status'] = 'queued' doc.delete 'index' doc end end # Adds pcap to db with status set to "queued". Returns nil w/out # updating db if the pcap was modified within the last queue_delay # seconds (because pcap may not be completely copied to pcap_dir). def add_pcap relative_path now = Time.new stat = File.stat(File.join(@pcap_dir, relative_path)) if now - stat.mtime < @queue_delay return end # Pick determistic doc id based on path and pcap size. # (for testing convenience). id = Digest::MD5.new id << "#{relative_path}:#{stat.size}" doc = CouchRest::Document.new({ :_id => id.to_s, :type => 'pcap', :filename => relative_path, :status => 'queued', :stat => { :inode => stat.ino, :size => stat.size, :ctime => stat.ctime, }, :created_at => now, :updated_at => now, }) @db.save_doc doc doc end # Indexes all documents in queue. Returns count of documents indexed. def index count = 0 @db.each_in_view("pcaps/queued", :include_docs => true) do |row| index_pcap row['doc'] count += 1 end count end # Creates xtractr index for pcap. Updates status from "queued" to "indexing" to "indexed". # Any exception will result in a status of "failed" with the exception's message copied # to the document's message attribute. def index_pcap pcap relative_path = pcap["filename"] pcap_path = File.join(File.expand_path(@pcap_dir), relative_path) index_dir = File.join(File.expand_path(@index_dir), relative_path) # Index Logger.info "Indexing #{relative_path}" begin @db.update_doc pcap["_id"] do |doc| doc["status"] = "indexing" doc end index_data = @xtractr.index pcap_path, index_dir @db.update_doc pcap["_id"] do |doc| doc['index'] = index_data doc['status'] = 'indexed' doc end rescue Logger.warn "Indexing failure: #{$!.message}" @db.update_doc pcap["_id"] do |doc| doc['status'] = "failed" doc['message'] = $!.message doc end end return end def pcap_path rel_path if rel_path.is_a? Hash rel_path = rel_path[:filename] or raise "path not found in #{rel_path.inspect}" end File.expand_path File.join(@pcap_dir, rel_path) end def index_path rel_path if rel_path.is_a? Hash rel_path = rel_path.fetch :filename end File.expand_path File.join(@index_dir, rel_path) end # Because FileUtils.rm_rf is too dangerous. def remove_index_for rel_path target = index_path rel_path if File.directory? target FileUtils.rm_rf Dir.glob("#{target}/*.db") FileUtils.rmdir target rescue nil end end # Checks each pcap in the database, purging or requeueing documents as necessary. # Any pcaps in fs_pcaps that are not in the database are added. def reconcile_with_db fs_pcaps fs_pcaps = fs_pcaps.dup indexed = Set.new @db.each_in_view("pcaps/indexed") do |row| indexed << row['key'] end @db.each_in_view("pcaps/by_filename") do |row| path = row['key'] # Delete record if from database if pcap is not present on the # file system. if not fs_pcaps.include? path Logger.warn "Indexer: removing database entry for missing pcap #{path}" @db.delete_doc @db.get(row['id']) remove_index_for(path) next end # Requeue pcap if xtractr index is missing or is older than the pcap. if indexed.include? path pcap_index_dir = File.join(@index_dir, path) if not Xtractr.index_dir?(pcap_index_dir) Logger.warn "Index is missing, requeueing #{path}" requeue_pcap path elsif Xtractr.index_time(pcap_index_dir) < File.mtime(pcap_path(path)).to_f Logger.info "Pcap is newer than index, requeueing #{path}" requeue_pcap path end end fs_pcaps.delete path end # Remaining pcaps are unknown, add them to database fs_pcaps.each do |path| Logger.debug "New pcap: #{path}" add_pcap path end end end end
Puppet::Type.type(:service).provide :service do desc "The simplest form of service support." def self.instances [] end # How to restart the process. # If the 'configvalidator' is passed, it will be executed and if the exit return # is different than 0, preventing the service to be stopped from a stable configuration # and crashing when restarting, or restarted with possible misconfiguration. def restart if @resource[:configvalidator] ucommand(:configvalidator) unless $CHILD_STATUS.exitstatus == 0 raise Puppet::Error, "Configuration validation failed. Cannot start service." end end if @resource[:restart] or restartcmd ucommand(:restart) else self.stop self.start end end # There is no default command, which causes other methods to be used def restartcmd end # A simple wrapper so execution failures are a bit more informative. def texecute(type, command, fof = true, squelch = false, combine = true) begin execute(command, :failonfail => fof, :override_locale => false, :squelch => squelch, :combine => combine) rescue Puppet::ExecutionFailure => detail @resource.fail Puppet::Error, "Could not #{type} #{@resource.ref}: #{detail}", detail end nil end # Use either a specified command or the default for our provider. def ucommand(type, fof = true) if c = @resource[type] cmd = [c] else cmd = [send("#{type}cmd")].flatten end texecute(type, cmd, fof) end end
require 'json' module ExceptionHub class Notifier def perform(exception, env) @exception = exception @env = env self.notify! self end def notify! begin issue = Issue.new issue.description = build_description(@exception, @env) issue.title = "#{@exception.class.name}: #{@exception.message}" issue.send_to_github rescue Exception => ex ExceptionHub.log_exception_hub_exception(ex) end end private def build_description(exception, env) backtrace = if exception.backtrace exception.backtrace.reduce("") {|memo, line| memo << line << "\n"} else "" end <<-DESC ## Exception Message #{exception.message} ## Data ### Backtrace ``` #{backtrace} ``` ### Rack Env ``` #{pretty_jsonify(env)} ``` DESC end def pretty_jsonify(env) json = env_to_hash(env) JSON.pretty_generate(JSON.parse(json.to_json)) end def env_to_hash(env) {}.tap do |hash| env.keys.each do |key| if env[key].is_a?(Hash) hash[key] = env_to_hash(env[key]) else hash[key] = env[key].to_s end end end end end end
Rails.application.routes.draw do resources :appellations resources :wines resources :varietals resources :producers resources :countries # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class ImagesController < InheritedResources::Base private def image_params params.require(:image).permit(:title, :description, :picture) end end
require 'spec_helper' describe 'Students' do before :each do DB.execute("CREATE TABLE students (id INTEGER PRIMARY KEY AUTOINCREMENT, student TEXT)") end after :each do DB.execute("DROP TABLE students") end end describe '#name' do it "has a name" do s = Students.new s.name = "Peter" expect m.name.to eq("Peter") end end describe "#save" do it "saves to a database" s = Students.new s.name = "Peter" s.save peter = DB.execute("CREATE TABLE students (id INTEGER PRIMARY KEY AUTOINCREMENT, grade INTEGER, student TEXT)") end after :each do DB.execute("DROP TABLE students") end it "has a grade & student" do school = School.new school.add_student = "George", 7 expect school.add_student.to eq({"george" => 7}) end
module EmailValidatorSpec class User include ActiveModel::Validations attr_accessor :email validates :email, presence: true, email: true end end RSpec.describe MailgunEmailValidator do before(:all) do ActiveRecord::Schema.define(version: 1) do create_table :email_validator_spec_users, force: true do |t| t.column :email, :string end end end after(:all) do ActiveRecord::Base.connection.drop_table(:email_validator_spec_users) end context "with regular validator" do let(:user) { ::EmailValidatorSpec::User.new } context 'valid email format' do it 'with simple structure' do user.email = 'an_unique_valid_email@example.com' user.valid? expect(user).to be_valid end it 'with multiple dots' do user.email = 'an.unique.valid.email@any.subdomain.example.com' user.valid? expect(user).to be_valid end end context 'wrong structure' do it 'without @' do I18n.locale = :ja user.email = 'invalid.example.com' user.valid? expect(user.errors[:email].first).to eq("メールアドレスが不正です") end it 'with multiple @s' do I18n.locale = :ja user.email = 'invalid@email@example.com' user.valid? expect(user.errors[:email].first).to eq("メールアドレスが不正です") end end context 'wrong domain structure' do it 'domain without dot' do I18n.locale = :ja user.email = 'invalid_email@example' user.valid? expect(user.errors[:email].first).to eq("メールアドレスが不正です") end it 'with dot in the wrong place' do I18n.locale = :ja user.email = 'invalid_email@example.' user.valid? expect(user.errors[:email].first).to eq("メールアドレスが不正です") end it 'with dot in the wrong place' do I18n.locale = :ja user.email = 'invalid_email@.example' user.valid? expect(user.errors[:email].first).to eq("メールアドレスが不正です") end end context 'wrong local-part structure' do it 'domain with dot in the wrong place' do I18n.locale = :ja user.email = 'invalid_email.@example.com' user.valid? expect(user.errors[:email].first).to eq("メールアドレスが不正です") end it 'domain with dot in the wrong place' do I18n.locale = :ja user.email = '.invalid_email@example.com' user.valid? expect(user.errors[:email].first).to eq("メールアドレスが不正です") end end context 'wrong structure' do it 'without @' do I18n.locale = :en user.email = 'invalid.example.com' user.valid? expect(user.errors[:email].first).to eq("invalid email") end it 'with multiple @s' do I18n.locale = :en user.email = 'invalid@email@example.com' user.valid? expect(user.errors[:email].first).to eq("invalid email") end end context 'wrong domain structure' do it 'domain without dot' do I18n.locale = :en user.email = 'invalid_email@example' user.valid? expect(user.errors[:email].first).to eq("invalid email") end it 'with dot in the wrong place' do I18n.locale = :en user.email = 'invalid_email@example.' user.valid? expect(user.errors[:email].first).to eq("invalid email") end it 'with dot in the wrong place' do I18n.locale = :en user.email = 'invalid_email@.example' user.valid? expect(user.errors[:email].first).to eq("invalid email") end end context 'wrong local-part structure' do it 'domain with dot in the wrong place' do I18n.locale = :en user.email = 'invalid_email.@example.com' user.valid? expect(user.errors[:email].first).to eq("invalid email") end it 'domain with dot in the wrong place' do I18n.locale = :en user.email = '.invalid_email@example.com' user.valid? expect(user.errors[:email].first).to eq("invalid email") end end end end
# # Cookbook Name:: pypy # Recipe:: default # # Copyright 2013, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # def install_pypy(source, file, build_dir, prefix) remote_file "#{Chef::Config[:file_cache_path]}/#{file}" do source source + file mode '0644' action :create_if_missing not_if "test -e #{prefix}/bin/pypy" end bash "install-#{build_dir}" do user 'root' cwd Chef::Config[:file_cache_path] code <<-EOH set -e tar xf #{file} cp -r #{build_dir} #{prefix} EOH not_if "test -e #{prefix}/bin/pypy" end end install_pypy( 'https://bitbucket.org/pypy/pypy/downloads/', 'pypy-2.1-linux64.tar.bz2', 'pypy-2.1', '/usr/local/pypy-2.1')
class ApplicationController < ActionController::Base include Oauth2Provider::ControllerMixin protect_from_forgery helper_method :current_user_session, :current_user before_filter :require_user private def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.user @current_user end def require_user if api_request oauth_authorized else unless current_user flash[:notice] = "You must be logged in to access this page" session[:return_url] = request.fullpath redirect_to new_user_session_url end end end def require_no_user if current_user flash[:notice] = "You must be logged out to access this page" redirect_to root_url return false end end end
module Taobao class PromotionDetail def self.attr_names [:id, :promotion_name, :discount_fee, :gift_item_name, :gift_item_id, :gift_item_num, :promotion_desc, :promotion_id] end attr_names.each do |attr_name| attr_accessor attr_name end end end
require 'spec_helper' describe DatasetStreamer, :database_integration => true do let(:database) { GpdbDatabase.find_by_name_and_gpdb_instance_id(GpdbIntegration.database_name, GpdbIntegration.real_gpdb_instance) } let(:dataset) { database.find_dataset_in_schema("base_table1", "test_schema") } let(:user) { GpdbIntegration.real_gpdb_account.owner } let(:streamer) { DatasetStreamer.new(dataset, user) } describe "#initialize" do it "takes a dataset and user" do streamer.user.should == user streamer.dataset.should == dataset end end describe "#enum" do it "returns an enumerator that yields the header and rows from the dataset in csv" do check_enumerator(streamer.enum) end context "with quotes in the data" do let(:dataset) { database.find_dataset_in_schema("stream_table_with_quotes", "test_schema3") } it "escapes quotes in the csv" do enumerator = streamer.enum enumerator.next.split("\n").last.should == %Q{1,"with""double""quotes",with'single'quotes,"with,comma"} finish_enumerator(enumerator) end end context "with row_limit" do let(:row_limit) { 3 } let(:streamer) { DatasetStreamer.new(dataset, user, row_limit) } it "uses the limit for the query" do enumerator = streamer.enum expect { row_limit.times do enumerator.next end }.to_not raise_error(StopIteration) expect { enumerator.next }.to raise_error(StopIteration) end end context "for connection errors" do it "returns the error message" do any_instance_of(GpdbSchema) do |schema| stub(schema).with_gpdb_connection(anything) { raise ActiveRecord::JDBCError, "Some friendly error message" } end enumerator = streamer.enum enumerator.next.should == "Some friendly error message" finish_enumerator enumerator end end context "for a dataset with no rows" do let(:dataset) { database.find_dataset_in_schema("stream_empty_table", "test_schema3") } it "returns the error message" do enumerator = streamer.enum enumerator.next.should == "The requested dataset contains no rows" finish_enumerator(enumerator) end end context "testing checking in connections" do it "does not leak connections" do conn_size = ActiveRecord::Base.connection_pool.send(:active_connections).size enum = streamer.enum finish_enumerator(enum) ActiveRecord::Base.connection_pool.send(:active_connections).size.should == conn_size end end context "when dataset is a chorus view" do let(:chorus_view) do ChorusView.create( { :name => "chorus_view", :schema => dataset.schema, :query => "select * from #{dataset.name};" }, :without_protection => true) end let(:streamer) { DatasetStreamer.new(chorus_view, user) } it "returns an enumerator that yields the header and rows from the dataset in csv" do check_enumerator(streamer.enum) end end let(:table_data) { ["0,0,0,apple,2012-03-01 00:00:02\n", "1,1,1,apple,2012-03-02 00:00:02\n", "2,0,2,orange,2012-04-01 00:00:02\n", "3,1,3,orange,2012-03-05 00:00:02\n", "4,1,4,orange,2012-03-04 00:02:02\n", "5,0,5,papaya,2012-05-01 00:02:02\n", "6,1,6,papaya,2012-04-08 00:10:02\n", "7,1,7,papaya,2012-05-11 00:10:02\n", "8,1,8,papaya,2012-04-09 00:00:02\n"] } def check_enumerator(enumerator) next_result = enumerator.next header_row = next_result.split("\n").first header_row.should == "id,column1,column2,category,time_value" first_result = next_result.split("\n").last+"\n" table_data.delete(first_result).should_not be_nil 8.times do table_data.delete(enumerator.next).should_not be_nil end finish_enumerator(enumerator) end end def finish_enumerator(enum) while true enum.next end rescue => e end end
require File.dirname(__FILE__) + '/spec_helper' require 'active_model' require 'active_model/core' ActiveModel::Base.send :include, ObserverDisabler class ObservedModel < ActiveModel::Base class Observer end end class FooObserver < JitObserver class << self public :new end attr_accessor :stub def on_spec(record) stub.event_with(record) if stub end end class Foo < ActiveModel::Base end describe JitObserver do before(:each) do ObservedModel.observers = :foo_observer Foo.delete_observers FooObserver.clear_observed_classes JitObserverRegistry.registry.clear end it "should guess the implicit observable model name" do FooObserver.default_observed_class_name.should == 'Foo' end it "should track implicit observed models" do instance = FooObserver.new instance.send(:observed_classes).should include(Foo) instance.send(:observed_classes).should_not include(ObservedModel) end it "should track explicitly observed model class" do old_instance = FooObserver.new old_instance.send(:observed_classes).should_not include(ObservedModel) FooObserver.observe ObservedModel instance = FooObserver.new instance.send(:observed_classes).should include(ObservedModel) end it "should track explicitly observed model as string" do old_instance = FooObserver.new old_instance.send(:observed_classes).should_not include(ObservedModel) FooObserver.observe 'ObservedModel' instance = FooObserver.new instance.send(:observed_classes).should include(ObservedModel) end it "should track explicitly observed model as symbol" do old_instance = FooObserver.new old_instance.send(:observed_classes).should_not include(ObservedModel) FooObserver.observe :observed_model instance = FooObserver.new instance.send(:observed_classes).should include(ObservedModel) end it "should call an observer event if it exists" do foo = Foo.new instance = FooObserver.new instance.stub = stub('foo_observer_instance') instance.stub.should_receive(:event_with).with(foo) Foo.with_observers do Foo.send(:changed) Foo.send(:notify_observers, :on_spec, foo) end end it "should skip nonexistent observer events without blowing up" do foo = Foo.new Foo.with_observers do Foo.send(:changed) Foo.send(:notify_observers, :whatever, foo) end end end
module PlayerStatistics ## # Statistic that computes how many matches a given [Player](#Player) has participated in. class MatchesPlayedStatistic < PlayerStatistics::PlayerStatistic def compute query = Match .joins('JOIN match_teams_players ON match_teams_players.match_team_id IN (matches.red_team_id, matches.blue_team_id)') .where('match_teams_players.player_id = ?', player.id) query = apply_filter(query) query.count(:all) end protected ## # Applies a filter to the Match query and returns the query. Is called with a query consisting of a join on matches # and match teams that contains a result of all matches and teams the current player has participated in. def apply_filter(match_query) match_query end end end
require 'spec_helper' describe "static pages" do describe "home page" do subject {page} before {visit root_path} #测试标题 it {should have_title("主页")} #测试内容 it {should have_content("国科大跳蚤市场")} it {should have_content("主页")} it {should have_content("注册")} it {should have_content("登录")} it {should have_content("商品信息")} it {should have_content("分类导航")} it {should have_content("商品信息")} it {should have_content("全部")} it {should have_content("电器")} it {should have_content("生活")} it {should have_content("图书")} it {should have_content("其他")} end describe "home page" do it "should have the right links on the layout"do ''' visit root_path click_link "主页" expect(page).to match(root_path) visit root_path click_link "注册"      expect(page).to  visit root_path click_link "登录"      expect(page).to  visit root_path click_link "退出"      expect(page).to  visit root_path click_link "发布" visit root_path click_link "主页"      expect(page).to  ''' end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'telegram/rabbit/version' Gem::Specification.new do |spec| spec.name = "telegram-rabbit" spec.version = Telegram::Rabbit::VERSION spec.authors = ["Stanislav E. Govorov"] spec.email = ["govorov.st@gmail.com"] spec.summary = %q{ RabbitMQ wrapper for telegram-bot-ruby } spec.license = "MIT" spec.files = Dir["{lib}/**/*.rb", "bin/*", "LICENSE", "*.md"] spec.bindir = "exe" spec.require_paths = ["lib"] spec.add_runtime_dependency "telegram-bot-ruby" spec.add_runtime_dependency "bunny" spec.add_development_dependency "bundler", "~> 1.14" spec.add_development_dependency "rake", "~> 10.0" end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html # get '/documents' => "documents#my_index" root "documents#index" resources :documents end
class CategorySalesPlan < ApplicationRecord extend CommercialCalendar::Period belongs_to :store belongs_to :category, foreign_key: 'category_cod' scope :by_store_month, ->(store_id, opts = {}) { where(store_id: store_id, year: opts[:year], month: opts[:month]) } scope :between, ->(period, store_id) { start_month = month_by_date(period[:start]) end_month = month_by_date(period[:end]) start_year = year_by_date(period[:start]) end_year = year_by_date(period[:end]) if start_year == end_year where('year = ? AND month >= ? AND month <= ? AND category_sales_plans.store_id = ?', start_year, start_month, end_month, store_id).order('category_sales_plans.year, category_sales_plans.month') else where('year = ? AND month >= ? AND category_sales_plans.store_id = ?', start_year, start_month, store_id).or(where('year = ? AND month <= ? AND category_sales_plans.store_id = ?', end_year, end_month, store_id)).order('category_sales_plans.year, category_sales_plans.month') end } end
log 'Started execution custom nuget.exe downloader' do level :info end temp_dir ='C:\\Users\\vagrant\\AppData\\Local\\Temp' scripts_dir = temp_dir.gsub('\\','/') system = node['kernel']['machine'] == 'x86_64' ? 'win64' : 'win32' download_url = node['custom_nuget']['download_url'] filename = node['custom_nuget']['filename'] package_title = 'console nuget client' assemblies = %w/ CsQuery Newtonsoft.Json / cookbook_file "#{scripts_dir}/wget.ps1" do source 'wget.ps1' path "#{scripts_dir}/wget.ps1" action :create_if_missing end powershell "Download #{package_title}" do code <<-EOH pushd '#{temp_dir}' . .\\wget.ps1 -download_url '#{download_url}' -local_file_path '#{temp_dir}' -filename '#{filename}' EOH not_if {::File.exists?("#{temp_dir}/#{filename}".gsub('\\', '/'))} end log "Completed download #{package_title}" do level :info end assemblies.each do |assembly| powershell "Install #{assembly}" do code <<-EOH $framework = 'net40' pushd '#{temp_dir}' $env:PATH = "${env:PATH};#{temp_dir}" & nuget.exe install '#{assembly}' | out-file "#{temp_dir}\\nuget.log" -encoding ASCII -append pushd '#{temp_dir}' get-childitem -filter '#{assembly}.dll' -recurse | where-object { $_.PSPath -match '\\\\net40\\\\'} | copy-item -destination '.' EOH not_if {::File.exists?("#{temp_dir}/#{assembly}.dll".gsub('\\', '/'))} end end cookbook_file "#{scripts_dir}/get_task_scheduler_events.ps1" do source 'get_task_scheduler_events.ps1' path "#{scripts_dir}/get_task_scheduler_events.ps1" action :create_if_missing end powershell 'Execute uploaded script' do code <<-EOH pushd '#{temp_dir}' . .\\get_task_scheduler_events.ps1 EOH end log 'Completed execution uploaded script with Nuget-provided dependency.' do level :info end
class ApplicationController < ActionController::Base include PublicActivity::StoreController include Pundit include Devise::Controllers::Helpers # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. # protect_from_forgery with: :exception # protect_from_forgery with: :null_session before_action :authorize_user rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized def after_sign_out_path(resource) new_user_session_path end def set_current_user User.current = current_user end private def authorize_user authenticate_user! self.set_current_user end def user_not_authorized flash[:alert] = "Vous n'êtes pas autorisé à faire cette action." redirect_to (request.referrer || root_path) end end
class AddColumnDate < ActiveRecord::Migration[5.0] def change add_column :orcamentos, :data, :date end end
require_relative 'clients' require_relative 'collect' require 'twitter' class Menu attr_accessor :input2, :collect def initialize @collect = Collect.new end def start_menu system 'clear' puts "" puts " ::::::::::::::::::::::::" puts " : Twitter_bot, Welcome :" puts " ::::::::::::::::::::::::" puts "" puts " What can I do for you ?" puts "" puts " <1> Data collect" puts "" puts " <2> Tweet automaticly" puts "" puts " <3> Like tweet" puts "" puts " <4> Follow user" puts "" puts " <0> Quit" puts "" input = gets.chomp if input == "1" system 'clear' puts "" puts " ::::::::::::::::::::::::" puts " : COLLECT DATA :" puts " ::::::::::::::::::::::::" puts "" @collect.collect_name elsif input == "2" @collect.tweet_update elsif input == "3" system 'clear' puts "" puts " ::::::::::::::::::::::::" puts " : LIKE TWEET :" puts " ::::::::::::::::::::::::" puts "" Collect.new.fav_tweet else exit end end end
require 'NumeroRacional.rb' require 'test/unit' class Testeo < Test::Unit::TestCase def setup #Crea un obejeto Racional como atributo de la clase Testeo. @nr = Racional.new(1,2) end def test_objeto #Determina si los tipos son correctos y si la función to_s funciona. assert_instance_of(String,@nr.to_s,"No es una string") assert_not_nil(@nr.denominador, "denominador no ha sido inicializado") assert_not_nil(@nr.numerador, "numerador no ha sido inicializado") assert_kind_of(Fixnum, @nr.denominador, "No es correcto") assert_kind_of(Fixnum, @nr.numerador, "No es correcto") assert_kind_of( String, @nr.numerador, "Es correcto") #Este método dará un error a propósito. end def test_suma #Determina que la suma funciona correctamente assert_equal "1/1", @nr+@nr assert_equal "1/1", Racional.new(10,20)+Racional.new(10,20) end def test_multiplicar #Determina que la multiplicación funciona correctamente assert_equal "1/4", Racional.new(10,20)*Racional.new(10,20) assert_equal "63/40", Racional.new(7,8)*Racional.new(9,5) end def test_resta #Determina que la resta funciona correctamente assert_equal "7/72", Racional.new(70,80)-Racional.new(70,90) assert_equal "0/1", @nr-@nr assert_equal "1/6", Racional.new(7,6)-Racional.new(6,6) end def test_division #Determina que la división funciona correctamente assert_equal "2/1", Racional.new(1,2).div(Racional.new(2,8)) assert_equal "15/16", Racional.new(9,8).div(Racional.new(6,5)) end end
module Roadie::Rails::InlineOnDelivery def deliver_now inline_styles super end end class ApplicationMailer < ActionMailer::Base include Roadie::Rails::Automatic before_action :attach_header_image ADMIN_ADDRESS = 'admin@tutoria.io' default from: 'no-reply@tutoria.io' layout 'mailer' def roadie_options super.merge(url_options: Rails.configuration.roadie_options) end def attach_header_image attachments.inline['logo.png'] = File.read('app/assets/images/tutoria_logo_full color_web.png') end end
require_relative "board" require_relative "cursor" class Game def initialize(grid_size, mine_count) @board = Board.new(grid_size, mine_count) @cursor = Cursor.new(grid_size) end def make_move(command, pos) case command when "flag" @board.toggle_flag(pos) when "reveal" @board.reveal(pos) end end def game_over? @board.lose? || @board.win? end def run render_prc = Proc.new { |pos| @board.render(pos) } until game_over? render_prc.call(@cursor.cursor_pos) inputs = @cursor.input_loop(render_prc) make_move(*inputs) end puts "Game over!" end end game = Game.new(20, 50) game.run
class ApplicationController < ActionController::Base before_filter :set_time_zone def ensure_sign_in if current_user.nil? redirect_to index_user_omniauth_authorize_path return false end end def set_time_zone Time.zone = 'Tokyo' end end
# frozen_string_literal: true require 'set' require 'stannum' module Stannum # An errors object represents a collection of errors. # # Most of the time, an end user will not be creating an Errors object # directly. Instead, an errors object may be returned by a process that # validates or coerces data to an expected form. For one such example, see # the Stannum::Constraint and its subclasses. # # Internally, an errors object is an Array of errors. Each error is # represented by a Hash containing the keys :data, :message, :path and :type. # # - The :type of the error is a short, unique symbol or string that identifies # the type of the error, such as 'invalid' or 'not_found'. The type is # frequently namespaced, e.g. 'stannum.constraints.present'. # - The :message of the error is a short string that provides a human-readable # description of the error, such as 'is invalid' or 'is not found'. The # message may include format directives for error data (see below). If the # :message key is missing or the value is nil, use a default error message # or generate the message from the :type. # - The :data of the error stores additional information about the error and # the expected behavior. For example, an out of range error might have # type: 'out_of_range' and data { min: 0, max: 10 }, indicating that the # expected values were between 0 and 10. If the data key is missing or the # value is empty, there is no additional information about the error. # - The :path of the error reflects the steps to resolve the relevant property # from the given data object. The path is an Array with keys of either # Symbols/Strings (for object properties or Hash keys) or Integers (for # Array indices). For example, given the hash { companies: [{ teams: [] }] } # and an expecation that a company's team must not be empty, the resulting # error would have path: [:companies, 0, :teams]. if the path key is missing # or the value is empty, the error refers to the root object. # # @example Creating An Errors Object # errors = Stannum::Errors.new # # @example Adding Errors # errors.add(:not_numeric) # # # Add an error with a custom message. # errors.add(:invalid, message: 'is not valid') # # # Add an error with additional data. # errors.add(:out_of_range, min: 0, max: 10) # # # Add multiple errors. # errors.add(:first_error).add(:second_error).add(:third_error) # # @example Viewing The Errors # errors.empty? #=> false # errors.size #=> 6 # # errors.each { |err| } #=> yields each error to the block # errors.to_a #=> returns an array containing each error # # @example Accessing Nested Errors via a Key # errors = Stannum::Errors.new # child = errors[:spell] # child.size #=> 0 # child.to_a #=> [] # # child.add(:insufficient_mana) # child.size # 1 # child.to_a # [{ type: :insufficient_mana, path: [] }] # # # Adding an error to a child makes it available on a parent. # errors.size # 1 # errors.to_a # [{ type: :insufficient_mana, path: [:spell] }] # # @example Accessing Nested Errors via an Index # errors = Stannum::Errors.new # child = errors[1] # # child.size #=> 0 # child.to_a #=> [] # # child.add(:unknown_monster) # child.size # 1 # child.to_a # [{ type: :unknown_monster, path: [] }] # # # Adding an error to a child makes it available on a parent. # errors.size # 1 # errors.to_a # [{ type: :unknown_monster, path: [1] }] # # @example Accessing Deeply Nested Errors # errors = Stannum::Errors.new # # errors[:towns][1][:name].add(:unpronounceable) # errors.size #=> 1 # errors.to_a #=> [{ type: :unpronounceable, path: [:towns, 1, :name] }] # # errors[:towns].size #=> 1 # errors[:towns].to_a #=> [{ type: :unpronounceable, path: [1, :name] }] # # errors[:towns][1].size #=> 1 # errors[:towns][1].to_a #=> [{ type: :unpronounceable, path: [:name] }] # # errors[:towns][1][:name].size #=> 1 # errors[:towns][1][:name].to_a #=> [{ type: :unpronounceable, path: [] }] # # # Can also access nested properties via #dig. # errors.dig(:towns, 1, :name).to_a #=> [{ type: :unpronounceable, path: [] }] # # @example Replacing Errors # errors = Cuprum::Errors.new # errors[:potions][:ingredients].add(:missing_rabbits_foot) # errors.size #=> 1 # # other = Cuprum::Errors.new.add(:too_hot, :brew_longer, :foul_smelling) # errors[:potions] = other # errors.size #=> 3 # errors.to_a # #=> [ # # { type: :brew_longer, path: [:potions] }, # # { type: :foul_smelling, path: [:potions] }, # # { type: :too_hot, path: [:potions] } # # ] # # @example Replacing Nested Errors # errors = Cuprum::Errors.new # errors[:armory].add(:empty) # # other = Cuprum::Errors.new # other.dig(:weapons, 0).add(:needs_sharpening) # other.dig(:weapons, 1).add(:rusty).add(:out_of_ammo) # # errors[:armory] = other # errors.size #=> 3 # errors.to_a # #=> [ # # { type: needs_sharpening, path: [:armory, :weapons, 0] }, # # { type: out_of_ammo, path: [:armory, :weapons, 1] }, # # { type: rusty, path: [:armory, :weapons, 1] } # # ] class Errors # rubocop:disable Metrics/ClassLength include Enumerable def initialize @children = Hash.new { |hsh, key| hsh[key] = self.class.new } @cache = Set.new @errors = [] end # Checks if the other errors object contains the same errors. # # @return [true, false] true if the other object is an errors object or an # array with the same class and errors, otherwise false. def ==(other) return false unless other.is_a?(Array) || other.is_a?(self.class) return false unless empty? == other.empty? compare_hashed_errors(other) end alias eql? == # Accesses a nested errors object. # # Each errors object can have one or more children, each of which is itself # an errors object. These nested errors represent errors on some subset of # the main object - for example, a failed validation of a named property, # of the value in a key-value pair, or of an indexed value in an ordered # collection. # # The children are created as needed and are stored with either an integer # or a symbol key. Calling errors[1] multiple times will always return the # same errors object. Likewise, calling errors[:some_key] multiple times # will return the same object, and calling errors['some_key'] will return # that same errors object as well. # # @param key [Integer, String, Symbol] The key or index of the referenced # value, item, or property. # # @return [Stannum::Errors] an Errors object. # # @raise [ArgumentError] if the key is not a String, Symbol or Integer. # # @example Accessing Nested Errors via a Key # errors = Stannum::Errors.new # child = errors[:spell] # child.size #=> 0 # child.to_a #=> [] # # child.add(:insufficient_mana) # child.size # 1 # child.to_a # [{ type: :insufficient_mana, path: [] }] # # # Adding an error to a child makes it available on a parent. # errors.size # 1 # errors.to_a # [{ type: :insufficient_mana, path: [:spell] }] # # @example Accessing Nested Errors via an Index # errors = Stannum::Errors.new # child = errors[1] # # child.size #=> 0 # child.to_a #=> [] # # child.add(:unknown_monster) # child.size # 1 # child.to_a # [{ type: :unknown_monster, path: [] }] # # # Adding an error to a child makes it available on a parent. # errors.size # 1 # errors.to_a # [{ type: :unknown_monster, path: [1] }] # # @example Accessing Deeply Nested Errors # errors = Stannum::Errors.new # # errors[:towns][1][:name].add(:unpronounceable) # errors.size #=> 1 # errors.to_a #=> [{ type: :unpronounceable, path: [:towns, 1, :name] }] # # errors[:towns].size #=> 1 # errors[:towns].to_a #=> [{ type: :unpronounceable, path: [1, :name] }] # # errors[:towns][1].size #=> 1 # errors[:towns][1].to_a #=> [{ type: :unpronounceable, path: [:name] }] # # errors[:towns][1][:name].size #=> 1 # errors[:towns][1][:name].to_a #=> [{ type: :unpronounceable, path: [] }] # # @see #[]= # # @see #dig def [](key) validate_key(key) @children[key] end # Replaces the child errors with the specified errors object or Array. # # If the given value is nil or an empty array, the #[]= operator will remove # the child errors object at the given key, removing all errors within that # namespace and all namespaces nested inside it. # # If the given value is an errors object or an Array of errors object, the # #[]= operation will replace the child errors object at the given key, # removing all existing errors and adding the new errors. Each added error # will use its nested path (if any) as a relative path from the given key. # # @param key [Integer, String, Symbol] The key or index of the referenced # value, item, or property. # # @param value [Stannum::Errors, Array[Hash], nil] The errors to insert with # the specified path. # # @return [Object] the value passed in. # # @raise [ArgumentError] if the key is not a String, Symbol or Integer. # # @raise [ArgumentError] if the value is not a valid errors object, Array of # errors hashes, empty Array, or nil. # # @example Replacing Errors # errors = Cuprum::Errors.new # errors[:potions][:ingredients].add(:missing_rabbits_foot) # errors.size #=> 1 # # other = Cuprum::Errors.new.add(:too_hot, :brew_longer, :foul_smelling) # errors[:potions] = other # errors.size #=> 3 # errors.to_a # #=> [ # # { type: :brew_longer, path: [:potions] }, # # { type: :foul_smelling, path: [:potions] }, # # { type: :too_hot, path: [:potions] } # # ] # # @example Replacing Nested Errors # errors = Cuprum::Errors.new # errors[:armory].add(:empty) # # other = Cuprum::Errors.new # other.dig(:weapons, 0).add(:needs_sharpening) # other.dig(:weapons, 1).add(:rusty).add(:out_of_ammo) # # errors[:armory] = other # errors.size #=> 3 # errors.to_a # #=> [ # # { type: needs_sharpening, path: [:armory, :weapons, 0] }, # # { type: out_of_ammo, path: [:armory, :weapons, 1] }, # # { type: rusty, path: [:armory, :weapons, 1] } # # ] # # @see #[] def []=(key, value) validate_key(key) value = normalize_value(value, allow_nil: true) @children[key] = value end # Adds an error of the specified type. # # @param type [String, Symbol] The error type. This should be a string or # symbol with one or more underscored, dot-separated values. # @param message [String] A custom error message to display. Optional; # defaults to nil. # @param data [Hash<Symbol, Object>] Additional data to store about the # error, such as the expected type or the min/max values of the expected # range. Optional; defaults to an empty Hash. # # @return [Stannum::Errors] the errors object. # # @raise [ArgumentError] if the type or message are invalid. # # @example Adding An Error # errors = Stannum::Errors.new.add(:not_found) # # @example Adding An Error With A Message # errors = Stannum::Errors.new.add(:not_found, message: 'is missing') # # @example Adding Multiple Errors # errors = Stannum::Errors.new # errors # .add(:not_numeric) # .add(:not_integer, message: 'is outside the range') # .add(:not_in_range) def add(type, message: nil, **data) error = build_error(data: data, message: message, type: type) hashed = error.hash return self if @cache.include?(hashed) @errors << error @cache << hashed self end # Accesses a (possibly deeply) nested errors object. # # Similiar to the #[] method, but can access a deeply nested errors object # as well. The #dig method can take either a list of one or more keys # (Integers, Strings, and Symbols) as arguments, or an Array of keys. # Calling errors.dig is equivalent to calling errors[] with each key in # sequence. # # @return [Stannum::Errors] the nested error object at the specified path. # # @raise [ArgumentError] if the keys are not Strings, Symbols or Integers. # # @overload dig(keys) # @param keys [Array<Integer, String, Symbol>] The path to the nested # errors object, as an array of Integers, Strings, and Symbols. # # @overload dig(*keys) # @param keys [Array<Integer, String, Symbol>] The path to the nested # errors object, as individual Integers, Strings, and Symbols. # # @example Accessing Nested Errors via a Key # errors = Stannum::Errors.new # child = errors.dig(:spell) # child.size #=> 0 # child.to_a #=> [] # # child.add(:insufficient_mana) # child.size # 1 # child.to_a # [{ type: :insufficient_mana, path: [] }] # # # Adding an error to a child makes it available on a parent. # errors.size # 1 # errors.to_a # [{ type: :insufficient_mana, path: [:spell] }] # # @example Accessing Nested Errors via an Index # errors = Stannum::Errors.new # child = errors.dig(1) # # child.size #=> 0 # child.to_a #=> [] # # child.add(:unknown_monster) # child.size # 1 # child.to_a # [{ type: :unknown_monster, path: [] }] # # # Adding an error to a child makes it available on a parent. # errors.size # 1 # errors.to_a # [{ type: :unknown_monster, path: [1] }] # # @example Accessing Deeply Nested Errors # errors = Stannum::Errors.new # # errors.dig(:towns, 1, :name).add(:unpronounceable) # errors.size #=> 1 # errors.to_a #=> [{ type: :unpronounceable, path: [:towns, 1, :name] }] # # errors.dig(:towns).size #=> 1 # errors.dig(:towns).to_a #=> [{ type: :unpronounceable, path: [1, :name] }] # # errors.dig(:towns, 1).size #=> 1 # errors.dig(:towns, 1).to_a #=> [{ type: :unpronounceable, path: [:name] }] # # errors.dig(:towns, 1, :name).size #=> 1 # errors.dig(:towns, 1, :name).to_a #=> [{ type: :unpronounceable, path: [] }] # # @see #[] def dig(first, *rest) path = first.is_a?(Array) ? first : [first, *rest] path.reduce(self) { |errors, segment| errors[segment] } end # Creates a deep copy of the errors object. # # @return [Stannum::Errors] the copy of the errors object. def dup # rubocop:disable Metrics/MethodLength child = self.class.new each do |error| child # rubocop:disable Style/SingleArgumentDig .dig(error.fetch(:path, [])) .add( error.fetch(:type), message: error[:message], **error.fetch(:data, {}) ) end child end # @overload each # Returns an Enumerator that iterates through the errors. # # @return [Enumerator] # # @overload each # Iterates through the errors, yielding each error to the provided block. # # @yieldparam error [Hash<Symbol=>Object>] The error object. Each error # is a hash containing the keys :data, :message, :path and :type. def each return to_enum(:each) { size } unless block_given? @errors.each { |item| yield item.merge(path: []) } @children.each do |path, child| child.each do |item| yield item.merge(path: item.fetch(:path, []).dup.unshift(path)) end end end # Checks if the errors object contains any errors. # # @return [true, false] true if the errors object has no errors, otherwise # false. def empty? @errors.empty? && @children.all?(&:empty?) end alias blank? empty? # Groups the errors by the error path. # # Generates a Hash whose keys are the unique error :path values. For each # path, the corresponding value is the Array of all errors with that path. # # This will flatten paths: an error with path [:parts] will be grouped in a # separate array from a part with path [:parts, :assemblies]. # # Errors with an empty path will be grouped with a key of an empty Array. # # @return [Hash<Array, Array>] the errors grouped by the error path. # # @overload group_by_path # # @overload group_by_path(&block) # Groups the values returned by the block by the error path. # # @yieldparam error [Hash<Symbol>] the error Hash. def group_by_path grouped = Hash.new { |hsh, key| hsh[key] = [] } each do |error| path = error[:path] value = block_given? ? yield(error) : error grouped[path] << value end grouped end # @return [String] a human-readable representation of the object. def inspect oid = super[2...].split.first.split(':').last "#<#{self.class.name}:#{oid} @summary=%{#{summary}}>" end # Adds the given errors to a copy of the errors object. # # Creates a copy of the errors object, and then adds each error in the # passed in errors object or array to the copy. The copy will thus contain # all of the errors from the original object and all of the errors from the # passed in object. The original object is not changed. # # @param value [Stannum::Errors, Array[Hash]] The errors to add to the # copied errors object. # # @return [Stannum::Errors] the copied errors object. # # @raise [ArgumentError] if the value is not a valid errors object or Array # of errors hashes. # # @see #update. def merge(value) value = normalize_value(value, allow_nil: false) dup.update_errors(value) end # The number of errors in the errors object. # # @return [Integer] the number of errors. def size @errors.size + @children.each_value.reduce(0) do |total, child| total + child.size end end alias count size # Generates a text summary of the errors. # # @return [String] the text summary. def summary with_messages .map { |error| generate_summary_item(error) } .join(', ') end # Generates an array of error objects. # # Each error is a hash containing the keys :data, :message, :path and :type. # # @return [Array<Hash>] the error objects. def to_a each.to_a end # Adds the given errors to the errors object. # # Adds each error in the passed in errors object or array to the current # errors object. It will then contain all of the original errors and all of # the errors from the passed in object. This changes the current object. # # @param value [Stannum::Errors, Array[Hash]] The errors to add to the # current errors object. # # @return [self] the current errors object. # # @raise [ArgumentError] if the value is not a valid errors object or Array # of errors hashes. # # @see #merge. def update(value) value = normalize_value(value, allow_nil: false) update_errors(value) end # Creates a copy of the errors and generates error messages for each error. # # @param force [Boolean] If true, overrides any messages already defined for # the errors. # @param strategy [#call] The strategy to use to generate the error # messages. # # @return [Stannum::Errors] the copy of the errors object. def with_messages(force: false, strategy: nil) strategy ||= Stannum::Messages.strategy dup.tap do |errors| errors.each_error do |error| next unless force || error[:message].nil? || error[:message].empty? message = strategy.call(error[:type], **(error[:data] || {})) error[:message] = message end end end protected def each_error(&block) return enum_for(:each_error) unless block_given? @errors.each(&block) @children.each_value do |child| child.each_error(&block) end end def update_errors(other_errors) other_errors.each do |error| dig(error.fetch(:path, [])) .add( error.fetch(:type), message: error[:message], **error.fetch(:data, {}) ) end self end private def build_error(data:, message:, type:) type = normalize_type(type) msg = normalize_message(message) { data: data, message: msg, type: type } end def compare_hashed_errors(other_errors) hashes = Set.new(map(&:hash)) other_hashes = Set.new(other_errors.map(&:hash)) hashes == other_hashes end def generate_summary_item(error) path = generate_summary_path(error[:path]) return error[:message] if path.nil? || path.empty? "#{path}: #{error[:message]}" end def generate_summary_path(path) return nil if path.empty? return path.first.to_s if path.size == 1 path[1..].reduce(path.first.to_s) do |str, item| item.is_a?(Integer) ? "#{str}[#{item}]" : "#{str}.#{item}" end end def invalid_value_error(allow_nil) values = ['an instance of Stannum::Errors', 'an array of error hashes'] values << 'nil' if allow_nil 'value must be ' + # rubocop:disable Style/StringConcatenation tools.array_tools.humanize_list(values, last_separator: ' or ') end def normalize_array_item(item, allow_nil:) unless item.is_a?(Hash) && item.key?(:type) raise ArgumentError, invalid_value_error(allow_nil) end item end def normalize_array_value(ary, allow_nil:) child = self.class.new ary.each do |item| err = normalize_array_item(item, allow_nil: allow_nil) data = err.fetch(:data, {}) path = err.fetch(:path, []) child.dig(path).add(err[:type], message: err[:message], **data) # rubocop:disable Style/SingleArgumentDig end child end def normalize_message(message) return if message.nil? unless message.is_a?(String) raise ArgumentError, 'message must be a String' end raise ArgumentError, "message can't be blank" if message.empty? message end def normalize_type(type) raise ArgumentError, "error type can't be nil" if type.nil? unless type.is_a?(String) || type.is_a?(Symbol) raise ArgumentError, 'error type must be a String or Symbol' end raise ArgumentError, "error type can't be blank" if type.empty? type.to_s end def normalize_value(value, allow_nil: false) return self.class.new if value.nil? && allow_nil return value.dup if value.is_a?(self.class) if value.is_a?(Array) return normalize_array_value(value, allow_nil: allow_nil) end raise ArgumentError, invalid_value_error(allow_nil) end def tools SleepingKingStudios::Tools::Toolbelt.instance end def validate_key(key) return if key.is_a?(Integer) || key.is_a?(Symbol) || key.is_a?(String) raise ArgumentError, 'key must be an Integer, a String or a Symbol', caller(1..) end end end
class AddUserIdToJobColumn < ActiveRecord::Migration def change add_column :job_columns, :user_id, :integer end end
class CandidateRevision < ActiveRecord::Base belongs_to :candidate belongs_to :revision end
require 'test_helper' class FriendTest < ActiveSupport::TestCase test 'requires name' do friend = Friend.new refute_predicate friend, :valid? assert_includes friend.errors.messages[:name], "can't be blank" end test 'validates name length' do name = 'a' * (Friend::MAX_NAME_LENGTH + 1) friend = Friend.new(name: name) refute_predicate friend, :valid? assert_includes friend.errors.messages[:name], "is too long (maximum is #{Friend::MAX_NAME_LENGTH} characters)" end test 'requires user' do friend = Friend.new refute_predicate friend, :valid? assert_includes friend.errors.messages[:user], 'must exist' end test 'updates matches when friend is deleted' do user = create(:user) account = create(:account, user: user) friend1 = create(:friend, user: user) friend2 = create(:friend, user: user) match1 = create(:match, account: account, group_member_ids: [friend1.id]) match2 = create(:match, account: account, group_member_ids: [friend1.id, friend2.id]) friend1.destroy! assert_empty match1.reload.group_member_ids assert_equal [friend2.id], match2.reload.group_member_ids end end
class MasterMind attr_accessor :input, :output, :gameEngine def initialize(input, output, gameEngine) @input = input; @output = output; @gameEngine = gameEngine; end def run() num = 0; combination = gameEngine.getCombination(); answer = ""; while(!gameEngine.match(combination, answer) && !gameEngine.endReached(num)) do num += 1 answer = @input.ask("Please try"); output.write(gameEngine.hint(combination, answer)); end end end
class AddPayStructureToEmployees < ActiveRecord::Migration def change add_column :employees, :pay_type, :string add_column :employees, :pay_rate, :decimal, :precision => 8, :scale => 2 end end
# frozen_string_literal: true # == Schema Information # # Table name: roles # # id :integer not null, primary key # name :string # resource_type :string # created_at :datetime not null # updated_at :datetime not null # resource_id :integer # # Indexes # # index_roles_on_name (name) # index_roles_on_name_and_resource_type_and_resource_id (name,resource_type,resource_id) # index_roles_on_resource (resource_type,resource_id) # require 'rails_helper' RSpec.describe Role, type: :model do let(:org) { create :organization } let(:user) { create :user } describe 'validations' do describe 'correct_role_scope' do describe 'super_admin' do it 'is valid when set as global role' do user.add_role :super_admin expect(user.has_role?(:super_admin)).to be true end it 'is invalid when set as a local role' do expect { user.add_role :super_admin, org }.to raise_error ActiveRecord::RecordInvalid expect(user.has_role?(:super_admin)).to be false expect(user.has_role?(:super_admin, org)).to be false end end describe 'global_admin' do it 'is valid when set as global role' do user.add_role :global_admin expect(user.has_role?(:global_admin)).to be true end it 'is invalid when set as a local role' do expect { user.add_role :global_admin, org }.to raise_error ActiveRecord::RecordInvalid expect(user.has_role?(:global_admin)).to be false expect(user.has_role?(:global_admin, org)).to be false end end describe 'admin' do it 'is invalid when set as a global role' do expect { user.add_role :admin }.to raise_error ActiveRecord::RecordInvalid expect(user.has_role?(:admin)).to be false end it 'is valid when set as a local role' do user.add_role :admin, org expect(user.has_role?(:admin)).to be false expect(user.has_role?(:admin, org)).to be true end end describe 'teacher' do it 'is invalid when set as a global role' do expect { user.add_role :teacher }.to raise_error ActiveRecord::RecordInvalid expect(user.has_role?(:teacher)).to be false end it 'is valid when set as a local role' do user.add_role :teacher, org expect(user.has_role?(:teacher)).to be false expect(user.has_role?(:teacher, org)).to be true end end describe 'researcher' do it 'is invalid when set as a global role' do expect { user.add_role :researcher }.to raise_error ActiveRecord::RecordInvalid expect(user.has_role?(:researcher)).to be false end it 'is valid when set as a local role' do user.add_role :researcher, org expect(user.has_role?(:researcher)).to be false expect(user.has_role?(:researcher, org)).to be true end end end end end
require_relative '../../config/application' class Controller HELP_MENU = <<EOF HELP MENU Type: add <task description> add a task to the end of the list remove <task id> delete a task complete <task id> complete a task list show all tasks save <file_name> save the list to a file sort_oustanding lists all outstanding by creation date sort_completed lists all completed by completion date sort_all lists all by creation date help display this menu quit or exit exit the program EOF command = ARGV[0] task = ARGV[1..-1] if !task.empty? Task.send(command, task) else Task.send(command) end end
class MessagesController < ApplicationController def index @messages = Message.all end def show @message = Message.find(params[:id]) end def new @message = Message.new(message_params) end def create @message = Message.create(message_params) respond_to do |format| format.html { redirect_to messages_url } format.js end end def destroy @message = Message.find(params[:id]) @message.destroy redirect_to messages_url end private def message_params params.require(:message).permit(:Body, :To, :From) end end
require 'httparty' class EpaApi include HTTParty base_uri('https://iaspub.epa.gov') def initialize(zipcode) @response = self.class.get("/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/#{zipcode}/json") end def hourly @response.parsed_response end end
class Author attr_accessor :name def initialize(name) @name = name @posts = [] end def posts @posts end def add_post(one_post) @posts << one_post one_post.author = self end def add_post_by_title(post_title) one_post = Post.new(post_title) @posts << one_post one_post.author = self end def self.post_count Post.all.count end end
Rails.application.routes.draw do get "/" => "tasks#home" end
module Common def initialize super() end def get_check_last_runtime(client, check) request = RestClient::Resource.new( "#{config[:sensu_scheme]}://#{config[:sensu_api]}:#{config[:sensu_port]}/#{client}/#{check}", timeout: config[:sensu_timeout], user: config[:sensu_user], password: config[:sensu_password] ) check = JSON.parse(request.get, symbolize_names: true) Time.at(check[:check][:issued]) rescue RestClient::ResourceNotFound nil rescue Errno::ECONNREFUSED warning 'Connection refused' rescue RestClient::RequestFailed warning 'Request failed' rescue RestClient::RequestTimeout warning 'Connection timed out' rescue RestClient::Unauthorized warning 'Missing or incorrect Sensu API credentials' rescue JSON::ParserError warning 'Sensu API returned invalid JSON' end end
class ReviewsController < ApplicationController def create @product = Product.find(params[:product_id]) @review = @product.reviews.create(review_params) redirect_to product_path(@product) end private def review_params params.require(:review).permit(:reviewer, :review_title, :review) end end
class Login def initialize(params) @params = params end def call user = User.find_by(email: @params['email']).try(:authenticate, @params['password']) token = user ? user.generate_access_token : nil if token.nil? Error.new(I18n.t('api.login_fail')) else Success.new(token) end end end
module LtreeRails module HasLtree extend ActiveSupport::Concern module ClassMethods def has_ltree(opt = {}) include_dependencies check_options!(opt) apply_options(opt) end alias_method :act_as_ltree, :has_ltree private def include_dependencies include ::LtreeRails::Support include ::LtreeRails::Configurable include ::LtreeRails::Model end def check_options!(opt) opt.assert_valid_keys(*::LtreeRails::Configuration::CONFIGURABLE_OPTIONS.keys) end def apply_options(opt) opt.each do |option, value| ltree_config[option] = value end end end end end