text
stringlengths
10
2.61M
require "rails_helper" RSpec.feature "User can navigate straight back to root page from any location via the navbar" do context "When user is on any page" do scenario "they can navigate directly back to the home page" do test_page = Page.create(title: "test title one", content: "test content one", slug: "test-slug-one") visit page_path(test_page.id) within "nav" do click_on "Home" end expect(page).to have_content("List of all Pages") end end end
class AddRegToCompanys < ActiveRecord::Migration[5.0] def change add_column :companies, :region, :string end end
# encoding: utf-8 require 'spec_helper' describe SimpleSpreadsheet do describe "Open Openoffice (.ods) file read-only mode" do before do @workbook = SimpleSpreadsheet::Workbook.read(File.join(File.dirname(__FILE__), "fixtures/file.ods")) end it "should can open the file" do @workbook.should_not be_nil end it "should use right class" do @workbook.class.to_s.should eq("OpenofficeReader") end it "should see the right number of sheets" do @workbook.sheets.count.should eq(2) end it "should read strings from first sheets" do @workbook.cell(1,1).should eq("String1") end it "should read integer from first sheets" do @workbook.cell(1,2).should eq(1) end it "should read strings from other sheets" do @workbook.cell(1, 1, 2).should eq("String2") end it "should read integer from other sheets" do @workbook.cell(1, 2, 2).should eq(2) end it "should read strings from other sheets (way 2)" do @workbook.selected_sheet = 2 @workbook.cell(1, 1).should eq("String2") end it "should read integer from other sheets (way 2)" do @workbook.selected_sheet = 2 @workbook.cell(1, 2).should eq(2) end it "should correctly count rows" do @workbook.last_row.should eq(1) end it "should correctly count column" do @workbook.last_column.should eq(2) end end end
require File.dirname(__FILE__) + '/../test_helper' require 'article_banners_controller' # Re-raise errors caught by the controller. class ArticleBannersController; def rescue_action(e) raise e end; end class ArticleBannersControllerTest < Test::Unit::TestCase fixtures :article_banners def setup @controller = ArticleBannersController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_should_get_index get :index assert_response :success assert assigns(:article_banners) end def test_should_get_new get :new assert_response :success end def test_should_create_article_banner old_count = ArticleBanner.count post :create, :article_banner => { } assert_equal old_count+1, ArticleBanner.count assert_redirected_to article_banner_path(assigns(:article_banner)) end def test_should_show_article_banner get :show, :id => 1 assert_response :success end def test_should_get_edit get :edit, :id => 1 assert_response :success end def test_should_update_article_banner put :update, :id => 1, :article_banner => { } assert_redirected_to article_banner_path(assigns(:article_banner)) end def test_should_destroy_article_banner old_count = ArticleBanner.count delete :destroy, :id => 1 assert_equal old_count-1, ArticleBanner.count assert_redirected_to article_banners_path end end
class BitLevelFileGroupsController < FileGroupsController def create_initial_cfs_assessment @file_group = BitLevelFileGroup.find(params[:id]) @file_group.ensure_cfs_directory authorize! :create_cfs_fits, @file_group if @file_group.is_currently_assessable? @file_group.schedule_initial_cfs_assessment flash[:notice] = 'CFS simple assessment scheduled' else flash[:notice] = 'CFS simple assessment already underway for this file group. Please try again later.' end redirect_to @file_group end def timeline @file_group = BitLevelFileGroup.find(params[:id]) @file_group.ensure_cfs_directory @directory = @file_group.cfs_directory timeline = Timeline.new(object: @directory) @yearly_stats = timeline.yearly_stats @monthly_stats = timeline.monthly_stats @all_monthly_stats = timeline.all_monthly_stats end end
class VideoPolicy < ApplicationPolicy alias index? user_renewal_date_is_in_future? alias show? user_renewal_date_is_in_future? end
require "pry" require_relative "artist.rb" require_relative "song.rb" class MP3Importer attr_accessor :path @files_arr = [] def initialize(path) #initialize with path @path = path self.files end def import # binding.pry @files_arr.each do |file| # artist = Artist.new(artist_name) # binding.pry song = Song.new_by_filename(file) end end def files @files_arr = Dir[@path + "/*.mp3"].map do |path| File.basename(path, "*.mp3") end # binding.pry @files_arr end end
class User < ActiveRecord::Base include Tokenable validates_presence_of :email, :password, :full_name validates_uniqueness_of :email has_secure_password has_many :reviews has_many :queue_items, -> {order(position: :asc)} has_many :videos, through: :queue_items has_many :leading_relationships, class_name: "Relationship", foreign_key: :leader_id #has_many :leaders, through: :relationship has_many :following_relationships, class_name: "Relationship", foreign_key: :follower_id #has_many :follwers, through: :following_relationships def queued_video?(video) queue_items.map(&:video).include?(video) end def follows?(another_user) following_relationships.map(&:leader).include?(another_user) end def follow(another_user) following_relationships.create(leader: another_user) if can_follows?(another_user) end def can_follows?(another_user) !(self.follows?(another_user) || self == another_user) end end
module Nhim class BaseModel < ::ActiveRecord::Base self.abstract_class = true def self.belongs_to(relationship, options={}) options[:optional] = true if ActiveRecord::VERSION::MAJOR >= 5 super(relationship, options) end end end
require_relative '../../token' module Tokenizer module Oracles class Value private_class_method :new class << self # Returns true if value is a primitive or a reserved keyword variable. def value?(value) !type(value).nil? end # rubocop:disable Metrics/CyclomaticComplexity # rubocop:disable Layout/ExtraSpacing def type(value) return Token::VAL_NUM if number? value return Token::VAL_STR if string? value case value when ID_SORE then Token::VAR_SORE when ID_ARE then Token::VAR_ARE when /\A(連想)?配列\z/ then Token::VAL_ARRAY when /\A(真|肯定|はい|正)\z/ then Token::VAL_TRUE when /\A(偽|否定|いいえ)\z/ then Token::VAL_FALSE when /\A(無(い|し)?|ヌル)\z/ then Token::VAL_NULL end end # rubocop:enable Metrics/CyclomaticComplexity # rubocop:enable Layout/ExtraSpacing def number?(value) value =~ /\A(-|ー)?([#{NUMBER}]+(\.|.)[#{NUMBER}]+|[#{NUMBER}]+)\z/ end def string?(value) value =~ /\A「.*」\z/m end def special?(value) [ID_SORE, ID_ARE, ID_ARGV, ID_ERR].include? value end def sanitize(value) if string? value # Strips leading and trailing whitespace and newlines within the string. # Whitespace at the beginning and ending of the string are not stripped. value.gsub(/[#{WHITESPACE}]*\n[#{WHITESPACE}]*/, '') elsif number? value value.tr 'ー.0-9', '-.0-9' else value end end end end end end
# frozen_string_literal: true class AddDescriptionToCommittees < ActiveRecord::Migration[6.1] def change add_column :committees, :description, :text end end
class EntriesController < ApplicationController def index @entries = Entry.all end def show if !(params[:id].blank?) @entry = Entry.find(params[:id]) else redirect_to(@entries) and return end end def create entry = Entry.create(entry_params) redirect_to(entry_path(entry)) end def destroy @removedEntry = @entry Entry.destroy(@removedEntry.id) redirect_to(entry_path) and return end def edit @entry end def update @entry.update(entry_params) redirect_to(entry_path(entry)) end private # use call backs def set_entry @entry = Entry.find(params[:id]) end # never trus the scary stuff from the internet def entry_params params[:entry].permit(:title, :contents) end end
class Zipcode attr_accessor :zipcode def initialize(zipcode=nil) @zipcode = zipcode.to_s.rjust(5, "0")[0..4] end end
require 'rails_helper' RSpec.describe 'User#update', type: :system do let(:user_page) { UserPage.new } before { log_in admin_attributes } it 'completes basic' do user = user_create user_page.load id: user.id expect(user_page.title).to eq 'Letting - Edit User' user_page.fill_form 'nother', 'nother@example.com', 'pass', 'pass' user_page.button 'Update' expect(user_page).to be_successful end it 'displays form errors' do user = user_create user_page.load id: user.id user_page.fill_form 'nother', 'nother&example.com', 'pass', 'pass' user_page.button 'Update' expect(user_page).to be_errored end end
# == Schema Information # # Table name: messages # # id :integer not null, primary key # body :text not null # author_id :integer not null # channel_id :integer not null # edited :boolean default(FALSE), not null # created_at :datetime not null # updated_at :datetime not null # class Message < ApplicationRecord # can't use presence validation with boolean field validates :author_id, :channel_id, :body, presence: true validates :edited, inclusion: { in: [true, false] } belongs_to( :author, primary_key: :id, foreign_key: :author_id, class_name: :User ) belongs_to :channel def time_str hour = self.created_at.strftime('%I') minutes = self.created_at.strftime('%M') am_pm = (((self.created_at.strftime('%k')).to_i) > 12 ) ? "PM" : "AM" @time_str = "#{hour}:#{minutes} #{am_pm}" end end
# frozen_string_literal: true require 'gomail/version' require 'gomail/client' module Gomail Error = Class.new(RuntimeError) SchemaError = Class.new(Error) end
require 'test_helper' class SteamProfileTest < ActiveSupport::TestCase # Test to validate that, based on vanity_name, SteamProfiles automatically # retrieve the steam_id when created. test 'should autopopulate steam_id when saving' do VCR.use_cassette('steam_api_requests') do p = SteamProfile.create( vanity_name: 'michael' ) p.reload assert p.steam_id == '76561197962180080', "Steam_id was not set right." end end # Test to ensure that the steam_profile can list out its favorite # played games test 'should be able to get favorite games' do VCR.use_cassette('steam_api_requests') do u = users(:one) p = u.steam_profile p.update_library assert p.favorite_games.count == 5, 'Incorrect favorite games returned' end end # Test to ensure that the steam_profile can list out its recently # played games test 'should be able to get recent games' do VCR.use_cassette('steam_api_requests') do u = users(:one) p = u.steam_profile p.update_library assert p.recent_games.count == 14, 'Incorrect recent games returned' end end end
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT require 'utils' module Errors # Root class for our internal ZAX errors # # Relay internal errors will inherit from ZAXError. # Catch block handles 3 types of errors: # - RbNaCl::CryptoError for encryption # - ZAXError of relay own error conditions # - general errors from other libraries # # All known relay errors related to the protocol will return :bad_request. # No details of crypto errors are given to the client besides formatting # errors of a client request. Error details are logged # in the relay logs at :warning or :error levels depending on severity. # # :internal_server_error - a grave internal error that the # relay can not recover from on its own, usually related to # external services (such as RNG). The system administrator should # investigate these errors, they are always logged at ERROR level. # Clients get a response with :internal_server_error code so that # they may avoid using given relay for the time being. class ZAXError < StandardError include Utils def initialize(ctrl, data = nil) @controller = ctrl @data = data @response_code = :bad_request end def http_fail # No information about the relay state is sent back to the client for known error conditions if @controller and @controller.class < ApplicationController @controller.expires_now xerr = @response_code != :internal_server_error ? 'Your request can not be completed.' : 'Something is wrong with this relay. Try again later.' @controller.head @response_code, x_error_details: xerr end @err_msg = ( @data and @data.is_a?(Hash) and @data[:msg] ) ? @data[:msg] : '' warn "#{INFO_NEG} #{@err_msg}" # Discard any set redis WATCH if Thread.current[:redis] begin rds = Thread.current[:redis] rds.discard if rds.connected? rescue # Ignore any redis issues since we already # dealing with some error end end end # Used when the relay's internal integrity is in doubt def severe_error(note ="", excpt) if @controller and @controller.class < ApplicationController @controller.expires_now @controller.head :internal_server_error, x_error_details: 'Something is wrong with this relay. Try again later.' end _log_exception ERROR,note,excpt end # This is used to log general non-ZAX exceptions def report(note, excpt) # handle non-ZAX errors, such as encoding, etc. @controller.expires_now @controller.head @response_code, x_error_details: 'Your request can not be completed.' _log_exception WARN,note,excpt end # This is used to log RbNaCl errors def NaCl_error(e) e1 = e.is_a?(RbNaCl::BadAuthenticatorError) ? 'The authenticator was forged or otherwise corrupt' : '' e2 = e.is_a?(RbNaCl::BadSignatureError) ? 'The signature was forged or otherwise corrupt' : '' error "#{ERROR} Decryption error for packet:\n"\ "#{e1}#{e2} "\ "#{@controller.body}" _log_exception ERROR, "Stack trace", e @controller.head @response_code, x_error_details: 'Your request can not be completed.' end # === Exception loging functions === def _log_exception(icon, note, excpt) warn "#{icon} #{note}:\n#{EXPT} \xE2\x94\x8C#{excpt} \xE2\x94\x90" warn excpt.backtrace[0..7].reduce("") { |s,x| s += "#{EXPT} \xE2\x94\x9C#{x}\n" } + "#{EXPT} \xE2\x94\x94#{BAR*25}\xE2\x94\x98" end def log_message(m) # "#{m}:\n#{dumpHex @data}:\n#{EXPT} #{self}\n---" "#{m}" end def info(m) Rails.logger.info log_message m # @controller.logger.info log_message m end def warn(m) Rails.logger.warn log_message m # @controller.logger.warn log_message m end def error(m) Rails.logger.error log_message m end end end
module Puppet::Parser::Functions newfunction(:get_resource, :type => :rvalue, :doc => "Traverses the catalog for a resource and returns the whole resource as a hash, or optionally if you provide the second arg, that particular parameter of the resource. For example: user { 'foo': home => '/bar' } $home = get_resource(User['foo'], 'home') Caveat: just as the native 'defined' function this suffers from being dependent on parse order so keep that in mind. ") do |val| rs = compiler.findresource(val[0].type, val[0].title) if val[1] != nil if rs != nil rs.to_data_hash['parameters'][val[1].to_sym] if rs.to_data_hash['parameters'].has_key? val[1].to_sym else nil end else if rs != nil rs.to_data_hash['parameters'].reduce({}) {|hash, (k,v)| hash.merge(k.to_s => v)} else nil end end end end
require 'rails_helper' RSpec.describe SettingsController, type: :controller do describe 'GET #index' do context 'User is not signed in' do before do get :index end include_examples 'redirects as un-authenticated user' end context 'User is signed in' do before do athlete = create(:athlete_user) sign_in(athlete) get :index end it 'assigns the @user variable' do expect(assigns(:user)).not_to be_nil end include_examples 'renders the template', :index end end describe 'PUT #update' do context 'User updates no settings' do it 'user profile information does not change' do user = create(:athlete_user) sign_in(user) user_before = user put :update, params: { id: user.id, user: attributes_for(:user) } expect(user).to eq(user_before) end end context 'user updates one setting' do it 'updates the user setting' do user = create(:athlete_user) sign_in(user) put :update, params: { id: user.id, user: { first_name: 'test' } } user = User.find(user.id) # reload expect(flash[:success]).to eq('User Profile Sucessfully Updated') expect(user.first_name).to eq('Test') end end context 'user updates multiple settings' do it 'updates all the settings' do user = create(:athlete_user) sign_in(user) new_settings = { first_name: 'test', phone: '0987654321' } put :update, params: { id: user.id, user: new_settings } user = User.find(user.id) # reload expect(flash[:success]).to eq('User Profile Sucessfully Updated') expect(user.first_name).to eq('Test') expect(user.phone).to eq('0987654321') end end context 'user provides an invalid value for a field' do it 'returns the validation error and does not update user' do user = create(:athlete_user) sign_in(user) new_settings = { first_name: '', phone: '1' } put :update, params: { id: user.id, user: new_settings } user_after = User.find(user.id) # reload error = "Validation failed: First name can't be blank, Phone Please enter a 10 "\ 'digit US Phone Number' expect(flash[:danger]).to eq(error) expect(user).to eq(user_after) end end end end
require "test_helper" describe MerchantsController do it "can successfully log in with github as an existing merchant" do iron_chef = merchants(:iron_chef) perform_login(iron_chef) must_redirect_to root_path expect(session[:merchant_id]).must_equal iron_chef.id # expect(flash[:status]).must_equal "Logged in as returning merchant #{merchant.name}" end it "can successfully log in with github as new merchant" do start_count = Merchant.count merchant = Merchant.new(provider: "github", uid: 293, name: "New Merchant", email: "new123@gmail.com") perform_login(merchant) must_redirect_to root_path Merchant.count.must_equal start_count + 1 session[:merchant_id].must_equal Merchant.last.id end it "does not create a new merchant when logging in with a invalid data" do start_count = Merchant.count invalid_new_merchant = Merchant.new(name: nil, email: nil) expect(invalid_new_merchant.valid?).must_equal false perform_login(invalid_new_merchant) must_redirect_to root_path expect( session[:merchant_id] ).must_equal nil expect( Merchant.count ).must_equal start_count end describe "Logged in merchant" do before do @hells = merchants(:hells) perform_login(@hells) end it "signed in merchant can succesfully log out" do id = @hells.id delete merchant_path(id) expect(session[:merchant_id]).must_equal nil expect(flash[:success]).must_equal "Successfully logged out!" must_redirect_to root_path end it "should respond with not found for non-exsiting merchant" do random_non_existant_id = 333 get merchant_path(random_non_existant_id) must_respond_with :missing end describe "status change" do it "logged in merchant can change their product status from activate to inactivate" do #get a product thyme = products(:thyme) #route with the id post status_change_path(thyme.id) thyme.reload expect(thyme.status).must_equal false #where it goes next must_redirect_to root_path end it "if logged in merchants try to change a product status that doesn't exist." do product = Product.first.id + 1 post status_change_path(product) must_respond_with :not_found end it "if logged in merchants status change doesn't work." do product = Product.first product.status = "fake" post status_change_path(product) expect(product.status).must_equal true end # it "logged in merchant can not change the product status of another merchants" do # # delete merchant_path(@hells.id) # # @bake_off = merchants(:bake_off) # perform_login(@bake_off) # # get merchant_account_path(@hells.id) # # must_respond_with :error # # end end describe "Merchant Add Products" do it "logged in merchant can successfully add a product" do get new_product_path must_respond_with :success end it "Not logged in merchant can not add a product" do delete merchant_path(@hells.id) must_redirect_to root_path get new_product_path flash[:status].must_equal :failure flash[:result_text].must_equal "Sign in as a merchant to access this page." must_respond_with :redirect end end describe "Merchant can ADD category" do it "logged in merchant can successfully add a category" do get new_category_path must_respond_with :success end it "A non logged in merchant can NOT add a category" do delete merchant_path(@hells.id) get new_category_path flash[:status].must_equal :failure flash[:result_text].must_equal "Sign in as a merchant to access this page." must_respond_with :redirect end end describe "Merchant Account Order Page" do it "logged in merchant can view their account orders" do get merchant_order_path must_respond_with :success end it "A Not logged in merchant can Not view their account orders" do delete merchant_path(@hells.id) get merchant_order_path must_respond_with :not_found end end it "logged in merchant can view their myaccount page" do get merchant_account_path must_respond_with :success end it "Not logged in merchant can Not view their myaccount page" do delete merchant_path(@hells.id) get merchant_account_path must_respond_with :not_found end end end
class Reader attr_reader :file_name def initialize(file) @file_name = file end def read File.read(file_name).chomp end end
class AddSubmitterToTexts < ActiveRecord::Migration def change change_table :texts do |t| t.integer :submitter_id, default: 1, null: false end add_index :texts, :submitter_id end end
# encoding: UTF-8 class Film # Raccourcis vers les METADATA # ---------------------------- def metadata ; @metadata ||= collecte.metadata.data end # {String} Identifiant du film dans le Filmodico # Pour le moment, ne peut être défini qu'explicitement. def id ; @id ||= metadata[:id] end # {String} Titre pour mémoire def titre ; @titre ||= metadata[:titre] end # {Fixnum} Temps de création du fichier film.msh # ou du fichier film.pstore # Attention : ne correspond pas au début de la collecte, # enregistrée elle dans collecte.debut ou # collecte.metadata.data[:debut] sous forme de JJ/MM/AAAA attr_accessor :created_at # {Fixnum} Time d'actualisation du fichier de données attr_accessor :updated_at # Instance {Collecte} rattachée au film # # Par exemple, pour obtenir le dossier de la collecte, on # peut faire `film.collecte.folder` attr_reader :collecte # {Film::Horloge} Temps de fin du film # Il devrait être défini par une ligne `HORLOGE FIN` mais # au cas où, on prend le temps de la dernière scène à # laquelle on ajoute une minute. def fin= value value.instance_of?(Film::Horloge) || value = Film::Horloge.new(self, value.s2h) @fin = value end def fin @fin ||= Film::Horloge.new(self, (scenes.last.horloge.time + 60).s2h) end alias :end :fin # {Film::Horloge} Temps de départ du film # Note : ce temps correspond au temps de la première # scène de la collecte def debut ; @debut ||= scenes.first.horloge end alias :start :debut # {Fixnum} Durée du film def duree @duree ||= fin.time - debut.time end end #/Film
load 'config/deploy/unicorn' load 'config/deploy/release' load 'config/deploy/delayed_job' require 'bundler/capistrano' require 'delayed/recipes' namespace :deploy do task :test_path, :roles => :app do run "env | grep -i path" end desc "deploy application" task :start, :roles => :app do end desc "initialize application for deployment" task :setup, :roles => :app do run "cd #{deploy_to} && mkdir -p releases shared shared/pids" end desc "clone repository" task :setup_code, :roles => :app do run "cd #{deploy_to} && git clone #{repository} cache" end desc "update VERSION" task :update_version, :roles => :app do run "cd #{deploy_to}/cache && git describe --abbrev=0 HEAD > ../current/VERSION && cat ../current/VERSION" end desc "dummy update_code task" task :update_code, :roles => :app do end desc "update codebase" task :pull_repo, :roles => :app do run "cd #{deploy_to}/cache && git pull" end desc "symlink stylesheets-less" task :symlink_stylesheets_less, :roles => :app do run "cd #{release_path}/public && ln -s #{deploy_to}/shared/stylesheets-less/ stylesheets-less" end desc "make release directory" task :make_release_dir, :roles => :app do run "mkdir #{release_path}" end desc "copy code into release folder" task :copy_code_to_release, :roles => :app do run "cd #{deploy_to}/cache && cp -pR * #{release_path}/" end desc "bundle install gems" task :bundle_install, :roles => :app do run "cd #{release_path} && sudo bundle install" end desc "run rake:db:migrate" task :migrate_db, :roles => :app do run "cd #{release_path} && RAILS_ENV=production bundle exec rake db:migrate" end desc "run rake roles:default_permissions" desc "restart server" task :restart, :roles => :app do #run "cd #{deploy_to}/current && mongrel_rails cluster::restart" unicorn.restart end desc "make tmp directories" task :make_tmp_dirs, :roles => :app do run "cd #{deploy_to}/current && mkdir -p tmp/pids tmp/sockets" end desc "symlink pids directory" task :symlink_pids_dir, :roles => :app do run "cd #{release_path}/tmp && ln -s #{deploy_to}/shared/pids" end desc "symlink system directory" task :symlink_system_dir, :roles => :app do run "cd #{release_path}/public && ln -s #{deploy_to}/shared/system" end desc "create tmp/cache directory" task :create_cache_dir, :roles => :app do run "cd #{release_path}/tmp && mkdir -p cache" end desc "symlink database.yml" task :symlink_database_yml, :roles => :app do run "cd #{release_path}/config && ln -s _database.yml database.yml" end desc "symlink initializers" task :symlink_initializers, :roles => :app do run "cd #{release_path}/config/initializers && ln -s #{deploy_to}/shared/config/initializers/site_keys.rb" end desc "compile assets" task :compile_assets, :roles => :app do run "cd #{release_path} && bundle exec rake assets:precompile" end desc "deploy the precompiled assets" task :deploy_assets, :except => { :no_release => true } do run_locally("RAILS_ENV=development rake assets:clean && RAILS_ENV=development rake assets:precompile") run_locally("tar -czvf public/assets.tgz public/assets") top.upload("public/assets.tgz", "#{release_path}/public/", { :via => :scp, :recursive => true }) run "cd #{release_path} && tar -zxvf public/assets.tgz 1> /dev/null" end task :finalize_update, :roles => :app do end end after 'deploy:setup', 'deploy:setup_code' after 'deploy:pull_repo', 'deploy:copy_code_to_release' before 'deploy:update_code', 'deploy:pull_repo' after 'deploy:update_code', 'deploy:finalize_update' #before 'deploy:restart', 'deploy:compile_assets' before 'deploy:restart', 'deploy:deploy_assets' before 'deploy:copy_code_to_release', 'deploy:make_release_dir' before 'deploy:restart', 'deploy:migrate_db' before 'deploy:symlink_database_yml', 'deploy:symlink_initializers' after 'deploy:create_symlink', 'deploy:update_version' after 'deploy:create_symlink', 'deploy:make_tmp_dirs' after 'deploy:make_tmp_dirs', 'deploy:create_cache_dir' before 'deploy:restart', 'deploy:symlink_system_dir' after 'deploy', 'deploy:cleanup'
class CreateWorkflowItemIngestRequests < ActiveRecord::Migration def change create_table :workflow_item_ingest_requests do |t| t.references :workflow_project_item_ingest, index: false, foreign_key: true t.references :item, index: false, foreign_key: true t.timestamps null: false end add_index :workflow_item_ingest_requests, :workflow_project_item_ingest_id, name: 'workflow_item_ingest_requests_pii_index' add_index :workflow_item_ingest_requests, :item_id, unique: true, name: 'workflow_item_ingest_requests_item_index' end end
class InitiativesController < ApplicationController def index @search = Initiative.search(params[:q]) @initiatives = Initiative.search_with_options(params[:q], {page: params[:page], order: params[:order]}) @initiatives = @initiatives.by_subject_id(params[:subject_id]) if params[:subject_id] @subjects = Subject.popular end def show @initiative = Initiative.find(params[:id]) @initiative.increase_views_count! end end
class BinaryHeap attr_accessor :heap_list, :current_size def initialize @heap_list = [0] @current_size = 0 end def perc_up(i) while i / 2 > 0 do if self.heap_list[i] < self.heap_list[i / 2] tmp = self.heap_list[i / 2] self.heap_list[i / 2] = self.heap_list[i] self.heap_list[i] = tmp end i = i / 2 end end def insert(k) self.heap_list.push(k) self.current_size += 1 self.perc_up(self.current_size) end def perc_down(i) while (i * 2) <= self.current_size do min_child = self.min_child(i) if self.heap_list[i] > self.heap_list[min_child] tmp = self.heap_list[i] self.heap_list[i] = self.heap_list[min_child] self.heap_list[min_child] = tmp end i = min_child end end def min_child(i) if i * 2 + 1 > self.current_size return i * 2 else if self.heap_list[i * 2] < self.heap_list[i * 2 + 1] return i * 2 else return i * 2 + 1 end end end def del_min return_value = self.heap_list[1] self.heap_list[1] = self.heap_list[self.current_size] self.current_size = self.current_size - 1 self.heap_list.pop self.perc_down(1) return return_value end def build_heap(list) i = list.length / 2 self.current_size = list.length self.heap_list = [0] + list while (i > 0) do self.perc_down(i) i = i - 1 end end end
require File.dirname(__FILE__) + '/../../../spec_helper' describe "File::Stat#dev_major" do platform_is_not :windows do it "returns the major part of File::Stat#dev" do File.stat(FileStatSpecs.null_device).dev_major.should be_kind_of(Integer) end end platform_is :windows do it "returns the number of the device on which the file exists" do File.stat(FileStatSpecs.null_device).dev_major.should be_nil end end end
class User < ApplicationRecord has_secure_password validates_presence_of :username, :email validates_uniqueness_of :username, :email belongs_to :game, required: false has_many :cards end
class CreateCards < ActiveRecord::Migration[6.0] def change create_table :cards do |t| t.string :playername t.string :team t.integer :year t.string :card_company t.integer :user_id end end end
Signal.trap("INT") do exit end Signal.trap("TERM") do exit end def cargo_build(mode = "") mode = "--#{mode.to_s}" unless mode.nil? system "cargo build #{mode}" or exit!(1) end def cmd_args if ARGV.include? '--' ARGV .join(' ') .split('--', 2) .last end end def run(mode, bin) cmd = ['.', 'target', mode, bin].map{|m| m.to_s}.join('/') cmd = [cmd, cmd_args].join(' ') puts cmd system cmd end namespace :build do desc 'Build debug' task :debug, [:run] do |task, args| cargo_build Rake::Task[:run].invoke(args[:run]) end desc 'Build release' task :release do |task, args| cargo_build :release Rake::Task[:run].invoke(args[:run], :release) end desc 'Build debug and release' task all: [:debug, :release] end desc 'Run bin' task :run, [:run, :mode] do |task, args| mode = args[:mode] || :debug bin = args[:run] run(mode, bin) unless bin.nil? end
require 'account_activity' require 'timecop' describe AccountActivity do subject { AccountActivity.new(10, 5) } before do Timecop.freeze(Date.parse("11/06/2020")) end it 'holds the balance' do expect(subject.balance).to eq(10) end it 'holds the value by which the balance changed' do expect(subject.value).to eq(5) end it 'holds the date it was created' do expect(subject.activity_date).to eq("11/06/2020") end end
module IOTA module Crypto class RubyCurl NUMBER_OF_ROUNDS = 81 HASH_LENGTH = 243 STATE_LENGTH = 3 * HASH_LENGTH TRUTH_TABLE = [1, 0, -1, 1, -1, 0, -1, 1, 0] def initialize(rounds = nil) @rounds = rounds || NUMBER_OF_ROUNDS reset end def reset @state = [0] * STATE_LENGTH end def absorb(trits) length = trits.length offset = 0 while offset < length start = offset stop = [start + HASH_LENGTH, length].min @state[0...stop-start] = trits.slice(start, stop-start) transform offset += HASH_LENGTH end end def squeeze(trits) trits[0...HASH_LENGTH] = @state.slice(0, HASH_LENGTH) transform end def transform previousState = @state.slice(0, @state.length) newState = @state.slice(0, @state.length) index = 0 round = 0 while round < @rounds previousTrit = previousState[index].to_i pos = 0 while true index += (index < 365) ? 364 : -365 newTrit = previousState[index].to_i newState[pos] = TRUTH_TABLE[previousTrit + (3 * newTrit) + 4] previousTrit = newTrit pos += 1 break if pos >= STATE_LENGTH end previousState = newState newState = newState.slice(0, newState.length) round += 1 end @state = newState end def version "Ruby" end end end end
module Renamer class Files COMMON_RATIO = 0.70 # if a string is in 70% of filenames, it is common attr_accessor :directory, :files, :parts, :duplicate_parts, :common_duplicate_parts, :known_episodes, :use_alternate_naming def initialize directory @directory = directory @files = @parts = @duplicate_parts = @common_duplicate_parts = @known_episodes = [] @use_alternate_naming = false end def load files = [] EXTS.each do |ext| new_files = Dir.glob("#{@directory}/*.#{ext}") next if new_files.empty? files += new_files end files.sort! end def process @files = load @files.map! do |f| name = f.gsub("#{@directory}/", '') { :name => name, :parts => name.split(/[ ,\-\.\(\)]/).compact.reject(&:empty?).reject do |p| QUALITIES.include?(p.downcase) or FORMATS.include?(p.downcase) or EXTS.include?(p.downcase) end } end @files.each_index do |idx| @files[idx][:parts].map! do |part| RomanNumerals.is_roman_numeral?(part) ? RomanNumerals.to_integer(part).to_s : part end end @parts = Hash.new(0) @files.each do |file| file[:parts].each do |part| @parts[part.downcase] += 1 end end @duplicate_parts = @parts.reject do |part, count| count < 2 end threshhold = @files.count.to_f * COMMON_RATIO @common_duplicate_parts = @parts.reject { |part, count| count < threshhold } @files.each_index do |idx| @files[idx][:search_title] = @files[idx][:parts].reject do |p| @common_duplicate_parts.include? p.downcase end.join ' ' end @files.each_index do |index| parts_plus_numbers = [] @files[index][:parts].each_index do |idx| guess_one, guess_two, guess_three, guess_four = find_numbers @files[index][:parts][idx] guess_episode = nil guess_part = nil guess_finder = -1 unless guess_four.empty? guess_episode = guess_four.first[0].to_i guess_part = guess_four.first[1] guess_finder = 4 end unless guess_three.empty? guess_episode = -1 guess_finder = 3 end unless guess_two.empty? guess_episode = guess_two.first[1] guess_part = guess_two.first[2] guess_finder = 2 end unless guess_one.empty? guess_episode = guess_one.first[1] guess_part = guess_one.first[2] guess_finder = 1 end parts_plus_numbers << { :idx => idx, :guess_finder => guess_finder, :guess_episode => guess_episode.to_i, :guess_part => guess_part } end parts_plus_numbers.sort! { |a,b| b[:guess_finder] <=> a[:guess_finder] } if parts_plus_numbers.first[:guess_episode].to_i <= @known_episodes.length @files[index][:guessed_filename_episode] = parts_plus_numbers.first[:guess_episode].to_i @files[index][:guessed_filename_part] = parts_plus_numbers.first[:guess_part].try(:downcase) else @files[index][:guessed_filename_episode] = -1 @files[index][:guessed_filename_part] = nil end @use_alternate_naming = true unless @files[index][:guessed_filename_part].nil? end end protected def find_numbers string # Format S01E01 guess_one = string.scan /S(\d{1,2})E(\d{1,2})([a-z])?/i # Format: 001x001 guess_two = string.scan /(\d{1,3})x(\d{1,3})([a-z])?/i # Format: S001 guess_three = string.scan /S(\d{1,2})/i # Format: 001 guess_four = string.scan /(\d{2,3})([a-e])?/i [guess_one, guess_two, guess_three, guess_four] end end end
class PortfolioItem < ApplicationRecord belongs_to :portfolio validates_uniqueness_of :symbol, scope: :portfolio_id end
Rails.application.routes.draw do devise_for :ad_users, path: 'ad_users' ,controllers: { sessions: 'ad_users/sessions', registrations: 'ad_users/registrations' } devise_for :st_users, path: 'st_users' ,controllers: { sessions: 'st_users/sessions', registrations: 'st_users/registrations' } # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "top#index" resources :ad_users, only: [:show, :edit, :update] do member do get :crossfollowing, :crossfollowers end end resources :st_users, only: [:show, :edit, :update] do member do get :following, :followers, :crossfollowing, :crossfollowers end end resources :relationships, only: [:create, :destroy] resources :crossfollows , only: [:create, :destroy] resources :speaks , except: :index resources :likes, only: [:create, :destroy] resources :comments , except: :index end
Puppet::Type.newtype(:f5_pool) do @doc = "Manage F5 pool." apply_to_device ensurable do defaultvalues defaultto :present end valid_lb_methods = ["ROUND_ROBIN", "RATIO_MEMBER", "LEAST_CONNECTION_MEMBER", "OBSERVED_MEMBER", "PREDICTIVE_MEMBER", "RATIO_NODE_ADDRESS", "LEAST_CONNECTION_NODE_ADDRESS", "FASTEST_NODE_ADDRESS", "OBSERVED_NODE_ADDRESS", "PREDICTIVE_NODE_ADDESS", "DYNAMIC_RATIO", "FASTEST_APP_RESPONSE", "LEAST_SESSIONS", "DYNAMIC_RATIO_MEMBER", "L3_ADDR", "UNKNOWN", "WEIGHTED_LEAST_CONNECTION_MEMBER", "WEIGHTED_LEAST_CONNECTION_NODE_ADDRESS", "RATIO_SESSION", "RATIO_LEAST_CONNECTION_MEMBER", "RATIO_LEAST_CONNECTION_NODE_ADDRESS"] newparam(:name, :namevar=>true) do desc "The pool name." validate do |value| unless Puppet::Util.absolute_path?(value) fail Puppet::Error, "Pool names must be fully qualified, not '#{value}'" end end end newparam(:membership) do desc "Whether the list of members should be considered the exact or the minimum list of members that should in the pool. Defaults to `minimum`." newvalues(:exact, :minimum) defaultto :minimum end newproperty(:description) do desc "The description of the pool." end newproperty(:lb_method) do desc "The load balancing methods of the pool." def should=(values) super(values.upcase) end validate do |value| unless valid_lb_methods.include?(value) fail Puppet::Error, "Parameter 'lb_method' must be one of #{valid_lb_methods.inspect},\ not '#{value}" end end end newproperty(:members, :array_matching => :all) do desc "The list of pool members. This must be a hash or list of hashes. e.g.: [{'address': '/Common/pc109xml-01', 'port': 443}]" def should_to_s(newvalue) newvalue.inspect end def is_to_s(currentvalue) currentvalue.inspect end def should return nil unless defined?(@should) should = @should is = retrieve if @resource[:membership] != :exact should += is if is.is_a?(Array) end should.uniq end def insync?(is) return true unless is if is == :absent is = [] end is.sort_by(&:hash) == self.should.sort_by(&:hash) end validate do |value| unless value.is_a?(Hash) fail Puppet::Error, "Members must be hashes, not #{value}" end unless Puppet::Util.absolute_path?(value["address"]) fail Puppet::Error, "Member names must be fully qualified, not '#{value["address"]}'" end end munge do |value| { address: value["address"], port: value["port"] } end end newproperty(:health_monitors, :array_matching => :all) do desc "The health monitors of the pool." def should_to_s(newvalue) newvalue.inspect end def insync?(is) is.sort == @should.sort end end ########################################################################### # Parameters used at creation. ########################################################################### # These attributes are parameters because, often, we want objects to be # *created* with property values X, but still let a human make changes # to them without puppet getting in the way. newparam(:atcreate_description) do desc "The description of the pool at creation." end newparam(:atcreate_health_monitors, :array_matching => :all) do desc "The health monitors of the pool at creation." end newparam(:atcreate_lb_method) do desc "The load balancing methods of the pool at creation." validate do |value| unless valid_lb_methods.include?(value) fail Puppet::Error, "Parameter 'atcreate_lb_method' must be one of #{valid_lb_methods.inspect},\ not '#{value}" end end defaultto 'ROUND_ROBIN' end newparam(:atcreate_members) do desc "The list of pool members. This must be a hash or list of hashes. e.g.: [{'address': '/Common/pc109xml-01', 'port': 443}]" validate do |value| value = [value] unless value.is_a?(Array) value.each do |item| unless item.is_a?(Hash) fail Puppet::Error, "Members must be hashes, not #{item}" end unless Puppet::Util.absolute_path?(item["address"]) fail Puppet::Error, "Member names must be fully qualified, not '#{item["address"]}'" end end end munge do |value| value = [value] unless value.is_a?(Array) value.collect do |item| { address: item["address"], port: item["port"] } end end defaultto [] end ########################################################################### # Validation / Autorequire ########################################################################### autorequire(:f5_partition) do File.dirname(self[:name]) end autorequire(:f5_monitor) do self[:health_monitors] end autorequire(:f5_node) do if !self[:members].nil? self[:members].collect do |member| member['address'] end end end end
class Note < ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :finders] acts_as_votable belongs_to :user has_many :comments , :dependent => :destroy validates_presence_of :name has_many :notearticles, :dependent => :destroy accepts_nested_attributes_for :notearticles, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true has_many :noteapplets, :dependent => :destroy accepts_nested_attributes_for :noteapplets, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true has_many :notequestions, :dependent => :destroy accepts_nested_attributes_for :notequestions, :reject_if => lambda { |a| a[:question_text].blank? }, :allow_destroy => true def should_generate_new_friendly_id? if !slug? || name_changed? || new_record? || slug.nil? || slug.blank? true else false end end def self.search(search) if search t = Note.arel_table Note.where(t[:name].matches("%#{search}%")) else where(nil) end end def self.isearch(search) if search t = Note.arel_table Note.where(t[:prereq].matches("%#{search}%")) else where(nil) end end end
Gem::Specification.new do |gem| gem.name = 'foreman-export-nature' gem.version = '0.0.8' gem.date = Date.today.to_s gem.add_dependency 'foreman', '>= 0.59.0' gem.add_development_dependency 'rspec', '~> 2.8.0' gem.add_development_dependency 'fuubar' gem.add_development_dependency 'ZenTest', '~> 4.4.2' gem.add_development_dependency 'fakefs' gem.summary = "Nature export scripts for foreman" gem.description = "Nature export scripts for foreman" gem.authors = ['Chris Lowder'] gem.email = 'c.lowder@nature.com' gem.homepage = 'http://github.com/nature/foreman-export-nature' gem.has_rdoc = false gem.extra_rdoc_files = ['README.md'] gem.files = Dir['{bin,lib,data}/**/*', 'README.md'] gem.executables = "nature-foreman" end
# Construir un programa que permita ingresar un número por teclado e imprimir # la tabla de multiplicar del número ingresado. Debe repetir la operación hasta # que se ingrese un 0 (cero). # Ingrese un número (0 para salir): _ num=1 while num !=0 do puts 'ingrese un numero para ver su tabla de multiplicar' puts 'Ingrese un número (0 para salir)' num=gets.chomp.to_i for i in 1..12 do break if num==0 puts "#{num}x#{i}=#{num*i}" end end
class ServicesController < ApplicationController before_filter :find_service, :except => :index # list all services def index @services = Infosell::Service.all((authenticated_user.try(:infosell_requisite) || '').to_param).select(&:accessible?) end # extended service description def show end # service offer def offer redirect_to service_path(@service) unless @service.offer? end # service price list def prices redirect_to service_path(@service) unless @service.prices? end private def find_service @service = Infosell::Service.find(params[:id], (authenticated_user.try(:infosell_requisite) || '').to_param) end end
class VenuesController < ApplicationController def show @venue = Venue.find_by(name: CGI.unescape(params[:id])) end end
# -*- coding : utf-8 -*- module Mushikago module Hanamgri class DeleteDictionaryRequest < Mushikago::Http::DeleteRequest def path; "/1/hanamgri/dictionary" end request_parameter :dictionary_name def initialize dictionary_name, options={} super(options) self.dictionary_name = dictionary_name end end end end
# frozen_string_literal: true # Model for user informations class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: %i[github] validates :name, :email, :admin, presence: true def self.from_omniauth(auth) where(provider: auth[:provider], uid: auth[:uid]).first_or_create do |user| user.provider = auth[:provider] user.uid = auth[:uid] user.email = auth[:info][:email] user.admin = true password = Devise.friendly_token[0, 20] user.password = password user.password_confirmation = password user.name = auth[:info][:name] end end end
class Paddle @@image = Rubygame::Surface.load_image("resources/paddle.png") def initialize(x, y, min_y, max_y) @step = 10 @x = x @y = y @min_y = min_y @max_y = max_y end def Paddle.height @@image.height end def Paddle.width @@image.width end def move_up @y -= @step unless (@y - @step) < @min_y end def move_down @y += @step unless (@y + @step + Paddle.height) > @max_y end def blit(surface) @@image.blit(surface,[@x,@y]) end def collide(x, y) result_x = ( (x >= @x) and (x <= (@x + Paddle.width)) ) result_y = ( (y >= @y) and (y <= (@y + Paddle.height)) ) result = (result_x and result_y) result end end
module Models class SmartRequest < ActiveRecord::Base belongs_to :app validates :ip, :geolocation, :status, presence: true validates :started_at, :ended_at, presence: true end end
module IOTA module Utils class ObjectValidator def initialize(keysToValidate) @validator = InputValidator.new @keysToValidate = keysToValidate end def valid?(object) valid = true @keysToValidate.each do |keyToValidate| key = keyToValidate[:key] func = keyToValidate[:validator] args = keyToValidate[:args] # If input does not have keyIndex and address, return false if !object.respond_to?(key) valid = false break end # If input function does not return true, exit method_args = [object.send(key)] method_args << args if !args.nil? if !@validator.method(func).call(*method_args) valid = false break end end valid end end end end
require 'rails_helper' describe FamilyBuilder do describe "#create_family_with_memberships" do it 'creates a new family' do user = FactoryGirl.create(:user) family_params = { name: "dixon" } builder = FamilyBuilder.new(family_params, user) families = Family.count builder.send(:create_family_with_membership) expect(Family.count).to eq (families + 1) end it 'creates family membership associated with family' do user = FactoryGirl.create(:user) family_params = { name: "dixon" } builder = FamilyBuilder.new(family_params, user) membership_count = FamilyMembership.count builder.send(:create_family_with_membership) expect(FamilyMembership.count).to eq (membership_count + 1) end end describe "#build" do it "returns false if user has a family already" do user = FactoryGirl.create(:family_membership).user family_params = { name: "dixon" } builder = FamilyBuilder.new(family_params, user) expect(builder.build).to eq false end it "returns true if user didn't have family" do user = FactoryGirl.create(:user) family_params = { name: "dixon" } builder = FamilyBuilder.new(family_params, user) expect(builder.build).to eq true end end end
class Customer < ActiveRecord::Base has_many :devices has_many :business_accounts has_many :accounting_types def lookup_accounting_category lookups = {} accounting_types.each do |at| lookups["accounting_categories[#{at.name}]"] = Hash[Hash[at.accounting_categories.pluck(:name, :id)].map{ |k,v| [k.strip, v] }] end lookups end end
require "contracts" class Employee < ActiveRecord::Base include Contracts::Core include Contracts::Builtin validates_presence_of :first_name, :last_name, :email validates_format_of :email, with: /\A[\w\._%\-\+]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/ attr_reader :tag_ids belongs_to( :department, class_name: Department.name, inverse_of: :employees, foreign_key: :department_id, ) has_many( :employee_tags, class_name: "::#{EmployeeTag.name}", foreign_key: :employee_id, dependent: :delete_all, ) def full_name full_name_array = [first_name, last_name] full_name_array&.compact&.join(" ") end def tag_names Tag.where(id: tag_ids).map do |tag| tag.name end.join(", ") end def tag_ids employee_tags.map do |employee_tag| employee_tag&.tag&.id end.compact end Contract Or[String, CollectionOf[Array, Or[String, Integer]]] => Any def tag_ids=(tag_id_values) # String input is mainly caused by incorrect hidden input, # and the value should be ignored whatever the content is employee_tags.clear if tag_id_values.is_a?(String) return end found_tags = Tag.where(id: tag_id_values) found_tags.each do |found_tag| employee_tags << EmployeeTag.new({ employee: self, tag: found_tag, }) end end end
# frozen_string_literal: true source "https://rubygems.org" gem "rake", "~> 13.0" group :development do gem "launchy", "~> 2.3" gem "pry" gem "pry-byebug" end # group :test do gem "cucumber", "~> 3.0" gem "jekyll_test_plugin" gem "jekyll_test_plugin_malicious" gem "memory_profiler" gem "nokogiri", "~> 1.7" gem "rspec" gem "rspec-mocks" gem "rubocop", "~> 0.81.0" gem "rubocop-performance" gem "minitest" gem "minitest-profile" gem "minitest-reporters" gem "shoulda" gem "simplecov" end # group :bridgetown_optional_dependencies do gem "mime-types", "~> 3.0" gem "yard", "~> 0.9" gem "tomlrb", "~> 1.2" gem "classifier-reborn", "~> 2.2" gem "liquid-c", "~> 4.0" gem "yajl-ruby", "~> 1.4" end # Bridgetown gem 'bridgetown-core', path: 'bridgetown-core' gem 'bridgetown-builder', path: 'bridgetown-builder' gem 'bridgetown-paginate', path: 'bridgetown-paginate'
class ShoppingCartsController < ApplicationController before_action :user_id before_action :prd, only: %i[create destroy] before_action :prod, only: :index helper_method :prod def index @total = 0 if user_signed_in? if !current_user.admin? seed_cart else error(products_path, 'You can\'t buy') end end end def new @shopping_cart = ShoppingCart.new end def destroy @cart_delete = ShoppingCart.find_by(user_id: @user_id, product_id: params[:id]) if @cart_delete.destroy ShoppingCart.update_quantity(@cart_delete.quantity, @prd, false) success(shopping_carts_path, 'Product deleted successfully.') else error(shopping_carts_path, 'Product was not deleted.') end end def create @cart_list = ShoppingCart.cart_list(@user_id, @prd.id, params[:shopping_cart][:quantity]) @cart_list ||= ShoppingCart.new(car_params) if @cart_list.save ShoppingCart.update_quantity(params[:shopping_cart][:quantity], @prd, true) success(shopping_carts_path, 'Product added successfully.') else error(shopping_carts_path, 'Product was not added.') end end private def car_params params.require(:shopping_cart).permit(:product_id, :quantity, :price).merge( user_id: @user_id ) end def user_id @user_id = if user_signed_in? current_user.id else unless session[:current_user_id] session[:current_user_id] = SecureRandom.random_number(999_999) end session[:current_user_id] end end def seed_cart if session[:current_user_id] @product_session = ShoppingCart.all.where(user_id: session[:current_user_id]) if @product_session @product_session.each do |item| item.user_id = current_user.id item.save end end session[:current_user_id] == '' end end def prd @prd = if action_name == 'create' Product.find(params[:shopping_cart][:product_id]) else Product.find(params[:id]) end end def prod @prod = if user_signed_in? unless current_user.admin? ShoppingCart.all.where(user_id: current_user.id).includes(product: :category) end else ShoppingCart.all.where(user_id: session[:current_user_id]).includes(product: :category) end end end
get '/comments' do @comments = Comment.order('id desc').limit(20) erb :comments_agg end
class QueryResult attr_accessor :columns attr_accessor :resultset attr_accessor :stats def initialize(response, opts = {}) # The response for any query is expected to be a nested array. # If compact (RedisGraph protocol v2) # The resultset is an array w/ three elements: # 0] Node/Edge key names w/ the ordinal position used in [1] # en lieu of the name to compact the result set. # 1] Node/Edge key/value pairs as an array w/ two elements: # 0] node/edge name id from [0] # 1..matches] node/edge values # 2] Statistics as an array of strings @metadata = opts[:metadata] @resultset = parse_resultset(response) @stats = parse_stats(response) end def print_resultset pretty = Terminal::Table.new headings: columns do |t| resultset.each { |record| t << record } end puts pretty end def parse_resultset(response) # In the v2 protocol, CREATE does not contain an empty row preceding statistics return unless response.length > 1 # Any non-empty result set will have multiple rows (arrays) # First row is header describing the returned records, corresponding # precisely in order and naming to the RETURN clause of the query. header = response[0] @columns = header.map { |(_type, name)| name } # Second row is the actual data returned by the query # note handling for encountering an id for propertyKey that is out of # the cached set. data = response[1].map do |row| i = -1 header.reduce([]) do |agg, (type, _it)| i += 1 el = row[i] case type when 1 # scalar agg << map_scalar(el[0], el[1]) when 2 # node props = el[2] agg << props.sort_by { |prop| prop[0] }.map { |prop| map_prop(prop) } when 3 # relation props = el[4] agg << props.sort_by { |prop| prop[0] }.map { |prop| map_prop(prop) } end agg end end data end def map_scalar(type, val) map_func = case type when 1 # null return nil when 2 # string :to_s when 3 # integer :to_i when 4 # boolean # no :to_b return val == "true" when 5 # double :to_f # TODO: when in the distro packages and docker images, # the following _should_ work # when 6 # array # val.map { |it| map_scalar(it[0], it[1]) } when 7 # relation props = val[4] return props.sort_by { |prop| prop[0] }.map { |prop| map_prop(prop) } when 8 # node props = val[2] return props.sort_by { |prop| prop[0] }.map { |prop| map_prop(prop) } end val.send(map_func) end def map_prop(prop) # maximally a single @metadata.invalidate should occur property_keys = @metadata.property_keys prop_index = prop[0] if prop_index > property_keys.length @metadata.invalidate property_keys = @metadata.property_keys end { property_keys[prop_index] => map_scalar(prop[1], prop[2]) } end # Read metrics about internal query handling def parse_stats(response) # In the v2 protocol, CREATE does not contain an empty row preceding statistics stats_offset = response.length == 1 ? 0 : 2 return nil unless response[stats_offset] parse_stats_row(response[stats_offset]) end def parse_stats_row(response_row) stats = {} response_row.each do |stat| line = stat.split(': ') val = line[1].split(' ')[0].to_i case line[0] when /^Labels added/ stats[:labels_added] = val when /^Nodes created/ stats[:nodes_created] = val when /^Nodes deleted/ stats[:nodes_deleted] = val when /^Relationships deleted/ stats[:relationships_deleted] = val when /^Properties set/ stats[:properties_set] = val when /^Relationships created/ stats[:relationships_created] = val when /^Query internal execution time/ stats[:internal_execution_time] = val end end stats end end
json.user do json.__typename 'User' json.id @user.id.to_s json.name @user.name json.avatarUrl @user.avatar_url json.followerCount @user.follower_count json.followingCount @user.following_count json.followedByMe @user.followed_by?(current_user) end
module Opener module KAF class Term attr_reader :document attr_reader :node def initialize document, node @document = document @node = node end def id @id ||= @node.attr :tid end def lemma @node.attr :lemma end def text @node.attr :text end def pos @node.attr :pos end def lexicon_id @node.attr :lexicon_id end def setPolarity attrs, polarity_pos #In case there is no pos info, we use the polarityPos @node[:pos] = polarity_pos if !pos and polarity_pos sentiment = @node.add_child('<sentiment/>') sentiment.attr attrs end end end end
# coding: utf-8 require "bundler" Bundler.setup(:rakefile) begin require "vlad" require "vlad/core" require "vlad/git" # Deploy config set :repository, "git@github.com:oleander/aftonbladet-most-read.git" set :revision, "origin/master" set :deploy_to, "/opt/apps/aftonbladet-most-read" set :domain, "webmaster@burken" set :mkdirs, ["."] set :skip_scm, false set :shared_paths, {"vendor" => "vendor"} set :bundle_cmd, "/usr/local/rvm/bin/webmaster_bundle" set :god_cmd, "sudo /usr/bin/god" namespace :vlad do desc "Deploys a new revision of webbhallon and reloads it using God" task :deploy => ["update", "copy_database", "bundle", "god:reload", "god:restart", "cleanup"] remote_task :bundle do run "cd #{current_release} && #{bundle_cmd} install --without=rakefile,test --deployment" end remote_task :copy_database do run "mkdir -p #{current_release}/db" run "ln -s #{shared_path}/db/database.sqlite3 #{current_release}/db" run "ln -s #{shared_path}/config.yml #{current_release}/lib" end namespace :god do remote_task :reload do run "#{god_cmd} load #{current_release}/worker.god" end remote_task :restart do run "#{god_cmd} restart aftonbladet-most-read" end end end rescue LoadError => e warn "Some gems are missing, run `bundle install`" warn e.inspect end
require "httparty" module Scraper module HearingsRequest # Fetches a page of committee hearings for the given chamber # Parameters: # - chamber: a Chamber model to fetch hearings for # - page_number: the page of committee hearings to fetch # Returns: # - a map of committee id -> committee-hearing data def self.fetch(chamber, page_number) hearings_url = "http://my.ilga.gov/Hearing/_GetPostedHearingsByDateRange" # modeled after curl request extracted from chrome # curl \ # 'http://my.ilga.gov/Hearing/_GetPostedHearingsByDateRange?chamber=H&committeeid=0&begindate=03%2F08%2F2017%2000%3A00%3A00&enddate=04%2F07%2F2017%2000%3A00%3A00&nodays=30&_=1489036405367' \ # -H 'X-Requested-With: XMLHttpRequest' \ # --data 'page=2&size=50' --compressed midnight = Time.now.midnight response = HTTParty.post(hearings_url, headers: { "X-Requested-With": "XMLHttpRequest" }, query: { chamber: chamber.key, committeeid: 0, begindate: format_datetime(midnight), enddate: format_datetime(midnight + 30.days), }, body: { size: 50, page: page_number + 1 } ) # transform response to map committee id response_data = response["data"] response_data.reduce({}) do |memo, data| entry = ActiveSupport::HashWithIndifferentAccess.new(data) memo[entry[:CommitteeId]] = entry memo end end private def self.format_datetime(datetime) datetime.strftime("%D %T") end end end
# Exception Handling is a specific process that deals with errors in a manageable and predictable way. # Ruby has an Exception class that makes handling these errors much easier. It also has a syntactic structure using the reserved words begin, rescue, and end to signify exception handling. The basic structure looks like this. begin # perform some dangerous operation rescue # do this if operation fails # for example, log the error end names = ['anne', 'argus', 'anne', nil, 'amanda'] # Iterate through names array with .each method(non-destructive) names.each do |name| begin puts "#{name}'s name has #{name.length} letters in it." rescue puts "Something went wrong!" end end # When the iterator hits the nil value in the names array, it will print out "Something went wrong!" from the rescue block, then continue executing this rest of the program. If the rescue block was not there then the program would stop its execution.
class ChangeReferenceIdToBeBigIntInMeasurementsReferences < ActiveRecord::Migration[5.2] def up change_column :measurements_references, :reference_id, :integer, using: 'reference_id::integer' end def down change_column :measurements_references, :reference_id, :boolean, using: 'reference_id::boolean' end end
require 'spec_helper' describe FunctionsController do ignore_authorization! let(:user) { users(:the_collaborator) } before do log_in user end describe "#index" do let(:database) { schema.database } let(:schema) { gpdb_schemas(:default) } before do @functions = [ GpdbSchemaFunction.new("a_schema", "ZOO", "sql", "text", nil, "{text}", "Hi!!", "awesome"), GpdbSchemaFunction.new("a_schema", "hello", "sql", "int4", "{arg1, arg2}", "{text, int4}", "Hi2", "awesome2"), GpdbSchemaFunction.new("a_schema", "foo", "sql", "text", "{arg1}", "{text}", "hi3", "cross joins FTW") ] any_instance_of(GpdbSchema) do |schema| mock(schema).stored_functions.with_any_args { @functions } end end it "should list all the functions in the schema" do mock_present { |model| model.should == @functions } get :index, :schema_id => schema.to_param response.code.should == "200" end it_behaves_like "a paginated list" do let(:params) {{ :schema_id => schema.to_param }} end it "should check for permissions" do mock(subject).authorize! :show_contents, schema.gpdb_instance get :index, :schema_id => schema.to_param end generate_fixture "schemaFunctionSet.json" do get :index, :schema_id => schema.to_param end end end
class SharedContact < ActiveRecord::Base belongs_to :user belongs_to :consultant validates :user, presence: true, uniqueness: { scope: :consultant } validates :consultant, presence: true validates :allowed, presence: true end
require 'faker' FactoryBot.define do factory :user do name { Faker::Name.name } position { Faker::Job.position } area { Faker::Job.field } world { Faker::Company.name } end end
class Democracy::SimpleCount def tally(ballots) counts = Hash.new(0) ballots.each do |ballot| cand = ballot.preferences.first unless ballot.preferences.empty? counts[cand] += 1 unless cand.nil? end counts end end
require 'yaml' MESSAGE = YAML.load_file('exercises.yml') =begin #1 How old is Teddy, uild a program that randomly generates and prints Teddy's age #To get the age generate a random number between 20 and 200 #PEDAC #Using a random number generator get the age of Teddy to appear #E: example/test cases #If I have a random number generated I can interpolate the string with a method definition so long as I convert the random integer to a string #D:ata Structure represent the final output as as string #A #C bear = "Teddy" def number rand(20..200) end puts "#{bear} is #{number} years old!" #2 How big is the room? Build a program that asks a user for the length and width of a room in meters #and diplays both meters and square feet. #1 sq meter is 10.7639 sq ft. #P: WE have 2 nuerical inputs for length and width of a room, (what if the persn doesn't know it in meters?) #E An example would be, this room is 5m by 5m so it is 25 sq meters #D DAta structure, in meters what if the person is American and uses feet? #Data will be represented with 2 inputs, as integers, and an output in sq meters #A Cinverting input to output #Integer input is a string so I need to change it to an integer #C:ode SQMTR_SQFT = 10.7639 puts ">>Enter the length of the room in meters:" length = gets.chomp.to_f puts ">>Enter the width of the room in meters:" width = gets.chomp.to_f square_meters = (length * width).round(2) square_feet = (square_meters * SQMTR_SQFT).round(2) puts "The area of the room is #{square_meters} square meters and #{square_feet} square feet." #Further Exploration Modify the program to input measurements in feet, and disply sq ft, sq inches and sq centimeters INCHES_SQFT = 144 CM_SQFT = INCHES_SQFT * 2.54 puts ">>Enter the length of your room in feet:" length = gets.to_f puts ">>Enter the width of your room in feet:" width = gets.to_f sqft = (length * width).round(2) inch_area = (length*width*INCHES_SQFT).round(2) cm_area = (length *width * CM_SQFT).round(2) puts "The area of the room is #{sqft} in square feet, #{inch_area} in sq inches and #{cm_area} in sq centimeters!" #3 Tip Calculator Create a simle Tip Calculator Prompt for the bill cost and the tip rate. #The program must compute the tip and then display both the tip and the amount of the bill. puts "What is the cost of the bill?" bill = gets.to_f puts "What percentage would you like to tip?" tip = gets.to_f gratuity = ((tip/100) * bill).round(2) total = bill + gratuity puts "The tip for your bill is #{format("$%0.2f", gratuity)}." puts "The total amounts to #{format("$%0.2f", total)}." #4 When will I retire? # Build a program that displats when the user will retire and how many years she has to wrok #until retirement P:roblem Ask the user how old they are ask the user at what age they would like to retire Indicate the current year and add the difference between the input ages, to the current year Print out the amount of years they have to go, the difference between the year it is and the year they wish to retire #E:xamples My age is 34 I want to retire at age 70 the difference in these two is 36 years so if it is 2020, I want to retire in 2056 I have 36 years to go! D:ata Structure I have two integer values that are inputs I have two Time class objects, I can use t = Time.now t.year to call the current year The other output will be the current year plus the difference between the inputs from the user A:lgorithm Define a method to get the difference in the two inputs from the user validate the inputs for an appropriate value, not negative Define another method which will get the differences in the year get user input that is an integer for their current age get user input that is an integer for the age they would like to retire This can be the same method, and validate the method to ensure it is not a negative number C:ode =end =begin def prompt(message) Kernel.puts ">>#{message}" end def age_value(input) input = nil loop do input = gets.chomp.to_i break if input >= 0 prompt(MESSAGE['invalid']) end input end def age_difference(age1, age2) age2 - age1 end age = 0 retirement_age = 0 t = Time.now prompt(MESSAGE['age']) age = age_value(age) prompt(MESSAGE['retire']) retirement_age = age_value(retirement_age) puts "It is currently #{t.year}. You will retire in #{t.year + age_difference(age, retirement_age)}." puts "You only have #{age_difference(age, retirement_age)} years of work to go unless you win the lottery!" # Greeting a user Write a program that asks for the users name. Program greets the user. If the person uses a ! at the end of their name have the computer YELL back to the user. P:roblem write a program the program greets the user and asks for their name. If the person uses a ! at the end of their name, have the computer yell back E:xample Can I please have your name? Erik => Hi Erik. Can I pelase have your name? Erik! => WHAT"S ALL THE FUSS ABOUT ERIK? D:ata Structure Input: persons name OR a persons name with an exclamation point Output: Normal Greeting or YELLING GREETING String for the input yields a input from the user String greeting either normal or YELLING A:lgorithim >>"Please enter your name." input = gets.chomp if the response ends in an ! YELL! otherwise Normal Boring Greetnig. Hello Muffintop. C:ode puts '>> Please enter your name.' input = gets.chomp if input[-1] == '!' input = input.chop puts "YO #{input} WHAT'S WITH ALL THE YELLING TODAY?" else puts "Hi #{input}." end # Odd Numbers, Print all Odd numbers 1-99, inclusive on separate lines P:roblem I need to print all the odd numbers from 1 - 99 including 1 and 99 on separate lines E:xample 1-9 1 3 5 7 9 D:ata Structures an inclusive list of numbers a condition of ODD input : a single number, check if it is odd output: the umber on a single line if it is odd A:lgorithim num = 1..99, the .. indicates it is inclusive for each value in the number scheme, print the number if it is odd C:ode for num in 1..99 if num.odd? puts num end end #try to do that a different way #all it asks is to print the odd nubers from one to 99 # start with a number until it is 100 # write it as a loop num = 1 loop do puts num num += 2 break if num > 99 end =end =begin #Even Numbers #print the even numbers from 1-99 inclusive, all numbers printed on separate lines #Do it differently than either program above from odd numbers def even(number) until number == 99 number += 1 if number.even? puts number end end end even(1) numbers = {scope: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} numbers.each do |key, value| value.each do |num| num.to_i if num % 2 == 0 puts num end end end #Sum or Product of Consectutive integers. Write a program that asks the user to enter an integer greater than 0 then asks if the user wants to determine the sum or product of all numbers between 1 and the entered integer. P:roblem write a program asking fo the user to put in a number greater than 0 then ask the user if they want the sum or the product of ALL numbers between 1 and the entered number E:xample Input a number: 10 Do you want the sum of the numbers between 1 and 10 or the product of 1 and 10? sum .....futuristic beeping computer adding 1, 2, 3, 4, 5, 6, 7, 8, 9 55 D:ata Structure String - asking for numerical input input is a string...convert to I String - Asking for sum or product input is a string or a single character for S or P (downcase) .........while the input is taken add or multiply.... OUTPUT: answer to the above A:lgorithm >>Please enter a number greater than 0 (loop) break if it is an integer, validate if it is not a number (loop) >>Would you like the sum 's' or the product 'p' of all the numbers between 1 and you number? (loop) to validate the s/p as the only acceptable answers OUTPUT: if input == 's' = sum 1..(number?) syntax is (1..55).sum = product 1..(number?) syntax is (1..55).product C:ode def compute_sum(number) (1..number).sum end def compute_product(number) total = 1 1.upto(number) {|value| total *= value} total end number = nil operator = nil loop do puts ">>Please enter a number greater than 0." number = gets.chomp.to_i break if number >= 1 puts "That is an invalid number." end loop do puts ">>Thank you. Would you like the sum 's' or product 'p' of" puts ">> all numbers from 1 to your input of #{number}?" operator = gets.chomp.downcase break if operator == ('s') break if operator == ('p') puts ">>That is not a valid input. Use 's' for sum or 'p' for product." end if operator == 's' puts "The sum of 1 to #{number} is #{compute_sum(number)}" elsif operator == 'p' puts "The product of 1 to #{number} is #{compute_product(number)}." else "Something funky is going on. Try again." end #String Assignment name = 'Bob' save_name = name name = 'Alice' puts name, save_name #what does that above code print? # 'Alice' # 'Bob' name = 'Bob' save_name = name name.upcase! puts name, save_name # But what does this print? # BOB # BOB # I believe they're both BOB, since BOB got changed from Bob, and the caller is mutated in space =end array1 = %w(Moe Larry Curly Shemp Harpo Chico Groucho Zeppo) array2 = [] array1.each { |value| array2 << value } array1.each { |value| value.upcase! if value.start_with?('C', 'S') } puts array2 puts array1 puts array2.object_id puts array1.object_id puts array2[2].object_id puts array1[2].object_id # What will happen in this code? # Remember that Array objects are their own object_id # while the values contained within the array also are their own, so if somethign is pusehd to a new array object, it maintains the same # object_id, so if it is modified, it is modified.
# input: num # output: sum of the multiples of a given num (3 and 5 if none are give) but not including num # data structure arr and integer # # rules: one is counted, but not num itself class SumOfMultiples def initialize(*multiples) @multiples = multiples end def self.to(limit) (1..limit).to_a.inject(0) do |total, num| if (num % 3 == 0 || num % 5 == 0) && num != limit total += num else total += 0 end end end def to(limit) (1..limit).to_a.inject(0) do |total, num| if part_of_multiples?(num) && num != limit total += num else total += 0 end end end def part_of_multiples?(num) @multiples.each do |multiple| return true if num % multiple == 0 end false end end
class KitOrder < ActiveRecord::Base belongs_to :order belongs_to :kit end
# frozen_string_literal: true class LiquidBook < SiteBuilder def build site.components_load_paths.each do |path| load_liquid_components(path) end layouts = Bridgetown::LayoutReader.new(site).read @components.each do |component_filename, component_object| doc "#{component_filename}.html" do layout :default collection :components excerpt "" component component_object title component_object["metadata"]["name"] content layouts["component_preview"].content end end liquid_tag "component_previews", :preview_tag end def load_liquid_components(dir, root: true) @components ||= {} @entry_filter ||= Bridgetown::EntryFilter.new(site) @current_root = dir if root return unless File.directory?(dir) && !@entry_filter.symlink?(dir) entries = Dir.chdir(dir) do Dir["*.{liquid,html}"] + Dir["*"].select { |fn| File.directory?(fn) } end entries.each do |entry| path = File.join(dir, entry) next if @entry_filter.symlink?(path) if File.directory?(path) load_liquid_components(path, root: false) else template = ::File.read(path) component = LiquidComponent.parse(template) unless component.name.nil? key = sanitize_filename(File.basename(path, ".*")) key = File.join(Pathname.new(File.dirname(path)).relative_path_from(@current_root), key) @components[key] = component.to_h.deep_stringify_keys.merge({ "relative_path" => key, }) end end end end def preview_tag(_attributes, tag) component = tag.context.registers[:page]["component"] preview_path = site.in_source_dir("_components", component["relative_path"] + ".preview.html") info = { registers: { site: site, page: tag.context.registers[:page], cached_partials: Bridgetown::Converters::LiquidTemplates.cached_partials, }, strict_filters: site.config["liquid"]["strict_filters"], strict_variables: site.config["liquid"]["strict_variables"], } template = site.liquid_renderer.file(preview_path).parse( File.exist?(preview_path) ? File.read(preview_path) : "" ) template.warnings.each do |e| Bridgetown.logger.warn "Liquid Warning:", LiquidRenderer.format_error(e, preview_path) end template.render!( site.site_payload.merge({ page: tag.context.registers[:page] }), info ) end private def sanitize_filename(name) name.gsub(%r![^\w\s-]+|(?<=^|\b\s)\s+(?=$|\s?\b)!, "") .gsub(%r!\s+!, "_") end end
require 'test_helper' class GsParametersControllerTest < ActionController::TestCase setup do @gs_parameter = gs_parameters(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:gs_parameters) end test "should get new" do get :new assert_response :success end test "should create gs_parameter" do assert_difference('GsParameter.count') do post :create, gs_parameter: @gs_parameter.attributes end assert_redirected_to gs_parameter_path(assigns(:gs_parameter)) end test "should show gs_parameter" do get :show, id: @gs_parameter.to_param assert_response :success end test "should get edit" do get :edit, id: @gs_parameter.to_param assert_response :success end test "should update gs_parameter" do put :update, id: @gs_parameter.to_param, gs_parameter: @gs_parameter.attributes assert_redirected_to gs_parameter_path(assigns(:gs_parameter)) end test "should destroy gs_parameter" do assert_difference('GsParameter.count', -1) do delete :destroy, id: @gs_parameter.to_param end assert_redirected_to gs_parameters_path end end
# # controller.rb # filemate # # Created by Vladimir Chernis on 2/9/12. # Copyright 2012 __MyCompanyName__. All rights reserved. # class FIMAController MAX_NUM_FILES = 100 attr_writer :filelist_tableview attr_accessor :filename_textfield attr_writer :path_control attr_writer :fileicon_imageview # NSNibAwaking # - (void)awakeFromNib def awakeFromNib @base_path = Pathname.new('/Users/vlad/code/filemate/test_dir') @files = [] @window = NSApplication.sharedApplication.delegate.window NSNotificationCenter.defaultCenter.addObserver self, selector:'windowDidBecomeKey:', name:NSWindowDidBecomeKeyNotification, object:@window reset_filelist @path_control.setURL(NSURL.URLWithString(@base_path.to_s)) end # NSWindowDelegate # - (void)windowDidBecomeKey:(NSNotification *)notification def windowDidBecomeKey(notification) @window.makeFirstResponder @filename_textfield end # NSTableViewDataSource # - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView def numberOfRowsInTableView(tableView) @files.length end # NSTableViewDataSource # - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex def tableView(aTableView, objectValueForTableColumn:aTableColumn, row:rowIndex) @files[rowIndex] end # NSTableViewDelegate # - (BOOL)tableView:(NSTableView *)aTableView shouldEditTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex def tableView(aTableView, shouldEditTableColumn:aTableColumn, row:rowIndex) NSWorkspace.sharedWorkspace.openFile(self.file_path_for_row(rowIndex)) false end # NSTableViewDelegate # - (void)tableViewSelectionDidChange:(NSNotification *)aNotification def tableViewSelectionDidChange(aNotification) selected_path = self.file_path_for_row(@filelist_tableview.selectedRow) @path_control.setURL(NSURL.URLWithString(selected_path)) img = NSWorkspace.sharedWorkspace.iconForFile selected_path @fileicon_imageview.setImage img end # NSControl delegate method # - (void)controlTextDidChange:(NSNotification *)aNotification def controlTextDidChange(aNotification) sender = aNotification.object path_exp = sender.stringValue.dup update_filelist(path_exp) end # NSControlTextEditingDelegate # - (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector def control(control, textView:fieldEditor, doCommandBySelector:commandSelector) puts "commandSelector: #{commandSelector}" selector_str = commandSelector.to_s if %w(insertNewline: moveDown: moveUp:).include?(selector_str) unless @files.empty? @window.makeFirstResponder @filelist_tableview row_index = 'moveUp:' == selector_str ? @files.length - 1 : 0 row = NSIndexSet.indexSetWithIndex row_index @filelist_tableview.selectRowIndexes row, byExtendingSelection:false end return true end false end protected def reset_filelist update_filelist '' end def update_filelist(path_exp) self.clear_file_selection path_exp << '*' unless path_exp.include? '*' path_exp = "**/#{path_exp}" glob = (@base_path + path_exp).to_s puts "glob: #{glob}" files = Pathname.glob(glob).slice(0, MAX_NUM_FILES) files.select! &:file? files.map! {|f| f.relative_path_from(@base_path) } @files = files puts "matches: #{@files}" @filelist_tableview.reloadData end def file_path_for_row(row_index) file = @files[row_index] puts "file #{row_index} #=> #{file}" (@base_path + file).to_s end def clear_file_selection # deselect any rows to prevent tableViewSelectionDidChange from firing # when there are no matching files to select from @filelist_tableview.deselectAll self @fileicon_imageview.setImage nil end end
require 'spec_helper' describe DiffResource do before do @parser = DiffResource::JsonParser.new({ "root" => "root.data", "key" => "key", "value" => "value" }) end it "parse json" do ret = @parser.parse <<-EOS { "root" :{ "data" : [ { "key" : "string1", "value" : "hello" } ] } } EOS expect(ret.length).to eql(1) expect(ret[0].key).to eql("string1") expect(ret[0].value).to eql("hello") end it "parse json with key value pair" do parser = DiffResource::JsonParser.new({ "root" => "root.data", "key" => "*" }) ret = parser.parse <<-EOS { "root" :{ "data" : { "string1" : "hello", "string2" : "hellohello" } } } EOS expect(ret.length).to eql(2) expect(ret[0].key).to eql("string1") expect(ret[0].value).to eql("hello") end it "error occured when parse resx" do ret = @parser.parse <<-EOS { "root" :{ "data" : [ { "key" : "string1", "value" : "hello" } } } EOS expect(ret).to eql([]) end end
require File.dirname(__FILE__) + '/../spec_helper' describe DeletedIssue do before do Site.delete_all @deleted_issue = Factory :deleted_issue end describe "methods:" do describe "restore" do it "should restore DeleteIssue back to Issue" do Issue.find_by_id(@deleted_issue.id).should == nil DeletedIssue.find_by_id(@deleted_issue.id).should_not == nil @deleted_issue.restore Issue.find_by_id(@deleted_issue.id).should_not == nil DeletedIssue.find_by_id(@deleted_issue.id).should == nil end it "should increase issues_count by +1" do @newsletter = Newsletter.first @newsletter.issues_count.should == 0 @newsletter.deleted_issues.first.restore @newsletter.reload.issues_count.should == 1 end end end end
# frozen_string_literal: true class AddIndexToSubjects < ActiveRecord::Migration[4.2] def change add_index :subjects, ["title"], :name => "index_subjects_title", :unique => true end end
class AddSpecialistRefToTreatments < ActiveRecord::Migration[5.0] def change add_reference :treatments, :specialist, foreign_key: true, index: true add_reference :treatments, :subcategory, foreign_key: true, index: true end end
class TweetsController < ApplicationController before_action :set_tweet, only:[:like, :unlike] def index @tweets = Tweet.includes(:user, :likes, :liked_users).order(created_at: :desc) @tweet = Tweet.new @users = User.order(followers_count: :desc).limit(10) #基於測試規格,必須講定變數名稱,請用此變數中存放關注人數 Top 10 的使用者資料 end def create @tweet = current_user.tweets.build(tweet_params) if @tweet.save! redirect_to tweets_path else @tweet = Tweet.order(created_at: :desc) render :index end end def like @tweet.likes.create!(user: current_user) redirect_to tweets_path end def unlike likes = Like.where(tweet: @tweet, user: current_user) likes.destroy_all redirect_to tweets_path #like = Tweet.where(tweet: @tweet, user:current_user) #@like.destroy_all #redirect_back(fallback_location: root_path) end private def set_tweet @tweet = Tweet.find(params[:id]) end def tweet_params params.require(:tweet).permit(:description) end end
require_relative '../lib/play' describe '#play' do it 'calls turn nine times' do board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] expect(self).to receive(:turn).at_least(9).times play(board) end end
class NovaScotia def scrape_people party_ids = {} { 'Nova Scotia Liberal Party' => ['LIB'], 'Nova Scotia New Democratic Party' => ['NDP'], 'Progressive Conservative Association of Nova Scotia' => ['PC'], 'Independent' => ['IND'], }.each do |name,abbreviations| organization = Pupa::Organization.new({ name: name, classification: 'political party', }) organization.add_source('http://electionsnovascotia.ca/candidates-and-parties/registered-parties', note: 'Elections Nova Scotia') abbreviations.each do |abbreviation| organization.add_name(abbreviation) end dispatch(organization) abbreviations.each do |abbreviation| party_ids[abbreviation] = organization._id end end legislature = Pupa::Organization.new({ _id: 'ocd-organization/country:ca/province:ns/legislature', name: 'Nova Scotia House of Assembly', classification: 'legislature', }) dispatch(legislature) # Darrell Dexter first appears in the debates as the Premier. However, we # don't want to create a person's whose name is "THE PREMIER". # @see http://nslegislature.ca/index.php/proceedings/hansard/C90/house_13may10/ person = Pupa::Person.new({ name: 'Darrell Dexter', family_name: 'Dexter', given_name: 'Darrell', sort_name: 'Dexter, Darrell', }) create_person(person, 'http://nslegislature.ca/index.php/people/members/Darrell_Dexter') # John MacDonald doesn't really have a URL. person = Pupa::Person.new({ name: 'John MacDonald', family_name: 'MacDonald', given_name: 'John', sort_name: 'MacDonald, John', }) create_person(person, 'http://nslegislature.ca/index.php/people/members/john_macdonnell') get('http://nslegislature.ca/index.php/people/member-bios').css('#content tbody tr').each do |tr| next if tr.text[/\bVacant\b/] tds = tr.css('td') # Create the person. url = "http://nslegislature.ca#{tr.at_css('a')[:href]}" doc = get(url) script = doc.at_css('dd script') family_name, given_name = tds[0].text.split(', ', 2) person = Pupa::Person.new({ name: "#{given_name} #{family_name}", family_name: family_name, given_name: given_name, sort_name: "#{family_name.sub(/\Ad'/, '')}, #{given_name}", image: doc.at_css('.portrait')[:src], }) if script characters = script.text.scan(/'( \d+|..?)'/).flatten.reverse person.email = characters[characters.index('>') + 1..characters.rindex('<') - 1].map{|c| Integer(c).chr}.join end create_person(person, url) # Shared post and membership properties. area_name = tds[2].text shared_properties = { label: "MLA for #{area_name}", role: 'MLA', organization_id: legislature._id, } # Create the post. post = Pupa::Post.new(shared_properties.merge({ area: { name: area_name, }, })) post.add_source('http://nslegislature.ca/index.php/people/members/', note: 'Legislature MLA list') dispatch(post) # Create the post membership. membership = Pupa::Membership.new(shared_properties.merge({ person_id: person._id, post_id: post._id, })) membership.add_source('http://nslegislature.ca/index.php/people/members/', note: 'Legislature MLA list') dispatch(membership) # Create the party membership. membership = Pupa::Membership.new({ person_id: person._id, organization_id: party_ids.fetch(tds[1].text), }) membership.add_source('http://nslegislature.ca/index.php/people/members/', note: 'Legislature MLA list') dispatch(membership) end end private def create_person(person, url) person.add_source(url) dispatch(person) @speaker_ids[url] = person._id # XXX end end
# frozen_string_literal: true require 'rails_helper' describe EventDecorator do describe '#rendered_description' do let(:event) { FactoryBot.create(:event, :with_markdown).decorate } it { expect(event.rendered_description).to eq %(<p>I&#39;m <strong>description</strong> with <em>markdown</em>.</p>\n) } end end
class CompareSort def self.run(info) data = info[:data] sorting_method = info[:sorting_method] timer = info[:timer] ValidateData.run(data) if timer sort = lambda { eval(sorting_method).run(data) } return self.timer(sort) else return eval(sorting_method).run(data) end end def self.timer(sorting_method) start_time = Time.now sorted_list = sorting_method.call end_time = Time.now return end_time - start_time end def self.compare_all(info) data = info[:data] view = info[:view] sorting_methods = %w(HeapSort QuickSort SelectionSort BubbleSort ModifiedBubbleSort InsertionSort MergeSort) sorting_times = {} info_hash = { data: data.dup, timer: true } sorting_methods.each do |method| info_hash = { data: data.dup, sorting_method: method, timer: true } sorting_times[method] = self.run(info_hash) end if view View.compare_all(sorting_times.sort_by{|method, time| time}) end return sorting_times end end class View def self.compare_all(data) puts "" print "SORTING METHOD" print " "*(6) puts "SECONDS" puts "-"*27 data.each do |datum| print datum[0] print " "*(20-datum[0].length) puts datum[1] end puts "" end end class ValidateData def self.run(data) @data = data self.isArray self.valuesAreConsistent end def self.isArray raise "Data must be an array" if (!@data.is_a?(Array)) end def self.valuesAreConsistent if @data[0].is_a?(String) valuesAreStrings else valuesAreNumbers end end def self.valuesAreNumbers @data.each do |datum| if (!datum.is_a?(Fixnum) && !datum.is_a?(Float)) raise "Values in array must be all numbers OR all strings" end end end def self.valuesAreStrings @data.each do |datum| if (!datum.is_a?(String)) raise "Values in array must be all numbers OR all strings" end end end end class InsertionSort def self.run(data) # iterate through each element data.each_with_index do |unsorted_num, i| data[0..i].each_with_index do |sorted_num, j| if sorted_num > unsorted_num # insert to its new spot data.insert(j, unsorted_num) # delete it from old spot data.delete_at(i+1) break end end end return data end end class SelectionSort def self.run(data) len = data.length # iterate through each element in the array for i in 0..len-2 min_index = i # iterate through the rest of the array for j in i+1..len-1 # if min, save index min_index = j if data[j] < data[min_index] end # put the min in it's correct spot data[i], data[min_index] = data[min_index], data[i] end return data end end class ModifiedBubbleSort def self.run(data) sorted = false while !sorted sorted = true # iterate through the whole array (data.length - 1).times do |i| # if the element ahead of the one we are on is smaller # then switch them if (data[i] > data[i+1]) data[i+1], data[i] = data[i], data[i+1] sorted = false end end end return data end end class BubbleSort def self.run(data) sorted = false (data.length).times do |i| (data.length - 1).times do |j| if (data[j] > data[j+1]) data[j+1], data[j] = data[j], data[j+1] end end end return data end end class MergeSort def self.run(nums) return nums if nums == [] #split into single arrays nums.map! {|num| [num]} #run until sorted while nums.length != 1 i = 0 #iterate through the nested array and merge them while i < nums.length merged_nums = self.merge(nums[i], nums[i+1]) nums.delete_at(i+1) nums.delete_at(i) nums.insert(i, merged_nums) i += 1 end end return nums[0] end def self.merge(nums1, nums2) # this will happen if there are an off number of arrays return nums1 if !nums2 total_length = nums1.length + nums2.length sorted_nums = [] until sorted_nums.length == total_length if nums2.empty? sorted_nums += nums1 elsif nums1.empty? sorted_nums += nums2 elsif nums2[0] < nums1[0] sorted_nums << nums2.shift else sorted_nums << nums1.shift end end return sorted_nums end end class QuickSort def self.run(data) return data if data.length <= 1 return self.sort_section(data, 0, data.length-1) end def self.sort_section(data, start_loc, end_loc) return data if end_loc - start_loc <1 wall = start_loc pivot = data[end_loc] for i in start_loc..end_loc #valid indicies if data[i]<pivot smaller_datum = data[i] data.delete_at(i) data.insert(wall, smaller_datum) wall += 1 end end data.insert(wall, pivot) data.delete_at(end_loc + 1) self.sort_section(data, start_loc, wall-1) self.sort_section(data, wall+1, end_loc) end end class HeapSort def self.run(data) return data if data.length <= 1 # create heap heap = self.create_heap(data) # then sort sorted_data = self.sort_heap(heap) return sorted_data end def self.create_heap(data) for i in 0..(data.length-1) # if they are greater than their parent swap them current_index = i current_value = data[i] parent_index = get_parent(i) while parent_index != nil && current_value > data[parent_index] parent_value = data[parent_index] # swap data[parent_index] = current_value data[current_index] = parent_value #reset values current_index = parent_index parent_index = get_parent(current_index) end end return data end def self.get_parent(index) parent_index = (index-1)/2 return nil if parent_index < 0 return parent_index end def self.sort_heap(heap) number_sorted = 0 while number_sorted < heap.length # switch the root and the last element # puts "swapping root: #{heap[0]} with bottom: #{heap[-1-number_sorted]}" heap[0], heap[-1-number_sorted] = heap[-1-number_sorted], heap[0] # p heap number_sorted += 1 current_index = 0 current_value = heap[0] while !self.valid_parent(current_index, heap, number_sorted) # find highest valid child index max_child_i = self.find_larger_child(current_index, heap, number_sorted) # swap them heap[max_child_i], heap[current_index] = heap[current_index], heap[max_child_i] # reset values current_index = max_child_i end end return heap end def self.find_larger_child(parent_index, heap, number_sorted) children_i = [] l_child_i = left_child_index(parent_index) r_child_i = right_child_index(parent_index) if l_child_i < (heap.length - number_sorted) children_i << l_child_i end if r_child_i < (heap.length - number_sorted) children_i << r_child_i end return nil if children_i.length == 0 max_child_i = children_i[0] children_i.each do |index| max_child_i = index if heap[index] > heap[max_child_i] end return max_child_i end def self.valid_parent(parent_index, heap, number_sorted) parent_value = heap[parent_index] valid = true l_child_i = left_child_index(parent_index) r_child_i = right_child_index(parent_index) if l_child_i < (heap.length - number_sorted) && heap[l_child_i] > heap[parent_index] valid = false end if r_child_i < (heap.length - number_sorted) && heap[r_child_i] > heap[parent_index] valid = false end return valid end def self.left_child_index(parent_index) return 2*parent_index + 1 end def self.right_child_index(parent_index) return 2*parent_index + 2 end end
module RailsParam module ErrorMessages class CannotBeLessThanMessage < RailsParam::ErrorMessages::BaseMessage def to_s "Parameter #{param_name} cannot be less than #{value}" end end end end
class TasksController < ApplicationController def new @task = Task.new end def create @project = Project.find(params[:article_id]) @task = @project.tasks.create(task_params) redirect_to project_path(@project) end private def task_params params.require(:task).permit(:title, :description) end end
require 'ffaker' require File.expand_path("#{APP_ROOT}/run/api", __FILE__) describe HomeApi do def app Api.new end before do @url_1 = FFaker::Internet.http_url end describe 'get /:key' do it '通过key获取链接' do get '/000001' expect(last_response.status).to eq 404 ShortUrl.create_short_url @url_1 get '/000001' expect(last_response.status).to eq 302 expect(last_response['Location']).to eq @url_1 end end end
module TLAW # Base parameter class for working with parameters validation and # converting. You'll never instantiate it directly, just see {DSL#param} # for parameters definition. # class Param # This error is thrown when some value could not be converted to what # this parameter inspects. For example: # # ```ruby # # definition: # param :timestamp, :to_time, format: :to_i # # this means: parameter, when passed, will first be converted with # # method #to_time, and then resulting time will be made into # # unix timestamp with #to_i before passing to API # # # usage: # my_endpoint(timestamp: Time.now) # ok # my_endpoint(timestamp: Date.today) # ok # my_endpoint(timestamp: '2016-06-01') # Nonconvertible! ...unless you've included ActiveSupport :) # ``` # Nonconvertible = Class.new(ArgumentError) def self.make(name, **options) # NB: Sic. :keyword is nil (not provided) should still # make a keyword argument. if options[:keyword] != false KeywordParam.new(name, **options) else ArgumentParam.new(name, **options) end end attr_reader :name, :type, :options def initialize(name, **options) @name = name @options = options @type = Type.parse(options) @options[:desc] ||= @options[:description] @options[:desc].gsub!(/\n( *)/, "\n ") if @options[:desc] @formatter = make_formatter end def required? options[:required] end def default options[:default] end def merge(**new_options) Param.make(name, @options.merge(new_options)) end def field options[:field] || name end def convert(value) type.convert(value) end def format(value) to_url_part(formatter.call(value)) end def convert_and_format(value) format(convert(value)) end alias_method :to_h, :options def description options[:desc] end def describe [ '@param', name, ("[#{doc_type}]" if doc_type), description, if @options[:enum] "\n Possible values: #{type.values.map(&:inspect).join(', ')}" end, ("(default = #{default.inspect})" if default) ].compact.join(' ') .derp(&Util::Description.method(:new)) end private attr_reader :formatter def doc_type type.to_doc_type end def to_url_part(value) case value when Array value.join(',') else value.to_s end end def make_formatter options[:format].derp { |f| return ->(v) { v } unless f return f.to_proc if f.respond_to?(:to_proc) fail ArgumentError, "#{self}: unsupporter formatter #{f}" } end def default_to_code # FIXME: this `inspect` will fail with, say, Time default.inspect end end # @private class ArgumentParam < Param def keyword? false end def to_code if required? name.to_s else "#{name}=#{default_to_code}" end end end # @private class KeywordParam < Param def keyword? true end def to_code if required? "#{name}:" else "#{name}: #{default_to_code}" end end end end require_relative 'param/type'
# Ingredients Controller class IngredientsController < ApplicationController helper_method :sort_column, :sort_direction # Authentication and Authorization hacks # before_action :authenticate_user! load_and_authorize_resource before_action :set_ingredient, only: [:show, :edit, :update, :destroy] # GET /ingredients # GET /ingredients.json def index @ingredients = Ingredient.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(per_page: 5, page: params[:page]) end # GET /ingredients/1 # GET /ingredients/1.json def show end # GET /ingredients/new def new @ingredient = Ingredient.new end # GET /ingredients/1/edit def edit end # POST /ingredients # POST /ingredients.json def create @ingredient = Ingredient.new(ingredient_params) respond_to do |format| if @ingredient.save format.html do redirect_to @ingredient, notice: 'Ingrediente criado com sucesso' end format.json { render :show, status: :created, location: @ingredient } else format.html { render :new } format.json do render json: @ingredient.errors, status: :unprocessable_entity end end end end # PATCH/PUT /ingredients/1 # PATCH/PUT /ingredients/1.json def update respond_to do |format| if @ingredient.update(ingredient_params) format.html do redirect_to @ingredient, notice: 'Ingrediente atualizado com sucesso' end format.json { render :show, status: :ok, location: @ingredient } else format.html { render :edit } format.json do render json: @ingredient.errors, status: :unprocessable_entity end end end end # DELETE /ingredients/1 # DELETE /ingredients/1.json def destroy @ingredient.destroy respond_to do |format| format.html do redirect_to ingredients_url, notice: 'Ingrediente excluído com sucesso' end format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_ingredient @ingredient = Ingredient.find(params[:id]) end # Never trust params from the scary net, only allow the white list through. def ingredient_params params.require(:ingredient).permit(:name, :description) end def sort_column Ingredient.column_names.include?(params[:sort]) ? params[:sort] : 'name' end def sort_direction %w(asc desc).include?(params[:direction]) ? params[:direction] : 'asc' end end
class LicenceController < ApplicationController include Previewable include Cacheable include Navigable before_action :set_content_item helper_method :postcode INVALID_POSTCODE = "invalidPostcodeFormat".freeze NO_LOCATION_ERROR = "validPostcodeNoLocation".freeze NO_MATCHING_AUTHORITY = "noLaMatch".freeze NO_MAPIT_MATCH = "fullPostcodeNoMapitMatch".freeze def start if @publication.continuation_link.present? render :continues_on elsif @licence_details.local_authority_specific? && postcode_search_submitted? @postcode = postcode @location_error = location_error redirect_to licence_authority_path(slug: params[:slug], authority_slug: local_authority_slug) if local_authority_slug elsif @licence_details.single_licence_authority_present? redirect_to licence_authority_path(slug: params[:slug], authority_slug: @licence_details.authority["slug"]) elsif @licence_details.multiple_licence_authorities_present? && authority_choice_submitted? redirect_to licence_authority_path(slug: params[:slug], authority_slug: CGI.escape(params[:authority][:slug])) end end def authority if @publication.continuation_link.present? redirect_to licence_path(slug: params[:slug]) elsif @licence_details.local_authority_specific? @licence_details = LicenceDetailsPresenter.new(licence_details_from_api_for_local_authority, params[:authority_slug], params[:interaction]) end end private def set_content_item super(LicencePresenter) @licence_details = LicenceDetailsPresenter.new(licence_details_from_api, params["authority_slug"], params[:interaction]) end def licence_details_from_api(snac = nil) return {} if @publication.continuation_link.present? begin GdsApi.licence_application.details_for_licence(@publication.licence_identifier, snac) rescue GdsApi::HTTPErrorResponse, GdsApi::TimedOutException {} end end def licence_details_from_api_for_local_authority raise RecordNotFound unless snac_from_slug licence_details_from_api(snac_from_slug) end def snac_from_slug @snac_from_slug ||= AuthorityLookup.find_snac_from_slug(params[:authority_slug]) end def postcode_search_submitted? params[:postcode] && request.post? end def authority_choice_submitted? params[:authority] && params[:authority][:slug] end def location_error return LocationError.new(NO_MAPIT_MATCH) if mapit_response.location_not_found? return LocationError.new(INVALID_POSTCODE) if mapit_response.invalid_postcode? || mapit_response.blank_postcode? return LocationError.new(NO_MATCHING_AUTHORITY) unless local_authority_slug end def mapit_response @mapit_response ||= location_from_mapit end def location_from_mapit if postcode.present? begin location = Frontend.mapit_api.location_for_postcode(postcode) rescue GdsApi::HTTPNotFound location = nil rescue GdsApi::HTTPClientError => e error = e end end MapitPostcodeResponse.new(postcode, location, error) end def local_authority_slug return nil unless mapit_response.location_found? @local_authority_slug ||= begin LocalAuthoritySlugFinder.call(mapit_response.location.areas, @licence_details.offered_by_county?) end end def postcode PostcodeSanitizer.sanitize(params[:postcode]) end end
require_relative '../grid' require 'test/unit' class TestCell < Test::Unit::TestCase def test_peers grid = Grid.new(4) grid.each_cell do | cell | assert_equal(7, cell.peers.count) end end def test_exclude cell = Cell.new(0, 0) assert_equal([], cell.excluded_values) cell.exclude(1) assert_equal([1], cell.excluded_values) cell.exclude(2) assert_equal([1,2], cell.excluded_values) cell.exclude(1) assert_equal([1, 2], cell.excluded_values) end def test_exclude_from_peers_when_setting grid = Grid.new(2) grid[0, 0].value = 1 grid[0, 0].peers.each do |cell| assert_equal([1], cell.excluded_values) end end end
require "rails_helper" describe "routes for repos" do it "routes GET /repo/foo.bar to the repositories controller" do expect(get("/repo/foo.bar")).to route_to( controller: "repositories", action: "show", repo: "foo.bar" ) end end describe "routes redirect for repos", type: :request do it "routes GET /foo.bar to the tags controller" do expect(get("/foo.bar")).to redirect_to('/repo/foo.bar') end end
require 'rails_helper' RSpec.describe Comment, type: :model do # let(:my_user) { create(:user, confirmed_at: DateTime.now) } # let(:my_cat) { create(:category) } # let(:my_post) { create(:post, category: my_cat, user: my_user ) } # let(:my_comment) { create(:comment, post: my_post, user: my_user ) } # # let(:comment) { Comment.create!(body: 'Comment Body', post: post, user: user) } # it { is_expected.to belong_to(:my_post) } # it { is_expected.to belong_to(:my_user) } # # it { is_expected.to validate_presence_of(:body) } # # it { is_expected.to validate_length_of(:body).is_at_least(5) } # describe "attributes" do # it "has a body attribute" do # expect(comment).to have_attributes(body: "Comment Body") # end # end # describe "after_create" do # before do # @another_comment = Comment.new(body: 'Comment Body', post: post, user: user) # end # it "sends an email to users who have favorited the post" do # favorite = user.favorites.create(post: post) # expect(FavoriteMailer).to receive(:new_comment).with(user, post, @another_comment).and_return(double(deliver_now: true)) # @another_comment.save! # end # it "does not send emails to users who haven't favorited the post" do # expect(FavoriteMailer).not_to receive(:new_comment) # @another_comment.save! # end # end end
class BuildHistoriesController < ApplicationController include SetBuildHistories protect_api only: :create before_action :find_scenario, only: %i[index create] before_action :find_build_history, except: %i[index create] before_action :set_scenario, except: %i[index create] before_action :set_project def index set_build_histories end def show end def create max_no = @scenario.build_histories.maximum('build_no') build_no = max_no.nil? ? 1 : max_no + 1 @created_build_histories = params[:devices].map.with_index(1) do |device, i| build_history = @scenario.build_histories.build build_history.build_sequence_code = params[:build_sequence_code] || @project.default_build_sequence_code build_history.branch_no = i build_history.build_no = build_no build_history.device = device build_history.transaction do build_history.populate_steps! end build_history end respond_to do |format| format.js do set_build_histories render 'index' end format.json end end private def find_scenario @scenario = Scenario.find(params[:scenario_id]) end def find_build_history @build_history = BuildHistory.find(params[:id]) end def set_scenario @scenario = @build_history.scenario end def set_project @project = @scenario.project end end
module ApplicationHelper include Pagy::Frontend def pagy_govuk_nav(pagy) render "pagy/paginator", pagy: pagy end def markdown(source) render = Govuk::MarkdownRenderer # Options: https://github.com/vmg/redcarpet#and-its-like-really-simple-to-use # lax_spacing: HTML blocks do not require to be surrounded by an empty line as in the Markdown standard. # autolink: parse links even when they are not enclosed in <> characters options = { autolink: true, lax_spacing: true } markdown = Redcarpet::Markdown.new(render, options) markdown.render(source).html_safe # Convert quotes to smart quotes source_with_smart_quotes = smart_quotes(source) markdown.render(source_with_smart_quotes).html_safe end def smart_quotes(string) return "" if string.blank? RubyPants.new(string, [2, :dashes], ruby_pants_options).to_html end def enrichment_error_link(model, field, error) href = case model when :course enrichment_error_url( provider_code: @provider.provider_code, course: @course, field: field.to_s, message: error, ) when :provider provider_enrichment_error_url( provider: @provider, field: field.to_s, ) end govuk_inset_text(classes: "app-inset-text--narrow-border app-inset-text--error") do govuk_link_to(error, href) end end def enrichment_summary(model, key, value, fields, truncate_value: true, change_link: nil, change_link_visually_hidden: nil) action = render_change_link(change_link, change_link_visually_hidden) if fields.select { |field| @errors&.key? field.to_sym }.any? errors = fields.map { |field| @errors[field.to_sym]&.map { |error| enrichment_error_link(model, field, error) } }.flatten value = raw(*errors) action = nil elsif truncate_value classes = "app-summary-list__row--truncate" end if value.blank? value = raw("<span class=\"app-!-colour-muted\">Empty</span>") end { key: key.html_safe, value: value, classes: classes, html_attributes: { data: { qa: "enrichment__#{fields.first}", }, }, action: action, } end private def render_change_link(path, visually_hidden) return if path.blank? govuk_link_to(path) do raw("Change<span class=\"govuk-visually-hidden\"> #{visually_hidden}</span>") end end # Use characters rather than HTML entities for smart quotes this matches how # we write smart quotes in templates and allows us to use them in <title> # elements # https://github.com/jmcnevin/rubypants/blob/master/lib/rubypants.rb def ruby_pants_options { double_left_quote: "“", double_right_quote: "”", single_left_quote: "‘", single_right_quote: "’", ellipsis: "…", em_dash: "—", en_dash: "–", } end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.require_version ">= 1.8.4" vm_hostname = "nodejs.mycompany.local" Vagrant.configure("2") do |config| config.vm.box = "server4001/nodejs-mysql-centos" config.vm.box_version = "0.1.0" config.vm.network :private_network, ip: "10.20.0.92" config.vm.hostname = "#{vm_hostname}" config.vm.synced_folder "./", "/vagrant", mount_options: ["dmode=777,fmode=777"] config.vm.provision :ansible_local do |ansible| ansible.playbook = "nodejs.yml" ansible.provisioning_path = "/vagrant/provisioners/ansible" ansible.install = false ansible.verbose = true ansible.extra_vars = { vm_hostname: "#{vm_hostname}", } end config.vm.provider "virtualbox" do |vb| vb.customize ["modifyvm", :id, "--cpuexecutioncap", "90"] vb.customize ["modifyvm", :id, "--memory", "1024"] vb.customize ["modifyvm", :id, "--cpus", "2"] vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"] end end
require "rails_helper" describe MarkPatientMobileNumbers, type: :model do it "marks non-mobile patient phone numbers as mobile" do mobile_number = create(:patient_phone_number, phone_type: "mobile") non_mobile_number = create(:patient_phone_number, phone_type: "landline") nil_type_number = create(:patient_phone_number, phone_type: nil) Flipper.enable(:force_mark_patient_mobile_numbers) MarkPatientMobileNumbers.call expect(mobile_number.reload.phone_type).to eq("mobile") expect(non_mobile_number.reload.phone_type).to eq("mobile") expect(nil_type_number.reload.phone_type).to eq("mobile") Flipper.disable(:force_mark_patient_mobile_numbers) end it "doesn't touch mobile numbers" do mobile_number = create(:patient_phone_number, phone_type: "mobile") Flipper.enable(:force_mark_patient_mobile_numbers) expect { MarkPatientMobileNumbers.call }.not_to change { mobile_number.reload.updated_at } Flipper.disable(:force_mark_patient_mobile_numbers) end it "does nothing if feature flag is not set" do non_mobile_number = create(:patient_phone_number, phone_type: "landline") nil_type_number = create(:patient_phone_number, phone_type: nil) MarkPatientMobileNumbers.call expect(non_mobile_number.reload.phone_type).to eq("landline") expect(nil_type_number.reload.phone_type).to eq(nil) end end
# frozen_string_literal: true require 'forwardable' module Apartment # The main entry point to Apartment functions # module Tenant extend self extend Forwardable def_delegators :adapter, :create, :drop, :switch, :switch!, :current, :each, :reset, :init, :set_callback, :seed, :default_tenant, :environmentify attr_writer :config # Fetch the proper multi-tenant adapter based on Rails config # # @return {subclass of Apartment::AbstractAdapter} # def adapter Thread.current[:apartment_adapter] ||= begin adapter_method = "#{config[:adapter]}_adapter" if defined?(JRUBY_VERSION) case config[:adapter] when /mysql/ adapter_method = 'jdbc_mysql_adapter' when /postgresql/ adapter_method = 'jdbc_postgresql_adapter' end end begin require "apartment/adapters/#{adapter_method}" rescue LoadError raise "The adapter `#{adapter_method}` is not yet supported" end unless respond_to?(adapter_method) raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter" end send(adapter_method, config) end end # Reset config and adapter so they are regenerated # def reload!(config = nil) Thread.current[:apartment_adapter] = nil @config = config end private # Fetch the rails database configuration # def config @config ||= Apartment.connection_config end end end
module Misspelling class Cli def initialize @options = {} end def run(args = ARGV) options = Misspelling::Options.new.parse(args) runner = Misspelling::Runner.new(options: options) runner.start runner.show_result end end end
require 'spec_helper' describe "email_templates/edit" do before(:each) do @email_template = assign(:email_template, stub_model(EmailTemplate, :name => "MyString", :language => "MyString", :content => "MyText" )) end it "renders the edit email_template form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => email_templates_path(@email_template), :method => "post" do assert_select "input#email_template_name", :name => "email_template[name]" assert_select "input#email_template_language", :name => "email_template[language]" assert_select "textarea#email_template_content", :name => "email_template[content]" end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Member.destroy_all Post.destroy_all Member.create({ name: 'Caitlin Connors', job: 'CEO', bio: 'Caitlin started her marketing career at a fashion studio in Barcelona Spain for a year during college. She then moved onto Search Engine Marketing (SEM) at Mindshare, a WPP company, where she was responsible for the optimization and analytics reporting of a multi-million dollar pharmaceutical account. Caitlin then moved to Sub Rosa, a boutique branding and experiential agency where she worked on branding and experiential campaigns for Levis, GE, Nike, and Pantone. Caitlin then began freelance digital marketing consulting until eventually forming Fox Den Digital.', img: 'http://caitlinconnors.com/images/caitlin/caitlin-connors.jpg', contact: 'linkedin, instagram, twitter', admin: true }) Member.create({ name: 'Emily Connors', job: 'Web Developer', bio: 'Flexitarian tote bag letterpress cray ennui, street art Brooklyn you probably havent heard of them fap fanny pack fingerstache food truck twee farm-to-table cronut. Wes Anderson food truck roof party, meggings sartorial raw denim keffiyeh four loko taxidermy bespoke actually. VHS viral fanny pack, cronut mlkshk Etsy Helvetica cliche art party Neutra tousled migas meditation you probably havent heard of them banjo. Quinoa vegan pop-up, yr normcore pug gentrify roof party. Kitsch Williamsburg brunch, stumptown narwhal slow-carb trust fund taxidermy McSweeneys fanny pack. Dreamcatcher deep v Williamsburg, beard flannel twee tilde cold-pressed. Four loko Shoreditch lomo +1 art party wolf.', img: 'http://ejconnors0427.files.wordpress.com/2014/05/me.jpg?w=230&h=300', contact: 'linkedin, instagram, twitter', admin: true }) Member.create({ name: 'Daisy', job: 'Poject Manager', bio: 'Flexitarian tote bag letterpress cray ennui, street art Brooklyn you probably havent heard of them fap fanny pack fingerstache food truck twee farm-to-table cronut. Wes Anderson food truck roof party, meggings sartorial raw denim keffiyeh four loko taxidermy bespoke actually. VHS viral fanny pack, cronut mlkshk Etsy Helvetica cliche art party Neutra tousled migas meditation you probably havent heard of them banjo. Quinoa vegan pop-up, yr normcore pug gentrify roof party. Kitsch Williamsburg brunch, stumptown narwhal slow-carb trust fund taxidermy McSweeneys fanny pack. Dreamcatcher deep v Williamsburg, beard flannel twee tilde cold-pressed. Four loko Shoreditch lomo +1 art party wolf.', img: 'http://ejconnors0427.files.wordpress.com/2014/05/me.jpg?w=230&h=300', contact: 'linkedin, instagram, twitter', admin: true }) Post.create({ title: 'Test Post 1', content: 'ipsum ipsum ipsum', likes: 5, member_id: 1, img: 'http://caitlinconnors.com/images/caitlin/caitlin-connors.jpg' }) Post.create({ title: 'Test Post 2', content: 'ipsum ipsum ipsum', likes: 5, member_id: 3, img: 'http://ejconnors0427.files.wordpress.com/2014/05/me.jpg?w=230&h=300' })
class ExpectedCalls attr_reader :calls, :executed_calls def initialize @calls = [] @executed_calls = [] @validate = [Proc.new{@current_call.count > 0}] end def add_call(call) @calls.push(@current_call = call) self end def with_params(*args) @current_call.params = args self end def once @validate.push(Proc.new{@current_call.count == 1}) self end def validate? @validate.inject(true){|x , block| x and block.yield} end def check_call(calling_method) @executed_calls.push calling_method if @current_call.eql? calling_method @current_call.count_call end end def check_in_order @validate.push(Proc.new{@calls.eql? @executed_calls} ) end end
require 'spec_helper' describe RemoteImageSearchResultSerializer do let(:image_model) { RemoteImage.new } it 'exposes the attributes to be jsonified' do serialized = described_class.new(image_model).as_json expected = [:source, :description, :is_official, :is_trusted, :star_count, :registry_id, :registry_name] expect(serialized.keys).to match_array expected end end
class UserSerializer < ActiveModel::Serializer attributes :id, :username, :password, :first_name, :last_name has_many :tags has_many :favorites has_many :favorite_tags, through: :tags has_many :destinations, through: :favorites end