text
stringlengths
10
2.61M
class HostnameQuery def initialize(options = {}) @including = options.fetch(:including, nil).to_s.split(',').map(&:strip) @excluding = options.fetch(:excluding, nil).to_s.split(',').map(&:strip) @page = options.fetch(:page, 1) end def call #hostnames = Hostname.find_by_sql([sql_script]) hostnames = Hostname. select("array_agg(drh.dns_record_id) as dns_records_ids, hostnames.id, hostnames.hostname, COUNT(*) as matching_dns_count"). joins("INNER JOIN dns_record_hostnames AS drh ON hostnames.id = drh.hostname_id").group("hostnames.id, hostnames.hostname") if @including.present? hostnames = hostnames.where(hostname: @including) end if @excluding.present? exclude_dns_records = DnsRecord.joins(dns_record_hostnames: :hostname).where(hostnames: {hostname: @excluding}) hostnames = hostnames.where.not(id: exclude_dns_records.map(&:hostnames).flatten.map(&:id)) #not(dns_record_hostnames: { dns_record_id: exclude_dns_records.ids }) end return hostnames end def sql_script <<-SQL SELECT array_agg(drh.dns_record_id) as dns_records_ids, h.id, h.hostname, COUNT(*) as matching_dns_count FROM hostnames AS h INNER JOIN dns_record_hostnames AS drh ON h.id = drh.hostname_id GROUP BY h.id, h.hostname SQL end end
class Company < ActiveRecord::Base attr_accessor :coe,:ece,:ice,:it,:mpae,:bt,:is,:pc,:sp before_save :combine_branches # or choose other callback type respectively def combine_branches self.branchesAllowed = "" if coe=="COE" self.branchesAllowed += "COE" end if ece=="ECE" if (self.branchesAllowed=="") self.branchesAllowed += "ECE" elsif self.branchesAllowed += ", ECE" end end if ice=="ICE" if (self.branchesAllowed=="") self.branchesAllowed += "ICE" elsif self.branchesAllowed += ", ICE" end end if it=="IT" if (self.branchesAllowed=="") self.branchesAllowed += "IT" elsif self.branchesAllowed += ", IT" end end if mpae=="MPAE" if (self.branchesAllowed=="") self.branchesAllowed += "MPAE" elsif self.branchesAllowed += ", MPAE" end end if bt=="BT" if (self.branchesAllowed=="") self.branchesAllowed += "BT" elsif self.branchesAllowed += ", BT" end end if is=="IS" if (self.branchesAllowed=="") self.branchesAllowed += "IS" elsif self.branchesAllowed += ", IS" end end if is=="IS" if (self.branchesAllowed=="") self.branchesAllowed += "SP" elsif self.branchesAllowed += ", SP" end end if pc=="PC" if (self.branchesAllowed=="") self.branchesAllowed += "PC" elsif self.branchesAllowed += ", PC" end end end validate :deadline_on_or_before_now def deadline_on_or_before_now errors.add(:deadline, "can't be in the past") if !deadline.blank? and deadline < (Time.zone.now+19800).to_datetime end validates :name, presence: true, length: { minimum: 2 }; validates :grade,:beCutoff,:details,:package, presence: true; validates_inclusion_of :beCutoff,:xiiCutoff,:xCutoff, :in=> 0..100,:message=>"Out of Range"; end
class UserRating < ActiveRecord::Base belongs_to :user belongs_to :movie after_save :calculate_average def calculate_average movie.update_attributes(average: movie.user_ratings.average(:rating)) end end
require 'sqlite3' require 'singleton' require_relative 'user' require_relative 'reply' require_relative 'question_follow' require_relative 'question_like' class QuestionsDatabase < SQLite3::Database include Singleton def initialize super('questions.db') self.type_translation = true self.results_as_hash = true end end class Question attr_accessor :id, :title, :body, :users_id def self.all data = QuestionsDatabase.instance.execute("SELECT * FROM questions") data.map { |datum| Question.new(datum) } end def initialize (options) @id = options['id'] @title = options['title'] @body = options['body'] @users_id = options['users_id'] end def save if @id QuestionsDatabase.instance.execute(<<-SQL, title, body, users_id, id) UPDATE questions SET title = ?, body = ?, users_id = ? WHERE questions.id = ? SQL else QuestionsDatabase.instance.execute(<<-SQL, title, body, users_id) INSERT INTO questions (title, body, users_id) VALUES (?, ?, ?) SQL @id = QuestionsDatabase.instance.last_insert_row_id end end def remove if @id QuestionsDatabase.instance.execute(<<-SQL, id) DELETE FROM questions WHERE questions.id = ? SQL end end def self.find_by_id(id) question_data = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM questions WHERE id = ? SQL return nil if question_data.nil? question_data.map {|q| Question.new(q) } end def self.find_by_author_id(users_id) question_data = QuestionsDatabase.instance.execute(<<-SQL, users_id) SELECT * FROM questions WHERE users_id = ? SQL return nil if question_data.nil? question_data.map {|question| Question.new(question) } end # Author of the question def author User.find_by_id(users_id) end # Replies to the question def replies Reply.find_by_question_id(id) end def followers QuestionFollow.followers_for_question_id(id) end def self.most_followed(n) QuestionFollow.most_followed_questions(n) end def likers QuestionLike.likers_for_question_id(id) end def num_likes QuestionLike.num_likes_for_question_id(id) end # Fetches n most liked questions. def self.most_liked(n) QuestionLike.most_liked_questions(n) end end
# controller class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [ :first_name, :last_name, :user_name ]) devise_parameter_sanitizer.permit( :account_update, keys: [ :first_name, :last_name, :user_name, :profile_photo, :profile_photo_cache, :remove_profile_photo ]) end end
class MessageRecipient < ActiveRecord::Base belongs_to :message belongs_to :messagable, :polymorphic => true validates_presence_of :messagable_id, :messagable_type, :protocol validates_uniqueness_of :message_id, :scope => [:messagable_id, :messagable_type] after_destroy :after_destroy_recipient # BEGIN acts_as_state_machine include AASM aasm_column :state aasm_initial_state :created aasm_state :created aasm_state :sent, :enter => :message_sent aasm_state :unread, :enter => :message_unread aasm_state :read, :enter => :message_read aasm_event :sent do transitions :to => :sent, :from => [:created] end aasm_event :read do transitions :to => :read, :from => [:sent, :unread] end aasm_event :unread do transitions :to => :unread, :from => [:sent, :read] end # END acts_as_state_machine # find messages by protocol named_scope :local, { :conditions => {:protocol => 'local'} } named_scope :email, { :conditions => {:protocol => 'email'} } named_scope :sms, { :conditions => {:protocol => 'sms'} } named_scope :for_messagable, lambda { |o| {:conditions => {:messagable_id => o.id, :messagable_type => o.class.to_s} }} # valid, supported protocols def self.protocols ['local', 'email', 'sms'] end # called when the message is marked as sent def message_sent self.update_attribute(:sent_at, Time.now) end # called when the message is marked as unread def message_unread end # called when the message is marked as read def message_read end protected def after_destroy_recipient # destroy message if there are no message recipients if self.message.message_recipients.empty? self.message.destroy end end end
# # Cookbook Name:: simple-python-app # Recipe:: default # # Copyright (c) 2016 The Authors, All Rights Reserved. appdir = node['simple-python-app']['app']['install_dir'] venvdir = "#{appdir}/venv" appuser = node['simple-python-app']['app']['user'] appgroup = node['simple-python-app']['app']['group'] group appgroup user appuser do gid appgroup end package 'unzip' python_runtime 'app' do version node['simple-python-app']['python']['version'] end directory appdir do recursive true owner appuser group appgroup end python_virtualenv 'app' do user appuser group appgroup python 'app' path venvdir end remote_file "#{appdir}/app.zip" do source node['simple-python-app']['app']['source'] owner appuser group appgroup use_conditional_get true use_last_modified true notifies :run, 'execute[unzip_app]', :immediately end execute 'unzip_app' do command 'unzip app.zip' user appuser group appgroup cwd appdir action :nothing notifies :install, 'pip_requirements[app]', :immediately end pip_requirements 'app' do path "#{appdir}/requirements.txt" user appuser group appgroup virtualenv 'app' action :nothing end include_recipe 'supervisor::default' supervisor_service 'app' do command "#{venvdir}/bin/python #{appdir}/app.py" environment "PATH" => "#{venvdir}/bin:$PATH" directory appdir user appuser redirect_stderr true stdout_logfile "#{appdir}/application.log" action [:enable, :restart] end apt_package 'nginx' template '/etc/nginx/nginx.conf' do source 'nginx.conf.erb' notifies :restart, 'service[nginx]' end template '/etc/nginx/sites-available/default' do source 'nginx-sites-default.erb' notifies :restart, 'service[nginx]' end service 'nginx' do action [:enable, :start] end
class Formulario < ActiveRecord::Base validates :derecho, :presence=>true validates :title, :presence=>true has_many :accions belongs_to :derecho end
require 'authenticate' require 'rails' module Authenticate # # Authenticate Rails engine. # Filter password, token, from spewing out. # class Engine < ::Rails::Engine initializer 'authenticate.filter' do |app| app.config.filter_parameters += [:password, :token] end config.generators do |g| g.test_framework :rspec g.fixture_replacement :factory_girl, dir: 'spec/factories' end end end
# frozen_string_literal: true require 'test_helper' class Admin::TicketsControllerTest < ActionDispatch::IntegrationTest setup do @admin_ticket = admin_tickets(:one) end test 'should get index' do get admin_tickets_url assert_response :success end test 'should get new' do get new_admin_ticket_url assert_response :success end test 'should create admin_ticket' do assert_difference('Admin::Ticket.count') do post admin_tickets_url, params: { admin_ticket: { happenings_id: @admin_ticket.happenings_id, seats: @admin_ticket.seats, user_id: @admin_ticket.user_id } } end assert_redirected_to admin_ticket_url(Admin::Ticket.last) end test 'should show admin_ticket' do get admin_ticket_url(@admin_ticket) assert_response :success end test 'should get edit' do get edit_admin_ticket_url(@admin_ticket) assert_response :success end test 'should update admin_ticket' do patch admin_ticket_url(@admin_ticket), params: { admin_ticket: { happenings_id: @admin_ticket.happenings_id, seats: @admin_ticket.seats, user_id: @admin_ticket.user_id } } assert_redirected_to admin_ticket_url(@admin_ticket) end test 'should destroy admin_ticket' do assert_difference('Admin::Ticket.count', -1) do delete admin_ticket_url(@admin_ticket) end assert_redirected_to admin_tickets_url end end
# encoding: utf-8 require 'cases/sqlserver_helper' require 'models/event' class Event < ActiveRecord::Base before_validation :strip_mb_chars_for_sqlserver protected def strip_mb_chars_for_sqlserver self.title = title.mb_chars.to(4).to_s if title && title.is_utf8? end end class UniquenessValidationTestSqlserver < ActiveRecord::TestCase end class UniquenessValidationTest < ActiveRecord::TestCase COERCED_TESTS = [:test_validate_uniqueness_with_limit_and_utf8] include SqlserverCoercedTest # I guess most databases just truncate a string when inserting. To pass this test we do a few things. # First, we make sure the type is unicode safe, second we extend the limit to well beyond what is # needed. At the top we make sure to auto truncate the :title string like other databases would do # automatically. # # "一二三四五".mb_chars.size # => 5 # "一二三四五六七八".mb_chars.size # => 8 # "一二三四五六七八".mb_chars.to(4).to_s # => "一二三四五" def test_coerced_validate_uniqueness_with_limit_and_utf8 with_kcode('UTF8') do Event.connection.change_column :events, :title, :nvarchar, :limit => 30 Event.reset_column_information # Now the actual test copied from core. e1 = Event.create(:title => "一二三四五") assert e1.valid?, "Could not create an event with a unique, 5 character title" e2 = Event.create(:title => "一二三四五六七八") assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique" end end end
class CategoriesController < ApplicationController def index @categories = Category.all end def new @category = Category.new end def create @category = Category.new(category_params) if @category.save flash[:notice] = "You created a new category!" redirect_to categories_path else flash[:notice] = "Your category could not be created as entered." render :new end end def show @category = Category.where(id: params[:category_id]) @drinks = Drink.where(category_id: params[:category_id]) end protected def category_params params.require(:category).permit(:name) end end
class FaxDocumentsController < ApplicationController load_and_authorize_resource :fax_account load_and_authorize_resource :fax_document, :through => [:fax_account] before_filter :spread_breadcrumbs def index @fax_documents = @fax_documents.order(:created_at).reverse_order end def show respond_to do |format| @fax_document = FaxDocument.find(params[:id]) format.html format.xml { render :xml => @fax_document } format.pdf { caller_number = @fax_document.caller_id_number.to_s.gsub(/[^0-9]/, '') if caller_number.blank? caller_number = 'anonymous' end if @fax_document.document.path send_file @fax_document.document.path, :type => "application/pdf", :filename => "#{@fax_document.created_at.strftime('%Y%m%d-%H%M%S')}-#{caller_number}.pdf" else render( :status => 404, :layout => false, :content_type => 'text/plain', :text => "<!-- Document not found -->", ) end } format.tiff { caller_number = @fax_document.caller_id_number.to_s.gsub(/[^0-9]/, '') if caller_number.blank? caller_number = 'anonymous' end if @fax_document.tiff send_file @fax_document.tiff, :type => "image/tiff", :filename => "#{@fax_document.created_at.strftime('%Y%m%d-%H%M%S')}-#{caller_number}.tiff" else render( :status => 404, :layout => false, :content_type => 'text/plain', :text => "<!-- Raw image not found -->", ) end } end end def new @fax_document = @fax_account.fax_documents.build @phone_number = @fax_document.build_destination_phone_number end def create @fax_document = @fax_account.fax_documents.build(params[:fax_document]) @fax_document.retry_counter = @fax_account.retries if @fax_document.save if @fax_document.tiff.blank? @fax_document.destroy @fax_document.errors.add(:document, t('fax_documents.controller.tiff_not_created')) render :new else @fax_document.queue_for_sending! redirect_to fax_account_fax_document_path(@fax_document.fax_account, @fax_document), :notice => t('fax_documents.controller.successfuly_created') end else render :new end end def destroy @fax_account = FaxAccount.find(params[:fax_account_id]) @fax_document = @fax_account.fax_documents.find(params[:id]) @fax_document.destroy redirect_to fax_account_fax_documents_url, :notice => t('fax_documents.controller.successfuly_destroyed') end private def spread_breadcrumbs if @fax_account && @fax_account.fax_accountable.class == User add_breadcrumb t("users.index.page_title"), tenant_users_path(@fax_account.fax_accountable.current_tenant) add_breadcrumb @fax_account.fax_accountable, tenant_user_path(@fax_account.fax_accountable.current_tenant, @fax_account.fax_accountable) end if @fax_account add_breadcrumb t("fax_accounts.index.page_title"), user_fax_accounts_path(@fax_account.fax_accountable) add_breadcrumb @fax_account, user_fax_account_path(@fax_account.fax_accountable, @fax_account) if @fax_document && !@fax_document.new_record? add_breadcrumb @fax_document, fax_account_fax_document_path(@fax_account, @fax_document) end end end end
class ReportsController < ApplicationController before_action :set_report, only: [:edit, :update, :destroy] before_action :authenticate_user!, only: [:edit, :update, :destroy, :new, :create] before_action :check_profile before_action do if !user_signed_in? && !tutor_signed_in? flash[:notice] = 'ログインして下さい' redirect_to root_path end end # GET /reports # GET /reports.json def index @reports = Report.where(user_id: current_user.id).order('created_at DESC') @events = UserEvent.where('user_id = ? AND (event_type = ? OR event_type = ?)', current_user.id, 7, 1).select(:event_type, :link, :created_at) @summaries = Summary.where(user_id: current_user.id) if @reports.count == 0 flash[:notice] = '記録がありません' redirect_to home_index_path end end # GET /reports/1 # GET /reports/1.json def show @report = Report.find(params[:id]) @yesterday_report = Report.where("created_at <= ? AND created_at >= ? AND user_id = ?", @report.created_at.beginning_of_day, @report.created_at.beginning_of_day - 1.day, current_user.id).first @subject_array = Array.new() @subject_time = Array.new() @yesterday_subject_time = Array.new() subject_hash.each do |key, value| str = "current_user.subject.#{key}" str2 = "@report.#{key}_percentage" str3 = "@yesterday_report.#{key}_percentage" if eval(str) @subject_array.push(value) @subject_time.push(eval(str2)) if @yesterday_report @yesterday_subject_time.push(eval(str3)) end end end #関係ない人のレポートを勝手に見られないようにするコード if user_signed_in? if @report.user != current_user render_404 end elsif tutor_signed_in? count = 0 current_tutor.users.each do |user| if @report.user == user break else count += 1 end end if count == current_tutor.users.count render_404 end else render_404 end end # GET /reports/new def new @report = Report.where("created_at >= ? AND user_id = ?", Time.zone.now.beginning_of_day, current_user.id).first @report ||= Report.new end # GET /reports/1/edit def edit end # POST /reports # POST /reports.json def create sum = 0 report_params.each do |key, value| if value.to_i != 0 sum += value.to_i / 60 end end report_params_array = report_params.to_a str1 = "report_params_array[0][1] = (report_params_array[0][1].to_i / 60).to_s" #str2 = "report_params_array[1][1] = @report.#{report_params_array[1][0]} + '\n' + report_params_array[1][1]" eval(str1) #eval(str2) report_params_array[2] = ["average_studytime", "#{sum}"] @report = Report.new(Hash[*report_params_array.flatten]) @report.average_studytime = sum @report.user_id = current_user.id @user_event = UserEvent.new(status: '勉強内容を記録しました。', user_id: current_user.id, event_type: 1) respond_to do |format| if @report.save current_user.update(studying_flag: false, studying_subject_attribute: 0, studying_started_at: nil) @user_event.link = "/reports/#{@report.id}" @user_event.save format.html { redirect_to @report, notice: '勉強内容を記録しました。' } format.json { render :show, status: :created, location: @report } else format.html { render :new } format.json { render json: @report.errors, status: :unprocessable_entity } end end end # PATCH/PUT /reports/1 # PATCH/PUT /reports/1.json def update # current_user.update(studying_flag: false, studying_subject_attribute: 0, studying_started_at: nil) sum = @report.average_studytime report_params.each do |key, value| if value.to_i != 0 sum += value.to_i / 60 end end report_params["average_studytime"] = "#{sum}" @user_event = UserEvent.new(status: '勉強内容を記録しました。', user_id: current_user.id, event_type: 1) respond_to do |format| if @report.update(report_params) @user_event.link = "/reports/#{@report.id}" @user_event.save format.html { redirect_to @report, notice: '勉強内容を記録しました。' } format.json { render :show, status: :ok, location: @report } else format.html { render :edit } format.json { render json: @report.errors, status: :unprocessable_entity } end end end def update_via_timer @report = Report.find(params[:id]) report_params_array = report_params.to_a #report_params.each_with_index do |(key, value), index| # str[index] = "former_data[#{index}] = @report.#{key}" #end str1 = "report_params_array[0][1] = (report_params_array[0][1].to_i / 60 + @report.#{report_params_array[0][0]}.to_i).to_s" #str2 = "report_params_array[1][1] = @report.#{report_params_array[1][0]} + '\n' + report_params_array[1][1]" eval(str1) #eval(str2) sum = @report.average_studytime report_params.each do |key, value| if value.to_i != 0 sum += value.to_i / 60 end end report_params_array[2] = ["average_studytime", "#{sum}"] @user_event = UserEvent.new(status: '勉強内容を記録しました。', user_id: current_user.id, event_type: 1) respond_to do |format| if @report.update(Hash[*report_params_array.flatten]) current_user.update(studying_flag: false, studying_subject_attribute: 0, studying_started_at: nil) @user_event.link = "/reports/#{@report.id}" @user_event.save format.html { redirect_to @report, notice: '勉強内容を記録しました。' } format.json { render :show, status: :ok, location: @report } else format.html { render :edit } format.json { render json: @report.errors, status: :unprocessable_entity } end end end # DELETE /reports/1 # DELETE /reports/1.json def destroy @report.destroy respond_to do |format| format.html { redirect_to reports_url, notice: 'Report was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_report @report = Report.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def report_params params.require(:report).permit(:japanese_percentage, :japanese_comment, :old_japanese_percentage, :old_japanese_comment, :old_chinese_percentage, :old_chinese_comment, :english_percentage, :english_comment, :math_percentage, :math_comment, :physics_percentage, :physics_comment, :chemistry_percentage, :chemistry_comment, :biology_percentage, :biology_comment, :geology_percentage, :geology_comment, :world_history_percentage, :world_history_comment, :japanese_history_percentage, :japanese_history_comment, :politics_and_economics_percentage, :politics_and_economics_comment, :modern_society_percentage, :modern_society_comment, :ethics_percentage, :ethics_comment, :geography_percentage, :geography_comment, :average_studytime, :free_comment, :user_id) end end
require_relative 'configuration/validatable' require_relative 'configuration/queue_configuration' require_relative 'configuration/redrive_policy_configuration' module Ehonda class Configuration include Validatable def initialize @queues = {} @queue_defaults = QueueConfiguration.new 'queue_defaults' @sns_protocol = @sqs_protocol = 'sqs' end attr_reader :queue_defaults, :sns_endpoint, :sns_protocol, :sqs_endpoint, :sqs_protocol attr_accessor :published_messages def add_queue name environmental_name = Aws::EnvironmentalName.new(name).to_s fail "A queue called #{name} already exists." if @queues.key? environmental_name queue = QueueConfiguration.new name @queue_defaults.copy_onto queue yield queue if block_given? @queues[environmental_name] = queue end def aws_options @aws_options ||= aws_hash.slice :access_key_id, :region, :secret_access_key end def aws_account_id aws_hash[:account_id] end def aws_region aws_options[:region] end def enable_cmb_mode @sns_protocol = @sqs_protocol = 'cqs' enable_custom_endpoints end def enable_custom_endpoints @sns_endpoint = aws_hash[:sns_endpoint] @sqs_endpoint = aws_hash[:sqs_endpoint] end def queues @queues.values end def get_queue environmental_name @queues[environmental_name] end def iam_group_name iam_hash[:group_name] end def iam_policy_name iam_hash[:policy_name] end def published_topics [published_messages].flatten.compact.uniq.sort.map do |message| Ehonda::Aws::EnvironmentalName.new(message.constantize.to_topic_name).to_s end end def shoryuken_config_path @shoryuken_config_path ||= begin (Rails.root + 'config' + 'shoryuken.yml') if defined?(::Rails) end end attr_writer :shoryuken_config_path def shoryuken_config @shoryuken_config ||= begin YAML.load( ERB.new( IO.read( shoryuken_config_path) ).result ).with_indifferent_access end end def sns_options aws_client_options :sns_endpoint end def sqs_options aws_client_options :sqs_endpoint end def use_ehonda_logging require 'ehonda/logging' Ehonda::Logging.logger = Logger.new(STDOUT).tap do |l| l.level = Shoryuken::Logging.logger.level l.formatter = Ehonda::Logging::Formatter.new end Shoryuken::Logging.logger = Ehonda::Logging.logger end def use_typed_message_registry dead_letter_queue_name require 'ehonda/worker_registries/typed_message_registry' Shoryuken.worker_registry = Ehonda::WorkerRegistries::TypedMessageRegistry.new dead_letter_queue_name end def validate [queue_defaults, queues].flatten.compact.each do |section| section.valid? errors.push *(section.errors) end errors << "AWS access key must be supplied." if aws_options[:access_key_id].blank? errors << "AWS account id must be supplied." if aws_account_id.blank? errors << "AWS secret key must be supplied." if aws_options[:secret_access_key].blank? end def validate! return if valid? fail %(Invalid configuration: \n\n#{errors.join("\n")}\n\n) end private def arns @arns ||= Ehonda::Aws::Arns.new end def aws_client_options endpoint_key options = aws_options endpoint = aws_hash[endpoint_key] options = options.merge(endpoint: endpoint) unless endpoint.blank? options end def aws_hash shoryuken_config[:aws] end def iam_hash iam = aws_hash.fetch(:iam) do fail 'IAM section not found within AWS yaml.' end end end end
class Restaurant attr_accessor :name @@all = [] def initialize(name) @name = name @reviews = [] @@all << self end def add_review(review) @reviews<<review end def self.all @@all end def self.find_by_name(name) self.all.detect{|restaurant| restaurant.name == name } end def reviews @reviews end def customers self.reviews.collect{|review| review.customer} end end
class Video < ApplicationRecord include Name, Publishable, Slug def path "/videos/#{slug}" end def content_rendered Kramdown::Document.new( content, input: content_format == "html" ? :html : :kramdown, remove_block_html_tags: false, transliterated_header_ids: true, html_to_native: true ).to_html.html_safe end end
class Gst::Pipeline < Gst::Element def initialize(name) self.java_element = JavaGst::Pipeline.new(name) end def add(*elements) java_elements = elements.collect { |element| element.java_element } java_elements = java_elements.to_java(:java.org.gstreamer::Element) java_element.add_many(java_elements) end def play java_element.play end def pause java_element.pause end def paused? self.state == Gst::State::PAUSED end def playing? self.state == Gst::State::PLAYING end def stop self.state = Gst::State::NULL end def stopped? self.state == Gst::State::NULL end def state state = java_element.state eval("Gst::State::#{state.to_s}") end def state=(state) return false if not state.is_a? Gst::State java_element.set_state(state.to_java) end end
class AddBicycleFootToTrails < ActiveRecord::Migration[5.0] def change add_column :trails, :bicycle, :boolean add_column :trails, :foot, :boolean end end
require 'spec_helper' module Stats describe Math do it "performs basic sums" do numbers = [1, 2, 3] Math.sum(numbers).should == 6 end it "integrates linear functions" do identity = lambda {|x| x } Math.integrate(0..1, &identity).should == 0.5 end it "integrates quadratic functions" do quadratic = lambda {|x| x ** 2 } Math.integrate(0..1, &quadratic).should be_pseudo_equal(1.0/3) end it "integrates trigonometric functions" do sin = lambda {|x| ::Math.sin(x) } Math.integrate(0..1, &sin).should == 1 - ::Math.cos(1) end it "integrates exponential function" do e = lambda {|x| ::Math.exp(x) } Math.integrate(0..1, &e).should be_pseudo_equal(::Math.exp(1) - 1) end end end
require 'mysql' require 'mysql2' class MySQLHealthcheck def self.connect Mysql.connect(host='localhost', user="root", password='root') end def self.connectv2 Mysql2::Client.new(host: 'localhost', username: "root", password: 'root') end def self.status_check(client = nil) client ||= self.connect (client.stat.split /(?=[A-Z])/).inject(hash={}) do |hash, e| hash.merge!("#{e.split(':')[0].gsub(" ", "_")}": "#{e.split(':')[1].to_f}") end end def self.memory(type, client = nil) client ||= self.connect res =[] client.query("SHOW ENGINE INNODB STATUS;").each {|r| res << r} out = nil case type when 'total' (res[0][2].split /\n/).each {|row| out = row unless row.match(/Total large memory allocated/).nil?} out.partition('Total large memory allocated')[2].to_f when 'buffer' (res[0][2].split /\n/).each {|row| out = row unless row.match(/Buffer pool size/).nil?} out.partition('Buffer pool size')[2].to_f when 'free_buffer' (res[0][2].split /\n/).each {|row| out = row unless row.match(/Free buffers/).nil?} out.partition('Free buffers')[2].to_f else raise "Wrong type in the argument" end end def self.max_connections(clientv2 = nil) clientv2 ||= connectv2 clientv2.query("SHOW GLOBAL VARIABLES LIKE 'max_connections';").first['Value'].to_i end def self.current_connections(clientv2 = nil) clientv2 ||= connectv2 clientv2.query("SHOW GLOBAL STATUS LIKE 'max_used_connections'").first['Value'].to_i end def self.available_connections self.max_connections-self.current_connections end def self.available_connections_percent (self.max_connections.to_f/self.current_connections.to_f).round(2) end def self.table_scan_data(clientv2 = nil) clientv2 ||= connectv2 clientv2.query("SHOW GLOBAL STATUS LIKE 'Handler_read%';") end def self.process_list(client = nil) client ||= self.connect client.query("SELECT * FROM information_schema.processlist;").each {|row| p row} client.query("SHOW GLOBAL STATUS LIKE 'aborted_connects';").each {|row| p row} end end
# frozen_string_literal: true require 'stannum/constraints/hashes/indifferent_key' require 'support/examples/constraint_examples' RSpec.describe Stannum::Constraints::Hashes::IndifferentKey do include Spec::Support::Examples::ConstraintExamples subject(:constraint) { described_class.new(**constructor_options) } let(:constructor_options) { {} } let(:expected_options) { {} } describe '::NEGATED_TYPE' do include_examples 'should define frozen constant', :NEGATED_TYPE, 'stannum.constraints.hashes.is_string_or_symbol' end describe '::TYPE' do include_examples 'should define frozen constant', :TYPE, 'stannum.constraints.hashes.is_not_string_or_symbol' end describe '.new' do it 'should define the constructor' do expect(described_class) .to be_constructible .with(0).arguments .and_any_keywords end end include_examples 'should implement the Constraint interface' include_examples 'should implement the Constraint methods' describe '#match' do let(:match_method) { :match } let(:expected_messages) do expected_errors.merge(message: 'is not a String or a Symbol') end describe 'with nil' do let(:actual) { nil } let(:expected_errors) do { type: Stannum::Constraints::Presence::TYPE } end let(:expected_messages) do expected_errors.merge(message: 'is nil or empty') end include_examples 'should not match the constraint' end describe 'with an Object' do let(:actual) { Object.new.freeze } let(:expected_errors) do { type: described_class::TYPE } end include_examples 'should not match the constraint' end describe 'with an empty String' do let(:actual) { '' } let(:expected_errors) do { type: Stannum::Constraints::Presence::TYPE } end let(:expected_messages) do expected_errors.merge(message: 'is nil or empty') end include_examples 'should not match the constraint' end describe 'with a String' do let(:actual) { 'a string' } include_examples 'should match the constraint' end describe 'with an empty Symbol' do let(:actual) { :'' } let(:expected_errors) do { type: Stannum::Constraints::Presence::TYPE } end let(:expected_messages) do expected_errors.merge(message: 'is nil or empty') end include_examples 'should not match the constraint' end describe 'with a Symbol' do let(:actual) { :a_symbol } include_examples 'should match the constraint' end end describe '#negated_match' do let(:match_method) { :negated_match } let(:expected_errors) do { type: described_class::NEGATED_TYPE } end let(:expected_messages) do expected_errors.merge(message: 'is a String or a Symbol') end describe 'with nil' do let(:actual) { nil } include_examples 'should match the constraint' end describe 'with an Object' do let(:actual) { Object.new.freeze } include_examples 'should match the constraint' end describe 'with an empty String' do let(:actual) { '' } include_examples 'should match the constraint' end describe 'with a String' do let(:actual) { 'a string' } include_examples 'should not match the constraint' end describe 'with an empty Symbol' do let(:actual) { :'' } include_examples 'should match the constraint' end describe 'with a Symbol' do let(:actual) { :a_symbol } include_examples 'should not match the constraint' end end end
# frozen_string_literal: true class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters #allowing devise to accept type attribute devise_parameter_sanitizer.permit(:sign_up, keys: [:type]) end #custom error message for unauthorised user rescue_from CanCan::AccessDenied do |exception| if user_signed_in? flash[:error] = "Access denied!" redirect_to root_url else flash[:error] = "Please Sign in" redirect_to new_user_session_path end end end
class ImportPresenter < Presenter delegate :created_at, :to_table, :target_dataset_id, :source_dataset_id, :to => :model def to_hash { :execution_info => { :to_table => to_table, :to_table_id => target_dataset_id, :started_stamp => created_at, :completed_stamp => created_at, :state => "success", :source_id => source_dataset_id, :source_table => Dataset.find(source_dataset_id).name }, :source_id => source_dataset_id, :source_table => Dataset.find(source_dataset_id).name } end end
namespace :pages do desc "Generate pages: Faq, Products, Contact, About and Checkout" task :generate_pages => :environment do puts "== Generating Pages \n" Page.where(name: "About").first_or_create(name:"About",title:"About",body:"Content for about page") Page.where(name: "Product").first_or_create(name:"Product",title:"Product",body:"Content for Products page") Page.where(name: "Checkout").first_or_create(name:"Checkout",title:"Checkout",body:"Content for Checkout page") Page.where(name: "Contact").first_or_create(name:"Contact",title:"Contact",body:"Content for Contact page") Page.where(name: "Faq").first_or_create(name:"Faq",title:"Faq",body:"Content for Faq page") Page.where(name: "New Restaurant How it works").first_or_create(name:"New Restaurant How it works",title:"How it works",body:"Content for New Restaurant page") end end
FactoryGirl.define do factory :referral_contact do open_lead false reminder_count 1 phone_number "MyString" user nil end end
class CreateIngredientsRecipesTable < ActiveRecord::Migration def up create_table :ingredients_recipes, id: false do |t| t.integer :ingredient_id t.integer :recipe_id end end end
json.array!(@hairdevices) do |hairdevice| json.extract! hairdevice, :id json.url hairdevice_url(hairdevice, format: :json) end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :touch do user nil item nil reaction_type "MyString" reaction_id 1 end end
class EventsController < ApplicationController before_action :set_event, only: [:show, :update, :destroy] before_action :check_password!, only: [:update, :destroy] def show render json: @event.as_json.merge({ participants: @event.participants }) end def create @event = Event.new(event_params) save_or_fail! @event end def update @event.assign_attributes(event_params) save_or_fail! @event end def destroy @event.destroy head :no_content end def time_selection @rows_number = params[:rows_number].to_i rescue nil @columns_number = params[:columns_number].to_i rescue nil if @rows_number.nil? || @columns_number.nil? || @rows_number == 0 || @columns_number == 0 render json: { error: 'invalid arguments' } end render end private def set_event @event = Event.find_by_token(params[:id]) rescue nil render_404 if @event.nil? end def check_password! password = params[:event].delete :current_password if params[:event] render_403 unless @event.authenticate(password) end def event_params params.require(:event).permit(:title, :description, :duration, :password, dates_attributes: [:id, :times, :date]) end end
class SimpleSums def initialize( number ) @number = number end def number @number end def s1 @number % 2 end def s2 sum_s2 = 0 @number.times do |num| sum_s2 += num + 1 end sum_s2 end end sum = SimpleSums.new(4) p.sum.number
require 'rails_helper' RSpec.describe Student, type: :model do # write your student model here describe 'attributes' do # it 'has a name' do # end # it 'has student_number' do # end # it 'has GPA' do # end #checks that the cloumn exists in the database? it{ should respond_to :name } it { should respond_to :student_number } it { should respond_to :gpa} end #check that data is correct in columns (validations) describe 'validations' do it { should validate_presence_of :name} it { should validate_presence_of :student_number} it { should validate_presence_of :gpa} # it { should validate_numericality_of :student_number } # it { should validate_numericality_of :gpa} # it 'has a unique name' do # before(:each) do # @student = Student.create( # name: 'jill', # student_number: 123, # gpa: 3.87, # school_id: 8 # ) # it { should validate_uniqueness_of :name } # end # end it 'has a student_number lower bound' do should validate_numericality_of(:student_number). is_greater_than_or_equal_to(0) end it 'as a student_number higer bound' do should validate_numericality_of(:student_number). is_less_than_or_equal_to(10000) end it 'has a gpa lower bound' do should validate_numericality_of(:gpa). is_greater_than_or_equal_to(0) end it 'has a gpa higer bound' do should validate_numericality_of(:gpa). is_less_than_or_equal_to(4.0) end end describe "uniqueness" do subject { @school = School.create!(name: 'foo', address: '123', principal: 'mt', capacity: 15) Student.create!( school_id: @school.id, name: 'jill', student_number: 123, gpa: 3.87 ) } # @student2 = Student.create!( # school_id: @school.id, # name: 'bob', # student_number: 123, # gpa: 3.87 # ) # it { should validate_uniqueness_of(:name) } # end #binding.pry # Student.create!(name: 'foo', student_number: '123', gpa: 3.4, school_id: @school.id) # subject { Student.new(name: 'foo', student_number: '123', gpa: 3.4, school_id: @school.id) } it { should validate_uniqueness_of(:name) } end end
require "./lib/minitest/should_syntax/version" Gem::Specification.new do |s| s.name = "minitest-should_syntax" s.version = MiniTest::ShouldSyntax.version s.summary = "RSpec-like syntax for MiniTest." s.description = "Lets you use a syntax similar to RSpec on your MiniTest tests." s.authors = ["Rico Sta. Cruz"] s.email = ["rico@sinefunc.com"] s.homepage = "http://github.com/rstacruz/minitest-should_syntax" s.files = `git ls-files`.strip.split("\n") s.add_dependency "minitest" s.add_development_dependency "mocha" s.add_development_dependency "rake" end
require 'spec_helper' describe Spree::EmailSenderController do let(:product) { create(:product) } before { controller.stub spree_current_user: nil } it 'use EmailSenderController' do expect(controller).to be_an_instance_of(Spree::EmailSenderController) end context '#send_mail' do # can be different types but no clue what they can be except from product specify do spree_get :send_mail, { type: 'product', id: product.id } expect(response).to be_success end end end
# frozen_string_literal: true module Delegable extend ActiveSupport::Concern included do scope :delegated, -> (user_id) { where('stewardships.user_id = ? OR organizations.created_by = ?', user_id, user_id) } end def owner_id organization.created_by end end
module MAILAPI # # Class that helps to connect to the Mail API. # class Call API_URL = (ENV["MAILAPI_URL"] ? ENV["MAILAPI_URL"] : MAILAPI::ENDPOINT) # Point our client to the API end point. # def initialize(apikey) @apikey = apikey @server = XMLRPC::Client.new2(API_URL) @server.http_header_extra = { "User-Agent" => "#{MAILAPI::PARTNER}/Ruby/#{MAILAPI::VERSION}" } end # Call desired function with the given parameters. # In case of an error return error message. # def executeMethod(method, params) # Add the apikey params.merge!({:apikey => @apikey}) begin response = @server.call(method,params) return response rescue XMLRPC::FaultException => e return MAILAPI::Error.new(e.faultCode, e.faultString) end end end end
# metaprogramming to the rescue! #a class Numeric @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1} def method_missing(method_id) singular_currency = nomalizeCurrency method_id if @@currencies.has_key?(singular_currency) self * @@currencies[singular_currency] else super end end #instance method to convert into differnt currencies def in (currency) self * (1/@@currencies[nomalizeCurrency currency]) end def nomalizeCurrency (currency) currency.to_s.gsub(/s$/, '') end end #Tests #puts 1.rupee.in(:yen) #puts 1.dollar.in(:rupees) #puts 45.rupees.in(:dollars) #puts 5.rupees.in(:yen) #b class String def palindrome? trimmedString = self.downcase.gsub(/[^a-z]/, "") #trimm the string to capture only a-z replacing none alphanumic chars trimmedString.eql? trimmedString.reverse #verifying if the resulting string is a palindrome or not end end #Tests #puts "foo".palindrome? #puts "foof".palindrome? #c module Enumerable def palindrome? arr = self.to_a arr.eql?arr.reverse end end class ValidPalindromeTest include Enumerable end #puts "1", [1,[2,1],5,7].palindrome? #puts "2", [1,2,3,2,1].palindrome? #puts "3", {"hello"=> "world"}.palindrome? #should not error #puts "4", ValidPalindromeTest.new(1,9).palindrome? #should be true #puts "5", (1..2).palindrome? #Should be false
# added in release 1.5.8 module GroupDocs class Document::Annotation::MarkerPosition< Api::Entity # # example # marker = GroupDocs::Document::Annotation::MarkerPosition.new() # marker.position = {:x => 100, :y => 100} # marker.page = 1 # @attr [Array](x,y) position attr_accessor :position # @attr [Int] page attr_accessor :page end end
require 'test_helper' class SobresControllerTest < ActionController::TestCase setup do @sobre = sobres(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:sobres) end test "should get new" do get :new assert_response :success end test "should create sobre" do assert_difference('Sobre.count') do post :create, sobre: { texto: @sobre.texto } end assert_redirected_to sobre_path(assigns(:sobre)) end test "should show sobre" do get :show, id: @sobre assert_response :success end test "should get edit" do get :edit, id: @sobre assert_response :success end test "should update sobre" do put :update, id: @sobre, sobre: { texto: @sobre.texto } assert_redirected_to sobre_path(assigns(:sobre)) end test "should destroy sobre" do assert_difference('Sobre.count', -1) do delete :destroy, id: @sobre end assert_redirected_to sobres_path end end
class AddFormatRefToStories < ActiveRecord::Migration def change add_reference :stories, :format, index: true end end
CarrierWave.configure do |config| config.cache_dir = File.join(Rails.root, 'tmp', 'uploads') config.storage = :fog config.fog_credentials = { :provider => 'AWS', :aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'], :aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'] } case Rails.env.to_sym when :development config.storage = :file when :production config.fog_directory = ENV['FOG_MEDIA'] end end
module Notification class Scale < Base def body "#{actor} scaled #{data['type']} to #{data['quantity']}:#{data['size']}" end end end
# 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 # # 示例: # # 输入: # [ # 1->4->5, # 1->3->4, # 2->6 # ] # 输出: 1->1->2->3->4->4->5->6 # Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val) # @val = val # @next = nil # end # end class ListNode attr_accessor :val, :next def initialize(val) @val = val @next = nil end end # @param {ListNode[]} lists # @return {ListNode} def merge_k_lists(lists) arr = [] lists.each do |x| arr << node_to_arr(x) end arr_to_list_node(arr.flatten!) end def node_to_arr(n) if n == nil return [] end result = [n.val] while n.next n = n.next result << n.val end result end def arr_to_list_node(lists, should_sort = true) if lists == nil || lists.length == 0 return nil end if should_sort lists.sort! do |a, b| b <=> a end end last_node = nil lists.each do |x| tmp_node = ListNode.new(x) tmp_node.next = last_node last_node = tmp_node end last_node end puts (merge_k_lists [[1,4,5],[1,3,4],[2,6]]).next.next.val # x1 = ListNode.new(1, nil) # x2 = ListNode.new(2, x1) # puts x2.next.val
class Tag < ActiveRecord::Base has_and_belongs_to_many :bookmarks belongs_to :user validates :name, presence: true end
class Journey < ApplicationRecord belongs_to :user has_many :starting_points, class_name: 'StartingPoint' has_many :destinations, class_name: 'Destination' end
require 'spec_helper' describe Tassadar::MPQ::MPQ do let(:mpq) { Tassadar::MPQ::MPQ.read(File.read(File.join(REPLAY_DIR, 'patch150.SC2Replay'))) } it "reads the user data size" do expect(mpq.user_data_length).to eq(60) end it "has block_table entries" do expect(mpq.block_table.blocks.size).to eq(10) end it "has hash_table entries" do expect(mpq.hash_table.hashes.size).to eq(16) end it "has files" do expect(mpq.file_data.size).to be > 1 end it "has a list of files" do expect(mpq.files.size).to eq(8) expect(mpq.files).to include("replay.attributes.events") end end
class AddUserIdToAirloge < ActiveRecord::Migration[5.2] def change add_column :airloges, :user_id, :string end end
module DetectOrCreate module ClassMethods # Finds or creates an object, based on parameters provided # # @param args [Hash] Parameters to detect or create # @option args [Hash] :by The parameters to use when finding a record # @option args [Hash] :with The parameters to use to update or create the record # @option args [Boolean] :overwrite_existing Allow overwriting of existing records # @return [Object] the updated instantiated or created object def detect_or_create(args={}) if errors = invalid_arguments(args) and errors.present? raise StandardError, "#{errors}" end found_object = self.first(:conditions => args[:by]) || self.create(args[:by].merge(args[:with])) if args[:overwrite_existing] && !found_object.new_record? found_object.update_attributes(args[:with]) end found_object end private # Sets required keys for argument hash # # @return [Array] Required keys to be sent in the options hash. def required_keys [:by] end # Only allow certain object types with specific keys # # @return [Hash] Used to set what type of object is allowed with certain parameters def required_types { :by => Hash, :with => Hash } end # Verify existence of required keys # # @param args [Hash] Argument hash # @return [Array] Required keys that have not been provided as arguments def missing_keys(args) required_keys - args.keys end # Verify argument object types match with required_types # # @param args [Hash] Argument Hash # @return [String] Error strings to return to consumer for mismatched key types def mismatched_types(args) required_types.collect { |key, type| "`#{key}` must be a #{type}" if args[key].present? && !args[key].is_a?(type) }.compact.join("\n") end # Validates arguments hash # # @param args [Hash] Argument Hash # @return [String] If invalid, error string is returned def invalid_arguments(args) case when missing_keys(args).present? "Missing Arguments: `#{missing_keys(args).join(",")}`" when mismatched_types(args).present? mismatched_types(args) when !args[:by].keys.present? "Missing keys to filter by" end end end end
ActiveAdmin.register Comment, :as => "PhotoComment" do permit_params :photo_id, :content, :user_id index do selectable_column column :id column :photo column "Album" do |comment| comment.photo.album end column :user column :created_at column :updated_at actions end end
class RenameAddress < ActiveRecord::Migration def change rename_column :buildings, :address, :postalcode end end
class AnswersController < ApplicationController def index if params[:user_id] @answers = Answer.where(user_id: params[:user_id]) else @answers = Answer.all end end def new @answer = Answer.new(question_id: params[:question_id]) @question = @answer.question end def edit @answer = current_user.answers.find(params[:id]) @question = @answer.question end def update @answer = current_user.answers.find(params[:id]) @question = @answer.question if @answer.update(answer: params[:answer][:answer]) redirect_to question_path(@question), notice: "Your answer has been updated" else render :edit end end def create @question = Question.find(params[:question_id]) @answer = current_user.answers.build(answer: params[:answer][:answer], question_id: @question.id) if @answer.save redirect_to question_path(@question), notice: "Your answer has been recorded" else render :new end end def select_answer # users can only select answers for their own questions @question = current_user.questions.find(params[:question_id]) @answer = @question.answers.find(params[:id]) if @question.update(selected_answer_id: @answer.id) redirect_to question_path(@question), notice: "Your question has been marked as answered" else redirect_to question_path(@question), notice: "Sorry, something went wrong. Your answer could not be selected" end end end
require 'rails_helper' feature "logout" do before(:each) do visit 'users/new' fill_in "user_username", with: "Bobby Gilmore" click_button "Sign In" expect(current_path).to eq('/messages') expect(page).to have_content "Post a Message" end scenario "logout succeeds" do visit '/messages' click_link "Log Out" expect(current_path).to eq('/users/new') expect(page).to have_content "Sign In" end end
require 'test_helper' class DoExercisesControllerTest < ActionController::TestCase setup do @do_exercise = do_exercises(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:do_exercises) end test "should get new" do get :new assert_response :success end test "should create do_exercise" do assert_difference('DoExercise.count') do post :create, do_exercise: { distance: @do_exercise.distance, hours: @do_exercise.hours, minutes: @do_exercise.minutes, reps: @do_exercise.reps, seconds: @do_exercise.seconds, visibility: @do_exercise.visibility } end assert_redirected_to do_exercise_path(assigns(:do_exercise)) end test "should show do_exercise" do get :show, id: @do_exercise assert_response :success end test "should get edit" do get :edit, id: @do_exercise assert_response :success end test "should update do_exercise" do put :update, id: @do_exercise, do_exercise: { distance: @do_exercise.distance, hours: @do_exercise.hours, minutes: @do_exercise.minutes, reps: @do_exercise.reps, seconds: @do_exercise.seconds, visibility: @do_exercise.visibility } assert_redirected_to do_exercise_path(assigns(:do_exercise)) end test "should destroy do_exercise" do assert_difference('DoExercise.count', -1) do delete :destroy, id: @do_exercise end assert_redirected_to do_exercises_path end end
require 'rails_helper' RSpec.describe 'On a Pet Applications show page a user', type: :feature do it 'can see application info' do user1 = User.create!(name: 'Dr. Evil', address: '56774 FLower Ave.', city: 'Smallville', state: 'Alaska', zip: 87645) shelter1 = Shelter.create(name: "Brett's Pet Palace", address: '456 Sesame Ave', city: 'Denver', state: 'CO', zip: 80222) pet1 = shelter1.pets.create!(name: 'Vernon', age: 18, sex: 'male', image: 'vernon.png') application = user1.applications.create!(name_of_user: 'Dr. Evil', address: '56774 FLower Ave.', description: 'I love this hairless cat', status: 'In Progress') application.pets << pet1 visit "/pets/#{pet1.id}" expect(page).to have_content("Pet's Applications") click_on "Pet's Applications" expect(current_path).to eq("/pets/#{pet1.id}/applications") expect(page).to have_content(user1.name) expect(page).to have_content(application.description) end it "if there aren't aren't any applications for this pet it will display a message" do shelter1 = Shelter.create(name: "Brett's Pet Palace", address: '456 Sesame Ave', city: 'Denver', state: 'CO', zip: 80222) pet1 = shelter1.pets.create!(name: 'Vernon', age: 18, sex: 'male', image: 'vernon.png') visit "/pets/#{pet1.id}/applications" expect(page).to have_content("There are no applications for this pet.") end end
require "spec_helper" describe I18nAccessors::Methods do let(:base_model_class) do Class.new do def title(**_); end def title?(**_); end def title=(_value, **_); end end end context "locales unset, uses I18n.available_locales" do before do @available_locales = I18n.available_locales I18n.available_locales = [:en, :pt] end after do I18n.available_locales = @available_locales end let(:model_class) do base_model_class.include described_class.new(:title) base_model_class end it_behaves_like "locale accessor", :title, :pt it "raises NoMethodError if locale not in I18n.available_locales" do model_class.include(described_class.new(:title)) instance = model_class.new aggregate_failures do expect { instance.title_de }.to raise_error(NoMethodError) expect { instance.title_de? }.to raise_error(NoMethodError) expect { instance.send(:title_de=, "value") }.to raise_error(NoMethodError) end end end context "locales set" do let(:model_class) do base_model_class.include described_class.new(:title, locales: [:cz, :de]) end it_behaves_like "locale accessor", :title, :cz it_behaves_like "locale accessor", :title, :de it "raises NoMethodError if locale not in locales" do instance = model_class.new aggregate_failures do expect { instance.title_en }.to raise_error(NoMethodError) expect { instance.title_en? }.to raise_error(NoMethodError) expect { instance.send(:title_en=, "value") }.to raise_error(NoMethodError) end end end end
require "first_gem_anna/version" # this adds functionality to the existing ruby String class class String def word_count self.split.count end def unique_words self.split.uniq end end
#require './perfil' require_relative './blog' #Clase que define un usuario de nuestros Blogs class Usuario attr_accessor :cuenta,:email,:perfil,:blogs def initialize cuenta,email @cuenta = cuenta @email = email end def blog(id) index = @blogs.index do |b| b.id == id end blog = index.nil? ? nil : blogs[index] return blog end end
#============================================================================== # ** Game_Event #------------------------------------------------------------------------------ # This class handles events. Functions include event page switching via # condition determinants and running parallel process events. Used within the # Game_Map class. #============================================================================== class Game_Event < Game_Character #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_accessor :enemy attr_reader :event attr_reader :terminated attr_reader :sight_timer attr_reader :sight_lost_timer attr_reader :stuck_timer attr_accessor :static_object #-------------------------------------------------------------------------- attr_accessor :default_weapon attr_accessor :last_target attr_accessor :cool_down attr_accessor :recover attr_accessor :target_switch attr_accessor :self_vars attr_accessor :aggressive_level attr_accessor :condition_flag attr_accessor :terminate_cd attr_accessor :priority_type #-------------------------------------------------------------------------- # * Overwrite: Object Initialization # event: RPG::Event #-------------------------------------------------------------------------- def initialize(map_id, event) super() @map_id = map_id @event = event @id = @event.id @terminate_cd = 0 moveto(@event.x, @event.y) collect_code_conditions refresh end #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- alias initialize_event_opt initialize def initialize(map_id, event) @self_vars = Array.new(4){|i| i = 0} @terminated = false @static_object = false @sight_timer = 5 + rand(20) @sight_lost_timer = 0 @stuck_timer = 0 @code_conditions = [] initialize_event_opt(map_id, event) hash_self end #-------------------------------------------------------------------------- # * Initialize. [REP] #-------------------------------------------------------------------------- alias init_effectus initialize def initialize(map_id, event) init_effectus(map_id, event) triggers = $game_map.effectus_etriggers tile_events = $game_map.effectus_tile_events @event.pages.each do |page| condition = page.condition if condition.switch1_valid trigger_symbol = :"switch_#{condition.switch1_id}" unless triggers[trigger_symbol].include?(self) triggers[trigger_symbol] << self end end if condition.switch2_valid trigger_symbol = :"switch_#{condition.switch2_id}" unless triggers[trigger_symbol].include?(self) triggers[trigger_symbol] << self end end if condition.variable_valid trigger_symbol = :"variable_#{condition.variable_id}" unless triggers[trigger_symbol].include?(self) triggers[trigger_symbol] << self end end if condition.self_switch_valid key = [@map_id, @event.id, condition.self_switch_ch] unless triggers[key].include?(self) triggers[key] << self end end if condition.item_valid trigger_symbol = :"item_id_#{condition.item_id}" unless triggers[trigger_symbol].include?(self) triggers[trigger_symbol] << self end end if condition.actor_valid trigger_symbol = :"actor_id_#{condition.actor_id}" unless triggers[trigger_symbol].include?(self) triggers[trigger_symbol] << self end end if page.graphic.tile_id > 0 && page.priority_type == 0 unless tile_events.include?(self) tile_events << self end end end end #-------------------------------------------------------------------------- def collect_code_conditions @event.pages.each do |page| for command in page.list condition_push_flag = false if command.code == 108 command.parameters[0].split(/[\r\n]+/).each do |line| if line =~ DND::REGEX::Event::Condition puts "#{event.name} code condition: #{$1}" page.condition.code_condition << $1 end end # each line in comment end # if the command is comment end # each command in page list end # each page in event end #-------------------------------------------------------------------------- # * Determine if Event Page Conditions Are Met #-------------------------------------------------------------------------- alias :code_condition_met? :conditions_met? def conditions_met?(page) re = code_condition_met?(page) return re if !re c = page.condition if !c.code_condition.empty? @condition_flag = true re = false $event = self c.code_condition.each do |code| puts "#{$event.id}: #{code} #{eval(code) rescue false}" re ||= eval(code) rescue false end return re end return true end #-------------------------------------------------------------------------- # * Init Public Members. [REP] #-------------------------------------------------------------------------- def init_public_members super @trigger = 0 @list = nil @starting = false if $game_map.effectus_event_starting == self $game_map.effectus_event_starting = nil end end #-------------------------------------------------------------------------- # * Start. [REP] #-------------------------------------------------------------------------- def start return if empty? @starting = true lock if trigger_in?([0,1,2]) $game_map.effectus_event_starting = self end #-------------------------------------------------------------------------- # * Start Event #-------------------------------------------------------------------------- alias start_gevt_dnd start def start return if SceneManager.time_stopped? start_gevt_dnd end #-------------------------------------------------------------------------- # * overwrite method: setup_page_settings #-------------------------------------------------------------------------- def setup_page_settings @tile_id = @page.graphic.tile_id @character_name = @page.graphic.character_name @character_index = @page.graphic.character_index if @original_direction != @page.graphic.direction @direction = @page.graphic.direction @original_direction = @direction @prelock_direction = 0 end if @original_pattern != @page.graphic.pattern @pattern = @page.graphic.pattern @original_pattern = @pattern end @move_type = @page.move_type @move_speed = @page.move_speed @move_frequency = @page.move_frequency #tag: modified here if !@on_path_finding || @on_path_finding.nil? @move_route = @page.move_route @move_route_index = 0 @move_route_forcing = false end @walk_anime = @page.walk_anime @step_anime = @page.step_anime @direction_fix = @page.direction_fix @through = @page.through @priority_type = @page.priority_type @trigger = @page.trigger @list = @page.list @interpreter = @trigger == 4 ? Game_Interpreter.new : nil end #-------------------------------------------------------------------------- # * Clear Starting Flag. [REP] #-------------------------------------------------------------------------- def clear_starting_flag @starting = false if $game_map.effectus_event_starting == self $game_map.effectus_event_starting = nil end end #---------------------------------------------------------------------------- # * Get comments in event page #---------------------------------------------------------------------------- def get_comments return unless @list comments = "" cnt = 0 listn = @list.size while cnt < listn if @list[cnt].code == 108 comments += @list[cnt].parameters[0] + 10.chr while cnt < listn && @list[cnt + 1].code == 408 cnt += 1 comments += @list[cnt].parameters[0] + 10.chr end end cnt += 1 end return comments end #-------------------------------------------------------- # *) check if comment is in event page #-------------------------------------------------------- def comment_include?(comment) return if comment.nil? || @list.nil? comment = comment.to_s for command in @list if command.code == 108 return true if command.parameters[0].include?(comment) end # if command.code end # for command return false end # def comment #------------------------------------------------------------------------------- # * Alias: setup page #------------------------------------------------------------------------------- alias setup_page_dnd setup_page def setup_page(new_page) setup_page_dnd(new_page) setup_enemy(new_page.nil?) end #------------------------------------------------------------------------------- # * Setup enemy #------------------------------------------------------------------------------- def setup_enemy(invalid) if @enemy BattleManager.resign_battle_unit(self) @enemy = nil end unless invalid && @list.nil? load_npc_attributes end end #------------------------------------------------------------------------------- # * Load comment command configs in page #------------------------------------------------------------------------------- def load_npc_attributes comments = get_comments npc_config = false comments.split(/[\r\n]+/).each do |line| case line when DND::REGEX::Event::Terminated terminate when DND::REGEX::Event::Frozen freeze when DND::REGEX::NPCEvent::Enemy spawn_npc_battler($1.to_i) when DND::REGEX::NPCEvent::ConfigON npc_config = true when DND::REGEX::NPCEvent::ConfigOFF npc_config = false when DND::REGEX::NPCEvent::StaticObject @static_object = true debug_print "#{event.name} #{@id} is a static object" end process_npc_event_config(line) if npc_config end # each comment line end #------------------------------------------------------------------------------- # * Load params of REGEX::Character in event comment command #------------------------------------------------------------------------------- def process_npc_event_config(line) case line when DND::REGEX::Character::DefaultWeapon @default_weapon = $data_weapons[$1.to_i] when DND::REGEX::Character::TeamID @team_id = $1.to_i when DND::REGEX::Character::DeathSwitchSelf @death_switch_self = $1.upcase when DND::REGEX::Character::DeathSwitchGlobal @death_switch_global = $1.to_i when DND::REGEX::Character::DeathVarSelf @death_var_self = [$1.to_i, $2.to_i] when DND::REGEX::Character::DeathVarGlobal @death_var_global = [$1.to_i, $2.to_i] when DND::REGEX::Character::VisibleSight @visible_sight = $1.to_i when DND::REGEX::Character::BlindSight @blind_sight = $1.to_i when DND::REGEX::Character::Infravision @infravision = $1.to_i.to_bool when DND::REGEX::Character::AggressiveLevel @aggressive_level = $1.to_i when DND::REGEX::Character::MoveLimit @move_limit = $1.to_i when DND::REGEX::Character::DeathAnimation @death_animation = $1.to_i end end #------------------------------------------------------------------------------- # * Spawn NPC battler #------------------------------------------------------------------------------- def spawn_npc_battler(id) if $game_map.event_battler_instance[$game_map.map_id][@id] @enemy = $game_map.event_battler_instance[$game_map.map_id][@id] @enemy = Game_Enemy.new($game_map.enemies.size, id) if @enemy.dead? @enemy.map_char = self else @enemy = Game_Enemy.new($game_map.enemies.size, id) @enemy.map_char = self end debug_print "Spawn enemy #{@enemy.name} at event #{@id}" BattleManager.register_battler(self) $game_map.make_unique_names @enemy.load_tactic_commands end #-------------------------------------------------------------------------- # * Move Type : Random. [REP] #-------------------------------------------------------------------------- def move_type_random case rand(6) when 0 then move_random when 1 then move_random when 2 then move_forward when 3 then move_forward when 4 then move_forward when 5 then @stop_count = 0 end end #-------------------------------------------------------------------------- # * Move Type : Approach. [REP] #-------------------------------------------------------------------------- def move_type_toward_player if near_the_player? case rand(6) when 0 then move_toward_player when 1 then move_toward_player when 2 then move_toward_player when 3 then move_toward_player when 4 then move_random when 5 then move_forward end else move_random end end #---------------------------------------------------------------------------- def update_terminate @terminate_cd -= 1 if @terminate_cd <= 0 @terminated = true end end #---------------------------------------------------------------------------- # * Permanently delete the event #---------------------------------------------------------------------------- def terminate @terminate_cd = 180 if (@terminate_cd || 0) <= 0 end #---------------------------------------------------------------------------- def terminated? @terminated end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- alias update_gvednd update def update active = MakerSystems::Effectus::PREVENT_OFFSCREEN_UPDATES update_terminate if @terminate_cd > 0 update_gvednd unless active if effectus_near_the_screen? || @effectus_wait_for_animation || @balloon_id > 0 update_gvednd update_effectus_sprite else update_effectus_route end update_position_registeration unless @effectus_position_registered update_position_moved if effectus_moved? end alias effectus_original_update update_gvednd #-------------------------------------------------------------------------- # * Overwrite: Update During Autonomous Movement #-------------------------------------------------------------------------- def update_self_movement return if $game_system.story_mode? if !@pathfinding_moves.empty? process_pathfinding_movement #elsif BattleManager.valid_battler?(self) && @current_target # chase_target elsif near_the_screen? && @stop_count > stop_count_threshold case @move_type when 1; move_type_random when 2; move_type_toward_player when 3; move_type_custom end end end #---------------------------------------------------------------------------- def battler return @enemy if @enemy return super end #-------------------------------------------------------------------------- def controlable? return true if !@enemy return super && @enemy.controlable? end #---------------------------------------------------------------------------- # * Freeze event from update #---------------------------------------------------------------------------- alias ruby_freeze freeze def freeze @frozen = true end #---------------------------------------------------------------------------- def unfreeze @frozen = false end #---------------------------------------------------------------------------- alias :ruby_frozen? :frozen? def frozen? @frozen end #---------------------------------------------------------------------------- def dead? return true if @enemy.nil? return @enemy.dead? end #---------------------------------------------------------------------------- def alive? return !dead? end #---------------------------------------------------------------------------- def name(original_event = false) return @enemy.name if !original_event && @enemy return event.name end #---------------------------------------------------------------------------- # * Die when hitpoint drop to zero #---------------------------------------------------------------------------- def kill process_event_death super refresh puts "#{event.id} #{event.name} killed" end #------------------------------------------------------------------------------- # * Params to method #------------------------------------------------------------------------------- def default_weapon return @default_weapon if @default_weapon return @enemy.enemy.default_weapon if @enemy returnDND::BattlerSetting::DefaultWeapon end #-------------------------------------------------------------------------- # * Refresh. tag: effectus [REP] #-------------------------------------------------------------------------- def refresh new_page = @erased ? nil : find_proper_page setup_page(new_page) if !new_page || new_page != @page @effectus_always_update = false if @page && @page.list @page.list.each do |command| next unless command.code == 108 MakerSystems::Effectus::PATTERNS.each do |string| next unless command.parameters[0].include?(string) @effectus_always_update = true break end break if @effectus_always_update end end @effectus_always_update = true if trigger == 3 || trigger == 4 if $game_map.effectus_hard_events.include?(self) unless @effectus_always_update $game_map.effectus_hard_events.delete(self) end else if @effectus_always_update $game_map.effectus_hard_events << self end end if tile? || @effectus_tile if $game_map.effectus_pass_table unless @effectus_tile && tile? $game_map.effectus_release(@x, @y) end end end @effectus_tile = tile? if @effectus_tile unless @effectus_tile_registered @effectus_tile_registered = true $game_map.effectus_etile_pos[@y * $game_map.width + @x] << self end else if @effectus_tile_registered $game_map.effectus_etile_pos[@y * $game_map.width + @x].delete(self) @effectus_tile_registered = nil end end unless @effectus_position_registered $game_map.effectus_event_pos[@y * $game_map.width + @x] << self @effectus_last_x = @x @effectus_last_y = @y @effectus_position_registered = true end unless @character_name == @effectus_last_character_name bitmap = Cache.character(@character_name) string = @character_name[/^[\!\$]./] if string && string.include?('$') @effectus_bw = bitmap.width / 3 @effectus_bh = bitmap.height / 4 else @effectus_bw = bitmap.width / 12 @effectus_bh = bitmap.height / 8 end @effectus_last_character_name = @character_name @effectus_special_calculus = @effectus_bw > 32 || @effectus_bh > 32 end end #-------------------------------------------------------------------------- # * Near the Screen? [NEW] #-------------------------------------------------------------------------- if MakerSystems::Effectus::SCREEN_TILE_DIVMOD def effectus_near_the_screen? if @effectus_special_calculus sx = (@real_x - $game_map.display_x) * 32 + 16 sy = (@real_y - $game_map.display_y) * 32 + 32 - shift_y - jump_height sx + @effectus_bw > 0 && sx - @effectus_bw < Graphics.width && sy + @effectus_bh > 0 && sy - @effectus_bh < Graphics.height else @real_x > $game_map.display_x - 1 && @real_x < $game_map.display_x + Graphics.width / 32 + 1 && @real_y > $game_map.display_y - 1 && @real_y < $game_map.display_y + Graphics.height / 32 + 1 end end else def effectus_near_the_screen? if @effectus_special_calculus sx = (@real_x - $game_map.display_x) * 32 + 16 sy = (@real_y - $game_map.display_y) * 32 + 32 - shift_y - jump_height sx + @effectus_bw > 0 && sx - @effectus_bw < Graphics.width && sy + @effectus_bh > 0 && sy - @effectus_bh < Graphics.height else @real_x > $game_map.display_x - 1 && @real_x < $game_map.display_x + Graphics.width / 32 && @real_y > $game_map.display_y - 1 && @real_y < $game_map.display_y + Graphics.height / 32 end end end #-------------------------------------------------------------------------- # * Determine if Movement is Possible #-------------------------------------------------------------------------- def movable? return false if @enemy && !@enemy.movable? return super end #---------------------------------------------------------------------------- def team_id return @team_id = @enemy.team_id if @enemy return nil #return DND::BattlerSetting::TeamID end #---------------------------------------------------------------------------- def death_switch_self return @death_switch_self if @death_switch_self return @enemy.enemy.death_switch_self if @enemy return DND::BattlerSetting::DeathSwitchSelf end #---------------------------------------------------------------------------- def death_switch_global return @death_switch_global if @death_switch_global return @enemy.enemy.death_switch_global if @enemy return DND::BattlerSetting::DeathSwitchGlobal end #---------------------------------------------------------------------------- def death_var_self return @death_var_self if @death_var_self return @enemy.enemy.death_var_self if @enemy return DND::BattlerSetting::DeathVarSelf end #---------------------------------------------------------------------------- def death_var_global return @death_var_global if @death_var_global return @enemy.enemy.death_var_global if @enemy return DND::BattlerSetting::DeathVarGlobal end #---------------------------------------------------------------------------- def visible_sight return @visible_sight if @visible_sight return @enemy.enemy.visible_sight if @enemy return DND::BattlerSetting::VisibleSight end #---------------------------------------------------------------------------- def blind_sight return @blind_sight if @blind_sight return @enemy.enemy.blind_sight if @enemy return DND::BattlerSetting::BlindSight end #---------------------------------------------------------------------------- def infravision return @infravision if @infravision return @enemy.enemy.infravision if @enemy return DND::BattlerSetting::Infravision end #---------------------------------------------------------------------------- def aggressive_level return @aggressive_level if @aggressive_level return @aggressive_level = @enemy.enemy.aggressive_level if @enemy return DND::BattlerSetting::AggressiveLevel end #---------------------------------------------------------------------------- def move_limit return @move_limit if @move_limit return @enemy.move_limit if @enemy return DND::BattlerSetting::MoveLimit end #--------------------------------------------------------------------------- def weapon_level_prof return @weapon_level_prof if @weapon_level_prof return @weapon_level_prof = @enemy.weapon_level_prof if @enemy return 0 end #---------------------------------------------------------------------------- def body_size return @enemy.enemy.body_size * @zoom_x if @enemy return DND::BattlerSetting::BodySize end #---------------------------------------------------------------------------- def death_animation return @enemy.enemy.death_animation if @enemy return DND::BattlerSetting::DeathAnimation end #-------------------------------------------------------------------------- def face_name return @enemy.face_name if @enemy return nil end #-------------------------------------------------------------------------- def face_index return @enemy.face_index if @enemy return 0 end #-------------------------------------------------------------------------- def weapon_cooldown return @enemy.weapon_cooldown if @enemy return {} end #-------------------------------------------------------------------------- def armor_cooldown return @enemy.armor_cooldown if @enemy return {} end #-------------------------------------------------------------------------- def skill_cooldown return @enemy.skill_cooldown if @enemy return {} end #-------------------------------------------------------------------------- def item_cooldown return @enemy.item_cooldown if @enemy return {} end #-------------------------------------------------------------------------- def hash_self base = (@map_id * 1000 + @id) base += @enemy.hashid if @enemy base = base.to_s + self.inspect @hashid = PONY.Sha256(base).to_i(16) super end #-------------------------------------------------------------------------- def default_ammo return @default_ammo if @default_ammo return @default_ammo = @enemy.default_ammo if @enemy return 0 end #-------------------------------------------------------------------------- def primary_weapon return @enemy.default_weapon if @enemy end #---------------------------------------------------------------------------- def secondary_weapon return @enemy.secondary_weapon if @enemy end #---------------------------------------------------------------------------- def static_object? return @static_object end #-------------------------------------------------------------------------- def casting_animation return super if !@enemy return @enemy.enemy.casting_animation rescue super end #-------------------------------------------------------------------------- def get_ammo_item(item) if item.is_a?(RPG::Weapon) && item.tool_itemcost_type > 0 return $data_weapons[default_ammo] elsif (item.tool_itemcost || 0) > 0 return $data_items[item.tool_itemcost] end end #-------------------------------------------------------------------------- # * Detect Collision with Character. [REP] #-------------------------------------------------------------------------- def collide_with_characters?(x, y) super || (normal_priority? && $game_player.collide?(x, y)) end #--------------------------------------------------------------------------- # * Method Missing # ---------------------------------------------------------------------- # DANGER ZONE: Redirect to Game_Enemy #--------------------------------------------------------------------------- def method_missing(symbol, *args) super(symbol, *args) if @enemy.nil? @enemy.method(symbol).call(*args) end end
FactoryGirl.define do factory :title_type do factory :official_type do title_type_id 1 title_type "official" end factory :short_type do title_type_id 2 title_type "short" end factory :popular_type do title_type_id 3 title_type "popular" end end end
# invites_controller_spec.rb require 'rails_helper' require 'spec_helper' describe InvitesController do describe "GET #new" do # it "assigns a new Invite to @invite" do # assigns(:invite).should eq(Invite.new) # end it "renders the :new view" do get :new expect(response).to render_template :new end end describe "GET #show" do it "assigns a new Invite to @invite" do invite = FactoryGirl.create(:invite) get :show, id: invite expect(assigns(:invite)).to eq(invite) end it "renders the :show view" do invite = FactoryGirl.create(:invite) get :show, id: invite.id expect(response).to render_template :show end end describe "GET #edit" do it "renders an existing Invite to @invite" do invite = FactoryGirl.create(:invite) get :edit, id: invite expect(assigns(:invite)).to eq(invite) end it "renders the :edit view" do invite = FactoryGirl.create(:invite) get :edit, id: invite.id expect(response).to render_template :edit end end describe "POST #create" do it "increments the Invite database count by 1" do expect { post :create, invite: FactoryGirl.attributes_for(:invite) }.to change(Invite, :count).by(1) end end describe "PUT #update" do it "locates the correct invite" do invite = FactoryGirl.create(:invite) put :update, id: invite.id, invite: FactoryGirl.attributes_for(:invite) expect(assigns(:invite)).to eq(invite) end it "changes the invite's attributes" do invite = FactoryGirl.create(:invite) put :update, id: invite.id, invite: FactoryGirl.attributes_for(:invite, name: "My Invite Name") invite.reload expect(invite.name).to eq("My Invite Name") end end describe "DELETE #destroy" do it "deletes the invite" do invite = FactoryGirl.create(:invite) expect{ delete :destroy, id: invite }.to change(Invite,:count).by(-1) end # it "redirects to the home page" do # end end describe "GET #accept" do # it "locates the correct invite" do # get :accept, email: "test@test.com" # expect(response).to render_template :accept # end # it "changes the invite's attributes" do # invite = FactoryGirl.create(:invite) # put :update, email: "test@test.com", invite: FactoryGirl.attributes_for(:invite, name: "My Invite Name") # invite.reload # expect(invite.name).to eq("My Invite Name") # end end end
require 'spec_helper' describe Spree::Upload do before(:each) do Spree::Upload.destroy_all #puts File.expand_path("../../support/files/*.jpg", __FILE__) @jpgs = Dir[File.expand_path("../../support/files/*.jpg", __FILE__)] @pngs = Dir[File.expand_path("../../support/files/*.png", __FILE__)] @gifs = Dir[File.expand_path("../../support/files/*.gif", __FILE__)] end it "should have attached file" do have_attached_file(:attachment) end it "should validate attachment" do upload = Spree::Upload.new expect(!upload.valid?).to eq(true) expect(!upload.save).to eq(true) end it "should create an upload" do upload = Spree::Upload.new(:attachment => File.open(File.expand_path(@jpgs.shuffle.first))) expect(upload.valid?).to eq(true) upload_count = Spree::Upload.count expect(upload.save).to eq(true) expect(Spree::Upload.count).to eq(upload_count+1) end context "with an existing upload" do before(:each) do @jpg = Spree::Upload.create(:alt => "jpg", :attachment => File.open(File.expand_path(@jpgs.shuffle.first))) @png = Spree::Upload.create(:alt => "png", :attachment => File.open(File.expand_path(@pngs.shuffle.first))) @gif = Spree::Upload.create(:alt => "gif", :attachment => File.open(File.expand_path(@gifs.shuffle.first))) @pdf = Spree::Upload.create(:alt => "pdf", :attachment => File.open(File.expand_path("../../support/files/test.pdf", __FILE__))) @zip = Spree::Upload.create(:alt => "zip", :attachment => File.open(File.expand_path("../../support/files/test.zip", __FILE__))) end it "should be image content" do [@jpg, @png, @gif].each do |upload| expect(upload.image_content?).not_to be_nil end end it "should not be image content" do [@pdf, @zip].each do |upload| expect(upload.image_content?).to be_nil end end end end
class MultiLogger attr_reader :loggers def initialize(*args) @loggers = args end def level=(level) @loggers.each { |logger| logger.level = level } end def levels @loggers.map(&:level) end def min_level levels.min end def close @loggers.map(&:close) end def add(level, *args) @loggers.each { |logger| logger.add(level, *args) } end Logger::Severity.constants.each do |level| define_method(level.downcase) do |*args| @loggers.each { |logger| logger.send(level.downcase, *args) } end define_method("#{ level.downcase }?".to_sym) do min_level <= Logger::Severity.const_get(level) end end end
class CreatePublicationArticles < ActiveRecord::Migration[5.0] def change create_table :publication_articles do |t| t.integer :publication t.integer :article t.string :status t.boolean :active t.integer :sequence t.timestamps end end end
class Publisher < ActiveRecord::Base has_many :applications validates :name, :presence => true validates :address, :presence => true # def applications # Application.order('name ASC') # end end
# frozen_string_literal: true module Comments # Service to create a article class CreateService def initialize(request_params, comment_create_params, user) @resource = request_params[1] @id = request_params[2] @comment_create_params = comment_create_params @user = user @comment = create_comment end def perform return Response::Failure.new(@comment) unless @comment.valid? Response::Failure.new(@comment) unless @comment.save # create_timeline Response::Success.new(@comment) end private def create_comment Comment.new( body: @comment_create_params[:body], commentable_type: @resource.singularize.capitalize, commentable_id: @id, user_id: @user.id ) end def create_timeline if @comment.commentable_type == 'article' || @comment.commentable_type == 'event' model = @comment.commentable_type.classify.constantize record = model.find(@comment.commentable_id) return unless record.published? end Timelines::CreateService.new(@comment, 'Comment', @user.id, nil).perform end end end
class AddCovid19RelatedToActivity < ActiveRecord::Migration[6.0] def change add_column :activities, :covid19_related, :integer, default: 0 end end
FactoryGirl.define do factory :spending_info, aliases: [:spending] do person { SampleDataMacros::Generator.person } has_business 'no_business' credit_score do min = CreditScore.min max = CreditScore.max min + rand(max - min) end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! before_action :initialize_pages_layout def initialize_pages_layout @navbar_categories = Category.all end end
# frozen_string_literal: true require 'open-uri' require 'nokogiri' # Scrapes HTML of Square account that User inputs # Square API recently changed, creating temp solution # class Scraper < ApplicationRecord # def self.scrape_square(merchant) # doc = Nokogiri::HTML(open(merchant.links.last.url)) # img = doc.at('.landing-header__merchant-info img')['src'] # stars = doc.search('div.welcome-content__loyalty_progress_text') # merchant.image = img # merchant.star_count = stars.text.strip.to_i # merchant.save # end # end
class Attendance < ApplicationRecord after_create :new_participant_send belongs_to :event belongs_to :participant, class_name: "User" def new_participant_send UserMailer.new_participant(self).deliver_now end end
class Resource < ActiveRecord::Base validates_presence_of :name has_many :company_providers, :as => :provider, :dependent => :destroy has_many :companies, :through => :company_providers, :source => :company # Appointments associations # TODO - what happens when the resource goes away? has_many :appointments, :as => :provider has_many :capacity_slots, :as => :provider named_scope :order_by_name, { :order => 'resources.name' } # return true if its the special user 'anything' def anything? self.id == 0 end alias :anyone? :anything? def tableize self.class.to_s.tableize end # resources do not have email addresses def email_addresses_count 0 end end
require 'wsdl_mapper/naming/default_namer' module WsdlMapper module Naming # Namer implementation which puts the generated classes into different namespaces, # according to their funtion: `Types` for types, `S8r` for serializers and `D10r` # for deserializers. class SeparatingNamer < DefaultNamer # @param [Array<String>] module_path Root module path, e.g. to generate classes in # `::MyApi::Types`, specify `['MyApi']` as root module path # @param [String] content_attribute_name Sets name of the attribute generated for direct content # of types. You can change it, if this clashes with attributes # in your schema. # @param [Array<String>] types_module Where to generate types # @param [Array<String>] s8r_module Where to genereate serializers # @param [Array<String>] d10r_module Where to generate deserializers def initialize(module_path: [], content_attribute_name: 'content', soap_array_item_name: 'item', types_module: ['Types'], s8r_module: ['S8r'], d10r_module: ['D10r']) super(module_path: module_path, content_attribute_name: content_attribute_name, soap_array_item_name: soap_array_item_name) @types_module = types_module @s8r_module = s8r_module @d10r_module = d10r_module end protected def get_s8r_module_path(type) @module_path + @s8r_module end def get_class_module_path(type) @module_path + @types_module end def get_d10r_module_path(type) @module_path + @d10r_module end def get_class_file_path(type) get_file_path get_class_module_path type end def get_s8r_file_path(type) get_file_path get_s8r_module_path type end def get_d10r_file_path(type) get_file_path get_d10r_module_path type end def get_d10r_file_name(type) underscore(type.name.name) + '_deserializer.rb' end def get_d10r_class_name(type) get_camelized_name(type.name.name) + 'Deserializer' end def get_s8r_file_name(type) underscore(type.name.name) + '_serializer.rb' end def get_s8r_class_name(type) get_camelized_name(type.name.name) + 'Serializer' end def get_class_name(type) get_camelized_name type.name.name end def get_class_file_name(type) get_file_name type.name.name end def get_constant_name(name) get_key_name(name).upcase end def get_key_name(name) underscore sanitize name end def get_accessor_name(name) get_key_name name end def get_var_name(name) "@#{get_accessor_name(name)}" end def get_camelized_name(name) camelize name end def get_file_name(name) underscore(name) + '.rb' end def get_file_path(path) path.map do |m| underscore m end end def sanitize(name) if valid_symbol? name name else "value_#{name}" end end end end end
APP_ENV = 'test' require File.expand_path(File.dirname(__FILE__) + "/../config/app") require 'rack/test' require 'database_cleaner' RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' config.include FactoryGirl::Syntax::Methods config.include Rack::Test::Methods config.before :suite do DataMapper.auto_migrate! # TODO remove this FactoryGirl.find_definitions DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end def app #Sinatra::Application HypermediaExample end def parsed_resp begin JSON.parse(last_response.body, symbolize_names: true) rescue fail "Invalid JSON response: #{last_response.body[0..1000]}..." end end # Test Helper Classes class Person attr_accessor :id, :name, :age def initialize @id = 1 @name = "Some Name" @age = 20 end end class PersonDecorator include Haler::Decorator field :name field :age link :self do "/person/1" end end
class Build < Place validates_presence_of :name def self.icon "home" end end
# # Cookbook Name:: cubrid # Attributes:: perl_driver # # Copyright 2012, Esen Sagynov <kadishmal@gmail.com> # # Distributed under MIT license # # Latest build numbers for each CUBRID Perl version in the form of 'version'=>'build_number'. build_numbers = {'9.1.0' => '0002', '9.0.0' => '0001', '8.4.3' => '0001', '8.4.1' => '0001', '8.4.0' => '0002'} # The default version of CUBRID to install. default['cubrid']['version'] = "9.1.0" # The version of a CUBRID Perl driver to install from CPAN. set['cubrid']['perl_version'] = "#{node['cubrid']['version']}.#{build_numbers[node['cubrid']['version']]}" # The file name of the the package to install. set['cubrid']['perl_filename'] = "DBD-cubrid-#{node['cubrid']['perl_version']}.tar.gz"
require 'rails_helper' RSpec.describe ApplicationHelper, type: :helper do describe "#mobile_device?" do context "when mobile device" do it "returns not nil" do controller.request.user_agent = "Mobile/1.0" expect(helper.mobile_device?).to_not be_nil end end context "when desktop device" do it "returns nil" do controller.request.user_agent = "Linux x86_64/1.0" expect(helper.mobile_device?).to be_nil end end end end
##################################################################### # tc_file.rb # # Test case for the Windows::File module. ##################################################################### base = File.basename(Dir.pwd) if base == 'test' || base =~ /windows-pr/ Dir.chdir '..' if base == 'test' $LOAD_PATH.unshift Dir.pwd + '/lib' Dir.chdir 'test' rescue nil end require 'windows/file' require 'test/unit' class Foo include Windows::File end class TC_Windows_File < Test::Unit::TestCase def setup @foo = Foo.new end def test_numeric_constants assert_equal(0x00000001, Foo::FILE_ATTRIBUTE_READONLY) assert_equal(0x00000002, Foo::FILE_ATTRIBUTE_HIDDEN) assert_equal(0x00000004, Foo::FILE_ATTRIBUTE_SYSTEM) assert_equal(0x00000010, Foo::FILE_ATTRIBUTE_DIRECTORY) assert_equal(0x00000020, Foo::FILE_ATTRIBUTE_ARCHIVE) assert_equal(0x00000040, Foo::FILE_ATTRIBUTE_ENCRYPTED) assert_equal(0x00000080, Foo::FILE_ATTRIBUTE_NORMAL) assert_equal(0x00000100, Foo::FILE_ATTRIBUTE_TEMPORARY) assert_equal(0x00000200, Foo::FILE_ATTRIBUTE_SPARSE_FILE) assert_equal(0x00000400, Foo::FILE_ATTRIBUTE_REPARSE_POINT) assert_equal(0x00000800, Foo::FILE_ATTRIBUTE_COMPRESSED) assert_equal(0x00001000, Foo::FILE_ATTRIBUTE_OFFLINE) assert_equal(0x00002000, Foo::FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) end def test_method_constants assert_not_nil(Foo::CopyFile) assert_not_nil(Foo::CopyFileEx) assert_not_nil(Foo::CreateFile) assert_not_nil(Foo::CreateFileW) assert_not_nil(Foo::CreateHardLink) assert_not_nil(Foo::DecryptFile) assert_not_nil(Foo::DeleteFile) assert_not_nil(Foo::EncryptFile) assert_not_nil(Foo::GetBinaryType) assert_not_nil(Foo::GetFileAttributes) assert_not_nil(Foo::GetFileAttributesEx) assert_not_nil(Foo::GetFileSize) assert_not_nil(Foo::GetFileSizeEx) assert_not_nil(Foo::GetFileType) assert_not_nil(Foo::GetFullPathName) assert_not_nil(Foo::GetFullPathNameW) assert_not_nil(Foo::GetLongPathName) assert_not_nil(Foo::GetShortPathName) assert_not_nil(Foo::LockFile) assert_not_nil(Foo::LockFileEx) assert_not_nil(Foo::ReadFile) assert_not_nil(Foo::ReadFileEx) assert_not_nil(Foo::SetFileAttributes) assert_not_nil(Foo::UnlockFile) assert_not_nil(Foo::UnlockFileEx) assert_not_nil(Foo::WriteFile) assert_not_nil(Foo::WriteFileEx) end def teardown @foo = nil end end
RSpec.describe Batch::DailyBatch do let (:config) { AppUtil.load_config } subject (:batch) { Batch::DailyBatch.new(config) } let (:stub_now) do allow(AppUtil).to receive(:get_now) do current_at.nil? ? Time.now : Time.parse(current_at) end end let (:actual) do get_actual.map { |row| row.serializable_hash(except: :id).symbolize_keys } end let (:retrieve_project_reports) do ProjectReport.joins(:project).select(:project_nm, :status_cd) end let (:retrieve_milestone_reports) do MilestoneReport.joins(:milestone).select(:milestone_nm, :status_cd) end let (:test_data) do file_path = Rails.root.join('spec', 'test_data', 'batch', '02_daily_batch.yml') YAML.load_file(file_path).deep_symbolize_keys end let (:pre_condition) do values = test_data[test_pattern] writer = TestDataWriter.new(values[:fixtures]) writer.execute end let (:execute) do pre_condition batch.execute({ mode: test_pattern }) actual end let (:expected) { test_data[test_pattern][:expected] } context '開始2日前のプロジェクトの場合' do let (:current_at) { '2018-12-01 00:00:00+09' } let (:test_pattern) { :project_before_2days } let (:get_actual) { retrieve_project_reports } it '報告されないこと' do expect(execute).to eq(expected) end end context '開始1日前でリリース日が登録されていないプロジェクトの場合' do let (:current_at) { '2018-12-02 00:00:00+09' } let (:test_pattern) { :project_not_scheduled } let (:get_actual) { retrieve_project_reports } it '警告ステータスで報告されること' do expect(execute).to eq(expected) end end context '未完了のマイルストーンがある場合' do let (:current_at) { '2018-12-05 00:00:00+09' } let (:test_pattern) { :milestone_not_completed } let (:get_actual) { retrieve_milestone_reports } it '警告ステータスで報告されること' do expect(execute).to eq(expected) end end end
class SeminarsController < ApplicationController def new @subject = Subject.find(params[:subject_id]) teacher_ids = Seminar.where(subject: @subject).pluck(:teacher_id) @teachers = Teacher.where.not(id: teacher_ids).and(Teacher.where(approved: true)) @seminar = authorize Seminar.new end def create @subject = Subject.find(params[:subject_id]) @seminar = authorize @subject.seminars.create(seminar_params) if @seminar.save! redirect_to @subject else render :new end end private def seminar_params params.require(:seminar).permit(:subject_id, :teacher_id) end end
module One class CreateUser < Operation def process(_params) add_user_to_group unless user_already_member_of_group? add_user_as_group_admin if become_group_admin? && !user_already_admin_of_group? end private def invite @params.fetch(:invite) end def one_user @one_user ||= find_or_create_user end def find_or_create_user one_client.user_by_password(current_user.remote_user) || one_client.create_user(current_user.proposed_one_username, current_user.remote_user) end def add_user_to_group one_client.add_user_to_group(one_user.id, invite.group_id) end def add_user_as_group_admin one_client.make_user_group_admin(one_user.id, invite.group_id) end def user_already_member_of_group? one_user.group_ids.include?(invite.group_id) end def become_group_admin? invite.role == Role.group_admin end def user_already_admin_of_group? one_client.user_admin_of_group?(one_user.id, invite.group_id) end def one_client @one_client ||= One::Client.new end end end
# Write your code here. katz_deli = [] def line(customers) output = "" if customers.empty? == false output = "The line is currently:" customers.each.with_index(1) do |person, index| output << " #{index}. #{person}" end elsif customers.empty? == true output = "The line is currently empty." end puts output end def take_a_number(line_of_customers, new_name_to_add) line_of_customers << new_name_to_add place_in_line = line_of_customers.size puts "Welcome, #{new_name_to_add}. You are number #{place_in_line} in line." line_of_customers end def now_serving(customers) if !(customers.empty?) puts "Currently serving #{customers[0]}." customers.shift else puts "There is nobody waiting to be served!" end end $ticket_queues = {} $current_numbers = {} def get_a_number(queue) if $ticket_queues.length == 0 $ticket_queues[:deli1] = queue $ticket_queues[:deli1] << 1 $current_numbers[:deli1] = 1 return 1 else if $ticket_queues[:deli1] == queue current_line = $ticket_queues[:deli1] if !(current_line.empty?) current_spot = current_line[-1] current_spot += 1 else current_spot = $current_numbers[:deli1] + 1 end $ticket_queues[:deli1] << current_spot $current_numbers[:deli1] = current_spot return current_spot elsif [:deli2].any? { |k| $ticket_queues.key?(k) } current_line = $ticket_queues[:deli2] if !(current_line.empty?) current_spot = current_line[-1] current_spot += 1 else current_spot = $current_numbers[:deli2] + 1 end $ticket_queues[:deli2] << current_spot $current_numbers[:deli2] = current_spot return current_spot else $ticket_queues[:deli2] = queue $ticket_queues[:deli2] << 1 $current_numbers[:deli2] = 1 return 1 end end end def serve_customer(queue) $ticket_queues.each do |key, value| if $ticket_queues[key] == queue current = queue[0] $ticket_queues[key].shift return current end end end
$:.unshift(File.dirname(__FILE__) + '/lib') require 'omnibus/version' Gem::Specification.new do |s| s.name = 'omnibus' s.version = Omnibus::VERSION s.platform = Gem::Platform::RUBY s.has_rdoc = true s.extra_rdoc_files = ["README.md" ] s.summary = "Installer builder DSL" s.description = s.summary s.author = "Opscode" s.email = "info@opscode.com" s.homepage = "http://wiki.opscode.com/" s.add_dependency "mixlib-shellout", "~>1.0" s.add_dependency "ohai", ">= 0.6.12" s.add_dependency "rake", ">= 0.9" s.add_dependency "fpm", "= 0.3.11" s.add_dependency "uber-s3" s.add_dependency "thor", ">= 0.16.0" s.add_development_dependency "rspec" s.add_development_dependency "rspec_junit_formatter" s.bindir = "bin" s.executables = 'omnibus' s.require_path = 'lib' s.files = %w(README.md) + Dir.glob("lib/**/*") end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require 'tzinfo/offset_rationals' require 'tzinfo/time_or_datetime' module TZInfo # A period of time in a timezone where the same offset from UTC applies. # # All the methods that take times accept instances of Time, DateTime or # integer timestamps. class TimezonePeriod # The TimezoneTransitionInfo that defines the start of this TimezonePeriod # (may be nil if unbounded). attr_reader :start_transition # The TimezoneTransitionInfo that defines the end of this TimezonePeriod # (may be nil if unbounded). attr_reader :end_transition # The TimezoneOffsetInfo for this period. attr_reader :offset # Initializes a new TimezonePeriod. def initialize(start_transition, end_transition, offset = nil) @start_transition = start_transition @end_transition = end_transition if offset raise ArgumentError, 'Offset specified with transitions' if @start_transition || @end_transition @offset = offset else if @start_transition @offset = @start_transition.offset elsif @end_transition @offset = @end_transition.previous_offset else raise ArgumentError, 'No offset specified and no transitions to determine it from' end end @utc_total_offset_rational = nil end # Base offset of the timezone from UTC (seconds). def utc_offset @offset.utc_offset end # Offset from the local time where daylight savings is in effect (seconds). # E.g.: utc_offset could be -5 hours. Normally, std_offset would be 0. # During daylight savings, std_offset would typically become +1 hours. def std_offset @offset.std_offset end # The identifier of this period, e.g. "GMT" (Greenwich Mean Time) or "BST" # (British Summer Time) for "Europe/London". The returned identifier is a # symbol. def abbreviation @offset.abbreviation end alias :zone_identifier :abbreviation # Total offset from UTC (seconds). Equal to utc_offset + std_offset. def utc_total_offset @offset.utc_total_offset end # Total offset from UTC (days). Result is a Rational. def utc_total_offset_rational unless @utc_total_offset_rational @utc_total_offset_rational = OffsetRationals.rational_for_offset(utc_total_offset) end @utc_total_offset_rational end # The start time of the period in UTC as a DateTime. May be nil if unbounded. def utc_start @start_transition ? @start_transition.at.to_datetime : nil end # The end time of the period in UTC as a DateTime. May be nil if unbounded. def utc_end @end_transition ? @end_transition.at.to_datetime : nil end # The start time of the period in local time as a DateTime. May be nil if # unbounded. def local_start @start_transition ? @start_transition.local_start.to_datetime : nil end # The end time of the period in local time as a DateTime. May be nil if # unbounded. def local_end @end_transition ? @end_transition.local_end.to_datetime : nil end # true if daylight savings is in effect for this period; otherwise false. def dst? @offset.dst? end # true if this period is valid for the given UTC DateTime; otherwise false. def valid_for_utc?(utc) utc_after_start?(utc) && utc_before_end?(utc) end # true if the given UTC DateTime is after the start of the period # (inclusive); otherwise false. def utc_after_start?(utc) !@start_transition || @start_transition.at <= utc end # true if the given UTC DateTime is before the end of the period # (exclusive); otherwise false. def utc_before_end?(utc) !@end_transition || @end_transition.at > utc end # true if this period is valid for the given local DateTime; otherwise false. def valid_for_local?(local) local_after_start?(local) && local_before_end?(local) end # true if the given local DateTime is after the start of the period # (inclusive); otherwise false. def local_after_start?(local) !@start_transition || @start_transition.local_start <= local end # true if the given local DateTime is before the end of the period # (exclusive); otherwise false. def local_before_end?(local) !@end_transition || @end_transition.local_end > local end # Converts a UTC DateTime to local time based on the offset of this period. def to_local(utc) @offset.to_local(utc) end # Converts a local DateTime to UTC based on the offset of this period. def to_utc(local) @offset.to_utc(local) end # Returns true if this TimezonePeriod is equal to p. This compares the # start_transition, end_transition and offset using ==. def ==(p) p.respond_to?(:start_transition) && p.respond_to?(:end_transition) && p.respond_to?(:offset) && start_transition == p.start_transition && end_transition == p.end_transition && offset == p.offset end # Returns true if this TimezonePeriods is equal to p. This compares the # start_transition, end_transition and offset using eql? def eql?(p) p.respond_to?(:start_transition) && p.respond_to?(:end_transition) && p.respond_to?(:offset) && start_transition.eql?(p.start_transition) && end_transition.eql?(p.end_transition) && offset.eql?(p.offset) end # Returns a hash of this TimezonePeriod. def hash result = @start_transition.hash ^ @end_transition.hash result ^= @offset.hash unless @start_transition || @end_transition result end # Returns internal object state as a programmer-readable string. def inspect result = "#<#{self.class}: #{@start_transition.inspect},#{@end_transition.inspect}" result << ",#{@offset.inspect}>" unless @start_transition || @end_transition result + '>' end end end
<<-doc Write a program interactively, through the command line Enter a blank line to evaluate. Enter 'q' to quit. doc puts "You can write your program here" puts "Enter a blank line to evaluate." puts "Enter 'q' to quit." program = "" line = "" loop do print "--> " line = gets case line.strip when "" eval(program) program = "" print "\n" when /q/i exit else program += line end end
require 'capybara/dsl' class EventsPage include Capybara::DSL BUTTON = '.button' LONDON_STUDENTS = '#london-students' def visit_events_page visit("/events") end def events_page_content page.find(:css, '.events-index') end def list_events page.find(:css, '.event') page.find(:id, 'minified') end def find_workshop page.find('section', text: 'Workshop') end def click_workshop find_workshop.click_link('Workshop') end def find_event page.find('section', text: 'Event') end def click_event find_event.click_link('Event') end def visit_event find('p', 'Attend our workshops to learn programming in a safe and supportive environment at your own pace, or to share your knowledge and coach our students.') end def sign_up_coach find('a', 'Sign up as a coach') end def sign_up_student find('a', 'I understand and meet the eligibility criteria. Sign me up as a student') end def event_details page.find(:css, '.large-12.columns') page.find(:css, '.medium-8.columns') page.find('h3', 'Venue') end def click_login find_link('Log in').click end def find_coach find_link('Attend as a coach') end def click_coach find_coach.click end def find_student find_link('Attend as a student') end def click_student find_student.click end def find_attend find_link('Attend') end def click_attend find_attend.click end def click_sign_up find_link('Sign up').click end def sign_up_page page.find('h2', 'Sign up') end def click_button(click) click_link(click) end def fail_student_coach page.find('a', 'Please tell us whether you want to attend as a student or coach.') end def click_fail fail_student_coach.click end def select_option page.find(:id, 'session_invitation_note_chosen') end def thanks_message page.find('div', 'Thanks for getting back to us ') end end
Vagrant.configure('2') do |config| config.vm.box = 'ubuntu/trusty64' config.vm.provider 'virtualbox' do |v| v.memory = 2048 v.cpus = 1 end config.vm.provision 'shell', inline: <<-eos # install ruby2.0 apt-get -y install build-essential git python-software-properties; apt-add-repository ppa:brightbox/ruby-ng; apt-get update; apt-get -y install ruby2.2 ruby-switch; ruby-switch --set ruby2.2; # install depedencies su - vagrant; cd /vagrant; gem install bundler; bundle install; eos end
json.array!(@posicos) do |posico| json.extract! posico, :id, :nome, :tipo, :description json.url posico_url(posico, format: :json) end
# In the below exercises, write code that achieves # the desired result. To check your work, run this # file by entering the following command in your terminal: # `ruby day_2/exercises/iteration.rb` # Example: Write code that iterates through a list of animals # and print each animal: animals = ["Zebra", "Giraffe", "Elephant"] animals.each do |animal| p animal end # Write code that iterates through a list of animals and prints # "The <animal> is awesome!" for each animal: animals.each do |animal| p "The #{animal} is awesome!" end # Write code that stores an array of foods in a variable, # then iterates over that array to print # "Add <food> to shopping list" for each food item: # YOUR CODE HERE foods = ["bread", "milk", "eggs", "tofo"] foods.each do |list| p "Add #{list} to the shopping list" end # Write code that stores an array of numbers in a variable, # then iterates over that array to print doubles of each number: # YOUR CODE HERE numbers = [1, 2, 3, 4, 5] numbers.each do |x| p x*2 end numbers.each do |x| print x print " " p x end #i was unclear if you wanted X printed twice or X multiplied by 2
require "spec_helper" describe ShowDefinitionPowerup do let(:player) { Player.new } let(:answer) { Answer.new("Batman") } let(:game) { Game.new(player, answer) } it "adds definition of word to game" do end it "costs 25% of final score to use" do answer.stub(find_definition: "Testing Avengers") game.use_powerup!(:show_definition) game.new_guess "batman" expect(game.score).to eq 963 end end
class Vor < ActiveRecord::Base # attr_accessor :elevation, :frq, :identifier, :lat, :lon, :name, :range, :slaved belongs_to :user before_save { |vor| vor.identifier = identifier.upcase } validates :lat, presence: true, numericality: { greater_than_or_equal_to: -90, less_than_or_equal_to: 90 } validates :lon, presence: true, numericality: { greater_than_or_equal_to: -180, less_than_or_equal_to: 180 } validates :elevation, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 30000, only_integer: true } validates :frq, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 999, only_integer: true } validates :range, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 5000, only_integer: true } validates :slaved, presence: true, numericality: true IDENTIFIER_REGEX = /\A[a-zA-Z0-9]{2,4}\Z/ validates :identifier, presence: true, format: { with: IDENTIFIER_REGEX }, length: {in: 2..4} NAME_REGEX = /\A[a-zA-Z0-9-_\s]+([V][O][R]|[V][O][R][T][A][C]|[V][O][R][-][D][M][E])\Z/ validates :name, presence: true, format: {with: NAME_REGEX }, length: { maximum: 50} end
module ApplicationHelper # Authentication def current_user if session.has_key?(:user_id) and ( @current_user.nil? or (session[:user_id] != @current_user.id)) @current_user = User.find_by_id(session[:user_id]) end @current_user end def set_return_redirect(meta = {}) if session[:redirect_hash].nil? meta[:expires_in] = 10.minutes.from_now unless meta.has_key? :expires_in session[:redirect_hash] = meta end end def authenticate_user!(meta = {}) if !current_user meta[:uri] = request.url unless meta.has_key? :uri meta[:title] = "LogIn Required" unless meta.has_key? :title meta[:text] = "Please login (or signup) to see #{meta[:uri]}" unless meta.has_key? :text meta[:return_text] = "Return to #{URI(meta[:uri]).host}" unless meta.has_key? :return_text meta[:display] = true meta[:expires_in] = 10.minutes.from_now unless meta.has_key? :expires_in session[:redirect_hash] = meta flash[meta[:title]] = meta[:text] redirect_to new_session_path end end def authenticate_ownership(object, admin_access = true) render :file => "public/401.html", :status => :unauthorized, :layout => false unless object.user == current_user or (admin_access and Rails.configuration.credport_admins.include?(current_user.id.to_s)) end def redirect_back(*params) uri = session[:redirect_hash][:uri] if session.has_key? :redirect_hash and session[:redirect_hash][:expires_in] > DateTime.now session[:redirect_hash] = nil if uri redirect_to uri else if request.env['omniauth.origin'] redirect_to request.env['omniauth.origin'] else redirect_to(*params) end end end def authenticate_admin! raise ActionController::RoutingError.new('Not Found') unless current_user and Rails.configuration.blog_admins.include? current_user.id.to_s end # Stats def mixpanel @mixpanel = Mixpanel::Tracker.new Rails.configuration.mixpanel_key, {} end # API def escape_objects(object) if object.class == Hash or object.class.ancestors.include? Hash ret = {} object.each{|sym, val| ret[sym] = escape_objects(val) } ret elsif object.class == Array object.map{|val| escape_objects val} else ERB::Util.h object end end def include_parameter(key) params.has_key?(:include) and params[:include].split(',').include?(key) end def include_education? include_parameter 'education' end def include_work? include_parameter 'work' end def include_stats? include_parameter 'stats' end def include_verifications? include_parameter 'verifications' end def include_reviews? include_parameter 'reviews' end def getStats viewer = params.has_key?(:viewer) ? User.find_param(params[:viewer]) : current_user if viewer.nil? or viewer == @user @stats = Rails.cache.fetch("api-stats-without-#{@user.cache_key}", :expires_in => 2.hours){ Connection.stats_without_viewer(@user)} else @stats = Rails.cache.fetch("api-stats-without-#{@user.cache_key}-#{viewer.cache_key}", :expires_in => 2.hours){Connection.stats_with_viewer(viewer, @user)} end @stats[:common_connections] = { :number => @stats[:common_connections], :title => t('Common Connections'), :desc => t('Number of connections you both share'), :image => "https://credport-assets.s3.amazonaws.com" + ActionController::Base.helpers.asset_path("community.png") } @stats[:common_interests] = { :number => @stats[:common_interests], :title => t('Common Interests'), :desc => t('Number of interests you both share'), :image => "https://credport-assets.s3.amazonaws.com" + ActionController::Base.helpers.asset_path("commoninterest.png") } @stats[:reviews] = { :number => @stats[:reviews], :title => t('Reviews'), :desc => t('Number of reviews'), :image => "https://credport-assets.s3.amazonaws.com" + ActionController::Base.helpers.asset_path("reviews.png") } @stats[:degree_of_seperation] = { :number => @stats[:degree_of_seperation], :title => t('Degrees of separation'), :desc => t('How many steps away you are'), :image => "https://credport-assets.s3.amazonaws.com" + ActionController::Base.helpers.asset_path("dos.png") } @stats[:accounts] = { :number => @stats[:accounts], :title => t('Accounts'), :desc => t('Number of verified accounts'), :image =>"https://credport-assets.s3.amazonaws.com" + ActionController::Base.helpers.asset_path("accounts.png") } @stats[:verifications] = { :number => @stats[:verifications], :title => t('Verifications'), :desc => t('Number of emails/phones'), :image => "https://credport-assets.s3.amazonaws.com" + ActionController::Base.helpers.asset_path("verifications.png") } @stats end # Actual helper functions def get_domain(url) return 'undefined' unless url url = URI(url).host if url.split('.').length > 1 url.split( "." )[-2,2].join(".") else url end end end
class DNA def initialize(file) #read every line in the file @dna = IO.readlines(file) #get individual sizes @sizes = @dna[0].split #convert sizes into an integer @sizes.each_index do |i| @sizes[i] = @sizes[i].to_i end @dna = @dna[1, num_lines] @dna.each_index do |i| @dna[i] = @dna[i].chomp end end #return the number of DNA strands def num_lines @sizes[0] end #return the size of each line def line_size @sizes[1] end #print the DNA strands def print puts @dna end def all_strands @dna end def strand(i) @dna[i] end def column(i) string = String.new @dna.each do |strand| string += strand[i].chr end string end end
class PeoplesController < ApplicationController def new @people = People.new end def create @people = People.new(params[:people]) if @people.save redirect_to :action => :show, :id => @people.id else render 'new' end end def show @people = People.find(params[:id]) end def index @peoples = People.all end def edit @people = People.find(params[:id]) end def update @people = People.find(params[:id]) if @people.update_attributes(params[:people]) redirect_to :action => :show, :id => @people.id else render 'edit' end end def destroy @people = People.find(params[:id]) @people.destroy redirect_to :action => :index end end
class ProductsController < ApplicationController before_action :set_product, except: [:index, :new, :create, :update, :order, :pay, :complete, :search] def index @products = Product.includes(:images).order('created_at DESC') end def new @product = Product.new @product.images.new end def create @product = Product.new(product_params) if @product.save redirect_to root_path else render :new end end def edit end def update @product = Product.find(params[:product_id]) if @product.update(product_params) redirect_to root_path else render :edit end end def destroy @product.destroy redirect_to root_path end def show @contents = Product.includes(:images).order('created_at DESC') end def order if user_signed_in? @product = Product.find(params[:product_id]) card = Card.where(user_id: current_user.id).first if card.blank? #登録された情報がない場合にカード登録画面に移動 redirect_to controller: "users/registrations", action: "new_card" else Payjp.api_key = ENV['PAYJP_ACCESS_KEY'] #保管した顧客IDでpayjpから情報取得 customer = Payjp::Customer.retrieve(card.customer_id) #保管したカードIDでpayjpから情報取得、カード情報表示のためインスタンス変数に代入 @default_card_information = customer.cards.retrieve(card.card_id) end else redirect_to users_login_path end end def pay @product = Product.find(params[:product_id]) card = Card.where(user_id: current_user.id).first Payjp.api_key = ENV['PAYJP_ACCESS_KEY'] Payjp::Charge.create( :amount => @product.price, #支払金額を入力(itemテーブル等に紐づけても良い) :customer => card.customer_id, #顧客ID :currency => 'jpy', #日本円 ) #完了画面に移動 redirect_to product_complete_path(params[:product_id]) end def complete @product = Product.find(params[:product_id]) end def search @search = params[:search] @products = Product.search(@search) end def set_product @product = Product.find(params[:id]) end private def product_params params.require(:product).permit(:name, :detail, :brand, :size, :price, :status, :situation, :postage, :method, :area, :category_parents, :category_children, :category_grand_children, images_attributes: [:image_url, :_destroy, :id]).merge(user_id: current_user.id) end end
# ============================================================================== # Required settings # ============================================================================== set :application, "mygreatapp.com" set :repository, "ssh://mygitrepo.com/home/git/repos/mygreatapp.com" set :deploy_to, "/var/www/#{application}" set :branch, "master" role :web, "myownserver.com" # ============================================================================== # Optional settings # ============================================================================== # set :cake_config_files, %w{core.php database.php bootstrap.php} # these are the defaults # set :cake_shared_dirs, %w{tmp Vendor Plugin} # these are the defaults set :upload_dirs, %w{ img/contents img/options files/downloads } set :upload_children, %w{ img/contents/thumbs } set :compile_css, true set :compile_js, true set :files_to_remove, %w{webroot/css/cake*.css webroot/img/cake.* webroot/img/test-*.png webroot/test.php} # ============================================================================== # Staging specific settings (overrides any production settings) # ============================================================================== task :staging do set :repository, "" set :deploy_to, "" set :branch, "staging" end
class MemberStatsController < ApplicationController before_action :set_member_stat, only: [:show, :edit, :update, :destroy] respond_to :html def index @member_stats = MemberStat.all respond_with(@member_stats) end def show respond_with(@member_stat) end def new @member_stat = MemberStat.new respond_with(@member_stat) end def edit end def create @member_stat = MemberStat.new(member_stat_params) @member_stat.save respond_with(@member_stat) end def update @member_stat.update(member_stat_params) respond_with(@member_stat) end def destroy @member_stat.destroy respond_with(@member_stat) end private def set_member_stat @member_stat = MemberStat.find(params[:id]) end def member_stat_params params.require(:member_stat).permit( :item1_point, :item2_point, :item3_point, :item4_point, :item5_point, :member_id ) end end
describe "Float#arg", -> xdescribe 'ruby_bug "#1715", "1.8.6.369"', -> it "returns NaN if NaN", -> f = R.Float.NAN expect(R(f).arg().nan() ).toEqual true describe 'ruby_version_is "1.9"', -> it "returns self if NaN", -> f = R(R.Float.NAN) expect(f.arg() == f).toEqual true it "returns 0 if positive", -> expect(R(1.0).to_f().arg() ).toEqual R(0).to_f() it "returns 0 if +0.0", -> expect(R(0.0).to_f().arg() ).toEqual R(0).to_f() it "returns 0 if +Infinity", -> expect(R(R.Float.INFINITY).to_f().arg() ).toEqual R(0).to_f() it "returns Pi if negative", -> expect(R((-1.0)).to_f().arg() ).toEqual R(Math.PI).to_f() # This was established in r23960 xit "returns Pi if -0.0", -> # BUG does not work expect(R(-0.0).to_f().arg() ).toEqual R(Math.PI).to_f() it "returns Pi if -Infinity", -> expect(R((-R.Float.INFINITY)).to_f().arg() ).toEqual R(Math.PI).to_f()
# frozen_string_literal: true module Quilt VERSION = "3.5.1" end
class Company < ApplicationRecord has_many :jobs has_secure_password validates(:name, presence: true, uniqueness: true) validates(:password, presence: true) end
class PostHashtag < ApplicationRecord belongs_to :post belongs_to :hashtag validates :post_id, presence: true validates :hashtag_id, presence: true end