text
stringlengths
10
2.61M
# Your code goes here! class Anagram def initialize(anagram_word) @anagram_word = anagram_word end def match(word_array) word_array.select do |word| anagram?(word) end end def anagram?(word) word.chars.sort == @anagram_word.chars.sort end end
class UsersController < Clearance::UsersController def edit @user = User.find(params[:id]) backgrounds = Dir.glob("app/assets/images/bground/**/*") @backgrounds = backgrounds.map do |x| x.slice(3..10) + x.slice(18..-1) end end def update @user = User.update(params[:id], edit_user_params) redirect_to edit_user_path end private def edit_user_params params.require(:user).permit(:name, :email, :password, :avatar, :background, :ourbackground) end end
Sword::Patch.new 'launchy' do module Sword::CLI on '-o', '--open', 'Open development page in the browser' do Launchy.open "http://127.0.0.1:#{@settings[:Port]}" end end end
require 'netlink/constants' # Imported from linux/genetlink.h module Netlink module Generic GENL_NAMSIZ = 16 GENL_MIN_ID = Netlink::NLMSG_MIN_TYPE GENL_MAX_ID = 1023 GENL_ID_GENERATE = 0 GENL_ID_CTRL = Netlink::NLMSG_MIN_TYPE # Constants for generic netlink controller CTRL_CMD_UNSPEC = 0 CTRL_CMD_NEWFAMILY = 1 CTRL_CMD_DELFAMILY = 2 CTRL_CMD_GETFAMILY = 3 CTRL_CMD_NEWOPS = 4 CTRL_CMD_DELOPS = 5 CTRL_CMD_GETOPS = 6 CTRL_CMD_NEWMCAST_GRP = 7 CTRL_CMD_DELMCAST_GRP = 8 CTRL_CMD_GETMCAST_GRP = 9 CTRL_CMD_MAX = CTRL_CMD_GETMCAST_GRP CTRL_ATTR_UNSPEC = 0 CTRL_ATTR_FAMILY_ID = 1 CTRL_ATTR_FAMILY_NAME = 2 CTRL_ATTR_VERSION = 3 CTRL_ATTR_HDRSIZE = 4 CTRL_ATTR_MAXATTR = 5 CTRL_ATTR_OPS = 6 CTRL_ATTR_MCAST_GROUPS = 7 CTRL_ATTR_MAX = CTRL_ATTR_MCAST_GROUPS CTRL_ATTR_OP_UNSPEC = 0 CTRL_ATTR_OP_ID = 1 CTRL_ATTR_OP_FLAGS = 2 CTRL_ATTR_OP_MAX = CTRL_ATTR_OP_FLAGS CTRL_ATTR_MCAST_GRP_UNSPEC = 0 CTRL_ATTR_MCAST_GRP_NAME = 1 CTRL_ATTR_MCAST_GRP_ID = 2 CTRL_ATTR_MCAST_GRP_MAX = CTRL_ATTR_MCAST_GRP_ID end end
module Roadmap # Retrieves roadmap data for current users # Params: chain_id = integer | chain_id can be retrived by running the get_me method on the current user. It is found listed under current_enrollement/chain_id def get_roadmap(chain_id) # Point the HTTParty GET method at the roadmaps/#{chain_id} endpoint of Bloc's API. # Use HTTParty's header option to pass the auth_token. response = self.class.get(api_url("roadmaps/#{chain_id}"), headers: { "authorization" => @auth_token }) # Parse the JSON document returned in the response into a Ruby hash. JSON.parse(response.body) end # Retrieves individual checkpoint data # Params: checkpoint_id = integer | checkpoint_id can be retrived by running the get_roadmap method on the current user. It is found listed under sections/checkpoint/id. def get_checkpoint(checkpoint_id) # Point the HTTParty GET method at the checkpoints/#{checkpoint_id} endpoint of Bloc's API. # Use HTTParty's header option to pass the auth_token. response = self.class.get(api_url("checkpoints/#{checkpoint_id}"), headers: { "authorization" => @auth_token }) # Parse the JSON document returned in the response into a Ruby hash. JSON.parse(response.body) end # Retrieves the remaining checkpoints for the current user # Params: chain_id = integer | chain_id can be retrived by running the get_me method on the current user. It is found listed under current_enrollement/chain_id def get_remaining_checkpoints(chain_id) # Point the HTTParty GET method at the enrollment_chains/#{chain_id}/checkpoints_remaining_in_section endpoint of Bloc's API. # Use HTTParty's header option to pass the auth_token. response = self.class.get(api_url("enrollment_chains/#{chain_id}/checkpoints_remaining_in_section"), headers: { "authorization" => @auth_token }) # Parse the JSON document returned in the response into a Ruby hash. JSON.parse(response.body) end end
class Api::V1::PostsController < Api::V1::ApplicationController def create @post = Post.new(post_params) @post.user_id = @current_user.id if @post.save render json: serialize(@post), status: :created else render json: {errors: @post.errors}, status: :unprocessable_entity end end def show find_post render json: serialize(@post) end def index @posts = [] # Preparing users posts posts = Api::V1::PostResource.apply_sort @current_user.posts, Api::V1::PostResource.default_sort, nil posts = JSONAPI::Paginator.paginator_for(:paged).new(index_params[:page]).apply(posts, nil) posts.each do |el| @posts << Api::V1::PostResource.new(el, nil) end @posts = JSONAPI::ResourceSerializer.new(Api::V1::PostResource).serialize_to_hash @posts total = Post.all.count response.headers['total'] = total response.headers['pages'] = (total/params[:page][:size].to_f).ceil render json: @posts, status: :ok end private def find_post @post = Post.find(params[:id]) end def index_params params.permit(page: [:size, :number]) end def post_params params.permit(:title, :body, :published_at) end end
Rails.application.routes.draw do root 'welcome#index' namespace :api do post 'auth_user' => 'user_token#create' post 'auth_admin' => 'admin_token#create' namespace :v1 do resources :user, only: [:create, :update, :show] resources :admin, only: [:create, :destroy, :show] resources :station resources :bus resources :route do resources :route_stop end end end end
# frozen_string_literal: true module Admin class QuestionsController < ApplicationController # before_action :authenticate, only: %i[create] def index @questions = Question.where(user_id: params[:user_id]) end def index_all @questions = Question.all end def create @question = Question.new(permit_params) @question.user_id = params[:user_id] redirect_to admin_user_question_path id: @question.id if @question.save end def show @question = Question.find(params[:id]) end def edit @question = Question.find(params[:id]) end def update @question = Question.find(params[:id]) @question.update(permit_params) redirect_to admin_question_path id: @question.id end private def permit_params params.require(:question).permit(:title, :description, :user_id) end end end
# To run all tests, in the project directory run the command: # bundle exec rails test # ---------------------------------------- # To run this test, in the project directory run the command: # bundle exec rails test test/models/event_test.rb require "test_helper" class EventTest < ActiveSupport::TestCase def setup @daily = events(:repeat_daily) @morning = @daily.date.at_beginning_of_day end test "repeat start and end shouldn't impact original event if repeat type is none" do event = events(:repeat_none_with_start_and_end) repeat_events = event.events_in_range event.date - 2.days, event.end_date + 2.days assert_equal 1, repeat_events.length end test "users should have access to their own events" do assert categories(:private).accessible_by?(users(:viktor)), "user does not have access to their own events (according to accessible_by?)" end test "hosted event privacy can be restricted by the host event" do host_event = events(:music_convention) host_event.update!(category: categories(:private)) hosted_event = events(:music_convention_joe) assert hosted_event.accessible_by? users(:joe) assert_not hosted_event.accessible_by? users(:putin) end test "private_version should return an event with its details hidden" do private_event = events(:simple).private_version assert_empty private_event.description, "event details were not hidden" end test "repeat clones should have proper date" do # DateTime is needed here, otherwise things just won't work # rubocop:disable DateTime start_date = (@daily.date - 2.days).to_datetime end_date = (@daily.end_date + 2.days).to_datetime repeat_dates = (start_date...end_date).map(&:to_date) # rubocop:enable DateTime # get the dates the repeat instances fall on event_dates = @daily.events_in_range(start_date, end_date).map { |r| r.date.to_date } # since the event repeats daily, it should use all of the dates. assert_equal repeat_dates, event_dates end test "get_name will return either the event name or a placeholder" do assert_equal events(:simple).name, events(:simple).get_name, "Named event did not return it's name" assert_not_empty events(:nameless_event).get_name, "Nameless event should return some placeholder name" end test "get_html_name will return either the event name or an html placeholder" do assert_equal events(:simple).name, events(:simple).get_html_name, "Named event did not return it's name" html_name = events(:nameless_event).get_html_name assert_not_empty html_name, "Nameless event should return some placeholder name" assert html_name.valid_html?, "Placeholder name must be valid html" end test "current? should return true for events that are happening right now" do event = events(:simple) event.date = 1.hour.ago event.end_date = 1.hour.from_now assert event.current?, "Current event was not considered current" event.date = 1.hour.from_now event.end_date = 2.hours.from_now assert_not event.current?, "Non-current event considered current" end test "events_in_range should ignore repeat events that have not started yet" do @daily.repeat_start = @morning + 1.day @daily.repeat_end = @morning + 3.days events = @daily.events_in_range(@morning, @morning + 4.days) assert_not_includes events, @daily end test "events_in_range should work with 1 directional infinite repeats" do @daily.repeat_start = @morning @daily.repeat_end = nil events = @daily.events_in_range(@morning - 5.days, @morning + 77.days) assert_equal 77, events.length end test "events_in_range should not include repeat events that are on break" do exception = repeat_exceptions(:one) exception.start = @morning exception.end = @morning.at_end_of_day + 2.days @daily.repeat_exceptions << exception events = @daily.events_in_range(@morning, @morning.at_end_of_day + 3.days) assert_equal 1, events.length, "repeated events that are on break not being excluded" end # DST EXPLAINED # # Chicago's time zone is Central Standard Time (CST); except, between dates such as # March 12, 2017 at 2:00am - November 5, 2:00am, Chicago is in Daylight Savings Time (DST). # When Chicago is in DST its clock "moves ahead 1 hour". test "you understand how daylight savings works" do user_time_zone = Time.find_zone("America/Chicago") # typically we're given a time from a user and store it in the database in UTC time. time_before_dst = user_time_zone.parse("1st March 2018 4:00:00 PM").utc assert_equal "10:00 PM", time_before_dst.strftime("%I:%M %p") # CST -> UTC offset is +6 hours # Now, UTC doesn't care about DST. If we go from CST to DST, it doesn't care. time_after_dst = time_before_dst + 1.month assert_equal "10:00 PM", time_after_dst.strftime("%I:%M %p") # When converting back into a time zone it *does* care, though. assert_equal "05:00 PM", time_after_dst.in_time_zone(user_time_zone).strftime("%I:%M %p") # If our goal is to get a UTC time that represents 4:00 PM regardless of DST, then # we must put our original date in the context of a time zone before generating any new # dates relative to the original date. test_time = time_before_dst.in_time_zone(user_time_zone) + 1.month assert_equal "04:00 PM", test_time.strftime("%I:%M %p") # Sure enough, the UTC time has been adjusted. assert_equal "09:00 PM", test_time.utc.strftime("%I:%M %p") # This is important because repeat events may have some dates that # occur in DST while others don't. Thus, the 'date' property of clones, # which is stored in UTC, must be adjusted in the same way this example was # to ensure that all clone occur at the same time as the origin event. end # see DST EXPLAINED test "events_in_range_fixed_timestep preserves event time across DST" do zone = Time.find_zone("America/Chicago") @daily.date = zone.parse("12th Mar 2017 01:00:00 AM") # event occurs before DST @daily.end_date = @daily.date + 1.hour # get events before and after DST goes into effect events = @daily.events_in_range(@daily.date, @daily.date + 2.days, zone) assert_equal 1, events.first.date.in_time_zone(zone).hour assert_equal 1, events.last.date.in_time_zone(zone).hour end # see DST EXPLAINED test "dates_in_range_certain_weekdays preserves event time across DST" do zone = Time.find_zone("America/Chicago") event = events(:current_event_1) event.date = zone.parse("1st March 2018 7:00:00 PM") # event created before DST event.end_date = event.date + 2.hour event.repeat = "certain_days-1" # repeat every monday # get events after DST has gone into effect events = event.events_in_range(Date.new(2018, 6, 4), Date.new(2018, 6, 10), zone) event_time = events.first.date.in_time_zone(zone).strftime("%I:%M %p") assert_equal "07:00 PM", event_time end test "events can be repeated daily, weekly, monthly, and yearly" do event = events(:repeat_daily) start = event.date event.end_date = start + 2.hours event.repeat = "daily" events = event.events_in_range start, start + 4.days assert_equal 4, events.length, "daily event should only repeat 4 times in 4 days" events = event.events_in_range start, start + 4.days + 3.hours assert_equal 5, events.length, "daily event should only repeat 5 times in 4.25 days" event.repeat = "weekly" events = event.events_in_range start.to_date.at_beginning_of_month, start.to_date.at_end_of_month assert_equal 5, events.length, "this weekly event should repeat 5 times in december of 2015" event.repeat = "monthly" events = event.events_in_range(start.at_beginning_of_year, start.at_end_of_year) assert_equal 12, events.length, "monthly event should only repeat 12 times in 1 year" event.repeat = "yearly" events = event.events_in_range(start.at_beginning_of_year, start.at_beginning_of_year + 2.years) assert_equal 2, events.length, "yearly event should only repeat 2 times in 2 years" end test "events can occur on certain days" do start_date = Time.current.at_beginning_of_week end_date = Time.current.at_end_of_week event = events(:repeat_daily) event.repeat = "certain_days-1,3,4,5" # M,W,R,F, totally an implementation detail event.repeat_start = start_date event.repeat_end = end_date assert_equal 4, event.events_in_range(start_date, end_date).length, "event should only repeat on 4/7 days of the week" end test "events with an improper repeat field just do not repeat" do event = events(:repeat_daily) event.repeat = "noot" event.date = 1.hour.from_now event.end_date = 2.hours.from_now event.repeat_start = Time.current event.repeat_end = 3.days.from_now events = event.events_in_range 1.week.ago.to_date, 1.week.from_now.to_date assert_equal 1, events.length end test "custom repeat events work" do event = events(:repeat_daily) # event is set for monday morning start = event.date.beginning_of_week event.date = start + 1.hour event.end_date = start + 2.hours event.repeat_start = start # every n days event.repeat = "custom-2-days" # implementation detail event.repeat_end = start + 1.week assert_equal 4, event.events_in_range(start, start + 1.week).length # negative test assert_empty event.events_in_range(start - 4.weeks, start - 2.weeks), "events_in_range returned events outside of the event's range" assert_empty event.events_in_range(start + 2.weeks, start + 4.weeks), "events_in_range returned events outside of the event's range" # randomly specific test assert_equal 2, event.events_in_range(start - 2.day, start + 4.days).length # every n weeks event.repeat = "custom-2-weeks" event.repeat_end = start + 4.weeks assert_equal 2, event.events_in_range(start, start + 4.weeks).length, "event should appear every other week over the course of the next 4 weeks" # negative test assert_empty event.events_in_range(start - 4.weeks, start - 2.weeks), "events_in_range returned events outside of the event's range" # every n months event.repeat = "custom-2-months" event.repeat_end = start + 4.months assert_equal 2, event.events_in_range(start, start + 4.month).length # negative test assert_empty event.events_in_range(start - 4.weeks, start - 2.weeks), "events_in_range returned events outside of the event's range" # every n years event.repeat = "custom-2-years" event.repeat_end = start + 3.years assert_equal 2, event.events_in_range(start, start + 3.year).length # negative test assert_empty event.events_in_range(start - 4.weeks, start - 2.weeks), "events_in_range returned events outside of the event's range" end test "events that repeat yearly appear on the correct dates" do event = events(:simple) event.date = Date.new(2015, 10, 21) event.end_date = event.date + 1.day event.repeat = "yearly" clone_date = event.events_in_range(Date.new(2017, 10, 1), Date.new(2017, 10, 30)).first.date.to_date assert_equal Date.new(2017, 10, 21), clone_date assert_equal 1, event.events_in_range(Date.new(2017, 10, 7), Date.new(2017, 10, 28)).length # negative tests: # in right day range but wrong month assert_empty event.events_in_range(Date.new(2017, 7, 1), Date.new(2017, 7, 30)) # in right month but before event assert_empty event.events_in_range(Date.new(2017, 10, 7), Date.new(2017, 10, 20)) assert_empty event.events_in_range(Date.new(2017, 10, 13), Date.new(2017, 10, 20)) # in right month but after event assert_empty event.events_in_range(Date.new(2017, 10, 22), Date.new(2017, 10, 29)) end test "changing event gives guest a notification" do event = events(:music_convention) # Has several invited users, but we just check one guest = users(:norm) event.name += " Changed" event.save # Ensure there is one notification for this event being updated assert Notification.exists?( entity: event, receiver: guest, event: Notification.events["event_update"] ) end test "changing event does not notify current user" do current_user = Current.user = users(:viktor) # set current user globals event = events(:music_convention) # Has several invited users, but we just check one event.name += " Changed" event.save # Ensure there are no notifications for this event being updated assert_not Notification.exists?( entity: event, receiver: current_user, event: Notification.events["event_update"] ) end test "changing host(ed) event category should not notify guests" do event = events(:music_convention) assert_no_difference -> { Notification.count } do event.update!(category: categories(:followers)) end end test "deleting host event removes hosted event" do host_event = events(:music_convention) # owned by viktor assert_difference -> { Event.count }, -2 do host_event.destroy! end end test "deleting a hosted event removes the associated invite" do hosted_event = events(:music_convention_joe) assert_difference -> { EventInvite.count }, -1 do hosted_event.destroy! end end test "updating a host event updates associated hosted events" do host_event = events(:music_convention) hosted_event = events(:music_convention_joe) host_event.update! name: "Pub Crawl" hosted_event.reload assert_equal "Pub Crawl", hosted_event.name end end
class AccountImport include Sidekiq::Worker sidekiq_options queue: :import_file, retry: 1 def perform(hash) @representative = Representative.find_by(representative_number: hash["representative_number"]) @account = Account.find_by(representative_id: @representative.id, policy_number_entered: hash["policy_number"] ) if @account @account.update_attributes(hash.except("representative_number", "policy_number")) else @account = Account.new(representative_id: @representative.id, policy_number_entered: hash["policy_number"]) @account.assign_attributes(hash.except("representative_number", "policy_number")) @account.save @policy_calculation = PolicyCalculation.where(account_id: @account.id).update_or_create( representative_number: @representative.representative_number, policy_number: @account.policy_number_entered, representative_id: @account.representative_id, account_id: @account.id ) end end end
class AddReviewRawToRating < ActiveRecord::Migration def change add_column :ratings, :review_raw, :text end end
# frozen_string_literal: true require 'yaml' module OfflineSort module Chunk module InputOutput class Yaml < OfflineSort::Chunk::InputOutput::Base # The yaml parser does not expose a document enumerator that we can call next on without loading the entire file def read_entry YAML.load(next_document) # rubocop:disable Security/YAMLLoad, this is loading from a trusted source end def write_entry(entry) io.write(YAML.dump(entry)) end private def next_document sio = StringIO.new document_count = 0 line = nil loop do line = io.gets document_count += 1 if line && line.start_with?('---') sio.write(line) break if line.nil? || document_count > 1 end # reset the io to the beginning of the document io.seek(io.pos - line.length, IO::SEEK_SET) if document_count > 1 raise EOFError unless sio.size > 0 # rubocop:disable Style/ZeroLengthPredicate sio.string end end end end end
class TimeTravelsController < ApplicationController def create tc_action = params[:tc_action] setting_time = Time.zone.parse(params[:tc_date]) if params[:tc_date].present? operation_name = "" result = case tc_action when "freeze" operation_name = "固定" Timecop.freeze(setting_time) when "travel" operation_name = "移動" Timecop.travel(setting_time) end if result flash[:notice] = "時刻を#{result}に#{operation_name}しました" else Timecop.return flash[:notice] = "時間を元に戻しました" end redirect_back(fallback_location: root_path) end end
class Transaction < ActiveRecord::Base has_many :transaction_categories has_many :categories, through: :transaction_categories belongs_to :account, primary_key: :plaid_account_id def self.create_plaid_transactions(plaid_transactions) return [] unless plaid_transactions.present? plaid_transactions.each do |transaction| account = Account.where('plaid_id = ?', transaction.account).first next unless account data = { plaid_account_id: transaction.account, description: transaction.name, amount: transaction.amount, posted_date: transaction.date, plaid_id: transaction.id } tran = where('plaid_id = ?', transaction.id).first if tran tran.update(data) tran.save else tran = Transaction.create(data) end if transaction.cat.hierarchy && transaction.cat.hierarchy.length > 0 transaction.cat.hierarchy.each do |category| c = Category.find_by(name: category) t_cat = TransactionCategory.find_by(category: c, transaction_id: tran.id) tran.categories << c if t_cat.nil? && !tran.categories.collect(&:name).include?(category) end tran.save end end end end
class ChangeTrain < ActiveRecord::Migration[5.1] def change add_reference :trains, :current_station, index: true add_foreign_key :trains, :stations, column: :current_station_id end end
# Process the list of successfully accessed urls for each day to produce a # single file containing the dates when each such url was first and last # accessed. require 'open3' require_relative 'config_logging' class FirstLastSuccessCalculator attr_reader :daily_successes_dir attr_reader :first_last_file attr_reader :first_last_sources_file def initialize(processed_dir) successes_dir = "#{processed_dir}/successes" @daily_successes_dir = "#{successes_dir}/daily" @first_last_file = "#{successes_dir}/first_last" @first_last_sources_file = "#{successes_dir}/first_last_sources" end def process remove_out_of_date_output update_first_last end private def current_daily_files_and_sizes @current_daily_files_and_sizes ||= begin Dir["#{daily_successes_dir}/successes_*"].each_with_object({}) { |path, result| result[path] = File.size(path) } end end def stored_daily_files_and_sizes @stored_daily_files_and_sizes ||= begin if File.exist? first_last_sources_file File.readlines(first_last_sources_file).each_with_object({}) { |line, result| path, stored_size = line.strip.split(/ /, 2) result[path] = stored_size.to_i } else {} end end end def remove_out_of_date_output if source_files_have_changed_or_gone? remove_generated_files end end def source_files_have_changed_or_gone? stored_daily_files_and_sizes.each do |path, stored_size| current_size = current_daily_files_and_sizes[path] if current_size.nil? || current_size != stored_size.to_i return true end end false end def remove_generated_files if File.exist? first_last_file $logger.info "Removing #{first_last_file}" File.unlink first_last_file end if File.exist? first_last_sources_file $logger.info "Removing #{first_last_sources_file}" File.unlink first_last_sources_file end @stored_daily_files_and_sizes = {} end def write_sources_used(dest_file) File.open(dest_file, "wb") do |output_fd| current_daily_files_and_sizes.sort.each do |daily_file, file_size| output_fd << "#{daily_file} #{file_size}\n" end end end def update_first_last # Maintain "first_last_file" with a line for the first and last successful # access of each path. Do this by finding any daily success files which # haven't been processed already (ie, aren't already in the # first_last_sources_file), sorting them together with the first_last_file, # and keeping the first and last entries for each url. source_files = ( current_daily_files_and_sizes.keys - stored_daily_files_and_sizes.keys ).sort if source_files.size == 0 $logger.info "No updated daily files" return end if File.exist?(first_last_file) source_files << first_last_file end $logger.info "Calculating first and last access times from:\n - #{source_files.join "\n - "}" temp_first_last_file = "#{first_last_file}.tmp" File.open(temp_first_last_file, "wb") do |output_file| Open3.popen2({"LC_ALL" => "C"}, "sort --files0-from=-") do |stdin, stdout, wait_thr| stdin.write(source_files.join("\0")) stdin.close last_path = nil last_line = nil stdout.each_line do |line| path, _date = line.split(" ") if path != last_path unless last_line.nil? output_file.write(last_line) end output_file.write(line) end last_path = path last_line = line end unless last_line.nil? output_file.write(last_line) end exit_status = wait_thr.value unless exit_status.success? raise "Sort failed, exit status #{exit_status.exitstatus}" end end end temp_first_last_sources_file = "#{first_last_sources_file}.tmp" write_sources_used(temp_first_last_sources_file) File.rename(temp_first_last_file, first_last_file) File.rename(temp_first_last_sources_file, first_last_sources_file) end end
# frozen_string_literal: true class CoinsController < ApplicationController def create @colleted_coins = ColletedCoin.new(collet_coins_params) if @colleted_coins.save Audit::CoinsWorker.perform_async(collet_coins_params[:user_id]) render json: { status: :success, msg: 'Has'}, status: :ok else render json: { status: :error, data: @colleted_coins.errors }, status: :unauthorized end end private def collet_coins_params params.permit(:value, :user_id) end end
class RemoveFurnitureSkuAndFurnitureIdFromOrders < ActiveRecord::Migration[6.0] def change remove_column :orders, :furniture_sku remove_column :orders, :furniture_id end end
require 'io/console' def input_students puts "Please enter a students' name and cohort" @students = [] name = gets.chomp while !name.empty? do cohort = gets.chomp cohort = cohort == '' ? :november : cohort.to_sym puts "Please enter the hobbies of the student" hobbies = gets.chomp puts "Please enter the country of birth of the student" country_of_birth = gets.chomp puts "Please enter the height of the student" height = gets.chomp @students << {name: name, cohort: cohort, hobbies: hobbies, country_of_birth: country_of_birth , height: height} puts "Now we have #{@students.count} student" + (@students.length == 1 ? '' : 's') puts "Please enter another name or just hit return twice to exit" name = gets.chomp end @students end def print_header puts 'The students of Villains Academy'.center(IO.console.winsize[1]) puts '-------------' end def print_students_list cohorts = [] @students.each do |student| if !cohorts.include?(student[:cohort]) then cohorts.push(student[:cohort]) end end cohorts.each do |cohort| @students.each do |student| if cohort == student[:cohort] puts "#{cohort.to_s.capitalize} cohort: #{student[:name]} (hobbies are: #{student[:hobbies]}, from #{student[:country_of_birth]}, #{student[:height]}cm tall)" end end end end def print_footer puts "Overall, we have #{@students.count} great student" + (@students.length == 1 ? '' : 's') end def print_menu puts "1. Input the student" puts "2. Show the student" puts "3. Save the list to students.csv" puts "4. Load the list from students.csv" puts "9. Exit" end def show_students print_header print_students_list print_footer end def process(selection) case selection when "1" input_students when "2" show_students when "3" save_students when "9" exit else puts "I don't know what you meant, try again" end end def interactive_menu loop do print_menu process(gets.chomp) end end def save_students file = File.open("students.csv", "w") @students.each do |student| student_data = [student[:name], student[:cohort]] csv_line = student_data.joi(",") file.puts csv_line end file.close end def load_students(filename = "students.csv") @students = [] file = File.open(filename, "r") file.readlines.each do |line| name, cohort = line.chomp.split(',') @students << {name: name, cohort: cohort.to_sym} end file.close end
class SpecialsController < ApplicationController before_filter :normalize_page_number, :only => [:city_day] before_filter :init_localities, :only => [:city, :city_day] before_filter :init_weather, :only => [:city, :city_day] # GET /specials def index @country = Country.us @state = @country.states.find_by_name("Illinois") @city = @state.cities.find_by_name("Chicago") redirect_to(specials_city_path(@country, @state, @city)) end # GET /specials/us/il/chicago def city # @country, @state, @city all iniitialized in before_filter @today = Time.zone.now @days = Special.days @title = [@city.name.titleize, 'Specials'].reject(&:blank?).join(' ') @h1 = @title track_special_ga_event(params[:controller], @city) end # GET /specials/us/il/chicago/weekly # GET /specials/us/il/chicago/monday def city_day # @country, @state, @city all iniitialized in before_filter @day = params[:day].to_s # find tags that specials should be marked with @tags = [Tag.find_by_name(Special.tag_name), Special.day?(@day) ? Tag.find_by_name(@day) : ''].reject(&:blank?) # build sphinx options @hash = Search.query('special') @attributes = Hash[:tag_ids => @tags.collect(&:id), :city_id => @city.id] @klasses = [Appointment] @sort_order = "@relevance desc" @eager_loads = [{:location => :company}, :tags] @page = params[:page] ? params[:page].to_i : 1 @sphinx_options = Hash[:classes => @klasses, :with_all => @attributes, :match_mode => :extended2, :rank_mode => :bm25, :order => @sort_order, :include => @eager_loads, :page => @page, :per_page => search_per_page, :max_matches => search_max_matches] self.class.benchmark("*** Benchmarking sphinx query", APP_LOGGER_LEVEL, false) do @specials = ThinkingSphinx.search(@hash[:query_quorum], @sphinx_options) # the first reference to 'specials' invokes the sphinx query logger.debug("*** [sphinx] specials: #{@specials.size}") end # build special keywords from special preferences # e.g. if the special has a preference called special_drink, the keyword will be 'drink' @keywords = @specials.inject([]) do |array, special| hash = Special.preferences(special.preferences) hash.keys.each do |key| tagging = Special.preference_name(key) array.push(tagging) unless array.include?(tagging) end array end.sort @other_days = Special.days - [@day.titleize] @title = [@city.name.titleize, @day.titleize, 'Specials'].reject(&:blank?).join(' ') @h1 = @title track_special_ga_event(params[:controller], @city, @day) end protected def search_max_matches 100 end def search_per_page mobile_device? ? 5 : 5 end def search_max_page search_max_matches / search_per_page end end
require 'rake/tasklib' module CovTasks module Spec class SegCov < Rake::TaskLib attr_accessor :spec_opts attr_accessor :rcov_opts attr_accessor :ruby_cmd attr_accessor :verbose def initialize(name=:segcov) @name = name @spec_files = [] @spec_opts = [] @rcov_opts = [] @rcov_include_files = [] @verbose = true yield self if block_given? end def define spec_script = `which spec`.chomp if spec_script.nil? || spec_script == "" spec_script = 'script/spec' end task @name do collect_files_to_run load_spec_opts_file load_rcov_opts_file add_segcov_rcov_opts unless @spec_files.empty? rm_rf('coverage') if File.exists?(File.join(Dir.pwd, 'coverage')) cmd_parts = [ruby_cmd || RUBY] cmd_parts << "-S rcov" cmd_parts += rcov_opts cmd_parts << spec_script cmd_parts << "--" cmd_parts += @spec_files cmd_parts += @spec_opts cmd = cmd_parts.join(' ') puts cmd if verbose unless system(cmd) raise("Command #{cmd} failed") end end end end def self.define!(name=:segcov, &block) self.new(name, &block).define end def self.run! self.define!.invoke end def collect_files_to_run @rcov_include_files = ENV['FILES'].split(/,/).select { |file| unless File.exists?(spec_for_file(file)) STDERR.puts "Missing spec file: #{spec_for_file(file)}" next false end true } @spec_files = @rcov_include_files.map { |file| spec_for_file(file) } end def spec_for_file(file) "spec/#{file.sub(/^app\//, '').sub(/\.rb$/, '_spec.rb')}" end def load_spec_opts_file if(File.exists?(File.join(Dir.pwd, 'spec/spec.opts'))) File.readlines(File.join(Dir.pwd, 'spec/spec.opts')).each do |line| self.spec_opts << line.chomp end end end def load_rcov_opts_file if(File.exists?(File.join(Dir.pwd, 'spec/rcov.opts'))) File.readlines(File.join(Dir.pwd, 'spec/rcov.opts')).each do |line| self.rcov_opts << line.chomp end end end def add_segcov_rcov_opts @rcov_opts << "--exclude 'app/*,lib/*,db/*,spec/*,vendor/*,config/*'" @rcov_opts << "--include-file '#{@rcov_include_files.join(',')}'" end end end end
class CreateRealms < ActiveRecord::Migration[5.0] def change create_table :realms do |t| t.string :name, null: false t.string :slug, null: false t.string :realm_type, null: false t.string :population, null: false t.string :battlegroup, null: false t.string :locale, null: false t.string :timezone, null: false t.timestamps end end end
require 'rails_helper' RSpec.describe Account, type: :model do subject { create(:account) } describe 'validations' do describe 'association' do it { is_expected.to belong_to(:user) } it { is_expected.to have_many(:account_transactions) } end describe 'presence' do it { is_expected.to validate_presence_of(:branch) } it { is_expected.to validate_presence_of(:account_number) } it { is_expected.to validate_presence_of(:limit) } it { is_expected.to validate_presence_of(:last_limit_update) } end describe 'uniqueness' do it do expect(subject).to validate_uniqueness_of(:account_number) .scoped_to(:branch).case_insensitive end end describe 'length' do it { is_expected.to validate_length_of(:branch).is_equal_to(4) } it { is_expected.to validate_length_of(:account_number).is_equal_to(5) } end describe 'numericality' do it { is_expected.to validate_numericality_of(:branch).only_integer } it { is_expected.to validate_numericality_of(:account_number).only_integer } it { is_expected.to validate_numericality_of(:limit).is_greater_than_or_equal_to(0.0) } it { is_expected.to validate_numericality_of(:balance).is_greater_than_or_equal_to(0.0) } end end end
require 'fileutils' module Wordx class ContentType def initialize() @file_path = "[Content_Types].xml" end def create(zos) ns = { "xmlns"=>"http://schemas.openxmlformats.org/package/2006/content-types" } builder = Nokogiri::XML::Builder.new do |xml| xml.Types(ns) { xml.Override("PartName"=>"/_rels/.rels" , "ContentType"=>"application/vnd.openxmlformats-package.relationships+xml") xml.Override("PartName"=>"/word/document.xml" , "ContentType"=>"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml") xml.Override("PartName"=>"/word/styles.xml" , "ContentType"=>"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml") xml.Override("PartName"=>"/word/_rels/document.xml.rels", "ContentType"=>"application/vnd.openxmlformats-package.relationships+xml") xml.Override("PartName"=>"/word/settings.xml" , "ContentType"=>"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml") xml.Override("PartName"=>"/word/fontTable.xml" , "ContentType"=>"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml") xml.Override("PartName"=>"/docProps/app.xml" , "ContentType"=>"application/vnd.openxmlformats-officedocument.extended-properties+xml") xml.Override("PartName"=>"/docProps/core.xml" , "ContentType"=>"application/vnd.openxmlformats-package.core-properties+xml") xml.Override("PartName"=>"/word/numbering.xml", "ContentType"=>"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml") } end zos.put_next_entry(@file_path) zos.write (builder.to_xml.sub!('<?xml version="1.0"?>','<?xml version="1.0" encoding="UTF-8"?>')) end end end
class RenamePursuitToTicket < ActiveRecord::Migration def change rename_table :pursuits, :tickets remove_column :tickets, :status remove_column :tickets, :image remove_column :tickets, :image_file_name remove_column :tickets, :image_content_type remove_column :tickets, :image_file_size remove_column :tickets, :image_updated_at remove_column :tickets, :description add_column :tickets, :section, :string add_column :tickets, :row, :string add_column :tickets, :seat, :string end end
# frozen_string_literal: true class UsersController < ApplicationController before_action :only_admin! before_action :load_user, only: %i[list_accounts edit update] def index @users = User.all end def edit; end def update @user.update(user_params) redirect_to edit_user_path(@user), notice: 'Настройки сохранены' end def list_accounts @accounts = @user.accounts end private def load_user @user = User.find(params[:id] || params[:user_id]) end def user_params params.require(:user).permit(:rucaptcha_key) end end
Then(/^debug$/) do save_and_open_page end Given(/^the application exists$/) do true # no set up required at this point end When(/^I visit the home page$/) do visit '/' end Then(/^I should be on the (.*) page$/) do |pagename| # assumes that content_for :title includes pagename # e.g. <% content_for :title do %>Bulldog-Clip:Home<% end %> title.should include pagename end Given(/^I am not signed in$/) do visit '/users/sign_out' end Then(/^I should see a (.*) link$/) do |link| expect(page.has_link?(link)).to be_true end Then(/^I should not see a (.*) link$/) do |link| expect(page.has_link?(link)).to be_false end Given /^I click the first table row$/ do find(:xpath, "//table/tbody/tr[1]").click end When(/^I click on (.+)$/) do |link| click_link(link) end When(/^I enter a valid email and password$/) do fill_in 'user_email', with: 'example@example.com' fill_in 'user_password', with: 'secret12' fill_in 'user_password_confirmation', with: 'secret12' click_on 'Sign Up' end Then(/^I should see "(.*?)"$/) do |text| page.should have_content text end Then(/^I should not see "(.*?)"$/) do |text| page.should_not have_content text end When(/^I fill in address details and click save$/) do fill_in 'account_name', with: 'My Name' fill_in 'account_address', with: 'My House\n My Street\n My Town' fill_in 'account_postcode', with: 'ABC 123' click_on 'Save' end Then(/^I have an Account record saved$/) do find_user account = Account.find_by user_id: @user.id expect(account).to be_true end When(/^I fill in customer details and click save$/) do fill_in 'customer_name', with: 'My Customer' fill_in 'customer_address', with: 'My House\n My Street\n My Town' fill_in 'customer_postcode', with: 'ABC 123' click_on 'Save' end Then(/^I should have a Customer record saved$/) do customer = Customer.find_by account_id: @account.id expect(customer).to be_true end Given(/^I have a customer$/) do create_customer end Given(/^I visit the Customers page$/) do visit '/customers' end Given(/^There is another account with a customer$/) do create_another_customer end Then(/^I should only see my customer$/) do page.should_not have_content 'Another' end
# frozen_string_literal: true require 'pry' class Follower attr_reader :name, :age, :life_motto attr_accessor :cult @@all = [] def initialize(name, age, life_motto) @name = name @age = age @life_motto = life_motto @@all << self end def self.all @@all end def cults BloodOath.all.map(&:cult) end def join_cult(cult) BloodOath.new(self, cult) end def self.of_a_certain_age(age) self.all.select { |follower| follower.age >= age } end def my_slogans cults.map(&:slogan).uniq end def self.most_active self.all.max_by(&:name) end def self.top_ten self.all.max_by(10, &:name) end end
require 'rails_helper' feature 'users can visit their profile' do scenario 'when a user gets created it redirects to profile page' do visit new_user_registration_path fill_in 'Email', with: 'spencer.dixon@gmail.com' fill_in 'Name', with: 'Spencer Dixon' fill_in 'Password', with: '12345678' fill_in 'Password confirmation', with: '12345678' click_on 'Sign up' expect(page).to have_content('Welcome, Spencer Dixon') end end
# frozen_string_literal: true ## # Allows running the lambda function on your local development machine for # testing purposes. # # bundle exec ruby ./run_lambda_locally.rb # require_relative 'lambda_function' lambda_handler( event: { 'command' => 'inspec exec https://github.com/mitre/redhat-enterprise-linux-7-stig-baseline/archive/master.tar.gz'\ ' -t ssh://ssm-user@i-00f1868f8f3b4eb03'\ ' --sudo'\ ' -i /tmp/tmp_ssh_key'\ ' --input=\'disable_slow_controls=true\''\ ' --proxy-command=\'sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p"\'', 'results_name' => 'redhat-enterprise-linux-7-stig-baseline-inspec-rhel7-test', 'results_buckets' => [ 'inspec-results-bucket-dev' ], 'eval_tags' => 'ServerlessInspec,RHEL7,inspec-rhel7-test,SSH-SSM', 'tmp_ssm_ssh_key' => { 'host' => 'i-00f1868f8f3b4eb03', 'user' => 'ssm-user', 'key_name' => 'tmp_ssh_key' } }, context: nil ) # SSH command _ = { 'command' => 'inspec exec /tmp/redhat-enterprise-linux-7-stig-baseline-2.6.6.tar.gz'\ ' -t ssh://ec2-user@ec2-15-200-235-74.us-gov-west-1.compute.amazonaws.com'\ ' --sudo'\ ' --input=disable_slow_controls=true', 'results_name' => 'redhat-enterprise-linux-7-stig-baseline-inspec-rhel7-test', 'results_buckets' => [ 'inspec-results-bucket-dev' ], 'eval_tags' => 'ServerlessInspec,RHEL7,inspec-rhel7-test,SSH', 'resources' => [ { 'local_file_path' => '/tmp/redhat-enterprise-linux-7-stig-baseline-2.6.6.tar.gz', 'source_aws_s3_bucket' => 'inspec-profiles-bucket-dev', 'source_aws_s3_key' => 'redhat-enterprise-linux-7-stig-baseline-2.6.6.tar.gz' } ] } # SSH via SSM command (with tmp key) _ = { 'command' => 'inspec exec https://github.com/mitre/redhat-enterprise-linux-7-stig-baseline/archive/master.tar.gz'\ ' -t ssh://ssm-user@i-00f1868f8f3b4eb03'\ ' --sudo'\ ' -i /tmp/tmp_ssh_key'\ ' --input=\'disable_slow_controls=true\''\ ' --proxy-command=\'sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p"\'', 'results_name' => 'redhat-enterprise-linux-7-stig-baseline-inspec-rhel7-test', 'results_buckets' => [ 'inspec-results-bucket-dev' ], 'eval_tags' => 'ServerlessInspec,RHEL7,inspec-rhel7-test,SSH-SSM', 'tmp_ssm_ssh_key' => { 'host' => 'i-00f1868f8f3b4eb03', 'user' => 'ssm-user', 'key_name' => 'tmp_ssh_key' } } # AWSSSM command _ = { 'command' => 'inspec exec https://github.com/mitre/redhat-enterprise-linux-7-stig-baseline/archive/master.tar.gz'\ ' -t awsssm://i-00f1868f8f3b4eb03'\ ' --input=\'disable_slow_controls=true\'', 'results_name' => 'redhat-enterprise-linux-7-stig-baseline-inspec-rhel7-test', 'results_buckets' => [ 'inspec-results-bucket-dev' ], 'eval_tags' => 'ServerlessInspec,RHEL7,inspec-rhel7-test,AWSSSM' } # WinRM command _ = { 'command' => 'inspec exec /tmp/microsoft-windows-server-2019-stig-baseline-1.3.10.tar.gz'\ ' -t winrm://localhost'\ ' --password $WIN_PASS', 'results_name' => 'windows-server-2019-stig-baseline-inspec-win2019-test', 'results_buckets' => [ 'inspec-results-bucket-dev' ], 'eval_tags' => 'ServerlessInspec,WinSvr2019,inspec-win2019-test,WinRM', 'resources' => [ { 'local_file_path' => '/tmp/microsoft-windows-server-2019-stig-baseline-1.3.10.tar.gz', 'source_aws_s3_bucket' => 'inspec-profiles-bucket-dev', 'source_aws_s3_key' => 'microsoft-windows-server-2019-stig-baseline-1.3.10.tar.gz' }, { 'env_variable' => 'WIN_PASS', 'source_aws_ssm_parameter_key' => '/inspec/inspec-win2019-test/password' } ], 'ssm_port_forward' => { 'instance_id' => 'i-0e35ab216355084ee', 'ports' => [5985, 5986] } } # AWS CIS Baseline command _ = { 'command' => 'inspec exec /tmp/aws-foundations-cis-baseline-1.2.2.tar.gz'\ ' -t aws://', 'results_name' => 'aws-foundations-cis-baseline-6756-0937-9314', 'results_buckets' => [ 'inspec-results-bucket-dev' ], 'eval_tags' => 'ServerlessInspec,AwsCisBaseline,6756-0937-9314,AWS', 'resources' => [ { 'local_file_path' => '/tmp/aws-foundations-cis-baseline-1.2.2.tar.gz', 'source_aws_s3_bucket' => 'inspec-profiles-bucket-dev', 'source_aws_s3_key' => 'aws-foundations-cis-baseline-1.2.2.tar.gz' } ] } # k8s command _ = { 'command' => 'inspec exec https://gitlab.dsolab.io/scv-content/inspec/kubernetes/baselines/k8s-cluster-stig-baseline/-/archive/master/k8s-cluster-stig-baseline-master.tar.gz'\ ' -t k8s://', 'results_name' => 'k8s-cluster-stig-baseline-dev-cluster', 'results_buckets' => [ 'inspec-results-bucket-dev' ], 'eval_tags' => 'ServerlessInspec,k8s', 'resources' => [ { 'local_file_path' => '/tmp/kube/config', 'source_aws_s3_bucket' => 'inspec-profiles-bucket-dev', 'source_aws_s3_key' => 'kube-dev/config' }, { 'local_file_path' => '/tmp/kube/client.crt', 'source_aws_ssm_parameter_key' => '/inspec/kube-dev/client_crt' }, { 'local_file_path' => '/tmp/kube/client.key', 'source_aws_ssm_parameter_key' => '/inspec/kube-dev/client_key' }, { 'local_file_path' => '/tmp/kube/ca.crt', 'source_aws_ssm_parameter_key' => '/inspec/kube-dev/ca_crt' } ], 'env' => { 'KUBECONFIG' => '/tmp/kube/config' } }
require "active_record" def HardCodeModel(*attributes) struct = Struct.new(*attributes) class << struct def all @all || (create_all; @all) end def create(*values) @all ||= [] @all << new(*values) end def find(id) find_by_id(id) || raise(ActiveRecord::RecordNotFound) end def find_by_id(id) all.detect { |ct| ct.id == id.to_i } end def first all.first end end struct end module ActiveRecord class Base def self.belongs_to_struct(association, options = {}) with_id = association.to_s + "_id" klass = (options[:class_name] || association.to_s.camelize).constantize define_method association do id = self.send(with_id) id ? klass.find(id) : nil end define_method association.to_s + "=" do |value| self.send(with_id + "=", value && value.id) end end end end
class DeliverySlipsController < ApplicationController before_action :authenticate_user! before_action :set_delivery_slip, only: [:show, :edit, :update, :destroy] layout "dashboard" # GET /delivery_slips # GET /delivery_slips.json def index @delivery_slips = DeliverySlip.all end # GET /delivery_slips/1 # GET /delivery_slips/1.json def show end # GET /delivery_slips/new def new @delivery_slip = DeliverySlip.new @orders = Order.all @customers = Customer.all end # GET /delivery_slips/1/edit def edit @orders = Order.all @customers = Customer.all end # POST /delivery_slips # POST /delivery_slips.json def create @delivery_slip = current_user.delivery_slips.build(delivery_slip_params) respond_to do |format| if @delivery_slip.save @delivery_slips = DeliverySlip.all format.html { redirect_to @delivery_slip, notice: 'Delivery slip was successfully created.' } format.json { render :show, status: :created, location: @delivery_slip } format.js else format.html { render :new } format.json { render json: @delivery_slip.errors, status: :unprocessable_entity } format.js end end end # PATCH/PUT /delivery_slips/1 # PATCH/PUT /delivery_slips/1.json def update respond_to do |format| if @delivery_slip.update(delivery_slip_params) @delivery_slips = DeliverySlip.all format.html { redirect_to @delivery_slip, notice: 'Delivery slip was successfully updated.' } format.json { render :show, status: :ok, location: @delivery_slip } format.js else format.html { render :edit } format.json { render json: @delivery_slip.errors, status: :unprocessable_entity } format.js end end end def delete @delivery_slip = DeliverySlip.find(params[:delivery_slip_id]) end # DELETE /delivery_slips/1 # DELETE /delivery_slips/1.json def destroy @delivery_slip.destroy @delivery_slips = DeliverySlip.all respond_to do |format| format.html { redirect_to delivery_slips_url, notice: 'Delivery slip was successfully destroyed.' } format.json { head :no_content } format.js end end private # Use callbacks to share common setup or constraints between actions. def set_delivery_slip @delivery_slip = DeliverySlip.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def delivery_slip_params params.require(:delivery_slip).permit(:ref, :order_id, :customer_id) end end
class RemoveTriedQueryFromHosts < ActiveRecord::Migration[5.2] def up remove_column :hosts, :tried_query end def down add_column :hosts, :tried_query, :boolean, :default => false end end
module Rubot module Message class PlainText < Message::Base attr_accessor :sender_id, :text def initialize (sender_id, text) @text = text super(sender_id) end end end end
class Proc def callback(callable, *args) self === Class.new do method_name = callable.to_sym define_method(method_name) { |&block| block.nil? ? true : block.call(*args) } define_method("#{method_name}?") { true } def method_missing(method_name, *args, &block) false; end end.new end end def tweet(message, &block) block.callback :success rescue => e block.callback :failure, e.message end tweet "testing this tweet" do |on| on.success do puts "Tweet successful!" end on.failure do |status| puts "Error: #{status}" end end tweet("hello") { |tweet| puts tweet }
class FixChaptersTable < ActiveRecord::Migration def change rename_table :chapiters, :chapters add_column :chapters, :page_id, :integer end end
require 'spec_helper' describe Comment do before { @comment = Comment.new(text: "Ten blog jest najlepszy",) } subject { @comment } it { should respond_to(:text) } it { should respond_to(:fieldname) } it { should respond_to(:author) } it { should respond_to(:post_id) } end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Party.delete_all filepath = Rails.root.join('db', 'g0v-lyparser', 'party.json') parties = JSON.parse(File.read(filepath)) parties.each do |p| party = Party.new(p) party.id = p['id'] party.save end ISO3166TW = { "CHA" => "彰化縣", "CYI" => "嘉義市", "CYQ" => "嘉義縣", "HSQ" => "新竹縣", "HSZ" => "新竹市", "HUA" => "花蓮縣", "ILA" => "宜蘭縣", "KEE" => "基隆市", "KHH" => "高雄市", "KHQ" => "高雄市", "MIA" => "苗栗縣", "NAN" => "南投縣", "PEN" => "澎湖縣", "PIF" => "屏東縣", "TAO" => "桃園縣", "TNN" => "台南市", "TNQ" => "台南市", "TPE" => "台北市", "TPQ" => "新北市", "TTT" => "台東縣", "TXG" => "台中市", "TXQ" => "台中市", "YUN" => "雲林縣", "JME" => "金門縣", "LJF" => "連江縣" } def constituency_parser(constituency) case (constituency[0]) when 'proportional' return '全國不分區' when 'aborigine' return '山地原住民' when 'foreign' return '僑居國外國民' else if ISO3166TW[constituency[0]] if (constituency[1] == 0) result = ISO3166TW[constituency[0]] else result = ISO3166TW[constituency[0]] + '第' + constituency[1].to_s + '選區' end end return result end end Legislator.delete_all filepath = Rails.root.join('db', 'g0v-lyparser', 'mly-8.json') legislators = JSON.parse(File.read(filepath)) legislators.each do |l| legislator = Legislator.new() legislator.id = l['id'] legislator.party_id = Party.where(abbreviation: l['party']).first.id legislator.name = l['name'] legislator.image = '/legislators/160x214/' + l['id'].to_s + '.jpg' legislator.constituency = constituency_parser(l['constituency']) legislator.save end categories = [{:id => 1, :name => '媒體新聞'}, {:id => 2, :name => '兵團評論'}] Category.delete_all categories.each do |c| category = Category.new() category.id = c.id category.name = c.name category.save end
require 'pry' cart = [ {:item => "AVOCADO", :price => 3.00, :clearance => true }, {:item => "AVOCADO", :price => 3.00, :clearance => true }, {:item => "KALE", :price => 3.00, :clearance => false} ] def find_item_by_name_in_collection(name, collection) # Implement me first! # Implement me first! # # # Consult README for inputs and outputs # Consult README for inputs and outputs found_item = nil collection.each do |count| if count[:item] == name found_item = count end end return found_item end def consolidate_cart(cart) #create an output hash output_cart = [] cart.each_with_index do |item, index| item_hash = find_item_by_name_in_collection(cart[index][:item], output_cart) #make use of our def above since its purpose is find item in cart #based on if item_hash is true (the item exists in our output_cart) if item_hash != nil item_hash[:count] += 1 #remember in item_hash above we are using the output_cart parameter thus this will be updating the output_cart!! # p output_cart else new_entry = { :item => cart[index][:item], :price => cart[index][:price], :clearance => cart[index][:clearance], :count => 1 } output_cart << new_entry #p output_cart end end output_cart end # binding.pry
#game.rb class Game attr_accessor :armor_list, :weapon_list, :equipment def initialize() #Game creates the city and mountain as two separate scenes @city = Scene.new("City", "The city.", @cm, @ls, "", self) @mountain = Scene.new("Mountain", "The mountain.", @em, @wh, @d, self) #Game creates armor and weapon array-name-holders, I couldn't find another way to make the equipment-selection work @a = Armor.new("armor_list", 0) @w = Weapon.new("weapon_list", 0) #Game creates weapons @ss = Weapon.new("Short sword", 5) @ls = Weapon.new("Long sword", 8) @ts = Weapon.new("Two-Handed sword", 12) @wh = Weapon.new("Warhammer", 10) #Game creates armors @la = Armor.new("Leather Armor", 5) @cm = Armor.new("Chain Mail", 10) @pm = Armor.new("Plate Mail", 15) @em = Armor.new("Elven Chain Mail", 50) #Game creates a hero and a dragon @h = Creature.new(name = "You", level = 5) @d = Creature.new(name = "Dragon", level = 12) #The default equipment list to provide an arsenal. I wish to separate them and put 1 or 2 into each scene @armor_list = [@a, @la, @cm, @pm, @em] @weapon_list = [@w, @ss, @ls, @ts, @wh] @equipment = [] end def play() intro() end # If I can find a way to pass arguments between scenes and game, I'm going to put a variable to change the starting point. Otherwise I know that both intro() and play() is useless. def intro() @city.intro() end end class Creature attr_accessor :name, :life, :armor, :weapon, :regen def initialize(name, level) #Attributes accoridng to level and dice @name = name @level = level @equipment = {:armor => nil, :weapon => nil} @armor = 0 @weapon = 0 #3.times rand(7) or 3*rand(7) doesn't create the effect, I tried rand(16)+3 but didn't like it. @strength = rand(7) + rand(7) + rand(7) @condition = rand(7) + rand(7) + rand(7) @life = @level * (rand(8) + 1) @power = @strength * (rand(4) + 1) @regen = @condition end def select_equipment(equipment) introduce_self() selection(equipment) choice = gets.chomp.to_i #@a and @w help to get the name of the array, armor or weapon. if equipment[0].name == "armor_list" wear_armor(equipment[choice]) elsif equipment[0].name == "weapon_list" wear_weapon(equipment[choice]) else raise ArgumentError, "Should be armor_list or weapon_list" end equipment.delete_at(choice) end def introduce_self() if @equipment[:armor] == nil puts "You wear no armor!" else puts "You wear #{@equipment[:armor]}." end if @equipment[:weapon] == nil puts "You carry no weapon!" else puts "You carry #{@equipment[:weapon]}." end end def selection(equipment) puts "You wanna some equipment?" for i in (1..equipment.length-1) do puts "#{i}. #{equipment[i].name}" i += 1 end end def wear_armor(armor) @armor = armor.power @equipment[:armor] = armor.name end def wear_weapon(weapon) @weapon = weapon.power @equipment[:weapon] = weapon.name end def battle(opp1, opp2) #a basic round system depending on even and uneven numbers i = 1 while opp1.life > 0 && opp2.life > 0 if i % 2 == 0 attack(opp1, opp2) elsif i % 2 == 1 attack(opp2, opp1) else #just learning to raise errors, not into rescue, yet raise ArgumentError, "The battle is over!" end i += 1 round_result(opp1, opp2) end end def round_result(opp1, opp2) puts "Hit points:" puts "#{opp1.name}: #{opp1.life}" puts "#{opp2.name}: #{opp2.life}" end def attack(attacker, defender) #this code below is just to prevent stuff like "hit with -27 points of damage" possible_attack = @power + @weapon - defender.armor if possible_attack > 0 attack = possible_attack else attack = 0 end defender.life -= attack puts "#{attacker.name} hit #{defender.name} with #{attack} points of damage!" if defender.life <= 0 puts "...and killed!" defender.life = "Dead as cold stone!" round_result(attacker, defender) #game exits if one of the creatures die Process.exit(0) else defender.life += defender.regen puts "#{defender.name} regenerates #{defender.regen} points of life!" end end end #separate classes for weapons and armors, probably unnecessary but still learning class Weapon attr_reader :name, :power def initialize(name, power) @name = name @power = power end end class Armor attr_reader :name, :power def initialize(name, power) @name = name @power = power end end # I want each scene have its own weapon or armor (scattered on the ground, maybe, according to the story..) but cannot achieve that with armors, weapon variables. The same thing applies to monsters. I would like to have for example rats and thieves in the city, but bats and a dragon in the mountain. However couldn't achieve this exactly. So far I'm only successful in passing the game object to the scene object as the last variable and I think that's a good start. class Scene attr_reader :name, :history, :armors, :weapons, :monsters def initialize(name, history, armor_list, weapon_list, monsters, game) @name = name @history = history @armor_list ||= [] @weapon_list ||= [] @monsters ||= [] @game = game end def intro() puts "You are in the " + @name + "." puts @history choices() end def choices() puts <<-CHOICES What would you like to do here? 1. Look for armor 2. Look for weapons 3. Look for monsters to fight 4. Go to another place! CHOICES choice = gets.chomp #this is where things go really bad! instance_variable_get saves the battle but as for the equipment selection, # as soon as I make a choice, it throws this error: # "game.rb:193:in 'choices': #<Armor:0x429720 @name="....> is not a symbol (TypeError)" # and I don't think that further addition of : or @ is needed here. #The solution should be much simpler but couldn't find it on the web. if choice == "1" @game.send(@game.instance_variable_get(:@h).select_equipment(@game.instance_variable_get(:@armor_list))) elsif choice == "2" @game.send(@game.instance_variable_get(:@h).select_equipment(@game.instance_variable_get(:@weapon_list))) elsif choice == "3" @game.send(@game.instance_variable_get(:@h).battle(@game.instance_variable_get(:@h), @game.instance_variable_get(:@d))) elsif choice == "4" puts "bad choice, since I am not ready yet!" else puts "Can't you read?" end end #this is just to show the player a list of equipment found in the scene. def equipment_list() @armor_list[1..@armor_list.length-1].each {|a| @equipment.push(a.name) } @weapon_list[1..@weapon_list.length-1].each {|w| @equipment.push(w.name) } puts "You see some #{@room_equipment.join(", ")} lying on the ground." end end game = Game.new() game.play()
class Appointment attr_accessor :location, :purpose, :hour, :min def initialize(location, purpose, hour, min) @location = location @purpose = purpose @hour = hour @min = min end def location end def purpose end def hour end def min end end class MonthlyAppointment < Appointment attr_accessor :day def initialize(location, purpose, hour, min, day) @location = location @purpose = purpose @hour = hour @min = min @day = day end def day end def occurs_on?(day) if (1..31) === @day true else false end end def to_s "Reunión mensual en NASA sobre Aliens el día #{@day} a la(s) #{@hour}:#{@min}." end end class DailyAppointment < Appointment def occurs_on?(hour,min) if((1..12) === @hour && (1..60) === @min) true else false end end def to_s "Reunión diaria en Desafío Latam sobre Educación a la(s) #{@hour}:#{@min}." end end class OneTimeAppointment < Appointment attr_accessor :day, :month, :year def initialize(location, purpose, hour, min, day, month, year) @location = location @purpose = purpose @hour = hour @min = min @day = day @month = month @year = year end def day end def month end def year end def occurs_on?(day,month,year) if((1..31) === @day && (1..12) === @month && (2000..2021) === @year) true else false end end def to_s "Reunión única en Desafío Latam sobre Trabajo el #{@day}/#{@month}/#{@year} a la(s) #{@hour}:#{@min}." end end prueba1 = OneTimeAppointment.new('Desafío Latam', 'Trabajo', 14, 30, 4, 6, 2019) puts prueba1.occurs_on?(prueba1.day,prueba1.month,prueba1.year) puts prueba1.to_s prueba2 = DailyAppointment.new('Desafío Latam', 'Educación', 8, 15) puts prueba2.occurs_on?(prueba2.hour,prueba2.min) puts prueba2.to_s prueba3 = MonthlyAppointment.new('NASA', 'Aliens', 8, 15, 23) puts prueba3.occurs_on?(prueba3.day) puts prueba3.to_s
require 'spec_helper' describe JanusGateway::Plugin::Audioroom do let(:transport) { JanusGateway::Transport::WebSocket.new('') } let(:client) { JanusGateway::Client.new(transport) } let(:session) { JanusGateway::Resource::Session.new(client) } let(:plugin) { JanusGateway::Plugin::Audioroom.new(client, session) } it 'should list audio rooms' do janus_response = { create: '{"janus":"success", "transaction":"ABCDEFGHIJK", "data":{"id":"12345"}}', attach: '{"janus":"success", "session_id":12345, "transaction":"ABCDEFGHIJK", "data":{"id":"54321"}}', message: [ '{"janus":"success", "session_id":12345, "sender_id":"54321", "transaction":"ABCDEFGHIJK"', '"plugindata":{"plugin":"janus.plugin.cm.audioroom", "data":{"audioroom":"list"', '"list": [{"sampling_rate": 16000, "record": "true", "id": "super-room", "num_participants": 3, "description": "super-room"}]}}}' ].join(',') } transport.stub(:_create_client).and_return(WebSocketClientMock.new(janus_response)) transport.stub(:transaction_id_new).and_return('ABCDEFGHIJK') expect(session).to receive(:create).once.and_call_original expect(plugin).to receive(:list).once.and_call_original expect(EventMachine).to receive(:stop).once.and_call_original client.on :open do session.create.then do plugin.list.then do EventMachine.stop end end end client.run end end
class ArtistsController < ApplicationController layout 'logged_in' before_action :not_logged_in before_action :set_artist, only: [:show, :next_artist, :previous_artist] def index @artists =Artist.all_artists respond_to do |format| format.html format.json { render json: @artists , status: 200} end end def show @mural = Mural.new @nextArtist = Artist.next(@artist) @previousArtist = Artist.previous(@artist) respond_to do |format| format.html format.json { render json: @artist , status: 200} end end def next_artist @next_artist = @artist.find_next_artist render json: @next_artist, status: 200 end def previous_artist @previous_artist = @artist.find_previous_artist render json: @previous_artist, status: 200 end def new @artist = Artist.new end def create @artist = Artist.new(artist_params) if @artist.save redirect_to artist_path(@artist) else render :new end end def edit set_artist end def update set_artist @artist.update(artist_params) redirect_to artist_path(@artist) end def popular @artists = Artist.most_popular render :index end def destroy set_artist @artist.destroy redirect_to artists_path end private def artist_params params.require(:artist).permit(:name, :artist_name, :instagram, :bio) end end
class UserSerializer include FastJsonapi::ObjectSerializer attributes :username, :score, :id, :highest_score end
require "rspec" require_relative "../src/object_spect" require_relative "../src/spy" describe 'Framework de Testing' do # Suite para probar class Persona attr_accessor :edad, :onda def initialize(edad_persona) self.edad = edad_persona self.onda = true end def viejo? self. edad > 29 end end class SuiteDePrueba def testear_que_funciona true.deberia ser true end def testear_que_funcionan_aserciones 7.deberia ser 7 leandro = Persona.new(22) leandro. edad. deberia ser mayor_a 20 leandro. edad. deberia ser menor_a 25 leandro. edad. deberia ser uno_de_estos [ 7, 22, "hola"] leandro. edad. deberia ser uno_de_estos 7, 22, "hola" end def testear_que_funciona_ser_guion nico = Persona.new(30) nico.deberia ser_viejo nico.viejo?.deberia ser true end def testear_que_funciona_entender leandro = Persona.new(22) leandro. deberia entender :viejo? leandro. deberia entender :class end def testear_que_funciona_el_tener javee = Persona.new(20) javee.deberia tener_onda true end def testear_que_funcione_espiar pato = Persona.new(23) pato = espiar(pato) pato.viejo? pato.edad=20 pato.edad=21 pato.deberia haber_recibido(:edad) pato.deberia haber_recibido(:viejo?).con_argumentos pato.deberia haber_recibido(:edad=).con_argumentos(20) pato.deberia haber_recibido(:edad=).veces(2) end def testear_que_funcione_explotar leandro = Persona.new(22) proc { 7/0 }.deberia explotar_con ZeroDivisionError proc { leandro.nombre }.deberia explotar_con NoMethodError proc { leandro.nombre}.deberia explotar_con StandardError end def testear_que_funcione_mockear ClaseNoSuite.mockear(:numerito) do 7 end ClaseNoSuite.new.numerito.deberia ser 7 end def testear_que_desmockeo ClaseNoSuite.new.numerito.deberia ser 8 end end class SuiteDePruebaQueFalla def testear_que_test_explota raise "ERROR" end def testear_que_test_falla 1.deberia ser 2 end def testear_que_falla_veces_espiar pato = Persona.new(23) pato = espiar(pato) pato.edad=20 pato.edad=21 pato.deberia haber_recibido(:edad) pato.deberia haber_recibido(:edad=).veces(3) end def testear_que_falla_con_argumentos_espiar pato = Persona.new(23) pato = espiar(pato) pato.edad=20 pato.edad=21 pato.deberia haber_recibido(:edad=).con_argumentos(22) end def testear_que_falla_explotar proc { 7/0 }.deberia explotar_con NoMethodError end def testear_que_falla_entender leandro = Persona.new(22) leandro.deberia entender :metodo_inexistente end def testear_que_falla_haber_recibido_cuando_objeto_no_es_espiado leandro = Persona.new(22) leandro.edad leandro.deberia haber_recibido(:edad) end end class ClaseNoSuite def saludar 'Hello World' end def numerito 8 end end it 'Rspec Funciona Bien' do expect(true).to eq(true) end it 'Reconozca Suites' do expect(ObjectSpect.es_suite_testing SuiteDePrueba).to be(true) end it 'Reconozca Clases No Suites' do expect(ObjectSpect.es_suite_testing ClaseNoSuite).to be(false) end it 'Ejecute Bien la Suite que Funciona' do expect(ObjectSpect.testear SuiteDePrueba).to eq(EJECUCION_CORRECTA) end it 'Ejecute y Explote la Suite que Explota' do expect(ObjectSpect.testear SuiteDePruebaQueFalla).to eq(EJECUCION_EXPLOTO) end it 'Ejecute Bien al Correr Todas las Suites del Contexto' do expect{ObjectSpect.testear}.to_not raise_error end it 'Ejecute Bien un test especifico de una Suite' do expect(ObjectSpect.testear SuiteDePrueba, :testear_que_funciona_el_tener).to eq(EJECUCION_CORRECTA) end it 'Ejecute Bien una lista de test de una Suite' do expect(ObjectSpect.testear SuiteDePrueba, :testear_que_funciona_el_tener, :testear_que_funciona).to eq(EJECUCION_CORRECTA) end it 'Ejecuta un test y muestra que Exploto' do expect(ObjectSpect.testear SuiteDePruebaQueFalla, :testear_que_test_explota ).to eq(EJECUCION_EXPLOTO) end it 'Ejecuta un test y muestra que Fallo' do expect(ObjectSpect.testear SuiteDePruebaQueFalla, :testear_que_test_falla ).to eq(EJECUCION_FALLIDA) end it 'Funcionan Aserciones' do expect(ObjectSpect.testear SuiteDePrueba, :testear_que_funcionan_aserciones).to eq(EJECUCION_CORRECTA) end it 'Funciona Ser_' do expect(ObjectSpect.testear SuiteDePrueba, :testear_que_funciona_ser_guion).to eq(EJECUCION_CORRECTA) end it 'Funciona Entender' do expect(ObjectSpect.testear SuiteDePrueba, :testear_que_funciona_entender).to eq(EJECUCION_CORRECTA) end it 'Mockeo una clase y se ejecuta el bloque asignado al mock' do expect(ObjectSpect.testear SuiteDePrueba, :testear_que_funcione_mockear).to eq(EJECUCION_CORRECTA) end it 'Mockeo una clase y devuelve el resultado mockeado, la desmockeo y vuelve a la normalidad' do ObjectSpect.inyectar_metodos # Para que inyecte metodo mockear ClaseNoSuite.mockear(:saludar) do 'Metodo mockeado' end expect( ClaseNoSuite.new.saludar ).to eq('Metodo mockeado') ClaseNoSuite.desmockear expect( ClaseNoSuite.new.saludar ).to eq('Hello World') end it 'Espio un objeto y se registran correctamente los metodos llamados' do expect(ObjectSpect.testear SuiteDePrueba, :testear_que_funcione_espiar).to eq(EJECUCION_CORRECTA) end end
#!/usr/bin/env ruby require 'fileutils' require 'time' def main(argv: ARGV) metadata_tarball = File.basename(argv.fetch(0)) top = File.expand_path('../../', __FILE__) template_name = metadata_tarball.match(/\b(ci-[a-z]+)\b/)[1] latest_image_name = metadata_tarball.match(/\b(travis-ci-[^\.]+)\b/)[1] outfile = File.join(top, 'tmp', template_name, 'latest-image-name') FileUtils.mkdir_p(File.dirname(outfile)) File.open(outfile, 'w') { |f| f.puts(latest_image_name) } $stdout.puts "time=#{Time.now.utc.iso8601} outfile=#{outfile} " \ "template=#{template_name} " \ "latest_image_name=#{latest_image_name}" 0 end exit(main) if $PROGRAM_NAME == __FILE__
class Cancellation < ActiveRecord::Base include CrossAssociatedModel belongs_to :transaction belongs_to_resource :organization flagstamp :cancelled after_save :cancel def url organization.cancellation_url end def https? organization.https? end def cancel Delayed::Job.enqueue Jobs::TransactionCancellationJob.new(id) end end
class Game < ActiveRecord::Base belongs_to :event has_many :game_users has_many :users, through: :game_users belongs_to :winner, class_name: "User", foreign_key: :user_id def is_player?(player_id) self.users.exists?(player_id) end def declare_winner(winner) self.update(winner_id: winner.id) self.update(status: "ended") self.event.next_game(winner) end end
require 'spec_helper' describe SearchController do describe 'index' do it "does not fail" do get :index expect(response).to be_success end it "assigns the view model" do get :index expect(assigns(:essay_search)).to be_a(EssaySearch) end end end
class AddSlugToRecipes < ActiveRecord::Migration def up add_column :recipes, :slug, :string add_index :recipes, :slug, unique: true say_with_time 'generating recipe slugs' do Recipe.find_each(&:save) end end def down remove_column :recipes, :slug, :string end end
# frozen_string_literal: true # https://github.com/joncalhoun/algorithmswithgo.com/tree/master/module01#08---fizzbuzz-code # FizzBuzz : class FizzBuzz def self.iterate(num) res = '' (1..num).each do |n| res += fizz_buzz(n) res += ', ' if n != num end res += "\n" end def self.fizz_buzz(num) if (num % 15).zero? 'Fizz Buzz' elsif (num % 3).zero? 'Fizz' elsif (num % 5).zero? 'Buzz' else num.to_s end end end
# frozen_string_literal: true module HasIcon extend ActiveSupport::Concern included do mount_uploader :icon, IconUploader validates :icon, file_size: { less_than_or_equal_to: 10.megabytes }, file_content_type: { allow: %w[image/jpeg image/png] } end end
class JobsController < ApplicationController before_action :authenticate_user! def index load_jobs end def new build_job end def edit load_job end def create build_job save_job or render 'new' end def update load_job update_job or render 'edit' end def destroy load_job @job.destroy redirect_to jobs_path end private def load_jobs @jobs = policy_scope(Job).order(created_at: :desc) end def load_job @job = Job.find(params[:id]) authorize @job end def build_job @job = Job.new(job_params) authorize @job end def save_job if @job.save redirect_to jobs_path end end def update_job if @job.update(job_params) redirect_to jobs_path end end def job_params job_params = params[:job] job_params ? job_params.permit(:title, :description, :is_expired, :user_id) : {} end end
module API module V1 class UsersController < ApplicationController def index rkey = '82a4ca11-464c-49ae-ab3c-9c9f99909b0d' data = request.headers['token'] begin decoded = JWT.decode data, rkey, true, algorithm: 'HS256' user_id = decoded[0]['user_id'] @user = User.find(user_id) render json: { user: @user } rescue JWT::VerificationError render json: { info: 'token expired' }, status: :unathorized rescue StandardError render json: { info: 'user not found' }, status: :not_found end end end end end
module Log::Format def self.line(message, time, subject, level, &message_formatter) "#{header(time, subject, level)} #{message(message, &message_formatter)}" end def self.message(message, &message_formatter) return message unless block_given? if Log::Defaults.formatters == :on return message_formatter.(message) else return message end end def self.header(time, subject, level) header = "[#{time}] #{subject}" unless level.nil? header << " #{level.to_s.upcase}" end header << ':' Color.header(header) end module Defaults def self.message_formatter proc {|message| message } end end end
# encoding: utf-8 class CreateDistincts < ActiveRecord::Migration def change create_table :distincts do |t| t.integer :prefecture_id, null: false t.string :name, null: false t.boolean :public, null: false, default: true t.timestamps end end end
require 'thor' require 'octokit' Octokit.auto_paginate = true class GitHubFavouriteLanguage < Thor attr_reader :username package_name "GitHub Favourite Language" map "-u" => "output" desc "-u USERNAME", "Identify the favourite language of a GitHub user" def output(argument) @username = argument begin puts "#{username}'s favourite language on GitHub is #{favourite}." rescue Octokit::NotFound puts "Username not found." rescue Octokit::TooManyRequests puts "You have run out of GitHub API requests." rescue NoPublicRepositories puts "#{username} has no public repositories." end end no_commands do def favourite f = favourite_language f == 'nil' ? 'unknown' : f end def favourite_language repositories.inject(Hash.new(0)) do |languages, repository| languages[repository.language] += repository.size languages end.max_by { |language, total_size| total_size }.first end def repositories response = Octokit.repositories(username) raise NoPublicRepositories if response.empty? @repositories ||= response end end end class NoPublicRepositories < StandardError; end GitHubFavouriteLanguage.start
def remove_every_other(arr) arr.reject.with_index { |x, y| y.odd? } end
require 'spec_helper' describe "kind_accounts/show" do before(:each) do @kind_account = assign(:kind_account, stub_model(KindAccount, :owner_name => "MyText", :number => "MyText", :bank_id => 1 )) end it "renders attributes in <p>" do render # Run the generator again with the --webrat flag if you want to use webrat matchers rendered.should match(/MyText/) rendered.should match(/MyText/) rendered.should match(/1/) end end
module BulkFetcher class Store attr_reader :klass, :id_queue, :cache, :finder, :index_by def initialize(options = {}) @finder = options.fetch(:finder) do klass = options.fetch(:klass) do raise ArgumentError, "must specify a :klass or a :finder method" end klass.method(:find) end @index_by = options.fetch(:index_by, :id) reset! end def queue(ids) id_queue.concat(Array(ids)) end # returns objects in the order they def fetch_all(id_or_ids) ids = Array(id_or_ids) # look in the cache for hits items, missing_ids = lookup_items(ids) # bulk fetch the missing ids fetch_items(missing_ids + read_queue) new_items, missing_ids = lookup_items(missing_ids) items_by_id = (items + new_items).inject({}){ |collection, item| collection[cache_key(item)] = item; collection} ids.map{|id| items_by_id[id] } end # return a single object def fetch(id) fetch_all(id).first end def reset! @cache = {} @id_queue = [] end protected def read_queue id_queue.dup.tap do |q| id_queue.clear end end def lookup_items(ids) missing = [] items = [] # find cache hits first ids.each do |id| if item = cache[id] items.push(item) else missing.push(id) end end [items, missing] end def fetch_items(ids) return [] if ids.empty? items = finder.call(ids) store_items(items) end def store_items(objects) Array(objects).each do |object| cache[cache_key(object)] = object end end def cache_key(object) object.public_send(index_by) end end end
class Post < ActiveRecord::Base belongs_to :user has_many :comment validates :title, presence: true, length: {minimum: 10, maximum: 100} validates :link, presence: true, :url => true end
describe :calling_a_method, :shared => true do it "works directly" do eval("@obj.#{@method}").should equal_clr_string(@result) end it "works via .send" do @obj.send(@method.to_sym).should equal_clr_string(@result) end it "works via .__send__" do @obj.__send__(@method.to_sym).should equal_clr_string(@result) end it "works via .instance_eval" do @obj.instance_eval(@method).should equal_clr_string(@result) end end
class RemoveReportingOrganisationIdFromActivities < ActiveRecord::Migration[6.1] def change remove_reference :activities, :reporting_organisation, type: :uuid, foreign_key: {to_table: :organisations} end end
class Code attr_reader :pegs POSSIBLE_PEGS = { "R" => :red, "G" => :green, "B" => :blue, "Y" => :yellow } def self.random(num) secret_code = Array.new(num) { POSSIBLE_PEGS.keys.sample } Code.new(secret_code) end def self.from_string(user_guess) submission = [] user_guess.each_char {|char| submission << char } Code.new(submission) end def [](index) @pegs[index] end def length @pegs.length end def num_exact_matches(guess) correct = 0 guess.pegs.each_with_index do |peg, index| if guess[index] == @pegs[index] correct+=1 end end correct end def num_near_matches(guess) near = 0 i=0 while i < @pegs.length if @pegs.include?(guess[i]) && guess[i] != @pegs[i] near += 1 end i+=1 end return near end def ==(guess) self.pegs == guess.pegs end def self.valid_pegs?(pegs) if pegs.all?{|peg| POSSIBLE_PEGS.has_key?(peg.upcase)} return true else return false end end def initialize(pegs) if Code.valid_pegs?(pegs) @pegs = pegs.map(&:upcase) else raise "That's not a valid move" end end end
module VirusScanner class HTTP attr_accessor :url, :options, :method def initialize @conn = ::Faraday.new(url: ENV["VIRUS_SCANNER_API_URL"]) do |c| c.request :url_encoded c.response :json, content_type: /\bjson$/ c.adapter ::Faraday.default_adapter c.headers = { "X-Auth-Token" => ENV["VIRUS_SCANNER_API_KEY"], "User-Agent" => "VirusScanner #{VirusScanner::VERSION} (#{RUBY_PLATFORM}, Ruby #{RUBY_VERSION})" } end rescue VirusScanner::HttpError => e handle_exception(e) end def post(uuid, url) response = @conn.post "/scan", uuid: uuid, url: url response.body rescue VirusScanner::Error => e handle_exception(e) end def get(uuid) response = @conn.get "/status/#{uuid}" response.body rescue VirusScanner::Error => e handle_exception(e) end private def handle_exception(e) puts e.message puts e.backtrace.inspect end end end
module Sequencescape::Api::Resource::InstanceMethods def self.included(base) base.class_eval do attr_reader :api, :actions, :attributes, :uuid private :api, :actions, :attributes alias_method(:model, :class) alias_method(:id, :uuid) delegate :hash, :to => :uuid delegate :read_timeout, :to => :api attribute_accessor :created_at, :updated_at, :conversion => :to_time end end def eql?(object_or_proxy) return false unless object_or_proxy.respond_to?(:uuid) self.uuid.eql?(object_or_proxy.uuid) end def initialize(api, json = nil, wrapped = false) @api, @attributes = api, {} end end
require 'typhoeus' require 'typhoeus/adapters/faraday' # Fall back on parameterized ElasticSearch connection if common URL not set. if ENV['ELASTICSEARCH_URL'].blank? user = CheckConfig.get('elasticsearch_user').to_s password = CheckConfig.get('elasticsearch_password').to_s host = CheckConfig.get('elasticsearch_host').to_s + ':' + CheckConfig.get('elasticsearch_port').to_s client = Elasticsearch::Client.new(log: (CheckConfig.get('elasticsearch_log').to_i == 1), user: user, password: password, host: host) do |f| f.adapter :typhoeus end else # NOTE: We may want to initialize explicitly with url: set for future compatibility. client = Elasticsearch::Client.new(log: (CheckConfig.get('elasticsearch_log').to_i == 1)) do |f| f.adapter :typhoeus end end $repository = MediaSearch.new(client: client)
require 'test/unit' require 'noofakku' require 'shoulda' module Noofakku class VMTest < Test::Unit::TestCase context 'Execution' do should 'produce "Hello World" in output' do input = -> { 0 } produced = '' output = ->value { produced << value } program = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.' Noofakku::VM.start(program, input, output) assert_equal "Hello World!\n", produced end should 'produce Fibonacci numbers in output' do program = '+.>+.>>>++++++++++[<<<[->>+<<]>>[-<+<+>>]<<<[->+<]>>[-<<+>>]<.>>>-]' input = -> { 0 } produced = [] output = ->value { produced << value } Noofakku::VM.start(program, input, output) assert_equal [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144], produced end should 'order numbers in input' do program = '>>,[>>,]<< [[-<+<]>[>[>>]<[.[-]<[[>>+<<-]<]>>]>]<<]' to_be_sorted = [5, 3, 2, 6, 0].each input = -> { to_be_sorted.next } produced = [] output = ->value { produced << value } Noofakku::VM.start(program, input, output) assert_equal [2, 3, 5, 6], produced end end end end
require '../data_structures/binary_search_tree.rb' =begin Implementations of various searching algorithms in Ruby. =end def binary_search(array, target) return nil if array.count == 0 median = array.length / 2 left = array[0...median] right = array[median + 1..-1] return median if array[median] == target if target < array[median] return binary_search(left, target) else sub_answer = binary_search(right, target) (sub_answer.nil?) ? nil : (sub_anser + median + 1) end end def depth_first_search(node, target) return node if node.value == target children = [node.left, node.right] children.each do |child| next if child.nil? result = depth_first_search(child, target) return result unless result.nil? end nil end def breadth_first_search(node, target) queue = [node] until queue.empty? current_node = queue.shift return current_node if current_node.value == target queue << current_node.left if current_node.left queue << current_node.right if current_node.right end nil end
#!/usr/bin/env ruby # Generic client for MCollective Simple RPC # # http://code.google.com/p/mcollective/wiki/SimpleRPCIntroduction require 'mcollective' include MCollective::RPC begin options = rpcoptions do |parser, options| parser.banner = "" parser.define_head "Generic Simple RPC client" parser.separator "" parser.separator "Usage: mc-rpc [options] [filters] --agent <agent> --action <action> [--argument <key=val> --argument ...]" parser.separator "Alternate Usage: mc-rpc [options] [filters] <agent> <action> [<key=val> <key=val> ...]" parser.separator "Alternate Usage: mc-rpc --agent-help agent" parser.separator "" options[:arguments] = {} parser.on('--no-results', '--nr', "Do not process results, just send request") do |v| options[:process_results] = false end parser.on('-a', '--agent AGENT', 'Agent to call') do |v| options[:agent] = v end parser.on('--action ACTION', 'Action to call') do |v| options[:action] = v end parser.on("--ah", "--agent-help AGENT", "Get help for an agent") do |v| options[:agent_help] = v end parser.on('--arg', '--argument ARGUMENT', 'Arguments to pass to agent') do |v| if v =~ /^(.+?)=(.+)$/ options[:arguments][$1.to_sym] = $2 else STDERR.puts("Could not parse --arg #{v}") end end end # Parse the alternative command line unless (options.include?(:agent) && options.include?(:action)) || options.include?(:agent_help) if ARGV.length >= 2 options[:agent] = ARGV[0] ARGV.delete_at(0) options[:action] = ARGV[0] ARGV.delete_at(0) ARGV.each do |v| if v =~ /^(.+?)=(.+)$/ options[:arguments][$1.to_sym] = $2 else STDERR.puts("Could not parse --arg #{v}") end end else STDERR.puts("No agent, action and arguments specified") exit! end end # handle fire and forget mode options[:process_results] = true unless options.include?(:process_results) options[:arguments][:process_results] = options[:process_results] if options[:agent_help] config = MCollective::Config.instance config.loadconfig(options[:config]) ddl = MCollective::RPC::DDL.new(options[:agent_help]) puts ddl.help("#{config.configdir}/rpc-help.erb") elsif options[:process_results] mc = rpcclient(options[:agent], {:options => options}) mc.agent_filter(options[:agent]) mc.discover :verbose => true printrpc mc.send(options[:action], options[:arguments]) printrpcstats :caption => "#{options[:agent]}##{options[:action]} call stats" else mc = rpcclient(options[:agent], {:options => options}) mc.agent_filter(options[:agent]) puts "Request sent with id: " + mc.send(options[:action], options[:arguments]) end rescue Exception => e STDERR.puts("Could not call agent: #{e}") end # vi:tabstop=4:expandtab:ai
#--------- # name: BlackJack.rb # #---------------- class Screen def cls puts ("\n" * 30) puts "\a" end def pause STDIN.gets end end class Game def display_greeting puts "Welcome to play Black Jack game\n\n" end def display_instruction Console_Screen.cls puts "Instruction\n\n" puts "This game is based on the Black Jack card game where the objective is to beat the dealet by acquring cards that total higher thann the dealers total without " + " without going over 21." puts "\n\n\n\n\n" puts "Press enter to continue." Console_Screen.pause end def play_game Console_Screen.cls playerHand = get_new_card dealerHand = get_new_card playerHand = complete_player_hand(playerHand, dealerHand) if playerHand.to_i <= 21 then dealerHand = play_dealer_hand(dealerHand) end determine_winner(playerHand, dealerHand) end def get_new_card card = 1 + rand(13) return 11 if card == 1 # value of 1 is ace so reassign 11 return 1 if card >= 10 # value of 10 or more is face card so reassign 10 return card end def complete_player_hand(playerHand, dealerHand) loop do Console_Screen.cls puts "Players hand: " + playerHand.to_s + "\n\n" puts "Dealers hand: " + dealerHand.to_s + "\n\n\n\n\n\n\n" print "Would you like another card? (y/n) " reply = STDIN.gets reply.chop! if reply =~ /y/i then playerHand = playerHand + get_new_card end if reply =~ /n/i then break end if playerHand > 21 then break end end return playerHand end def play_dealer_hand(dealerHand) loop do if dealerHand < 17 then dealerHand = dealerHand + get_new_card else break end end return dealerHand end def determine_winner(playerHand, dealerHand) Console_Screen.cls puts "Players hand: " + playerHand.to_s + "\n\n" puts "Dealers hand: " + dealerHand.to_s + "\n\n\n\n\n\n\n" if playerHand.to_i > 21 then puts "You have gone bust!\n\n" print "Press enter to continue." else if playerHand == dealerHand then puts "Tie!\n\n" print "Press enter to continue." end if dealerHand > 21 then puts "The dealer has gone bust!!\n\n" print "Press enter to continue." else if playerHand.to_i > dealerHand then puts "You have won!\n\n" print "Press enter to continue." end if playerHand.to_i < dealerHand then puts "The dealer has won!\n\n" print "Press enter to continue." end end end Console_Screen.pause end def display_credits puts "Thank you for playing the game!\n\n" end Console_Screen = Screen.new BJ = Game.new BJ.display_greeting answer = "" loop do Console_Screen.cls print "Are you ready to play Ruby BlackJack? (y/n): " answer = STDIN.gets answer.chop! break if answer =~ /y|n/i end if answer =~ /n/i then Console_Screen.cls puts "Okay, perhaps another time!!\n\n" else BJ.display_instruction playAgain = "" loop do BJ.play_game loop do Console_Screen.cls playAgain = STDIN.gets playAgain.chop! break if playAgain =~ /n|y/i end break if playAgain =~ /n/i end BJ.display_credits end end
module Telegram module Bot class UpdatesController # Provides helpers similar to AbstractController::Translation # but by default uses `action_name_i18n_key` in lazy translation keys # which strips `!` from action names by default. This makes translating # strings for commands more convenient. # # To disable this behaviour use `alias_method :action_name_i18n_key, :action_name`. module Translation extend ActiveSupport::Concern module ClassMethods # Class-level helper for lazy translations. def translate(key, **options) key = "#{controller_path.tr('/', '.')}#{key}" if key.to_s.start_with?('.') I18n.translate(key, **options) end alias :t :translate end # See toplevel description. def translate(key, **options) if key.to_s.start_with?('.') path = controller_path.tr('/', '.') defaults = [:"#{path}#{key}"] defaults << options[:default] if options[:default] options[:default] = defaults.flatten key = "#{path}.#{action_name_i18n_key}#{key}" end I18n.translate(key, **options) end alias :t :translate # Strips trailing `!` from action_name. def action_name_i18n_key action_name.chomp('!') end def localize(*args) I18n.localize(*args) end alias :l :localize end end end end
class LanguagesController < ApplicationController before_action :set_language, only: [:show, :edit, :update, :destroy] before_action :signed_in_user before_action :correct_user #before_action :load_user # GET /languages # GET /languages.json def index #@user = User.find(params[:id]) @languages = @user.languages.all unless @user.nil? end # GET /languages/1 # GET /languages/1.json def show end # GET /languages/new def new #@user = User.find(params[:id]) @language = Language.new end # GET /languages/1/edit def edit end # POST /languages # POST /languages.json def create @language = @user.languages.new(language_params) respond_to do |format| if @language.save format.html { redirect_to user_language_path(@user, @language), notice: 'Language was successfully created.' } format.json { render :show, status: :created, location: @language } else format.html { render :new } format.json { render json: @language.errors, status: :unprocessable_entity } end end end # PATCH/PUT /languages/1 # PATCH/PUT /languages/1.json def update respond_to do |format| if @language.update(language_params) format.html { redirect_to user_language_path(@user, @language), notice: 'Language was successfully updated.' } format.json { render :show, status: :ok, location: @language } else format.html { render :edit } format.json { render json: @language.errors, status: :unprocessable_entity } end end end # DELETE /languages/1 # DELETE /languages/1.json def destroy @language.destroy respond_to do |format| format.html { redirect_to user_languages_url, notice: 'Language was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_language @user = User.find(params[:user_id]) @language = @user.languages.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def language_params params.require(:language).permit(:name, :note) end def signed_in_user redirect_to root_url unless signed_in? end def correct_user @user = User.find(params[:user_id]) redirect_to(root_url) unless current_user?(@user) end def load_user @user = User.find(params[:user_id]) end end
require "rails_helper" RSpec.describe Actual::Import do let(:project) { create(:project_activity, title: "Example Project", description: "Longer description") } let(:reporter_organisation) { project.organisation } let(:reporter) { create(:partner_organisation_user, organisation: reporter_organisation) } let! :report do create(:report, :active, fund: project.associated_fund, organisation: project.organisation, financial_year: 1999, financial_quarter: 4) end let :importer do Actual::Import.new(report: report, uploader: reporter) end describe "importing a single refund" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => nil, "Refund Value" => "12.00", "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "This is a Refund" } end before do importer.import([actual_row]) end it "imports a single refund" do expect(report.refunds.count).to eq(1) expect(report.refunds.first.comment.body).to eq("This is a Refund") end end describe "importing a single actual" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => "50.00", "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "Puppy" } end before do importer.import([actual_row]) end it "imports a single actual" do expect(report.actuals.count).to eq(1) expect(report.actuals.first.comment.body).to eq("Puppy") end it "assigns the attributes from the row data" do actual = report.actuals.first expect(actual).to have_attributes( parent_activity: project, financial_quarter: 4, financial_year: 2019, value: 50.0, receiving_organisation_name: "Example University", receiving_organisation_type: "80", description: "FQ4 1999-2000 spend on Example Project" ) end it "assigns a default currency" do actual = report.actuals.first expect(actual.currency).to eq("GBP") end # https://iatistandard.org/en/iati-standard/203/codelists/transactiontype/ it "assigns 'disbursement' as the actual type" do actual = report.actuals.first expect(actual.transaction_type).to eq("3") end it "assigns the providing organisation based on the activity" do actual = report.actuals.first expect(actual).to have_attributes( providing_organisation_name: project.providing_organisation.name, providing_organisation_type: project.providing_organisation.organisation_type, providing_organisation_reference: project.providing_organisation.iati_reference ) end context "when the reporter is not authorised to report on the Activity" do let(:reporter_organisation) { create(:partner_organisation) } it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Activity RODA Identifier", project.roda_identifier, t("importer.errors.actual.unauthorised")) ]) end end context "when the Activity does not belong to the given Report" do let(:another_project) { create(:project_activity, organisation: reporter_organisation) } let :actual_row do super().merge("Activity RODA Identifier" => another_project.roda_identifier) end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Activity RODA Identifier", another_project.roda_identifier, t("importer.errors.actual.unauthorised")) ]) end end context "when the Activity Identifier is not recognised" do let :actual_row do super().merge("Activity RODA Identifier" => "not-a-real-id") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Activity RODA Identifier", "not-a-real-id", t("importer.errors.actual.unknown_identifier")) ]) end end context "when the Financial Quarter is blank" do let :actual_row do super().merge("Financial Quarter" => "") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Financial Quarter", "", t("activerecord.errors.models.actual.attributes.financial_quarter.inclusion")) ]) end end context "when the Financial Year is blank" do let :actual_row do super().merge("Financial Year" => "") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Financial Year", "", t("activerecord.errors.models.actual.attributes.financial_year.blank")) ]) end end context "when the Financial Quarter is invalid" do let :actual_row do super().merge("Financial Quarter" => "5") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Financial Quarter", "5", t("activerecord.errors.models.actual.attributes.financial_quarter.inclusion")) ]) end end context "with additional formatting in the Value field" do let :actual_row do super().merge("Actual Value" => "£ 12,345.67") end it "imports the actual" do expect(report.actuals.count).to eq(1) end it "interprets the Value as a number" do actual = report.actuals.first expect(actual.value).to eq(12_345.67) end end context "when the Value is not numeric" do let :actual_row do super().merge("Actual Value" => "This is not a number") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value", "This is not a number", "Actual and refund values must be blank or numeric") ]) end end context "when the Value is partially numeric" do let :actual_row do super().merge("Actual Value" => "3a4b5.c67") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value", "3a4b5.c67", "Actual and refund values must be blank or numeric") ]) end end context "when the Receiving Organisation Name is blank" do let :actual_row do super().merge("Receiving Organisation Name" => "") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Receiving Organisation Name", "", t("activerecord.errors.models.actual.attributes.receiving_organisation_name.blank")) ]) end end # https://iatistandard.org/en/iati-standard/203/codelists/organisationtype/ context "when the Receiving Organisation Type is not a valid IATI type" do let :actual_row do super().merge("Receiving Organisation Type" => "81") end it "does not import any actuals" do expect(report.actuals.count).to eq(0) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Receiving Organisation Type", "81", t("importer.errors.actual.invalid_iati_organisation_type")) ]) end end context "when a Receiving Organisation IATI Reference is provided" do let :actual_row do super().merge("Receiving Organisation IATI Reference" => "Rec-Org-IATI-Ref") end it "imports the actual" do expect(report.actuals.count).to eq(1) end it "saves the IATI reference on the actual" do actual = report.actuals.first expect(actual.receiving_organisation_reference).to eq("Rec-Org-IATI-Ref") end end context "when the Receiving Organisation fields are blank" do let :actual_row do super().merge( "Receiving Organisation Name" => "", "Receiving Organisation Type" => "", "Receiving Organisation IATI Reference" => "" ) end it "imports a single actual" do expect(report.actuals.count).to eq(1) end it "assigns the attributes from the row data" do actual = report.actuals.first expect(actual).to have_attributes( parent_activity: project, financial_quarter: 4, financial_year: 2019, value: 50.0, receiving_organisation_name: nil, receiving_organisation_type: nil, description: "FQ4 1999-2000 spend on Example Project" ) end end end describe "error messages" do before { importer.import([actual_row]) } context "when actual and refund are both filled in" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => "50.00", "Refund Value" => "10.00", "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "This is ambiguous" } end it "does not import any actuals" do expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) end it "returns a clear error message" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value/Refund Value", "50.00, 10.00", "Actual and refund are both filled") ]) end end context "when actual and refund are both blank" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => nil, "Refund Value" => nil, "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "This is ambiguous" } end it "does not import any actuals" do expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) end it "returns a clear error message" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value/Refund Value", "blank, blank", "Actual and refund are both blank") ]) end end context "when actual is blank and refund is zero" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => nil, "Refund Value" => "0.00", "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "This is ambiguous" } end it "does not import any actuals" do expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) end it "returns a clear error message" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value/Refund Value", "blank, 0.00", "Refund can't be zero when actual is blank") ]) end end context "when actual is zero and refund is blank" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => "0.00", "Refund Value" => nil, "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "This is ambiguous" } end it "does not import any actuals" do expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) end it "returns a clear error message" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value/Refund Value", "0.00, blank", "Actual can't be zero when refund is blank") ]) end end context "when actual and refund are both zero" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => "0.00", "Refund Value" => "0.00", "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "This is ambiguous" } end it "does not import any actuals" do expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) end it "returns a clear error message" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value/Refund Value", "0.00, 0.00", "Actual and refund are both zero") ]) end end context "when actual is filled in and refund is zero" do let :actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "4", "Financial Year" => "2019", "Actual Value" => "1000.00", "Refund Value" => "0.00", "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Receiving Organisation IATI Reference" => "", "Comment" => "This is ambiguous" } end it "does not import any actuals" do expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) end it "returns a clear error message" do expect(importer.errors).to eq([ Actual::Import::Error.new(0, "Actual Value/Refund Value", "1000.00, 0.00", "Refund can't be zero when actual is filled") ]) end end end describe "importing multiple actuals" do let :sibling_project do create(:project_activity, organisation: project.organisation, parent: project.parent, title: "Sibling Project") end let :first_actual_row do { "Activity RODA Identifier" => sibling_project.roda_identifier, "Financial Quarter" => "3", "Financial Year" => "2020", "Actual Value" => "50.00", "Receiving Organisation Name" => "Example University", "Receiving Organisation Type" => "80", "Comment" => "A comment!" } end let :second_actual_row do { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "3", "Financial Year" => "2020", "Actual Value" => "150.00", "Receiving Organisation Name" => "Example Corporation", "Receiving Organisation Type" => "70", "Comment" => "" } end let :third_actual_row do { "Activity RODA Identifier" => sibling_project.roda_identifier, "Financial Quarter" => "3", "Financial Year" => "2019", "Actual Value" => "£5,000", "Receiving Organisation Name" => "Example Foundation", "Receiving Organisation Type" => "60", "Comment" => "Not blank" } end before do importer.import([ first_actual_row, second_actual_row, third_actual_row ]) end it "imports all actuals successfully" do expect(importer.errors).to eq([]) expect(importer.imported_actuals.count).to eq(3) expect(importer.imported_actuals).to match_array(report.actuals) comments = report.actuals.map { |actual| actual.comment&.body } expect(comments).to match_array([nil, "A comment!", "Not blank"]) end it "assigns each actual to the correct report" do expect(report.actuals.pluck(:description)).to contain_exactly( "FQ4 1999-2000 spend on Example Project", "FQ4 1999-2000 spend on Sibling Project", "FQ4 1999-2000 spend on Sibling Project" ) end it "assigns each actual to the correct activity" do expect(project.actuals.pluck(:description)).to eq([ "FQ4 1999-2000 spend on Example Project" ]) expect(sibling_project.actuals.pluck(:description)).to eq([ "FQ4 1999-2000 spend on Sibling Project", "FQ4 1999-2000 spend on Sibling Project" ]) end context "when any row is not valid" do let :third_actual_row do super().merge("Actual Value" => "fish") end it "does not import any actuals" do expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) end it "returns an error" do expect(importer.errors).to eq([ Actual::Import::Error.new(2, "Actual Value", "fish", "Actual and refund values must be blank or numeric") ]) end end context "when there are multiple errors" do let :first_actual_row do super().merge("Receiving Organisation Type" => "81", "Actual Value" => "fish") end let :third_actual_row do super().merge("Financial Quarter" => "5") end it "does not import any actuals" do expect(Actual.count).to eq(0) end it "returns all the errors" do errors = importer.errors.sort_by { |error| [error.row, error.column] } expect(errors.size).to eq(3) expect(errors).to eq([ Actual::Import::Error.new(0, "Actual Value", "fish", "Actual and refund values must be blank or numeric"), Actual::Import::Error.new(0, "Receiving Organisation Type", "81", t("importer.errors.actual.invalid_iati_organisation_type")), Actual::Import::Error.new(2, "Financial Quarter", third_actual_row["Financial Quarter"], t("activerecord.errors.models.actual.attributes.financial_quarter.inclusion")) ]) end end end describe "importing one valid row alongside rows with invalid values" do let(:valid_row) { { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "1", "Financial Year" => "2020", "Actual Value" => "150.00", "Refund Value" => nil } } context "when the invalid values are the default values" do let(:invalid_default_row) { { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "2", "Financial Year" => "2020", "Actual Value" => "0.00", "Refund Value" => nil } } context "and there are no comments in the invalid row" do it "imports the valid row and ignores the rest" do importer.import([valid_row, invalid_default_row]) expect(importer.errors).to eq([]) expect(importer.imported_actuals.count).to eq(1) expect(importer.imported_actuals).to match_array(report.actuals) end end context "but there is a comment in the invalid row" do it "does not import any actuals and retains error information" do importer.import([valid_row, invalid_default_row.merge({"Comment" => "Are you gonna error now?"})]) expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) expect(importer.errors).to eq([ Actual::Import::Error.new(1, "Actual Value/Refund Value", "0.00, blank", "Actual can't be zero when refund is blank") ]) end end end context "when non-default invalid values are included" do let(:invalid_non_default_row) { { "Activity RODA Identifier" => project.roda_identifier, "Financial Quarter" => "2", "Financial Year" => "2020", "Actual Value" => "0.00", "Refund Value" => "0.00" } } it "does not import any actuals and retains error information" do importer.import([valid_row, invalid_non_default_row]) expect(Actual.count).to eq(0) expect(importer.imported_actuals).to eq([]) expect(importer.errors).to eq([ Actual::Import::Error.new(1, "Actual Value/Refund Value", "0.00, 0.00", "Actual and refund are both zero") ]) end end end end
class HasProduct < ApplicationRecord belongs_to :provider belongs_to :product_mercerium end
# frozen_string_literal: true module Brcobranca module Retorno module Cnab240 # Formato de Retorno CNAB 240 # Baseado em: http://www.caixa.gov.br/downloads/cobranca-caixa-manuais/LEIAUTE_CNAB_240_SIGCB_COBRANCA_CAIXA.pdf class Caixa < Brcobranca::Retorno::RetornoCnab240 class Line < Brcobranca::Retorno::RetornoCnab240::Line # Fixed width layout for Caixa fixed_width_layout do |parse| # REGISTRO_T_FIELDS # Not applicable # :cedente_com_dv # Same inherited from parent # parse.field :data_vencimento, 73..80 # parse.field :valor_titulo, 81..95 # parse.field :banco_recebedor, 96..98 # parse.field :sequencial, 8..12 # parse.field :valor_tarifa, 198..212 # parse.field :agencia_com_dv, 17..22 parse.field :codigo_ocorrencia, 15..16 parse.field :nosso_numero, 39..55 parse.field :agencia_recebedora_com_dv, 99..103 parse.field :motivo_ocorrencia, 213..222, lambda { |motivos| motivos.scan(/.{2}/).reject(&:blank?).reject { |motivo| motivo == '00' } } # REGISTRO_U_FIELDS # Same inherited from parent # parse.field :desconto_concedito, 32..46 # parse.field :valor_abatimento, 47..61 # parse.field :iof_desconto, 62..76 # parse.field :juros_mora, 17..31 # parse.field :valor_recebido, 77..91 # parse.field :outras_despesas, 107..121 # parse.field :outros_recebimento, 122..136 # parse.field :data_credito, 145..152 end end end end end end
class ApplicationController < ActionController::Base protect_from_forgery def storenvy_oauth_client Rails.logger.debug "\n\n #{STORENVY_OAUTH.inspect} \n\n" @client ||= OAuth2::Client.new(STORENVY_OAUTH[:app_id], STORENVY_OAUTH[:secret], :site => 'https://api.storenvy.com') end def storenvy_access_token @token ||= OAuth2::AccessToken.new(storenvy_oauth_client, current_user.storenvy_access_token) if current_user end private def oauth_client @oauth_client ||= OAuth2::Client.new(ENV["OAUTH_ID"], ENV["OAUTH_SECRET"], site: "http://localhost:3000") end def access_token if session[:access_token] @access_token ||= OAuth2::AccessToken.new(oauth_client, session[:access_token]) end end end
class VendorToServicesController < ApplicationController def new @vendor_to_service = VendorToService.new() @available_services = Service.pluck(:service_name) end def create @vendor_to_service = VendorToService.new(vendor_to_service_params) @vendor_to_service.vendor_id = current_user.vendor_id @vendor_to_service.service_id = Service.find_or_create_by(service_name: vendor_to_service_params[:service_id]).id if @vendor_to_service.save flash[:success] = "Service added!" redirect_to user_path(current_user) else flash[:danger] = @vendor_to_service.errors.full_messages.join(", ") render 'new' end end def destroy vendor_to_service = VendorToService.find(params[:id]) service_id = vendor_to_service.service_id vendor_to_service.destroy if VendorToService.where(:service_id => service_id).count == 0 Service.find(service_id).destroy end flash[:success] = "Service deleted" redirect_to user_path(current_user) end def edit @vendor_to_service = VendorToService.find(params[:id]) end def update @vendor_to_service = VendorToService.find(params[:id]) if @vendor_to_service.update_attributes(vendor_to_service_params) flash[:success] = "Profile updated" redirect_to user_path(current_user) else render 'edit' end end private def vendor_to_service_params params.require(:vendor_to_service).permit(:service_id,:vendor_id,:price) end end
# encoding: utf-8 class CreateRecipes < ActiveRecord::Migration def change create_table :recipes do |t| t.integer :user_id, null: false t.string :title, null: false, default: '' t.text :description, null: false, default: '' t.boolean :public, null: false, default: false t.string :recipe_image, null: true t.text :one_point, null: false, default: '' t.integer :love_count, null: false, default: 0 t.integer :eatstyle_id, null: false, default: 0 t.integer :amount, null: true t.integer :calorie, null: false, default: 0 t.integer :view_count, null: false, default: 0 t.integer :recipe_food_id, null: true t.time :deleted_at, null: true t.timestamps end end end
require "lucie/server" module Service # # A controller class of nfsroot service. This class automatically # (re-)builds nfsroot directory. # class Installer < Common # # Builds an +installer+ if need be. Lucie server's IP address is # specified with +lucie_server_ip_address+. # def setup installer, lucie_server_ip_address installer.build lucie_server_ip_address, @debug_options end end end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
class ApiCallLogsController < ApplicationController def index respond_to do |format| format.html { set_variables_count_by_path } format.js { set_variables_count_by_api_type } end end private def set_variables_count_by_api_type count_table = BF::ApiCallLog.recent.group(:api_type).count @public_api_call_logs_count = count_table["public_api"] || 0 @private_api_call_logs_count = count_table["private_api"] || 0 end def set_variables_count_by_path api_call_log_table = BF::ApiCallLog.recent.group_by(&:api_type) public_api_paths = (api_call_log_table["public_api"] || []).map { |x| x.request_body =~ /^(.+?)\?/ && $1 } @public_api_table = count_by_path(public_api_paths) private_api_paths = (api_call_log_table["private_api"] || []).map { |x| x.request_body =~ /^(.+?)\?/ && $1 } @private_api_table = count_by_path(private_api_paths) end def count_by_path(paths) Hash.new { |h,k| h[k] = 0 }.tap do |hash| paths.each { |path| hash[path] = hash[path] + 1 } end end end
class PresentationPreviewer < ActiveStorage::Previewer class << self def accept?(blob) blob.content_type = '' end end end
# frozen_string_literal: true describe UseCase::CheckGameStatus do let(:board_gateway) do Class.new do def save(board) @board = board end attr_reader :board end.new end let(:game_status_checker) { described_class.new } it 'determines a win for a winning board' do winning_board = [ %i[O O X], %i[X X X], %i[O X O] ] board_gateway.save(Domain::Board.new(winning_board)) expect(game_status_checker.execute(board_gateway: board_gateway)[:status]).to eq(:win) end it 'determines a tie for a tying board' do tying_board = [ %i[X O X], %i[X O X], %i[O X O] ] board_gateway.save(Domain::Board.new(tying_board)) expect(game_status_checker.execute(board_gateway: board_gateway)[:status]).to eq(:tie) end it 'determines the correct winner for a board' do winning_board = [ %i[O O X], %i[X O X], %i[X O O] ] board_gateway.save(Domain::Board.new(winning_board)) expect(game_status_checker.execute(board_gateway: board_gateway)[:winner]).to eq(:O) end it 'determines the correct status for an incomplete game' do incomplete_board = [ [nil, nil, nil], %i[X O X], %i[X O O] ] board_gateway.save(Domain::Board.new(incomplete_board)) expect(game_status_checker.execute(board_gateway: board_gateway)[:status]).to eq(:incomplete) end end
#============================================================================== # ** F12 Reset Fix # Author: Acezon # Date: 2 June 2013 #------------------------------------------------------------------------------ # Version 2.1 # - Fixed issue where game window is not in focus # when Console_on is set to false # - Now compatible with Tsuki's Test Edit script # Version 2.0 # - Console option added # - Automatically focuses window after pressing F12 # Version 1.1 # - Respawning the exe was better # Version 1.0 # - Initial Release #------------------------------------------------------------------------------ # Just credit me. Free to use for commercial/non-commercial games. # Thanks to Tsukihime and Cidiomar for the console scriptlet #============================================================================== $imported = {} if $imported.nil? $imported["Acezon-F12ResetFix"] = true #============================================================================== # ** START Configuration #============================================================================== module Config Console_on = false # duh end #============================================================================== # ** END Configuration #============================================================================== alias f12_reset_fix rgss_main def rgss_main(*args, &block) f12_reset_fix(*args) do if $run_once_f12 pid = spawn ($TEST ? 'Game.exe test' : 'Game') # Tell OS to ignore exit status Process.detach(pid) sleep(0.01) exit end $run_once_f12 = true # Run default rgss_main block.call end end module SceneManager class << self alias :acezon_f12_first :first_scene_class end def self.first_scene_class focus_game_window acezon_f12_first end end
require File.expand_path('../../test_helper', __FILE__) module Stripe class ReaderTest < Test::Unit::TestCase @@example_valid = "%B1234123412341234^CardUser/John^030510100000019301000000877000000?" @@example_invalid = "%B9319293219392193?" should "allow Stripe::Reader to read in valid card data" do @parsed = Stripe::Reader.parse(@@example_valid) assert_equal "1234123412341234", @parsed[:number] assert_equal "JOHN CARDUSER", @parsed[:name] assert_equal "05", @parsed[:exp_month] assert_equal "03", @parsed[:exp_year] assert_equal "", @parsed[:cvc] end should "allow Stripe::Reader to pass in CVC" do @parsed = Stripe::Reader.parse(@@example_valid, { :cvc => "321" }) assert_equal "1234123412341234", @parsed[:number] assert_equal "JOHN CARDUSER", @parsed[:name] assert_equal "05", @parsed[:exp_month] assert_equal "03", @parsed[:exp_year] assert_equal "321", @parsed[:cvc] end should "ensure Stripe::Reader errors invalid card data" do assert_raises(Stripe::StripeError) do Stripe::Reader.parse(@@example_invalid) end end end end
require 'rails_helper' RSpec.describe User, type: :model do %i( slack_identifier slack_handle real_name profile_image slack_messages slack_reactions slack_channels ).each do |attr| it "responds_to #{attr}" do expect(subject).to respond_to(attr) end end end
require "command/app" require "confidential-data-server" module Command module ConfidentialDataServer class App < Command::App def initialize argv = ARGV, debug_options = {} super argv, debug_options @global_options.check_mandatory_options end def main cds = new_server custom_port = @global_options.port custom_port ? cds.start( custom_port.to_i ) : cds.start end ########################################################################## private ########################################################################## def new_server ::ConfidentialDataServer.new( @global_options.encrypted_file, password, @debug_options ) end def password pw = ENV[ "LUCIE_PASSWORD" ] || @global_options.password raise "password is missing" unless pw pw end end end end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
# coding: utf-8 class Zenithal::Tag attr_accessor :name attr_accessor :content def initialize(name = nil, clazz = nil, close = true) @name = name @attributes = (clazz) ? {"class" => clazz} : {} @content = "" @close = close end def [](key) return @attributes[key] end def []=(key, value) @attributes[key] = value end def class return @attributes["class"] end def class=(clazz) @attributes["class"] = clazz end def <<(content) @content << content end def to_s result = "" if @name result << "<" result << @name @attributes.each do |key, value| result << " #{key}=\"#{value}\"" end result << ">" result << @content if @close result << "</" result << @name result << ">" end else result << @content end return result end def to_str return self.to_s end def self.build(name = nil, clazz = nil, close = true, &block) tag = Tag.new(name, clazz, close) block.call(tag) return tag end end class REXML::Element alias old_get_index [] alias old_set_index []= def [](key) if key.is_a?(String) return attribute(key).to_s else return old_get_index(key) end end def []=(key, *values) if key.is_a?(String) return add_attribute(key, values.first) else return old_set_index(key, *values) end end def each_xpath(*args, &block) if block REXML::XPath.each(self, *args) do |element| block.call(element) end else enumerator = Enumerator.new do |yielder| REXML::XPath.each(self, *args) do |element| yielder << element end end return enumerator end end def get_texts_recursive texts = [] self.children.each do |child| case child when REXML::Text texts << child when REXML::Element texts.concat(child.get_texts_recursive) end end return texts end def inner_text(compress = false) text = REXML::XPath.match(self, ".//text()").map{|s| s.value}.join("") if compress text.gsub!(/\r/, "") text.gsub!(/\n\s*/, " ") text.gsub!(/\s+/, " ") text.strip! end return text end def self.build(name, &block) element = REXML::Element.new(name) block.call(element) return element end end class REXML::Parent alias old_push << def <<(object) if object.is_a?(REXML::Nodes) object.each do |child| old_push(child) end else old_push(object) end end end class REXML::Nodes < Array alias old_push << def <<(object) if object.is_a?(REXML::Nodes) object.each do |child| old_push(child) end else old_push(object) end return self end def +(other) return REXML::Nodes.new(super(other)) end def trim_indents texts = [] if self.last.is_a?(REXML::Text) self.last.value = self.last.value.rstrip end self.each do |child| case child when REXML::Text texts << child when REXML::Element texts.concat(child.get_texts_recursive) end end indent_length = Float::INFINITY texts.each do |text| text.value.scan(/\n(\x20+)/) do |match| indent_length = [match[0].length, indent_length].min end end texts.each do |text| text.value = text.value.gsub(/\n(\x20+)/){"\n" + " " * ($1.length - indent_length)} end if self.first.is_a?(REXML::Text) self.first.value = self.first.value.lstrip end end end class String def ~ return REXML::Text.new(self, true, nil, false) end end
# Root namespace for ProjectRazor module ProjectRazor module BrokerPlugin # Root namespace for Brokers defined in ProjectRazor for node hand off # @abstract class Base < ProjectRazor::Object attr_accessor :name attr_accessor :plugin attr_accessor :servers attr_accessor :description attr_accessor :user_description attr_accessor :hidden def initialize(hash) super() @hidden = true @plugin = :base @noun = "broker" @servers = [] @description = "Base broker plugin - not used" @_namespace = :broker from_hash(hash) if hash end def template @plugin end def agent_hand_off(options = {}) end def proxy_hand_off(options = {}) end # Method call for validating that a Broker instance successfully received the node def validate_broker_hand_off(options = {}) # return false because the Base object does nothing # Child objects do not need to call super false end def print_header if @is_template return "Plugin", "Description" else return "Name", "Description", "Plugin", "Servers", "UUID" end end def print_items if @is_template return @plugin.to_s, @description.to_s else return @name, @user_description, @plugin.to_s, "[#{@servers.join(",")}]", @uuid end end def line_color :white_on_black end def header_color :red_on_black end end end end
require './lib/mars/plateau' require './lib/mars/rover' describe Mars::Rover do it 'should be created with default parameters' do rover = Mars::Rover.new expect(rover.state[:x]).to eql(0) expect(rover.state[:y]).to eql(0) expect(rover.state[:direction]).to eql('N') expect(rover.state[:actions]).to eql('') end it 'should be presented as string' do rover = Mars::Rover.new expect(rover.to_s).to eql('0 0 N') end it 'should be created with parameters' do rover = Mars::Rover.new(x: 5, y: 7, direction: 'S', actions: 'LMLMLMLMLMMM') expect(rover.state[:x]).to eql(5) expect(rover.state[:y]).to eql(7) expect(rover.state[:direction]).to eql('S') expect(rover.state[:actions]).to eql('LMLMLMLMLMMM') end it 'should be able to move in vacuum' do rover = Mars::Rover.new(direction: 'N', actions: 'MMRMMLMM') rover.move expect(rover.state[:x]).to eql(2) expect(rover.state[:y]).to eql(4) expect(rover.state[:direction]).to eql('N') expect(rover.state[:actions]).to eql('') end it 'should do nothing when actions were not set' do rover = Mars::Rover.new(direction: 'N') rover.move expect(rover.state[:x]).to eql(0) expect(rover.state[:y]).to eql(0) expect(rover.state[:direction]).to eql('N') expect(rover.state[:actions]).to eql('') end it 'should be able to turn in place' do rover = Mars::Rover.new(direction: 'N', actions: 'RRRRLL') rover.move expect(rover.state[:x]).to eql(0) expect(rover.state[:y]).to eql(0) expect(rover.state[:direction]).to eql('S') expect(rover.state[:actions]).to eql('') end it 'should be able to move on plateau' do plateau = Mars::Plateau.new(3, 3) rover = Mars::Rover.new(direction: 'N', actions: 'MMMMRMMMM') rover.on_plateau(plateau).move expect(rover.state[:x]).to eql(3) expect(rover.state[:y]).to eql(3) expect(rover.state[:direction]).to eql('E') expect(rover.state[:actions]).to eql('') end end
namespace :generate do desc "Generate a timestamped, empty Sequel migration." task :migration, :name do |_, args| if ARGV[1].nil? puts "You must specify a migration name (e.g. rake generate:migration NAME)!" exit false end content = "Sequel.migration do\n up do\n \n end\n\n down do\n \n end\nend\n" timestamp = Time.now.to_i filename = File.join('db/migrations', "#{timestamp}_#{ARGV[1]}.rb") File.open(filename, 'w') do |f| f.puts content end puts "[+] Created the migration #{filename}" exit false end end
=begin じゃんけん問題をつくってくる puts “じゃんけん・・・・” puts “[0]グー[1]チョキ[2]パー” この続きを完成させてください。 自分の手を0、1、2で入力し、グー、チョキ、パーを判定。また自分の手をplayer_hand、相手の手をprogram_handとし、相手の手はランダムで決定される =end class Player attr_accessor :hand def initialize(player_hand) @hand = player_hand print "あなたの出した手: " + "[" + hand.to_s + "]" printHandName end #出した手の日本語名を出力する def printHandName if hand == 0 puts "グー" elsif hand == 1 puts "チョキ" else puts "パー" end end end class ProgramPlayer < Player def initialize(program_hand) @hand = program_hand print "相手の出した手: " + "[" + hand.to_s + "]" printHandName end end puts "じゃんけん・・・・" puts "[0]グー[1]チョキ[2]パー" error = 1 #errorフラグが1のとき繰り返す while error == 1 do print "自分が出す手を0,1,2の番号で入力してください: " player_hand = gets.chomp.to_i #入力値が0,1,2以外の時にerrorフラグを1にする if player_hand == 0 || player_hand == 1 || player_hand == 2 error = 0 else puts "0,1,2の数字で入力してください" error = 1 end end #結果を出力する puts "" puts "結果・・・・" player = Player.new(player_hand) program_hand = rand(3) programPlayer = ProgramPlayer.new(program_hand) puts "" #勝敗を出力する if player_hand - program_hand == -1 || player_hand - program_hand == 2 puts "あなたの勝ちです" elsif program_hand - player_hand == -1 || program_hand - player_hand == 2 puts "相手の勝ちです" else puts "引き分けです" end
class Machine < ApplicationRecord validates_presence_of :location belongs_to :owner has_many :snacks def self.avg_price require "pry"; binding.pry avg(snacks.price) end end
require 'sequel' require_relative 'row' module PseudoDb class Database include Logging def initialize(sequel_connection, data_dictionary, dry_run = false) @database = sequel_connection @data_dictionary = data_dictionary @dry_run = dry_run logger.warn 'Running in "dry-run" mode, database will not be updated' if dry_run end def anonymize @database.tables.each do |table_name| #next unless table_name == :borrower_companies table = @database[table_name] table_schema = @database.schema(table) columns = table_schema.map { |row| row[0] } next unless @data_dictionary.entry_for_table?(table_name, columns) logger.debug "Anonymizing #{table_name}" table.all.each do |row| updateable_row = table.where(*row) row_anonymizer = Row.new(row, table_name, @data_dictionary) anonymized_data = row_anonymizer.anonymize updateable_row.update(**anonymized_data) unless @dry_run end end end end end
class FixIronPole < ActiveRecord::Migration def change character = OfficialCharacter.find_by_name 'The Iron Pole' character.official_specials.delete_all s1 = OfficialSpecial.new s1.official_character_id = character.id s1.description = 'Can move through Cavern walls at extra Move cost of 3.' s1.survival = 25 s1.ranged = s1.melee = 0 s1.adventure = 30 s1.save! s2 = OfficialSpecial.new s2.official_character_id = character.id s2.description = 'Gains +2 on Strength adventures.' s2.survival = s2.ranged = s2.melee = 0 s2.adventure = 10 s2.save! end end
class Tempacct < ActiveRecord::Base validates :firstname, :surname, :uid, :passwd, :expiry_date, :owner, :account_type_id, :presence => true validates :ftp_login, :in_ldap, :printing, :inclusion => { :in => [true, false, 0, 1], :message => "Error: Boolean value must be 0 or 1" } validates :uid, :uniqueness => true #validates :description, :presence => true validate :expiry_date_cannot_be_in_the_past, on: :create validate :expiry_date_cannot_too_far_in_future validate :passwd_validity has_one :account_type #attr_accessor :account_type_id def fullname "#{firstname} #{surname}" end # Check http://edgeguides.rubyonrails.org/active_record_validations.html#custom-methods def expiry_date_cannot_be_in_the_past if expiry_date < Date.today errors.add(:expiry_date, "can't be in the past") end end # Check that the expiry date is not beyond the max for the account type def expiry_date_cannot_too_far_in_future ed = AccountType.max_expiry?(account_type_id) if expiry_date > ed atn = AccountType.account_type_name(account_type_id) errors.add(:expiry_date, "can't exceed #{atn} account type limit of #{ed.to_s(:my_date)}.") end end def passwd_validity if passwd.length < 8 errors.add(:passwd, "must contain at least 8 characters.") end if ! passwd.match(/\A(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\W_ ]).{8,}\z/) errors.add(:passwd, "must contain upper and lower case, a number and a punctuation character.") end end # Filter account names by their first letter - used for alphabetic pagination scope :by_letter, ->(initial) {where("surname LIKE \'#{initial}%\'").order(:surname) } end
class ChangeReviewAffiliationFromEnumToVarchar < ActiveRecord::Migration def self.up change_column :reviews, :affiliation, :string, :null => true end def self.down change_column :reviews, :affiliation, :enum, :limit => Review::AFFILIATION_VALUES end end
require 'rails_helper' RSpec.describe PlacesController, :type => :controller do describe "places/located" do it "returns all the places with coordinates ordered alfabetically" do place1 = FactoryGirl.create(:place) place2 = FactoryGirl.create(:place) place3 = FactoryGirl.create(:place, coord_x: nil) place4 = FactoryGirl.create(:place, coord_x: nil) get :located, format: "json" expect(assigns(:places)).to eq([place1, place2].sort_by {|p| p.name}) end end describe "GET index" do it "returns http success" do get :index expect(response).to be_success expect(response).to have_http_status(200) end it "renders the index template" do get :index expect(response).to render_template("index") end it "renders list of places ordered alfabetically" do place1 = FactoryGirl.create(:place) place2 = FactoryGirl.create(:place) place3 = FactoryGirl.create(:place) place4 = FactoryGirl.create(:place) get :index expect(assigns(:places)).to match_array([place1, place2, place3, place4].sort_by {|p| p.name}) end end describe "GET show" do let(:place) { FactoryGirl.create(:place) } context "HTML" do it "returns http success" do get :show, id: place expect(response).to be_success expect(response).to have_http_status(200) end it "renders the show template" do get :show, id: place expect(response).to render_template("show") end end context "JSON" do it "returns the place information" do get :show, format: "json", id: place expect(assigns(:place)).to eq(place) end end end describe "GET edit" do let(:place) { FactoryGirl.create(:place) } it "returns http success" do get :edit, id: place expect(response).to be_success expect(response).to have_http_status(200) end it "renders the edit template" do get :edit, id: place expect(response).to render_template("edit") end end end
module Aethyr module Core module Help class HelpEntry attr_reader :topic, :redirect, :content, :see_also, :aliases, :syntax_formats def initialize(topic, redirect: nil, content: nil, see_also: nil, aliases: nil, syntax_formats: nil) #do some validity checking on the arguments raise "Topic can not be nil" if topic.nil? raise "Redirect cant be defined alongside other arguments" unless redirect.nil? || (content.nil? && see_also.nil? && aliases.nil? and syntax_formats.nil?) raise "either content or redirect must be defined" if redirect.nil? && content.nil? raise "syntax_format must be defined when content is defined" if (not content.nil?) && (syntax_formats.nil? || syntax_formats.empty?) @topic = topic @redirect = redirect @content = content @see_also = see_also @aliases = aliases @syntax_formats = syntax_formats @see_also = [] if @see_also.nil? && (not @content.nil?) @aliases = [] if @aliases.nil? && (not @content.nil?) end def redirect? return (not @redirect.nil?) end end end end end
module ModelStack module DSLMethod class DefaultAttributes attr_accessor :generator def self.handle(generator, block) da = DefaultAttributes.new da.generator = generator da.instance_eval(&block) end def attribute(identifier, options) a = ModelStack::DSLReader::Attribute.read_attribute(identifier, options) self.generator.default_attributes << a end end end end