text
stringlengths
10
2.61M
# frozen_string_literal: true class Balance include ActiveModel::Model Wrapper = Struct.new(:user, :balance, :pending_balance, :created_at) do include ActiveModel::Serialization end def initialize(user) @user = user end def pending_debt Money.new( BalanceQuery.new(user).pending_balances .merge(all_balances) { |_, pending, balance| pending + balance } .select { |_, balance| balance < 0 } .sum { |_, balance| balance }, 'PLN' ) end def pending_balance_for(other_user) Money.new(BalanceQuery.new(user).pending_balances[other_user.id], 'PLN') end # returns the total account debt for user def total_debt Money.new(all_debts.sum { |_, debt| debt }, 'PLN') end # returns the current balance between user and other def balance_for(other_user) Money.new(all_balances[other_user.id], 'PLN') end # returns a list of all debts and credits for user and other def payments_for(_other_user) fail NotImplementedError end # rubocop:disable Metrics/MethodLength def build_wrapper(other_user) last_paid = payments_as_payer.where(user: other_user).first last_received = payments_as_beneficiary.where(payer: other_user).first created_at = [ last_paid&.created_at || Time.new(0), last_received&.created_at || Time.new(0), ].max Wrapper.new( other_user, balance_for(other_user), pending_balance_for(other_user), created_at, ) end # rubocop:enable Metrics/MethodLength private attr_reader :user def pending_transfers @pending_transfers ||= Transfer .where(from_id: user.id, status: :pending) .group('to_id') .pluck('to_id, SUM(amount_cents)') .to_h end def all_balances @all_balances ||= PaymentQuery.new(user).balances .merge(pending_transfers) { |_, balance, transfer| balance + transfer } end def all_debts PaymentQuery.new(user).debts .merge(pending_transfers) { |_, debt, transfer| debt + transfer } .select { |_, balance| balance < 0 } end def payments_as_beneficiary @payments_as_beneficiary ||= Payment.newest_first.where(user: user) end def payments_as_payer @payments_as_payer ||= Payment.newest_first.where(payer: user) end end
class CreateTransactions < ActiveRecord::Migration[5.1] def change create_table :transactions do |t| t.references :event t.references :attendee t.integer :status_after t.integer :status_before t.timestamps end end end
class ApplicationController < ActionController::Base # around_action :switch_locale def switch_locale(&action) locale = user_signed_in? ? current_user.configuration.locale : 'en' I18n.with_locale(locale, &action) end rescue_from CanCan::AccessDenied do |exception| flash[:notice] = 'You are unauthorized to access to specific page' redirect_to root_path end end
module JsonSpec module Exclusion extend self def exclude_keys(ruby) case ruby when Hash ruby.sort.inject({}) do |hash, (key, value)| hash[key] = exclude_key?(key) ? 1 : exclude_keys(value) hash end when Array ruby.map{|v| exclude_keys(v) } else ruby end end def exclude_key?(key) excluded_keys.include?(key) end def excluded_keys @excluded_keys ||= Set.new(JsonSpec.excluded_keys) end end end
class RequirementSeverity < ActiveRecord::Base has_many :requirements validates_presence_of :code, :name validates_uniqueness_of :code, :name end
require "json" require "selenium-webdriver" require "test/unit" class LogIn < Test::Unit::TestCase def setup @driver = Selenium::WebDriver.for :chrome @base_url = "https://staging.shore.com/merchant/bookings" @accept_next_alert = true @driver.manage.timeouts.implicit_wait = 30 @verification_errors = [] end def teardown @driver.quit() assert_equal [], @verification_errors end def test_booking_request_payment_accept target_size = Selenium::WebDriver::Dimension.new(1420, 940) @driver.manage.window.size = target_size #check bookingrules if request is enable or not @driver.get "https://staging.shore.com/merchant/sign_in" @driver.find_element(:id, "merchant_account_email").clear @driver.find_element(:id, "merchant_account_email").send_keys "js@shore.com" @driver.find_element(:id, "merchant_account_password").clear @driver.find_element(:id, "merchant_account_password").send_keys "secret" @driver.find_element(:name, "button").click @driver.get "https://staging.shore.com/merchant/bookings" checkbox = @driver.find_element(:css, "input#merchant_profile_direct_bookable.boolean.optional"); if checkbox.selected? checkbox.click end @driver.find_element(:css, "input.btn-blue").click sleep 1 # set payment optional @driver.get "https://staging.shore.com/merchant/bookings" @driver.find_element(:css, "#merchant_profile_config_attributes_customer_payment_chosen > a").click @driver.find_element(:css, "ul.chosen-results > li:nth-of-type(2)").click @driver.find_element(:css, "#edit_merchant_profile_3 > div.tile-footer > input").click #book appointment with payment @driver.get "https://staging-connect.shore.com/widget/endeavourdude?locale=de" @driver.find_element(:css, "div.item-group-title").click sleep 1 @driver.find_element(:css, "div.item-content").click sleep 1 @driver.find_element(:css, "button.widget-button.services-submit-button").click sleep 1 verify { assert_include @driver.find_element(:css, "div.services-row-price.flex-cell.text-right").text, "55,00" } verify { assert_include @driver.find_element(:css, "div.total-row.flex-row > div.total-row-price.flex-cell.text-right").text, "60,50" } @driver.find_element(:css, "div.item-content.with-icons").click sleep 1 @driver.find_element(:css, "#resourceStep > div.step-content-wrapper > div.step-footer > button.widget-button.services-submit-button").click sleep 5 @driver.find_element(:css, "div.jspPane > div:nth-of-type(5) > div:nth-of-type(1)").click sleep 1 @driver.find_element(:css, "#timeslotStep > div.step-content-wrapper > div.step-footer > button.widget-button.services-submit-button").click sleep 1 @driver.find_element(:css, "select#gender.ember-view.ember-select.form-control").click sleep 1 @driver.find_element(:css, "input#first-name.ember-view.ember-text-field.form-control").send_keys "Lindsey" @driver.find_element(:css, "input#last-name.ember-view.ember-text-field.form-control").send_keys "James" @driver.find_element(:css, "input#email.ember-view.ember-text-field.form-control").send_keys "js+lin@shore.com" @driver.find_element(:css, "input#mobile.ember-view.ember-text-field.phonable.form-control").send_keys "666666666666" @driver.find_element(:css, "input#addressStreet.ember-view.ember-text-field.form-control").send_keys "Masterroad" @driver.find_element(:css, "input#addressPostalCode.ember-view.ember-text-field.form-control").send_keys "8000" @driver.find_element(:css, "input#addressCity.ember-view.ember-text-field.form-control").send_keys "Minga" @driver.find_element(:css, "input#customer-custom_attribute-89.ember-view.ember-text-field.form-control").send_keys "At home" @driver.find_element(:css, "input#special-wishes.ember-view.ember-text-field.form-control").send_keys "keine" @driver.find_element(:id, "pmcc").click @driver.find_element(:css, "input#ccnum.ember-view.ember-text-field.form-control").send_keys "4242 4242 4242 4242" @driver.find_element(:css, "input#cc_holder.ember-view.ember-text-field.form-control").send_keys "The Dude" Selenium::WebDriver::Support::Select.new(@driver.find_element(:id, "exp-month")).select_by(:text, "12") Selenium::WebDriver::Support::Select.new(@driver.find_element(:id, "exp-year")).select_by(:text, "2026") @driver.find_element(:id, "cc-cvc").send_keys "121" @driver.find_element(:css, "div.form-container.data > div.action-row.step-footer > button.widget-button.widget-button-submit").click sleep 3 verify { assert_equal "Ihre Terminanfrage wurde übermittelt.", @driver.find_element(:css, "h5.status-headline").text } #check payment status @driver.get "https://staging.shore.com/merchant/app/payments" verify { assert_include @driver.find_element(:css, "tbody.mtw-rows > tr:nth-of-type(1) > td:nth-of-type(6) > div.mtw-column-charge-status > span").text, "Autorisiert" } #accept request @driver.get "https://staging.shore.com/merchant/appointments/weekly" @driver.find_element(:css, "button.btn.dropdown-toggle.mnw-btn-default.mnw-appointments > i.shore-icon-backend-nav-appointments").click sleep 3 @driver.find_element(:css, "div.mnw-headline.mnw-one-liner").click @driver.find_element(:css, "div.actions-template > button.btn.btn-primary").click #check status payment @driver.get "https://staging.shore.com/merchant/app/payments" verify { assert_include @driver.find_element(:css, "tbody.mtw-rows > tr:nth-of-type(1) > td:nth-of-type(6) > div.mtw-column-charge-status > span").text, "Erfolgreich" } end def verify(&blk) yield rescue Test::Unit::AssertionFailedError => ex @driver.quit() @verification_errors << ex end end
# Uncomment this if you reference any of your controllers in activate # require_dependency 'application' class AdvancedTaxonExtension < Spree::Extension version "0.1" description "Adds an opportunity to attach a picture and description for the taxon." url "http://yourwebsite.com/extended_taxon" # Please use extended_taxon/config/routes.rb instead for extension routes. # def self.require_gems(config) # config.gem "gemname-goes-here", :version => '1.2.3' # end def activate Admin::TaxonsController.class_eval do def adv_edit load_object unless request.get? if @taxon.update_attributes(params[:taxon]) flash[:notice] = t('advanced_taxon.succesfully_updated') redirect_to edit_admin_taxonomy_url(@taxon.taxonomy) end end end end Taxon.class_eval do validates_presence_of :name has_attached_file :icon, :styles => { :mini => '32x32>', :normal => '128x128>' }, :default_style => :mini, :url => "/assets/taxons/:id/:style/:basename.:extension", :path => ":rails_root/public/assets/taxons/:id/:style/:basename.:extension", :default_url => "/images/default_taxon.png" end # Add your extension tab to the admin. # Requires that you have defined an admin controller: # app/controllers/admin/yourextension_controller # and that you mapped your admin in config/routes #Admin::BaseController.class_eval do # before_filter :add_yourextension_tab # # def add_yourextension_tab # # add_extension_admin_tab takes an array containing the same arguments expected # # by the tab helper method: # # [ :extension_name, { :label => "Your Extension", :route => "/some/non/standard/route" } ] # add_extension_admin_tab [ :yourextension ] # end #end # make your helper avaliable in all views # Spree::BaseController.class_eval do # helper YourHelper # end end end
class PartePagamentosController < ApplicationController before_action :set_parte_pagamento, only: [:show, :edit, :update, :destroy] # GET /parte_pagamentos # GET /parte_pagamentos.json def index @parte_pagamentos = PartePagamento.all end # GET /parte_pagamentos/1 # GET /parte_pagamentos/1.json def show end # GET /parte_pagamentos/new def new @parte_pagamento = PartePagamento.new end # GET /parte_pagamentos/1/edit def edit end # POST /parte_pagamentos # POST /parte_pagamentos.json def create @parte_pagamento = PartePagamento.new(parte_pagamento_params) respond_to do |format| if @parte_pagamento.save format.html { redirect_to @parte_pagamento, notice: t('message.create_success') } format.json { render :show, status: :created, location: @parte_pagamento } else format.html { render :new } format.json { render json: @parte_pagamento.errors, status: :unprocessable_entity } end end end # PATCH/PUT /parte_pagamentos/1 # PATCH/PUT /parte_pagamentos/1.json def update respond_to do |format| if @parte_pagamento.update(parte_pagamento_params) format.html { redirect_to @parte_pagamento, notice: t('message.update_success') } format.json { render :show, status: :ok, location: @parte_pagamento } else format.html { render :edit } format.json { render json: @parte_pagamento.errors, status: :unprocessable_entity } end end end # DELETE /parte_pagamentos/1 # DELETE /parte_pagamentos/1.json def destroy @parte_pagamento.destroy respond_to do |format| format.html { redirect_to parte_pagamentos_url, notice: t('message.destroy_success') } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_parte_pagamento @parte_pagamento = PartePagamento.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def parte_pagamento_params params.require(:parte_pagamento).permit(:quantia, :forma_pagamento_id, :venda_id, :compra_id) end end
class Item < ApplicationRecord with_options presence: true do validates :title validates :price validates :content validates :images end has_many_attached :images belongs_to :user has_many :comments, dependent: :destroy has_one :order end
class AddVariablesToScrambles < ActiveRecord::Migration def change add_column :scrambles, :currentDiscountStatus, :string add_column :scrambles, :totalBids, :integer add_column :scrambles, :nextMilestone, :string add_column :scrambles, :bidsUntilNextMilestone, :integer add_column :scrambles, :availableItems, :integer add_column :scrambles, :currentPrice, :decimal end end
class ProblemsController < ApplicationController include ApplicationHelper before_action :check_is_admin, except: [:index, :show] before_action :set_problem, only: [:show, :edit, :update, :destroy] def index @problems = Problem.all if params.has_key?(:origin_id) @problems = Origin.find(params[:origin_id]).problems.all end end def show end def new @problem = Problem.new end def edit end def create @user = User.find(current_user.id) @problem = @user.problems.create(problem_params) respond_to do |format| if @problem.save flash[:success] = "문제가 성공적으로 만들어 졌습니다." format.html { render :show } else flash[:error] = "부족한 곳을 채워주세요" format.html { render :new } format.json { render json: @problem.errors } end end end def update respond_to do |format| if @problem.update(problem_params) flash[:success] = "문제가 성공적으로 업데이트 되었습니다." format.html { render :show} else flash[:error] = "부족한 곳을 채워주세요" format.html { render :new} format.json { render json: @problem.errors } end end end def destroy if @problem.destroy respond_to do |format| format.html { redirect_to :show, notice: 'Post was successfully destroyed.' } end else respond_to do |format| format.html { redirect_to :back, error: 'failed destroy' } end end end private def set_problem @problem = Problem.find(params[:id]) if @problem.publish == 0 unless user_signed_in? and current_user.has_role? :admin redirect_to root_path end end end def problem_params params.require(:problem).permit(:title, :origin_id, :timelimit, :memorylimit, :special, :publish, :description, :input, :output) end end
Rails.application.routes.draw do devise_for :users root to: 'pages#home' resources :matches, only: [:index, :show] do resources :bookings, only: [:create] end resources :bookings, only: [:destroy] resources :seats, only: [:new, :create, :show] do end get 'dashboard', to: 'pages#dashboard' # get 'matches', to: 'match#index' # get 'matches/:id', to: 'match#show' # get 'matches/new', to: 'match#new' # post 'matches', to: 'match#create' # get 'matches/:id/match_tickets', to: 'match_tickets#index' # get 'matches/:id/match_tickets/:match_ticket_id', to: 'match_tickets#show' # get 'matches/:id/match_tickets/new', to: 'match_ticket#new' # post 'matches/:id/match_tickets', to: 'match_ticket#create' # get 'users/:id', to: 'user#show' # get 'users/:id/seats/new', to: 'seat#new' # post 'users/:id/seats', to: 'seat#create' # get 'users/:id/bookings/new', to: 'bookings#new' # post 'users/:id/bookings/create', to: 'bookings#create' # get 'matches/:id/match_tickets/:match_ticket_id/bookings/new', to: 'bookings#new' # post 'matches/:id/match_tickets/:match_ticket_id/bookings', to: 'bookings#create' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 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 bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # Testing data # Creating coins # coin_a = Coin.create(coin_api_id: "bitgesell", name: "Bitgesell", symbol: "bgl") # coin_b = Coin.create(coin_api_id: "bitget-defi-token", name: "Bitget DeFi Token", symbol: "bft") # coin_c = Coin.create(coin_api_id: "bitgrin", name: "BitGrin", symbol: "xbg") # coin_d = Coin.create(coin_api_id: "bitguild", name: "BitGuild PLAT", symbol: "plat") # coin_e = Coin.create(coin_api_id: "bithachi", name: "Bithachi", symbol: "bith") # # # Creating watchlists watchlist_a = Watchlist.create(name: "Top 20", description: "Top 20 coins by market cap") watchlist_b = Watchlist.create(name: "Most searched", description: "Most searched coins in the last 24hrs") # # # Creating watchlist_coins # watchlist_coins_a = WatchlistCoin.create(coin: coin_a, watchlist: watchlist_a) # watchlist_coins_b = WatchlistCoin.create(coin: coin_b, watchlist: watchlist_b) # watchlist_coins_c = WatchlistCoin.create(coin: coin_c, watchlist: watchlist_a) # watchlist_coins_d = WatchlistCoin.create(coin: coin_d, watchlist: watchlist_b) # watchlist_coins_e = WatchlistCoin.create(coin: coin_e, watchlist: watchlist_a) # watchlist_coins_f = WatchlistCoin.create(coin: coin_a, watchlist: watchlist_b) # Seed all coins from Coin Gecko API and create coin objects. require 'net/http' url = "https://api.coingecko.com/api/v3/coins/list?include_platform=false" request = URI.parse(url) response = Net::HTTP.get_response(request) crypto_hash = JSON.parse(response.body) crypto_hash.each do |crypto_object| Coin.find_or_create_by(coin_api_id: crypto_object['id'], name: crypto_object['name'], symbol: crypto_object['symbol']) end
module Awesome module Definitions module Stopwords QUOTED_REGEX = /("[^"]*")/ UNQUOTED_REGEX = /"([^"]*)"/ RM_QUOTED_REGEX = /"[^"]*"/ BEG_OPERATORS = /^[+-]/ END_OPERATORS = /[,+-]$/ EXCLUSION_OPERATORS = /^[-]/ INCLUSION_OPERATORS = /^[+]/ def self.included(base) base.extend ClassMethods base.cattr_accessor :search_stopwords base.cattr_accessor :verbose_stopwords end module ClassMethods def stopwords(key = :none) case key when :none then self.search_stopwords[:none] when :standard then self.search_stopwords[:standard] when :custom then self.search_stopwords[:custom] when :both then self.search_stopwords[:custom] | self.search_stopwords[:standard] else Rails.logger.warn("AwesomeSearch: Stopwords Key Invalid, defaulting to :both") self.search_stopwords[:custom] | self.search_stopwords[:standard] end end end #Instance Methods: #remove the stopwords from regular search terms, BUT NOT from exact phrase searches (quoted) #example: # txt = "+hair \"in the\" on the grapes, \"middle fork\" wrath \"age of man\" -end" def process_stopwords(txt = self.search_text) #Needs to be set so highlighting will work properly (can't match quotes) self.highlight_token_array(txt) #Now put humpty dumpty back together without the nasty stopwords, sort the tokens by length self.search_token_array(txt).join(" ") end def search_token_array(txt) self.search_tokens ||= (self.quoted_exact_phrases_array(txt) | self.gowords_array(txt)).sort {|a,b| b.length <=> a.length } end def highlight_token_array(txt) self.highlight_tokens ||= begin array = (self.unquoted_exact_phrases_array(txt) | self.gowords_array(txt)).sort {|a,b| b.length <=> a.length } remove_exclusions(array) end end def set_clean_search_query self.clean_search_query = self.highlight_tokens.join(" ") end def remove_exclusions(array) array.map do |tok| tok.match(Awesome::Definitions::Stopwords::EXCLUSION_OPERATORS) ? nil : tok.match(Awesome::Definitions::Stopwords::RM_QUOTED_REGEX) ? tok : tok.gsub(Awesome::Definitions::Stopwords::INCLUSION_OPERATORS, '') end.compact end #All tokens that are quoted def tokenize_quot(txt) self.tokenize_quoted ||= txt.split(Awesome::Definitions::Stopwords::QUOTED_REGEX) end #All tokens that are quoted, in their unquoted form def tokenize_unquot(txt) self.tokenize_unquoted ||= txt.split(Awesome::Definitions::Stopwords::UNQUOTED_REGEX) end #Remove all tokens that are quoted def tokenize_without_quot(txt) self.tokenize_without_quoted ||= txt.split(Awesome::Definitions::Stopwords::RM_QUOTED_REGEX) end # ["\"in the\"", "\"middle fork\"", "\"age of man\""] def quoted_exact_phrases_array(txt) self.quoted_exact_phrases ||= self.tokenize_quot(txt) - self.tokenize_without_quot(txt) - [''] end # ["in the", "middle fork", "age of man"] def unquoted_exact_phrases_array(txt) self.unquoted_exact_phrases ||= self.tokenize_unquot(txt) - self.tokenize_without_quot(txt) - [''] end # "+hair on the grapes, wrath -end" def query_wo_exact_phrases(txt) self.query_without_exact_phrases ||= txt.gsub(Awesome::Definitions::Stopwords::QUOTED_REGEX, '') end # ["+hair", "on", "the", "grapes,", "wrath", "-end"] def array_with_stopwords(txt) qa = self.query_wo_exact_phrases(txt).split qa.delete(',') #delete works on self (qa here), so won't work chained onto the statement above! qa end # ["+hair", "grapes,", "wrath", "-end"] def gowords_array(txt) self.gowords ||= self.array_with_stopwords(txt).map do |token| cleaned_token = self.clean_token(token) self.stopwords.include?(cleaned_token) ? nil : cleaned_token.blank? ? nil : token end.compact end def clean_token(token) token.gsub(Awesome::Definitions::Stopwords::BEG_OPERATORS, '').gsub(Awesome::Definitions::Stopwords::END_OPERATORS, '') end end end end
class AddSpreeProductAdditionalInstructionsPosition < ActiveRecord::Migration def change add_column :spree_product_additional_instructions, :position, :integer end end
class FeedPostSubject < ActiveRecord::Base has_one :notification, as: :subject belongs_to :poster, class_name: "User" delegate :name, to: :poster, prefix: true validates :user_id, :poster_id, presence: true end
class PomodorosController < ApplicationController before_action :set_pomodoro, only: [:show, :update, :destroy] # GET /pomodoros # GET /pomodoros.json def index @pomodoros = Pomodoro.all render json: @pomodoros end # GET /pomodoros/1 # GET /pomodoros/1.json def show render json: @pomodoro end # POST /pomodoros # POST /pomodoros.json def create @pomodoro = Pomodoro.new(pomodoro_params) id = "" request_url = request.env["HTTP_REFERER"] array = request_url.split('/') id = array[-3] to_do = ToDo.find(id.to_i) @pomodoro.to_do = to_do if @pomodoro.save render json: @pomodoro, status: :created, location: @pomodoro else render json: @pomodoro.errors, status: :unprocessable_entity end end # PATCH/PUT /pomodoros/1 # PATCH/PUT /pomodoros/1.json def update @pomodoro = Pomodoro.find(params[:id]) if @pomodoro.update(pomodoro_params) head :no_content else render json: @pomodoro.errors, status: :unprocessable_entity end end # DELETE /pomodoros/1 # DELETE /pomodoros/1.json def destroy @pomodoro.destroy head :no_content end private def set_pomodoro @pomodoro = Pomodoro.find(params[:id]) end def pomodoro_params params.require(:pomodoro).permit(:task, :to_do_id) end end
require 'spec_helper' require_relative '../../../lib/sucker_punch/testing/inline' class PatchedWorker include SuckerPunch::Worker def perform "do stuff" end end SuckerPunch::Queue.new(:patched_queue).register(PatchedWorker, 2) describe "SuckerPunch Inline Testing" do let(:queue) { SuckerPunch::Queue.new(:patched_queue) } it "processes jobs inline" do job = queue.async.perform expect(job).to eq "do stuff" end end
class UsersController < ApplicationController before_filter :require_login, :only => ['show', 'settings'] def show @user_id = current_user.id puts current_user.inspect @user = current_user.get_full_info @friends = current_user.get_friends @groups = current_user.groups @transactions = current_user.transactions end def create if params[:error] flash[:error] = "Please allow Boosted Payments to use Venmo on your behalf" return redirect_to :controller => :welcome, :action => :index end user_json = JSON.parse(RestClient.post('https://api.venmo.com/v1/oauth/access_token', 'client_id' => 1843, 'client_secret' => "9wgWKHkzY5pLdcAbwJq3wqy7uEAFHzaR", 'code' => params[:code])) if User.exists?(:venmo_id => user_json['user']['id']) user = User.where(venmo_id: user_json['user']['id']).first session[:user_id] = user.id user.update_access_token_if_needed return redirect_to :action => :show, id: user.id end user_params = { :access_token => user_json['access_token'], :refresh_token => user_json['refresh_token'], :venmo_id => user_json['user']['id'], :expires_in => user_json['expires_in'], :updated_at => Time.now } user = User.new(user_params) if user.save session[:user_id] = user.id redirect_to :action => :show, id: user.id else flash[:error] = user.errors.full_messages redirect_to :controller => :welcome, :action => :index end end end
class Administrator < ActiveRecord::Base has_many :messages, dependent: :destroy before_create :create_remember_token validates :login, presence: true validates :password, presence: true, length: { minimum: 6 } has_secure_password def self.new_remember_token SecureRandom.urlsafe_base64 end def self.encrypt(token) Digest::SHA1.hexdigest(token.to_s) end private def create_remember_token self.remember_token = Administrator.encrypt(Administrator.new_remember_token) end end
FactoryGirl.define do factory :question, class: Question do sequence(:text){ |n| "Pregunta-#{n}" } question_type "MULTIPLE" required true end end
require 'test_helper' class SketchesControllerTest < ActionDispatch::IntegrationTest setup do @sketch = sketches(:one) end test "should get index" do get sketches_url assert_response :success end test "should get new" do get new_sketch_url assert_response :success end test "should create sketch" do assert_difference('Sketch.count') do post sketches_url, params: { sketch: { date: @sketch.date, image: @sketch.image, name: @sketch.name, type: @sketch.type } } end assert_redirected_to sketch_url(Sketch.last) end test "should show sketch" do get sketch_url(@sketch) assert_response :success end test "should get edit" do get edit_sketch_url(@sketch) assert_response :success end test "should update sketch" do patch sketch_url(@sketch), params: { sketch: { date: @sketch.date, image: @sketch.image, name: @sketch.name, type: @sketch.type } } assert_redirected_to sketch_url(@sketch) end test "should destroy sketch" do assert_difference('Sketch.count', -1) do delete sketch_url(@sketch) end assert_redirected_to sketches_url end end
require 'bundler' Bundler.require # https://stackoverflow.com/a/71994319 require 'uri' def URI.escape(url) url end set :markdown_engine, :redcarpet set :markdown, layout_engine: :erb, fenced_code_blocks: true, lax_html_blocks: true, with_toc_data: true activate :syntax activate :blog do |blog| blog.prefix = "blog" end activate :directory_indexes set :images_dir, 'images' page "/docs/*", :layout => "docs" page "/blog/*", :layout => :blog configure :build do activate :minify_css end helpers do def body_for(resource) html = resource.render layout: nil Nokogiri::HTML::DocumentFragment.parse html end def javascript_include_tag(name, options = {}) options.merge!(onload: Opal::Sprockets.load_asset(name) + ";console.log('loaded #{name}')") super(sprockets_path(name + ".js") || name, options) end def stylesheet_link_tag(name, options = {}) super(sprockets_path(name + ".css") || name, options) end def sprockets_path(name) assets_path = Dir["#{__dir__}/source/assets/.*.json"].first assets = File.exist?(assets_path) ? JSON.parse(File.read(assets_path)) : {} asset = assets.dig("assets", name) asset ? "/assets/#{asset}" : nil end def table_of_contents(resource) body = body_for resource content = [] in_list = false headings = body.css('h2,h3') headings.each_with_index do |h, idx| subheading = h.name == 'h3' if subheading and !in_list in_list = true content << %Q{\n<ul class="subchapter">} elsif !subheading and in_list in_list = false content << "\n</ul>" elsif subheading in_list = true end li_class = subheading ? 'toc-list-subchapter' : 'toc-list-chapter' content << %Q{\n<li class="#{li_class}">} content << content_tag(:a, h.text, href: '#' + h[:id].to_s) unless headings[idx + 1] && headings[idx + 1].name == 'h3' content << '</li>' end end content << "\n</ul></li>" if in_list %Q{<ul class="nav opal-sidebar">#{content.join}</ul>} end end ignore '*.sass' ignore '*.scss' activate(:external_pipeline, name: :sprockets, command: "bin/build-sprockets #{'--watch' unless build?}", source: "assets/", )
feature "viewing bookmarks" do let(:bookmarks) { ['Google', 'Makers Academy'] } scenario "see bookmarks at the /bookmarks route" do visit("/") click_button("View Bookmarks") expect(page).not_to have_content "Hello World! Here are your bookmarks" expect(page).to have_content "Here is your list of bookmarks:" end scenario "returns a list of bookmarks at /bookmarks" do Bookmarks.add(url: 'http://www.makersacademy.com/', title: 'Makers Academy') Bookmarks.add(url: 'http://www.google.com/', title: 'Google') visit("/") click_button("View Bookmarks") bookmarks.each do |url| expect(page).to have_content(url) end end end
#!/usr/bin/env ruby # A simple tool to generate Sub Resource Integrity hashes # and store them in a JSON file which can also be versioned # or consumed programatically. require 'digest/sha2' require 'json' files = {} Dir.glob('*.{js,css}').each do |file_name| next if File.directory? file_name files[file_name] = "sha384-#{Digest::SHA384.file(file_name).base64digest}" end Dir.glob('{css,lists,node_modules}/**/*.{js,css}').each do |file_name| next if File.directory? file_name files[file_name] = "sha384-#{Digest::SHA384.file(file_name).base64digest}" end File.open('sri-hashes.json','w') do |f| f.write(JSON.pretty_generate(files)) end
# frozen_string_literal: true require 'divvyup/utils' require 'json' # Service is responsible for abstracting all of the redis interactions. class DivvyUp::Service include DivvyUp::Utils def initialize(redis: nil, namespace: nil) @redis = redis || DivvyUp.redis || Redis.new @namespace = namespace || DivvyUp.namespace end def enqueue(job_class:, args: []) log(:trace, 'Enqueuing work', queue: job_class.queue, namespace: @namespace, job_class: job_class, args: args) @redis.sadd("#{@namespace}::queues", 'job_class.queue') @redis.lpush("#{@namespace}::queue::#{job_class.queue}", { class: job_class.name, args: args, queue: job_class.queue }.to_json) end def worker_check_in(worker) @redis.hset("#{@namespace}::workers", worker.worker_id, Time.now.to_i) @redis.hset("#{@namespace}::worker::#{worker.worker_id}", 'queues', worker.queues.to_json) end def work_starting(worker, work) @redis.hset("#{@namespace}::worker::#{worker.worker_id}::job", 'started_at', Time.now.to_i) @redis.hset("#{@namespace}::worker::#{worker.worker_id}::job", 'work', work.to_json) end def work_finished(worker, _work) @redis.del "#{@namespace}::worker::#{worker.worker_id}::job" end def work_failed(worker, work, exc) @redis.lpush("#{@namespace}::failed", { work: work, worker: worker.worker_id, message: exc.message, backtrace: exc.backtrace }.to_json) log(:error, 'Work failed', work: work, exception: exc) end def work_retrieve(worker) reclaim_stuck_work(worker) retrieve_new_work(worker) end private def reclaim_stuck_work(_worker) checkin_threshold = Time.now.to_i - 30 * 10 @redis.hgetall("#{@namespace}::workers").each_pair do |worker_id, last_checkin| next if last_checkin.to_i > checkin_threshold log(:trace, 'Reaping worker', id: worker_id) reap_worker(worker_id) end end def reap_worker(worker_id) job = @redis.hget("#{@namespace}::worker::#{worker_id}::job", 'work') if job job = JSON.parse(job) log(:info, 'Requeuing reaped work', id: worker_id, job: job) @redis.lpush("#{@namespace}::queue::#{job['queue']}", job.to_json) end @redis.del("#{@namespace}::worker::#{worker_id}::job") @redis.del("#{@namespace}::worker::#{worker_id}") @redis.hdel("#{@namespace}::workers", worker_id) end def retrieve_new_work(worker) worker.queues.each do |queue| log(:trace, 'Checking Queue for Work', queue: queue, namespace: @namespace) work = @redis.rpop("#{@namespace}::queue::#{queue}") return JSON.parse(work) if work end nil end end
require_relative 'helpers' class TestBot < Minitest::Spec include Rack::Test::Methods include Helpers def setup ENV['SLACK_TOKEN_OUT'] = '0000000000000000' ENV['SLACK_TOKEN_IN'] = '1111111111111111' ENV['DECAUX_TOKEN'] = '2222222222222222' ENV['SLACK_TEAM'] = 'bikebotser' end def test_help %w{ help wat wtf }.each { |cmd| _(say(cmd)['text']).must_equal(Bot.help) } end def test_free_bikes station = bike_station Bot.stub :station, station do _(say("free #{station.number}")['text']).must_equal(Bot.bikes_free_message(station.available_bikes)) end end def test_free_slots station = bike_station Bot.stub :station, station do _(say("slots #{station.number}")['text']).must_equal(Bot.slots_free_message(station.available_bike_stands)) end end # Some of the commands just say sorry def test_sorries %w{ faves commutes scrub }.each { |cmd| _(say(cmd)['text']).must_equal(Bot.sorry(cmd, user_name)) } end # Returns a hash of the result def say(cmd) data = payload("bikes #{cmd}") post '/', data case last_response.status when 200, 201 JSON.parse(last_response.body) when 400..499 when 500..599 last_response.status.must_equal 200, JSON.parse(last_response.body)['error'] end end end
Rails.application.routes.draw do # Websites With Authorization authenticate :user do resources :websites end devise_for :users #Profile Routing get '/profile', to: 'profiles#new' post '/profiles', to: 'profiles#create' #Skill Routing get '/skill', to: 'skills#new' post '/skills', to: 'skills#create' delete '/skills/:id', to: 'skills#destroy', as: 'destroy_skills' #Language get '/language', to: 'languages#new' post '/languages', to: 'languages#create' delete '/languages/:id', to: 'languages#destroy', as: 'destroy_languages' #Experience Routing get '/experience', to: 'experiences#new' post '/experiences', to: 'experiences#create' delete '/experiences/:id', to: 'experiences#destroy', as: 'destroy_experinces' #Education Routing get '/education', to: 'educations#new' post '/educations', to: 'educations#create' delete '/educations/:id', to: 'educations#destroy', as: 'destroy_educations' #Network get '/network', to: 'networks#new' post '/networks', to: 'networks#create' delete '/networks/:id', to: 'networks#destroy', as: 'destroy_network' #Templates get '/templates/:id', to: 'templates#show', as: 'templates' #Root root "pages#index" end
class Admin::HeightsController < ApplicationController before_action :authenticate_admin! def index @height = Height.new @heights = Height.all end def edit @height = Height.find(params[:id]) end def create @heights = Height.all @height = Height.new(permit_height) if @height.save redirect_to admin_heights_path flash[:notice] = "Height Created Successfully" else render 'index' end end def update @height = Height.find(params[:id]) if @height.update(permit_height) redirect_to admin_heights_path flash[:notice] = "Height Updated Successfully" else render 'edit' end end def destroy @height = Height.find(params[:id]) if @height.destroy redirect_to admin_heights_path flash[:notice] = "Height Deleted Successfully" else redirect_to admin_heights_path flash[:alert] = "Height Not Deleted" end end private def permit_height params.require(:height).permit(:name) end end
class ApplicationController < ActionController::Base protect_from_forgery layout :layout before_filter :set_current_account before_filter :set_current_order_if_front before_filter :clear_completed_order_if_front before_filter :authenticate_admin! private def set_current_account # Cases if request.host == 'www.jamminjava.com' || request.host == 'jamminjava.thintix.com' redirect_to 'https://jamminjava.com' end current_host = "#{request.host}" # 1. Requesting a root level company domain. Redirect to thinio.com if ['thintix.com', 'localtix.com', 'litetix.com'].include? current_host redirect_to 'http://thinio.com' return end # 2. A subdomain of (thintix or localtix).com unless current_host.scan(/thintix.com|localtix.com|litetix.com/).empty? @current_account = Account.find_by_subdomain(request.subdomains.first) return unless @current_account.nil? # 3. A customer's custom domain name else @current_account = AccountDomain.find_by_domain(current_host).account return unless @current_account.nil? end # If nothing has been found, 404 raise ActionController::RoutingError.new("'#{current_url}' not found in ThinTix ") end def layout if devise_controller? || action_name == 'sign_in' || action_name == 'sign_up' "front_user" elsif request.fullpath.slice(0,8) == '/manager' "manager" elsif request.fullpath.slice(0,6) == '/admin' "application" else "application" end end def manager_path? request.fullpath.slice(0,8) == '/manager' end # def not_found # raise ActionController::RoutingError.new('Not Found') # end def after_sign_in_path_for(resource) # if resource.is_a?(User) && resource.has_at_least_role(:employee) # '/manager' # else # super # end if params.has_key?(:after_sign_in_path) params[:after_sign_in_path] else super end end # def after_sign_in_path_for(resource) # sign_in_url = url_for(:action => 'new', :controller => 'sessions', :only_path => false, :protocol => 'http') # if request.referer == sign_in_url # super # else # stored_location_for(resource) || request.referer || root_path # end # end def authenticate_admin! # Pass if this isn't the manager page return true unless manager_path? # User must be signed in. # If not, redirect to sign in page unless user_signed_in? # redirect_to new_user_session first, :notice => 'Must sign in first' # return false authenticate_user! end # Must be employee or higher # If not, take home unless current_user.has_at_least_role(:manager) redirect_to '/', :notice => 'Insufficient permissions' return false end end protected # CKEDITOR def ckeditor_filebrowser_scope(options = {}) super({ :assetable_id => @current_account.id, :assetable_type => 'Account' }.merge(options)) end def ckeditor_before_create_asset(asset) asset.assetable = @current_account return true end def not_found raise ActionController::RoutingError.new('Not Found') end private def manager_page? request.fullpath.slice(0,8) == '/manager' end def set_current_order_if_front set_current_order() unless manager_path? # only set the current order if front end end def clear_completed_order_if_front clear_completed_order() unless manager_path? # only clear the current order if front end end # If current order is expired, clear stored session order # Otherwise, create a new order and attach to current session # (Order becomes abandonded (expired_at > Now + LIFESPAN) def ensure_employee unless @current_user.has_at_least_role(:employee) redirect_to '/', :notice => 'Only employees of Jammin\' Java may check you in!' end end def set_current_order # For case when order is deleted (mostly in early development) # clear session if order is blank. TODO: remove this session[:order_id] = nil if @current_account.orders.where(:id => session[:order_id]).empty? if session[:order_id] @current_order ||= @current_account.orders.find(session[:order_id]) if @current_order.expired? #|| @current_order.purchased_at || if @current_order.tickets.count == 0 @current_order.destroy end session[:order_id] = nil end end if session[:order_id].nil? @current_order = @current_account.orders.create!( :ip_address => request.remote_ip) session[:order_id] ||= @current_order.id end @current_order end def clear_completed_order if @current_order.complete? order_path = front_order_path(@current_order) session[:success_order_id] = session[:order_id] session[:order_id] = nil redirect_to '/orders/success' end end end
require 'rails_helper' RSpec.describe TrackPoint, type: :model do let(:track_point) { FactoryGirl.create :track_point } describe '#to_coordinates' it 'returns an array of coordinates' do expect(track_point.to_coordinates).to eq [52.13, 13.14] end end
# a method that determines and returns ASCII string value # should be the sum of every character's value def ascii_value(input) input.split('').reduce(0) do |sum , i| sum + i.ord end end p ascii_value('Four score') == 984 p ascii_value('Launch School') == 1251 p ascii_value('a') == 97 p ascii_value('') == 0
require "rails_helper" RSpec.describe Api::JwtsController, type: :controller do before do setup_application_instance @user = FactoryBot.create(:user) @user.confirm @user_token = AuthToken.issue_token( { application_instance_id: @application_instance.id, user_id: @user.id, }, ) end context "as user" do describe "GET show" do it "should not be authorized" do get :show, params: { id: @user.id }, format: :json expect(response).to have_http_status(:unauthorized) end it "should get a new jwt" do request.headers["Authorization"] = @user_token get :show, params: { id: @user.id }, format: :json expect(response).to have_http_status(:success) result = JSON.parse(response.body) expect(result["jwt"]).to be_present end end end describe "includes JwtToken" do it { expect(Api::JwtsController.ancestors.include?(JwtToken)).to eq(true) } end end
module Frontend class UsersController < FrontendController attr_reader :user def next_step if current_user case current_user.state when "invited" redirect_to register_path when "registered" redirect_to booking_calendar_url when "booked" if TimeSlot.where(:assigned_to => current_user.id).present? redirect_to my_booking_page_url else redirect_to booking_calendar_url end when "test_taken" redirect_to my_booking_page_url else redirect_to error_page_url end end end def register @user = current_user redirect_to_next_step unless @user.invited? end def update @user = User.find(params[:id]) if user.register_with_attributes(params[:user]) redirect_to_next_step else render :action => :register end end def update_qualifications_rating user = User.find(params[:user_id]) user.qualifications_rating = params[:user]["qualifications_rating"] user.save! redirect_to root_url, :notice => t('update_qualifications_rating.success') end end end
class Order < ApplicationRecord #responsibilty: persistance of orders #reason to change: order schema changes has_many :product_requests, inverse_of: :order has_many :order_items, inverse_of: :order has_many :products, through: :product_requests, inverse_of: :orders has_many :product_packages, through: :order_items, inverse_of: :orders accepts_nested_attributes_for :product_requests validates :product_requests, :order_items, :total, presence: true def set_total t = 0 order_items.each do |oi| if oi.valid? t += oi.quantity * oi.product_package.value else t = nil break end end self.total = t end end
class ChangePositionWorkerFromworkercontract < ActiveRecord::Migration def change change_column :worker_contracts, :charge_id, :integer end end
class Admin::AdminsController < Admin::UsersController protected def users_scope User.admin end def redirect_path admin_admins_path end end
# As Player 1, # So I can win a game of Battle, # I want to attack Player 2, and I want to get a confirmation feature 'Attacking...' do before :each do allow(Kernel).to receive(:rand).and_return 10 end scenario 'Player 2 is attacked' do sign_in_and_play click_button('Attack') expect(page).to have_content 'Rajeev attacked Julien' end scenario "Player's trurn changes" do sign_in_and_play click_button('Attack') click_button('Next Turn') click_button('Attack') expect(page).to have_content "Rajeev's hit points reduced to: 70HP" end end
require 'spec_helper' describe Admin::OrdersController do before(:each) do @request.env["devise.mapping"] = Devise.mappings[:user] FactoryGirl.create(:configuration_setting) @user = FactoryGirl.create(:user, payment_method: true, role: 3, confirmed_at: "2013-05-28 06:38:19.499604") @order = FactoryGirl.create(:order) @user.confirm! # set a confirmed_at inside the factory. Only necessary if you are using the confirmable module sign_in @user end describe "GET #index" do it "populates an array of orders" do get :index assigns(:orders).should eq([@order]) end it "renders the :index view" do get :index response.should render_template :index end end describe "GET #show" do it "assigns the requested order to @order" do get :show, id: @order assigns(:order).should eq(@order) end it "renders the #show view" do get :show, id: @order response.should render_template :show end end #=====================fail case=========================== describe "GET #index" do it "populates an array of orders" do get :index assigns(:orders).should_not eq([@order]) end it "renders the :index view" do get :index response.should_not render_template :index end end describe "GET #show" do it "assigns the requested order to @order" do get :show, id: @order assigns(:order).should_not eq(@order) end it "renders the #show view" do get :show, id: @order response.should_not render_template :show end end end
class Admin::DisciplinesController < Admin::BaseController before_action :_set_discipline, except: %i[index new create] def index @disciplines = Discipline.all end def show; end def new @discipline = Discipline.new render partial: 'form', layout: false end def edit render partial: 'form', layout: false end # JS def create @discipline = Discipline.new update_and_render_or_redirect_in_js @discipline, _discipline_params, ->(discipline) { admin_discipline_path(discipline) } end # JS def update update_and_render_or_redirect_in_js @discipline, _discipline_params, admin_discipline_path(@discipline) end def destroy @discipline.destroy! redirect_to admin_disciplines_path, notice: helpers.t_notice('successfully_deleted', Discipline) end def _set_discipline @discipline = Discipline.find params[:id] end def _discipline_params params.require(:discipline).permit( *Discipline::FIELDS ) end end
class QuestionController < BasicInstrumentController def show respond_to do |f| f.json { render json: @object} f.xml { render body: @object.to_xml_fragment, content_type: 'application/xml' } end end def create update_question @object = collection.new(safe_params) do |obj| obj.save end end def update update_question @object do |obj| obj.update(safe_params) end end private def update_question(object, &block) if block.call object if params.has_key? :instruction object.instruction = params[:instruction] object.save! end if params.has_key? :rds object.update_rds params[:rds] object.save! end if params.has_key? :cols object.update_cols params[:cols] object.save! end render :show, status: :ok else render json: @object.errors, status: :unprocessable_entity end end end
class Artist < ActiveRecord::Base has_many :songs has_many :genres, through: :songs end
# frozen_string_literal: true module Brcobranca module Boleto # Banco do Nordeste class BancoNordeste < Base # <b>REQUERIDO</b>: digito verificador da conta corrente attr_accessor :digito_conta_corrente validates_length_of :agencia, maximum: 4, message: 'deve ser menor ou igual a 4 dígitos.' validates_length_of :conta_corrente, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.' validates_length_of :digito_conta_corrente, is: 1, message: 'deve ser igual a 1 dígitos.' validates_length_of :carteira, maximum: 2, message: 'deve ser menor ou igual a 2 dígitos.' validates_length_of :nosso_numero, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.' # Nova instancia do Banco do Nordeste # @param (see Brcobranca::Boleto::Base#initialize) def initialize(campos = {}) campos = { carteira: '21' }.merge!(campos) super(campos) end # Codigo do banco emissor (3 dígitos sempre) # # @return [String] 3 caracteres numéricos. def banco '004' end # Número da conta corrente # @return [String] 7 caracteres numéricos. def conta_corrente=(valor) @conta_corrente = valor.to_s.rjust(7, '0') if valor end # Número sequencial utilizado para identificar o boleto. # @return [String] 7 caracteres numéricos. def nosso_numero=(valor) @nosso_numero = valor.to_s.rjust(7, '0') if valor end # Dígito verificador do nosso número. # @return [String] 1 caracteres numéricos. def nosso_numero_dv nosso_numero.modulo11( multiplicador: (2..8).to_a, mapeamento: { 10 => 0, 11 => 0 } ) { |total| 11 - (total % 11) } end # Nosso número para exibir no boleto. # @return [String] # @example # boleto.nosso_numero_boleto #=> "0020572-9" def nosso_numero_boleto "#{nosso_numero}-#{nosso_numero_dv}" end # Agência + codigo do cedente do cliente para exibir no boleto. # @return [String] # @example # boleto.agencia_conta_boleto #=> "0059/189977-5" def agencia_conta_boleto "#{agencia}/#{conta_corrente}-#{digito_conta_corrente}" end # Segunda parte do código de barras. # 9(04) | Agência <br/> # 9(08) | Conta corrente com DV <br/> # 9(08) | Nosso Numero Com DV<br/> # 9(02) | Carteira<br/> # 9(03) | Zeros<br/> # # @return [String] 25 caracteres numéricos. def codigo_barras_segunda_parte "#{agencia}#{conta_corrente}#{digito_conta_corrente}#{nosso_numero}#{nosso_numero_dv}#{carteira}000" end end end end
# # Cookbook Name:: kidsruby_os # Recipe:: chroot_bootstrap # # make sure the customization-scripts directory exists directory "#{node[:kidsruby_os][:remaster_root]}/customization-scripts" do owner "root" group "root" action :create end # setup bootstrap files inside the chroot %w[chroot-bootstrap.sh chef-bootstrap.sh].each do |file| cookbook_file "#{node[:kidsruby_os][:remaster_root]}/customization-scripts/#{file}" do source file owner "root" group "root" mode "0755" action :create end end # prime rvm profile helper template "#{node[:kidsruby_os][:remaster_root]}/remaster-root/etc/profile.d/rvm.sh" do source "rvm.sh.erb" owner "root" group "root" mode "0755" action :create end # copy the host chef configuration to the chroot execute "Copy Chef to the chroot" do command [ "rm -rf #{node[:kidsruby_os][:remaster_root]}/customization-scripts/chef/", "cp -R #{node[:kidsruby_os][:chef_directory]} #{node[:kidsruby_os][:remaster_root]}/customization-scripts/" ].join(" && ") end # update paths and role for chroot execute "update chef configuration paths in the chroot" do command "sed -i 's/role\\[ec2_host\\]/role\\[livecd\\]/' #{node[:kidsruby_os][:remaster_root]}/customization-scripts/chef/config/dna.json" environment ({"CFLAGS" => "-m32"}) end execute "bootstrap and run chef within the chroot" do command "#{node[:kidsruby_os][:remaster_root]}/customization-scripts/chroot-bootstrap.sh" environment ({"CFLAGS" => "-m32"}) end
module Steppable def moves array = [] origin = self.pos x, y = origin.first, origin.last self.move_diffs.each do |diff| dx, dy = diff.first, diff.last new_pos = [x + dx, y + dy] #in bounds check if new_pos.all? { |coord| coord.between?(0,7) } if self.board[new_pos].instance_of?(NullPiece) #empty? array << new_pos elsif self.board[new_pos].color != self.color array << new_pos end end end array end def move_diffs raise "You forgot to implement me!!!" end end # End Steppable Module
# frozen_string_literal: true FactoryBot.define do factory :customer do name { Faker::Company.bs } ssn { Faker::CPF.numeric } end end
require 'rails_helper' feature 'Searching', js: true do scenario 'When I visit the main page I see basic layout' do visit root_path expect(page).to have_content 'Welcome to database search' expect(page).to have_css '#search-form' end scenario 'When I fill in input, the button text changes' do visit root_path expect(find('#search-form')).to have_button 'All' fill_in('Search Input', :with => 'something') expect(find('#search-form')).to have_button 'Search' end scenario 'When I look up all the data' do visit root_path click_button 'All' expect(page).to have_css('.result', count: 500) end end
class MigracionCompleta < ActiveRecord::Migration[5.1] def change add_column :question_comments, :fecha, :date add_column :question_comments, :texto, :string add_reference :question_comments, :user add_reference :question_comments, :question end end
class CreateProfileEmailAccesses < ActiveRecord::Migration def change create_table :profile_email_accesses do |t| t.integer :email_access_id t.integer :profile_id end end end
module Apple module DeviceEnrollmentProgram class Device attr_reader :serial_number, :model, :profile_status def initialize(serial_number:, attributes: {}) @serial_number = serial_number update attributes end def update(attributes = {}) @model = attributes['model'] if attributes['model'] @description = attributes['description'] if attributes['description'] @color = attributes['color'] if attributes['color'] @asset_tag = attributes['asset_tag'] if attributes['asset_tag'] @profile_status = attributes['profile_status'] if attributes['profile_status'] @profile_uuid = attributes['profile_uuid'] if attributes['profile_uuid'] @profile_assign_time = DateTime.parse(attributes['profile_assign_time']) if attributes['profile_assign_time'] @device_assigned_date = DateTime.parse(attributes['device_assigned_date']) if attributes['device_assigned_date'] @device_assigned_by = attributes['device_assigned_by'] if attributes['device_assigned_by'] end def <=>(other_device) serial_number <=> other_device.serial_number end def empty_profile_status? profile_status == 'empty' end end end end
require_relative 'board' require_relative 'human_player' class Game def initialize(size, *marks) # @player_1 = HumanPlayer.new(mark_1) # @player_2 = HumanPlayer.new(mark_2) @players = marks.map { |mark| HumanPlayer.new(mark) } @game_board = Board.new(size) @curr_player = @players[0] end def switch_turn # @curr_player == @player_1 ? @curr_player = @player_2 : @curr_player = @player_1 curr_i = @players.index(@curr_player) @curr_player = @players[(curr_i + 1) % @players.length] # rotate! @curr_player = @players.rotate![0] end def play while @game_board.empty_positions? @game_board.print puts "It's #{@curr_player.mark}'s turn" @game_board.place_mark(@curr_player.get_position, @curr_player.mark) if @game_board.win?(@curr_player.mark) puts "#{@curr_player.mark} Won!" return else self.switch_turn end end puts "Draw!" end end
require 'rails_helper' RSpec.describe Api::V1::AnswersController, :type => :controller do describe 'POST /games/:game_id/answers' do it_behaves_like 'an authenticated only action' do subject { post(:create, :game_id => 1) } end describe 'successful call' do let(:player) { build(:player) } let(:user) { player.user } let(:answer) { build(:answer, :player => player) } let(:game) { double } before do allow(Game).to receive(:find).with('10').and_return(game) api_user(user) end subject do post(:create, { :game_id => 10, :trivia_id => 15, :trivia_option_id => 25, :format => :json }) end it 'answers the trivia in the current game' do expect(game).to receive(:answer!).with(user, { :trivia_id => 15, :trivia_option_id => 25 }).and_return(answer) expect(subject).to be_success expect(subject.body).to serialize_object(answer).with(AnswerSerializer, :scope => user, :include => 'game,game.trivia,game.trivia.options,game.players') end end end end
class Ability include CanCan::Ability def initialize(user) if user.admin? can :manage,:all else can :update,Product do |product| product.seller == user end can :destroy,Product do |product| product.seller == user end can :create,Product can :create,Bid end end end
class AddAttachmentEpsProductToProduct < ActiveRecord::Migration def self.up add_column :products, :eps_product_file_name, :string add_column :products, :eps_product_content_type, :string add_column :products, :eps_product_file_size, :integer add_column :products, :eps_product_updated_at, :datetime end def self.down remove_column :products, :eps_product_file_name remove_column :products, :eps_product_content_type remove_column :products, :eps_product_file_size remove_column :products, :eps_product_updated_at end end
require "rails_helper" describe SessionsController do describe "GET new" do it "renders new template" do get :new expect(response).to render_template :new end end describe "POST create" do context "with valid credentials" do let(:paquito) { Fabricate :user } before do post :create, email: paquito.email, password: paquito.password end it "puts the signed in user in the session" do expect(session[:user_id]).to eq(paquito.id) end it "redirects to home page" do expect(response).to redirect_to root_path end it "sets the notice" do expect(flash[:notice]).to be_present end end context "with invalid credentials" do let(:paquito) { Fabricate :user } it "does not set the session with an incorrect email" do post :create, email: "correo_erroneo@mal.com", password: paquito.password expect(session[:user_id]).to be_nil end it "does not set the session with an incorrect password" do post :create, email: paquito.email, password: "passwordmal" expect(session[:user_id]).to be_nil end it "redirect to sign_in page" do post :create, email: paquito.email, password: "passwordmal" expect(response).to redirect_to sign_in_path end it "sets the error message" do post :create, email: paquito.email, password: "passwordmal" expect(flash[:error]).to be_present end end describe "GET destroy" do it "redirect to root page" do get :destroy expect(response).to redirect_to root_path end it "sets session to nil" do paquito = Fabricate :user session[:user_id] = paquito.id get :destroy expect(session[:user_id]).to be_nil end end end end
# deck.rb VALUES_LIST = (1..13).to_a SUITS_LIST = [:hearts, :clubs, :spades, :diamonds] require_relative 'card' class Deck def initialize(values, suits) @cards = [] values.each do |value| suits.each do |suit| @cards << Card.new(suit, value) end end end def draw drawn_card = @cards.last end def shuffle return @cards.shuffle! end end
# frozen_string_literal: true require 'smarter_csv' class CSVDataSeeder DEFAULT_SKILL_NAMES = { memorization: 'Memorization', grit: 'Grit', teamwork: 'Teamwork', discipline: 'Discipline', self_esteem: 'Self-Esteem', creativity: 'Creativity & Self-Expression', language: 'Language' }.freeze def initialize(csv_file_path) @csv_file_path = csv_file_path @groups = {} @students = {} @lessons = {} @group_names = { 1 => 'A', 2 => 'B', 3 => 'C' } @skill_ids = {} @gds = {} end def seed_data(chapter, default_subject) @subject = default_subject read_csv_file.each { |r| seed_row r, chapter } end private def read_csv_file SmarterCSV.process @csv_file_path end def seed_row(row, chapter) group = create_group(row[:group], chapter) student = create_student(row[:id], group, row[:gender] == 1 ? 'male' : 'female', row[:age] || 13) lesson = create_lesson(group, row[:date]) grade_student student, lesson, get_row_grades(row) end def create_group(group_id, chapter) @groups[group_id] ||= chapter.groups.create!(mlid: group_id, group_name: generate_group_name(group_id)) end def generate_group_name(group_id) return group_id if group_id.respond_to? :to_str @group_names[group_id] end def create_student(id, group, gender, age) @students[id] ||= Student.create!( mlid: id, first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, gender: gender, dob: age.years.ago, estimated_dob: 'true', group: group ) end def create_lesson(group, date) d = parse_date(date) # rubocop:disable Rails/Output @lessons[:"#{group.id}-#{date}"] ||= puts("Lesson: #{d} - Chapter: #{group.chapter.chapter_name} - Group: #{group.group_name}") || Lesson.create(group: group, date: d, subject: @subject) # rubocop:enable Rails/Output end def parse_date(date_string) return Date.strptime date_string, '%m/%d/%y' if date_string.split('/')[2].length == 2 Date.strptime date_string, '%m/%d/%Y' end def get_row_grades(row) { memorization: row[:memorization], grit: row[:grit], teamwork: row[:teamwork], discipline: row[:discipline], self_esteem: row[:self_esteem], creativity: row[:creativity], language: row[:language] } end def grade_student(student, lesson, grades) new_grades = [] grades.each do |skill_name, mark| return lesson.mark_student_as_absent(student) if mark.nil? skill_id = get_skill_id skill_name gd = get_gd skill_id, mark new_grades << Grade.new(lesson: lesson, student: student, grade_descriptor: gd) end Grade.transaction do new_grades.each(&:save!) end end def get_skill_id(skill_name) @skill_ids[:"#{skill_name}"] ||= Skill.where(skill_name: DEFAULT_SKILL_NAMES[skill_name]).first.id end def get_gd(skill_id, mark) @gds[:"#{skill_id}-#{mark}"] ||= GradeDescriptor.where(skill_id: skill_id, mark: mark).first end end
Rails.application.routes.draw do devise_for :users, controllers: { registrations: "registrations" } root "static_pages#home" get "about" => "static_pages#about" get "contact" => "static_pages#contact" resources :activities resources :subjects resources :users, only: [:index, :show, :update] resources :courses, only: [:show] resources :courses_subjects resources :users_subjects namespace :supervisor do root "courses#index" resources :activities resources :users, only: [:index, :destroy] resources :subjects resources :courses do resources :courses_subjects, only: [:show, :edit, :update] resource :assign_supervisors, only: [:show, :update] resource :assign_trainees, only: [:show, :update] end end end
require "minitest/autorun" require "change" class ChangeTest < MiniTest::Unit::TestCase def setup @change = Change.new(0.51) end def test_that_change_can_be_created refute_nil @change, 'Change is nil!' end def test_change_stores_argument assert_equal 0.51, @change.money end def test_we_can_get_change 5.times do |i| change_hash = Change.new(i / 100.0).make_change assert_equal({ :pennies => i }, change_hash[:pennies => 0]) end end def test_that_nickels_work assert_equal({ :nickels => 1 }, Change.new(0.05).make_change) end end
require 'rake/testtask' begin require 'rake/extensiontask' rescue LoadError abort <<-error rake-compile is missing; Rugged depends on rake-compiler to build the C wrapping code. Install it by running `gem i rake-compiler` error end Rake::ExtensionTask.new('rugged') do |r| r.lib_dir = 'lib/rugged' end task :embedded_clean do lib_path = File.expand_path '../ext/rugged/libgit2_embed.a', __FILE__ system "rm #{lib_path}" end Rake::Task[:clean].prerequisites << :embedded_clean # # Tests # task :default => [:compile, :test] task :pack_dist do dir = File.dirname(File.expand_path(__FILE__)) output = File.join(dir, 'ext', 'rugged', 'vendor', 'libgit2-dist.tar.gz') Dir.chdir(ENV['LIBGIT2_PATH']) do `git archive --format=tar --prefix=libgit2-dist/ HEAD | gzip > #{output}` end end task :cover do ruby 'test/coverage/cover.rb' end Rake::TestTask.new do |t| t.libs << 'lib' t.pattern = 'test/**/*_test.rb' t.verbose = false end begin require 'rdoc/task' Rake::RDocTask.new do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.rdoc_files.include('ext/**/*.c') rdoc.rdoc_files.include('lib/**/*.rb') end rescue LoadError end
require 'test_helper' class HourTest < ActiveSupport::TestCase test "Saving with variable parameters" do assert save_with, "Valid input" [:project_id, :user_id, :hourtype_id].each { |p| assert_not save_with( { "#{p}" => 'asdc' } ), "Non numieric #{p}" assert_not save_with( { "#{p}" => nil } ), "Omitted #{p}" } end private def save_with( params = {} ) user = User.first project = Project.first hourtype = Hourtype.first valid = { user_id: user.id, project_id: project.id, hourtype_id: hourtype.id, start_time: DateTime.now - (5/24.0), end_time: DateTime.now - (2/24.0), description: 'Blaaa blaa bla' }.merge( params ) return Hour.create( valid ).valid? end end
require 'test_helper' class EmployeesShowTest < ActionDispatch::IntegrationTest include ApplicationHelper def setup @user = users(:jane) @employee = employees(:one) end test "redirect show as logged-out user" do get employee_path(@employee) assert_redirected_to login_path follow_redirect! assert_not flash.empty? get users_path assert_template 'users/index' end test "show as logged-in user" do log_in_as(@user) get employee_path(@employee) assert_template 'employees/show' assert_select 'title', full_title("Employee " + @employee.id.to_s) assert_select 'h1', text: "Employee " + @employee.id.to_s # Edit employee button assert_select 'a[href=?]', edit_employee_path(@employee), text: 'Edit' # Delete employee button assert_select 'a[href=?]', employee_path(@employee), text: 'Delete', method: :delete assert_difference 'Employee.count', -1 do delete employee_path(@employee) end end end
require 'rails_helper' RSpec.describe Product, type: :model do it { should validate_presence_of :name; :description; :price } it { should have_many :reviews } it { should have_many(:users).through(:reviews) } end
# == Schema Information # # Table name: comments # # id :bigint not null, primary key # content :text not null # created_at :datetime not null # updated_at :datetime not null # tweet_id :bigint not null # user_id :bigint not null # # Indexes # # index_comments_on_tweet_id (tweet_id) # index_comments_on_user_id (user_id) # require 'rails_helper' RSpec.describe Comment, type: :model do let!(:user) { create(:user) } let!(:tweet) { create(:tweet, user: user) } let!(:comment) { create(:comment, tweet: tweet, user: user) } context 'バリデーション' do it '有効な状態であること' do expect(comment).to be_valid end it 'user_idがなければ無効な状態であること' do comment = build(:comment, user_id: nil) expect(comment).not_to be_valid end it 'tweet_idがなければ無効な状態であること' do comment = build(:comment, tweet_id: nil) expect(comment).not_to be_valid end it '内容がなければ無効な状態であること' do comment = build(:comment, content: nil) expect(comment).not_to be_valid end it '内容が300文字以内であること' do comment = build(:comment, content: 'a' * 301) comment.valid? expect(comment.errors[:content]).to include('は300文字以内で入力してください') end end end
class SpendingInfo < SpendingInfo.superclass module Cell class Show < Abroaders::Cell::Base def initialize(account, options = {}) super unless eligible_people.any? raise 'account must have >= 1 eligible person' end end property :eligible_people property :people def title 'My Financials' end private def financials_for_each_person content_tag :div, class: 'row' do # owner first: cell(PersonFinancials, collection: people.sort_by(&:type).reverse) end end # @!method self.call(person, options = {} # @param person [Person] # @option options [Boolean] use_name class PersonFinancials < Abroaders::Cell::Base include ::Cell::Builder include Escaped property :first_name property :spending_info builds do |person| person.eligible ? self : Ineligible end subclasses_use_parent_view! private def body cell(SpendingInfo::Cell::Table, spending_info) end def editable? true end def link_to_edit link_to 'Edit', edit_person_spending_info_path(model) end def wrapper(&block) end class Ineligible < self def editable? false end def body <<-HTML <p>You told us that #{first_name} is not eligible to apply for credit cards in the U.S., so we don't need to know his/her financial information.</p> HTML end end end end end end
# # Cookbook Name:: jolokia-jvm-agent # Spec:: default # require 'spec_helper' describe 'jolokia-jvm-agent::default' do platforms = { 'centos' => ['6.6', '7.0'], 'ubuntu' => ['14.04'] } platforms.each do |platform, versions| versions.each do |version| context "on #{platform.capitalize} #{version}" do let(:chef_run) do ChefSpec::SoloRunner.new(log_level: :error, platform: platform, version: version) do |node| node.set['jolokia-jvm-agent']['version'] = '1.3.2' node.set['jolokia-jvm-agent']['dir'] = '/opt/jolokia' end.converge(described_recipe) end it 'should create the default jolokia-jvm-agent installation directory' do expect(chef_run).to create_directory('/opt/jolokia').with(owner: 'root') end it 'creates the jolokia-jvm-agent jar file' do expect(chef_run).to create_remote_file('/opt/jolokia/jolokia-jvm-1.3.2-agent.jar').with(owner: 'root') end it 'creates a link to the jolokia-jvm-agent' do expect(chef_run).to create_link('/opt/jolokia/jolokia-jvm-agent.jar').with( to: '/opt/jolokia/jolokia-jvm-1.3.2-agent.jar') end end end end end
class CreateProducts < ActiveRecord::Migration[5.1] def change create_table :products do |t| t.string :sku, null: false t.string :name, null: false t.text :description, null: false t.belongs_to :product_kind, foreign_key: true, null: false t.bigint :stock, null: false t.bigint :cost, null: false t.bigint :selling_price, null: false t.timestamps end add_index :products, :sku, {unique: true} end end
require "net/ftp" class FTPConnectionError < Net::FTPError; end class DownloadError < Net::FTPError; end class SchemaDumpError < RuntimeError; end class DatabaseDumpError < RuntimeError; end class DatabaseUploadError < RuntimeError; end
# Bugfix: Team.offset(1).limit(1) throws an error ActiveRecord::Base.instance_eval do def offset(*args, &block) scoped.__send__(:offset, *args, &block) rescue NoMethodError if scoped.nil? 'depends on :allow_nil' else raise end end end
require 'rails_helper' RSpec.describe 'registration page' do it 'displays correct fields to create new user' do visit '/users' click_link 'New User' expect(current_path).to eq('/users/new') expect(page).to have_field('user[first_name]') expect(page).to have_field('user[last_name]') expect(page).to have_field('user[email]') expect(page).to have_field('user[password]') end end
class MakeEmailEventIdDefaultToNull < ActiveRecord::Migration def change change_column :emails, :event_id, :integer, :null => true, :default => nil end end
require_relative 'questions_module' require_relative 'save_module' require_relative 'models' class User extend QuestionsModule include SaveModule def self.table_name "users" end def self.find_by_name(fname, lname) user = QuestionsDatabase.instance.execute(<<-SQL, fname, lname) SELECT * FROM users WHERE fname = ? AND lname = ? SQL User.new(user.first) unless user.empty? end attr_accessor :id, :fname, :lname def initialize(options = {}) @id = options['id'] @fname = options['fname'] @lname = options['lname'] end def authored_questions Question.find_by_author_id(id) end def authored_replies Reply.find_by_user_id(id) end def followed_questions QuestionFollow.followed_questions_for_user_id(id) end def liked_questions QuestionLikes.liked_questions_for_user_id(id) end def average_karma QuestionsDatabase.instance.execute(<<-SQL, id) SELECT CAST(COUNT(ql.id) AS FLOAT) / COUNT(DISTINCT(qu.id)) FROM questions qu LEFT OUTER JOIN question_likes ql ON ql.question_id = qu.id -- JOIN -- users us ON us.id = qu.user_id -- WHERE -- us.id = ? WHERE qu.user_id = ? SQL .first.values.first end end if __FILE__ == $PROGRAM_NAME t = User.find_by_id(2) p t.average_karma b = User.find_by_id(5) p b.average_karma end
require 'action_view/helpers/date_helper' include ActionView::Helpers::DateHelper class Meta < ActiveRecord::Base def self.last_commit begin commits = GitHub::API.commits('beilabs','www.beilabs.com') message = "This site was last updated on #{ commits.first.committed_date.to_time + 7.hours }" File.open("#{ Rails.root }/app/views/shared/_last_commit.html.haml", 'w') {|f| f.write( message ) } rescue Exception => e logger.error "An exception occured when saving the file #{e.to_s}" end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :lockable, :timeoutable, :trackable validates :first_name, presence: true,format: { with: /\A[a-zA-Z]+\z/,message: "Please enter valid first name" } validates :last_name,presence: true,format: { with: /\A[a-zA-Z]+\z/,message: "Please enter valid last name" } validates :phone_number,numericality: { only_integer: true },presence: true,length: { minimum:6,maximum:10 } has_many :payments has_many :reservations has_one :wallet has_many :transaction_histories end
module SPV # Keeps options which are used to identify path to fixtures # and options for a waiter which holds execution until expectation # has been met. class Options attr_accessor :waiter, :waiter_options, :shortcut_paths def initialize(options = {}) @shortcut_paths = {} options.each do |key, val| public_send("#{key}=", val) end end # Defines shortcut path to fixtures. # # @param shortcut [String] # @param path [String] Path to fixtures. # # @return [void] # # @api private def add_shortcut_path(shortcut, path) path << '/' unless path[-1, 1] == '/' self.shortcut_paths[shortcut] = path end # Returns a full path associated with a shortcut. # # @param shortcut [String] # # @return [String] # # @api private def shortcut_path(shortcut) self.shortcut_paths[shortcut] end # Returns a copy of itself. # # @return [SPV::Options] # # @api private def clone_options dup end # Returns options of a waiter in a hash format. # If no options are defined, returns an empty hash. # # @return [Hash] # # @api private def waiter_options @waiter_options || {} end # Merges already defined waiter's options with a given hash. # # If waiter's options are not defined yet, it will define waiter options # with a given hash. # # @return [void] # # @api private def merge_waiter_options!(options) self.waiter_options = self.waiter_options.merge(options) end end # class Options end # module SPV
module EmailRegexpValidator #http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address def valid_email?(email) !/^.+@.+\..+$/.match(email).nil? end module_function :valid_email? end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :confirmable, :rememberable, :trackable, :validatable apply_simple_captcha # Setup accessible (or protected) attributes for your model #attr_accessible :email, :password, :password_confirmation, :remember_me attr_accessor :eula validates_uniqueness_of :nickname, :message => "Gebruikersnaam is bezet." validates_uniqueness_of :intname validates_length_of :nickname, :within => 2..90, :too_long => "De gebruikersnaam is te lang" validates_length_of :email, :maximum => 200, :message => "Het e-mail adres is te lang." validates :voornaam, :achternaam, presence: true validates_format_of :nickname, :with => /^[A-Z0-9_]*$/i, :message => "De gebruikersnaam bevat foutieve tekens, gebruik alleen letters en cijfers." validates_confirmation_of :email validates :eula, :acceptance => { :accept => 'yes' }, :if => :should_validate_eula? attr_protected :role_id, :created_at, :original_email, :ip belongs_to :role delegate :permissions, :to => :role has_many :login_sessions, :dependent => :destroy #avatars has_many :avatars, :dependent => :destroy has_one :avatar, :conditions => ['avatars.selected_avatar = ?', true] has_many :kunstvoorwerps has_many :interieurs, :dependent => :destroy has_many :aankoops has_many :rents has_many :forummessages has_many :forumtopics before_validation :create_intname # eula should be 'yes' every time its present on a form def should_validate_eula? new_record? || !eula.nil? end # Dont validate voornaam and achternaam fields when registering user def should_validate_voornaam? !new_record? end def can(name) if permissions != nil if permissions.find_by_name(name) return true else return false end else return false end end def isrole(name) if role.name.downcase == name return true else return false end end def activated self.confirmed_at != nil end def full_name "#{self.voornaam} #{self.tussenvoegsel} #{self.achternaam}" end protected def self.find_for_database_authentication(conditions) u = User.find_by_nickname(conditions[:nickname]) || User.find_by_email(conditions[:nickname]) u end def create_intname self.intname = self.nickname.gsub(/\W*\s*/, "").downcase unless self.intname end end
class Table < ApplicationRecord belongs_to :club has_one :reservation # Validates Table Name validates :table_name, presence: true, length: { maximum: 30 } # # # Validates Minimum as String validates :minimum, presence: true, length: { maximum: 15 } # Validates Minimum as Int # validates :minimum, presence: true, numericality: { only_integer: true } end
class UpdateOneGemJob < ApplicationJob def perform nekst = LaserGem.unscoped.order( updated_at: :asc).limit(1).first weeks = (Time.now - nekst.updated_at) / 1.week return if weeks < 1 UpdateLaserGemJob.perform_later( nekst.name ) end end
class Api::V1::InvoiceItems::InvoiceItemsInvoicesController < ApplicationController def show invoice_item = InvoiceItem.find(params["invoice_item_id"]) @invoice = invoice_item.invoice end end
class Admin < ActiveRecord::Base attr_accessible :email, :password, :password_confirmation validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i attr_accessor :password validates :password, :presence => true, :confirmation => true, :length => { :minimum => 5, :maximum => 40 }, :on => :create validates :email, :presence => true before_destroy :last_admin? before_save :encrypt_password def self.authenticate(email, password) admin = find_by_email(email.downcase) if admin && admin.password_hash == BCrypt::Engine.hash_secret(password, admin.password_salt) admin else nil end end def self.special_select @admins = self.all(:select => ["email", "id", "super_user"]) end def last_admin? if Admin.one? errors.add( :base, "You cannot delete the last admin") return false end end private def encrypt_password if password.present? self.password_salt = BCrypt::Engine.generate_salt self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) end end def self.one? if self.count == 1 @status = true end end end # == Schema Information # # Table name: admins # # id :integer not null, primary key # email :string(255) # password_hash :string(255) # password_salt :string(255) # created_at :datetime # updated_at :datetime # super_user :boolean #
# encoding: utf-8 control "V-52353" do title "The DBMS must provide a mechanism to automatically terminate accounts designated as temporary or emergency accounts after an organization-defined time period." desc "Temporary application accounts could ostensibly be used in the event of a vendor support visit where a support representative requires a temporary unique account in order to perform diagnostic testing or conduct some other support related activity. When these types of accounts are created, there is a risk that the temporary account may remain in place and active after the support representative has left. To address this, in the event temporary application accounts are required, the application must ensure accounts designated as temporary in nature shall automatically terminate these accounts after an organization-defined time period. Such a process and capability greatly reduces the risk that accounts will be misused, hijacked, or data compromised. User authentication and account management should be done via an enterprise-wide mechanism whenever possible. Examples of enterprise-level authentication/access mechanisms include, but are not limited to, Active Directory and LDAP. This requirement applies to cases where it is necessary to have accounts directly managed by Oracle. Temporary database accounts must be automatically terminated after an organization-defined time period in order to mitigate the risk of the account being used beyond its original purpose or timeframe.false" impact 0.5 tag "check": "If the organization has a policy, consistently enforced, forbidding the creation of emergency or temporary accounts, this is not a finding. If all user accounts are authenticated by the OS or an enterprise-level authentication/access mechanism, and not by Oracle, this is not a finding. Check DBMS settings, OS settings, and/or enterprise-level authentication/access mechanisms settings to determine if the site utilizes a mechanism whereby temporary or emergency accounts can be terminated after an organization-defined time period. If not, this is a finding. Check the profiles to see what the password_life_time is set to in the table dba_profiles. The password_life_time is a value stored in the LIMIT column, and identified by the value PASSWORD_LIFE_TIME in the RESOURCE_NAME column. SQL>select profile, resource_name, resource_type, limit from dba_profiles where upper(resource_name) like 'PASSWORD_LIFE_TIME'; Verify that the user in question is assigned to a profile with the PASSWORD_LIFE_TIME set to the amount of time the user is expected to be using the password. If not, this is a finding." tag "fix": "If all user accounts are authenticated by the OS or an enterprise-level authentication/access mechanism, and not by Oracle, no fix to the DBMS is required. If using database mechanisms to satisfy this requirement, use a profile with a distinctive name (for example, TEMPORARY_USERS), so that temporary users can be easily identified. Whenever a temporary user account is created, assign it to this profile. Create a job to lock accounts under this profile that are more than n days old, where n is the organization-defined time period." # Write Check Logic Here end
class LogStash::Inputs::KinesisCloudWatchLogSubscription::Worker include com.amazonaws.services.kinesis.clientlibrary.interfaces::IRecordProcessor attr_reader( :checkpoint_interval, :codec, :decorator, :logger, :output_queue, ) def initialize(*args) # nasty hack, because this is the name of a method on IRecordProcessor, but also ruby's constructor if !@constructed @codec, @output_queue, @decorator, @checkpoint_interval, @logger = args @next_checkpoint = Time.now - 600 @constructed = true else _shard_id, _ = args @decoder = java.nio.charset::Charset.forName("UTF-8").newDecoder() end end public :initialize def processRecords(records, checkpointer) records.each { |record| process_record(record) } if Time.now >= @next_checkpoint checkpoint(checkpointer) @next_checkpoint = Time.now + @checkpoint_interval end end def shutdown(checkpointer, reason) if reason == com.amazonaws.services.kinesis.clientlibrary.types::ShutdownReason::TERMINATE checkpoint(checkpointer) end end protected def checkpoint(checkpointer) checkpointer.checkpoint() rescue => error @logger.error("Kinesis worker failed checkpointing: #{error}") end def process_record(record) # I'm SOOOO SORRY. This is fugly. But it works. And lets me ship. # Please make this right. I was always getting incorrect header errors. # Either with JRuby zlib, or raw java zlib :( raw = record.getData File.open( '/tmp/sequence-' + record.sequenceNumber, 'w+') do |file| file.write(raw.array) end raw = `zcat /tmp/sequence-#{record.sequenceNumber}` File.delete "/tmp/sequence-#{record.sequenceNumber}" @codec.decode(raw) do |event| @decorator.call(event) @output_queue << event end rescue => error @logger.error("Error processing record: #{error}") end end
# encoding: utf-8 # core/plugin/gtk 互換プラグイン module Plugin::Gtk class GtkError < StandardError; end end Plugin.create(:gtk) do # 互換クラスのインスタンスを保持する @pseudo_instances = { postbox: Plugin::GUI::Postbox.instance, timeline: Plugin::GUI::Timeline.instance } def widgetof(slug_or_instance) if slug_or_instance.is_a? Symbol @pseudo_instances[slug_or_instance] else @pseudo_instances[slug_or_instance.class.to_s.split('::').last.downcase.to_sym] end end end
require 'spec_helper' describe "groups you are a part of" do let(:post1) {create(:post, :recipients => "testonid@onid.oregonstate.edu", :allow_onid => true)} before do RubyCAS::Filter.fake("testonid") visit signin_path visit root_path end context "when logged in as the recipient of a post" do before do post1 visit root_path end context "when looking at posts that you are a part of tab" do before do click_link "Groups you are part of" end it "should display that group" do expect(page).to have_content(post1.title) end context "when the onid is allowed to be displayed" do before do post1.allow_onid = true post1.save visit root_path click_link "Groups you are part of" end it "should display the onid" do expect(page).to have_content("Contact ONID") expect(page).to have_content(post1.onid) end end context "when the onid is not allowed to be displayed" do before do post1.allow_onid = false post1.save visit root_path click_link "Groups you are part of" end it "should not display the onid" do expect(page).to have_content("Contact ONID") expect(page).to_not have_content(post1.onid) end end end end end
class CLI attr_accessor :user, :animal, :last_selected_species def initialize @user = nil @animal = nil @last_selected_species = nil end def art_ puts " ______ _ ___ ______ _ | ___| | | / _ \\ | ___ \ | | | | _ ___ ___| |_ ______/ /_\\ \\_____| |_/ /__| |_ | _/ _ \/ __|__ |_______| _ |_____| __/ _\\ __| | || (_) \__ \ |_| | | | | | | | __/ |_ \\_| \___/|___/\\_| \\_| |_/ \\_| \\___|\\__|" puts"" puts"" end def art_two puts " ..,,,,,,,,,.. .,;%%%%%%%%%%%%%%%%%%%%;,. %%%%%%%%%%%%%%%%%%%%////%%%%%%, .,;%%;, .,;%/,%%%%%/////%%%%%%%%%%%%%%////%%%%,%%//%%%, .,;%%%%/,%%%///%%%%%%%%%%%%%%%%%%%%%%%%%%%%,////%%%%;, .,%%%%%%//,%%%%%%%%%%%%%%%%@@%a%%%%%%%%%%%%%%%%,%%/%%%%%%%;, .,%//%%%%//,%%%%///////%%%%%%%@@@%%%%%%///////%%%%,%%//%%%%%%%%, ,%%%%%///%%//,%%//%%%%%///%%%%%@@@%%%%%////%%%%%%%%%,/%%%%%%%%%%%%% .%%%%%%%%%////,%%%%%%%//%///%%%%@@@@%%%////%%/////%%%,/;%%%%%%%%/%%% %/%%%%%%%/////,%%%%///%%////%%%@@@@@%%%///%%/%%%%%//%,////%%%%//%%%' %//%%%%%//////,%/%a` 'a%///%%%@@@@@@%%////a` 'a%%%%,//%///%/%%%%% %///%%%%%%///,%%%%@@aa@@%//%%%@@@@S@@@%%///@@aa@@%%%%%,/%////%%%%% %%//%%%%%%%//,%%%%%///////%%%@S@@@@SS@@@%%/////%%%%%%%,%////%%%%%' %%//%%%%%%%//,%%%%/////%%@%@SS@@@@@@@S@@@@%%%%/////%%%,////%%%%%' `%/%%%%//%%//,%%%///%%%%@@@S@@@@@@@@@@@@@@@S%%%%////%%,///%%%%%' %%%%//%%%%/,%%%%%%%%@@@@@@@@@@@@@@@@@@@@@SS@%%%%%%%%,//%%%%%' `%%%//%%%%/,%%%%@%@@@@@@@@@@@@@@@@@@@@@@@@@S@@%%%%%,/////%%' `%%%//%%%/,%%%@@@SS@@SSs@@@@@@@@@@@@@sSS@@@@@@%%%,//%%//%' `%%%%%%/ %%S@@SS@@@@@Ss` .,,. 'sS@@@S@@@@%' ///%/%' `%%%/ %SS@@@@SSS@@S. .S@@SSS@@@@' //%%' /`S@@@@@@SSSSSs, ,sSSSSS@@@@@' %%//`@@@@@@@@@@@@@Ss,sS@@@@@@@@@@@'/ %%%%@@00`@@@@@@@@@@@@@'@@@@@@@@@@@'//%% %%%%%%a%@@@@000aaaaaaaaa00a00aaaaaaa00%@%%%%% %%%%%%a%%@@@@@@@@@@000000000000000000@@@%@@%%%@%%% %%%%%%a%%@@@%@@@@@@@@@@@00000000000000@@@@@@@@@%@@%%@%% %%%aa%@@@@@@@@@@@@@@0000000000000000000000@@@@@@@@%@@@%%%% %%@@@@@@@@@@@@@@@00000000000000000000000000000@@@@@@@@@%%%%% " end def greet puts "" puts ' Welcome Friend, Thank you for helping our pets have a temporary home!' puts puts puts " Let's Begin!" end def get_user_name puts "Please enter username!" username_input = gets.chomp #finds repeater customer or create a new user @user = User.find_by(name: username_input) if @user puts "Welcome, back #{@user.name}!" else @user = User.create(name: username_input) puts "Hi #{@user.name}! Looks like it's your first time." end end def main_menu puts "Please select one of the following options" puts "1. See your Fosterings" puts "2. Foster A New Animal" puts "3. Exit" u_input = gets.chomp if u_input == "1" # curr_user = User.find_by(name: @user.name) # curr_user.animals.each_with_index do |animal, index| @user.animals.each_with_index do |animal, index| puts "#{index+1}. #{animal.name}" end puts "Thank you for being an awesome Foster Parent!" puts "" puts "Pick from the following:" puts "A. Edit A Fostering" puts "B. Delete A Fostering" puts "C. Return to Main Menu" sec_input = gets.chomp.upcase if sec_input == "A" if @user.animals.empty? puts "You currently do not have fosterings. Please go back to the Main Menu!" else puts "Please enter the NAME you will like to change length of time" @user.animals.each_with_index do |animal, index| puts "#{index+1}. #{animal.name}" end four_input= gets.chomp.capitalize puts "Please type in the length of time you want to foster" puts "1. One week" puts "2. Two weeks" puts "3. Three weeks" puts "4. Four weeks" puts "5. Five weeks" fost_input = gets.chomp.capitalize ani= Animal.find_by(name: four_input) fos2 = Fostering.find_by(animal_id: ani.id, user_id: @user.id) fos2.update(length_of_time: fost_input) puts "Thank you changing your length of time to #{fos2.length_of_time}!" main_menu end end # un_input = gets.chomp # if @user.fosterings.empty? # binding.pry # end # Fostering.where("user_id = '#{user.id}' and animal_id = '#{animal.id}'") if sec_input == "B" if @user.animals.empty? puts "You currently do not have fosters. Please go back to the Main Menu!" main_menu else puts "Type the name of the animal you will like to remove" @user.animals.each_with_index do |animal, index| puts "#{index+1}. #{animal.name}" third_input = gets.chomp.capitalize an_remove = Animal.find_by(name: third_input) an_remove.delete end end end main_menu elsif u_input == "2" select_species_menu elsif u_input == "3" puts "Not today, but maybe tomorrow!" exit end end def select_species_menu #user selects animal species to foster puts "Please, enter NUMBER to select an animal you will like to foster?" puts "1. Dog" puts "2. Cat" puts "3. Rabbit" puts "4. Parrot" puts "5. Guinea pig" #picks number that associates with species user will like to foster species_input = gets.chomp.capitalize #displays list of animals available to foster for each specie if species_input == "1" picks_list("Dog") @last_selected_species = "Dog" # array_of_dogs = Animal.where(species: "Dog") # puts "" # puts "Please choose from the available candidates!" # array_of_dogs.each_with_index do |dog, index| # puts "#{index+1}. #{dog.name}" # end elsif species_input == "2" picks_list("Cat") @last_selected_species = "Cat" elsif species_input == "3" picks_list("Rabbit") @last_selected_species = "Rabbit" elsif species_input == "4" picks_list("Parrot") @last_selected_species = "Parrot" elsif species_input == "5" picks_list("Guinea pig") @last_selected_species = "Guinea pig" end #user picks animal name puts "Please TYPE name of animal you will like to foster!" animal_selection_name = gets.chomp.capitalize #method for misspelled name misspelled_name(animal_selection_name) #method_to_put_selection_attributes(animal_selection_name) end #refactored if loop ieration def picks_list(name) array_of_animals = Animal.where(species: name) puts "Please choose from the available candidates!" array_of_animals.each_with_index do |animal, index| puts "#{index+1}. #{animal.name}" end end def method_to_put_selection_attributes(name) #need iterator to print out each attribute from array @animal = Animal.find_by(name: name) puts "Name: #{@animal.name}" puts "Birth Year: #{@animal.birth_year}" puts "Size: #{@animal.size}" puts "Gender: #{@animal.gender}" puts "Spayed or Neutered: #{@animal.spayed_neutered}" foster_option end def misspelled_name(name) if @animal = Animal.find_by(name: name) method_to_put_selection_attributes(name) else puts "Please enter a Valid name!" gets_input = gets.chomp.capitalize misspelled_name(gets_input) end end def foster_option puts "Would you like to foster the animal you selected? y/n" ans_input = gets.chomp.downcase if ans_input == "y" puts "Yassss!!!!!, The world needs more people like you!!!!!" time = foster_length fostering = Fostering.create(user_id: @user.id, animal_id: @animal.id, length_of_time: time) # binding.pry # @user.fosterings elsif ans_input == "n" puts "Would you like to see another animal? y/n" end sec_input = gets.chomp.downcase if sec_input == "y" select_species_menu else sec_input == "n" puts "Please, come back as we're always getting new animals to foster." end end # def foster_mod # input = gets.chomp # p Fostering.find_by :name input # end def foster_length puts puts " Enter NUMBER to indicate how long you can foster this bundle of joy!" puts "1. One week" puts "2. Two weeks" puts "3. Three weeks" puts "4. Four weeks" puts "5. Five weeks" foster_length_input = gets.chomp if foster_length_input == "1" puts "You're amazing human. Thank you for sharing your home for 1 week!" puts "Come back soon!" return "1 week" exit elsif foster_length_input == "2" puts "You're amazing human. Thank you for sharing your home for 2 weeks!" puts "Come back soon!" return "2 weeks" exit elsif foster_length_input =="3" puts "You're amazing human. Thank you for sharing your home for 3 weeks!" puts "Come back soon!" return "3 weeks" exit elsif foster_length_input == "4" puts "You're amazing human. Thank you for sharing your home for 4 weeks!" puts "Come back soon!" return "4 weeks" exit elsif foster_length_input == "5" puts "You're amazing human. Thank you for sharing your home for 5 weeks!" puts "Come back soon!" return "5 weeks" exit end end end
class TermsController < ApplicationController before_action :logged_in_user, only: [:index, :new, :edit, :destroy] before_action :check_guest_user def new @term = Term.new end def create @term = Term.new(term_params) if @term.save flash[:success] = "新しい用語が登録されました" redirect_to terms_url else render 'new' end end def index @terms = Term.search(params[:search]).order('id') end def ajax_search @terms = Term.page().partiallysearch(params[:key]) @nicknames = [] for term in @terms nickname = User.find(term.user_id).nickname @nicknames.push(nickname) end render json: [@terms, @nicknames] end def edit @term = Term.find(params[:id]) end def update @term = Term.find(params[:id]) if @term.update_attributes(term_params) flash[:success] = "用語が更新されました" redirect_to terms_url else render 'edit' end end def destroy @term = Term.find(params[:id]) @term.destroy flash[:success] = "用語が削除されました" redirect_to terms_url end private def term_params params.require(:term).permit(:name, :content, :key, :create_user_id, :user_id) end end
require 'test_helper' module Adminpanel class SortableGalleryUnitTest < ActiveSupport::TestCase setup :instance_objects def test_has_and_ordered_scope gallery = adminpanel_galleries(:one) ordered_galleries = gallery.galleryfiles.ordered.pluck(:position) assert_equal [1,2,3,4,5], ordered_galleries end def test_creation_callback gallery = adminpanel_galleries(:one) assert_equal 5, gallery.galleryfiles.count galleryfile = gallery.galleryfiles.new galleryfile.save assert_equal 6, galleryfile.reload.position assert_equal 6, gallery.galleryfiles.count end def test_destroy_callback @fgo_p2.destroy assert_equal 1, @fgo_p1.reload.position assert_equal 2, @fgo_p3.reload.position assert_equal 3, @fgo_p4.reload.position assert_equal 4, @fgo_p5.reload.position assert_equal 1, @sgo_p1.reload.position assert_equal 2, @sgo_p2.reload.position @fgo_p1.destroy assert_equal 1, @fgo_p3.reload.position assert_equal 2, @fgo_p4.reload.position assert_equal 3, @fgo_p5.reload.position assert_equal 1, @sgo_p1.reload.position assert_equal 2, @sgo_p2.reload.position @fgo_p5.destroy assert_equal 1, @fgo_p3.reload.position assert_equal 2, @fgo_p4.reload.position assert_equal 1, @sgo_p1.reload.position assert_equal 2, @sgo_p2.reload.position end def test_moving_and_object_to_lower_priority # make sure fixtures are as expected assert_equal 1, @fgo_p1.position assert_equal 2, @fgo_p2.position assert_equal 3, @fgo_p3.position assert_equal 4, @fgo_p4.position assert_equal 5, @fgo_p5.position assert_equal 1, @sgo_p1.position assert_equal 2, @sgo_p2.position @fgo_p2.move_to_position(5) # make sure they are updated from database assert_equal 1, @fgo_p1.reload.position assert_equal 5, @fgo_p2.reload.position assert_equal 2, @fgo_p3.reload.position assert_equal 3, @fgo_p4.reload.position assert_equal 4, @fgo_p5.reload.position assert_equal 1, @sgo_p1.reload.position assert_equal 2, @sgo_p2.reload.position end def test_moving_and_object_to_higher_priority @fgo_p5.move_to_position(1) # make sure they are updated from database assert_equal 2, @fgo_p1.reload.position assert_equal 3, @fgo_p2.reload.position assert_equal 4, @fgo_p3.reload.position assert_equal 5, @fgo_p4.reload.position assert_equal 1, @fgo_p5.reload.position assert_equal 1, @sgo_p1.reload.position assert_equal 2, @sgo_p2.reload.position end def test_moving_to_same_position @fgo_p5.move_to_position(5) # make sure they are updated from database assert_equal 1, @fgo_p1.reload.position assert_equal 2, @fgo_p2.reload.position assert_equal 3, @fgo_p3.reload.position assert_equal 4, @fgo_p4.reload.position assert_equal 5, @fgo_p5.reload.position assert_equal 1, @sgo_p1.reload.position assert_equal 2, @sgo_p2.reload.position end private def instance_objects # fgo => first gallery object # sgo => second gallery object (since there are 2 galleries according to fixtures) # p1 => means original position 1 and so on... @fgo_p1 = adminpanel_images(:first) @fgo_p2 = adminpanel_images(:second) @fgo_p3 = adminpanel_images(:third) @fgo_p4 = adminpanel_images(:fourth) @fgo_p5 = adminpanel_images(:fifth) @sgo_p1 = adminpanel_images(:first_2) @sgo_p2 = adminpanel_images(:second_2) end end end
class DistillerSerializer < ActiveModel::Serializer attributes :id, :name, :region, :region_name belongs_to :region has_many :whiskeys def region_name object.region.country end end
require "rails_helper" RSpec.describe RingGroupCall, type: :model do context "validations" do it "is valid with valid attributes" do expect(build_stubbed(:ring_group_call)).to be_valid end it { should validate_presence_of(:from_phone_number) } it { should validate_presence_of(:from_sid) } end describe ".for_ring_group" do it "finds calls for a ring group" do ring_group = create(:ring_group) call = create(:ring_group_call, ring_group: ring_group) result = described_class.for_ring_group(ring_group) expect(result).to include(call) end end describe ".receive" do it "creates a ring group call and associated incoming calls" do ring_group = create(:ring_group_with_number) create(:ring_group_member, :available, ring_group: ring_group) create(:ring_group_member, :available, ring_group: ring_group) call = described_class.receive( ring_group: ring_group, from: "+18282555500", sid: "1234" ) expect(call.ring_group).to eq(ring_group) expect(call.incoming_calls.count).to eq(2) expect(Contact.count).to eq(2) end end describe "#owner?" do it "returns true for a user that is a member of the ring group" do user = create(:user) ring_group = create(:ring_group, users: [user]) call = create(:ring_group_call, ring_group: ring_group) result = call.owner?(user) expect(result).to be(true) end it "returns false for a user that is not a member of the ring group" do user = create(:user) call = create(:ring_group_call) result = call.owner?(user) expect(result).to be(false) end end describe "#greeting" do it "does not play a greeting" do response = Twilio::TwiML::VoiceResponse.new result = subject.greeting(response) expect(result.to_s).not_to include("</Play>") end end describe "#hangup" do it "sets the ring group call to missed and ends all associated incoming calls" do ring_group_call = create(:ring_group_call) create(:incoming_call, ring_group_call: ring_group_call) create(:incoming_call, ring_group_call: ring_group_call) end_call = stub_const("EndCall", spy) result = ring_group_call.hangup expect(result).to be(true) expect(end_call).to have_received(:call).twice expect(ring_group_call.reload).to be_missed end end describe "#unanswered?" do it "returns true if no incoming calls were answered" do ring_group_call = create(:ring_group_call) create(:incoming_call, :no_answer, ring_group_call: ring_group_call) result = ring_group_call.unanswered? expect(result).to be(true) end it "returns false if it has a incoming call that was answered" do ring_group_call = create(:ring_group_call) create(:incoming_call, :in_progress, ring_group_call: ring_group_call) result = ring_group_call.unanswered? expect(result).to be(false) end end end
module BCrypt # A password management class which allows you to safely store users' passwords and compare them. # # Example usage: # # include BCrypt # # # hash a user's password # @password = Password.create("my grand secret") # @password #=> "$2a$12$C5.FIvVDS9W4AYZ/Ib37YuWd/7ozp1UaMhU28UKrfSxp2oDchbi3K" # # # store it safely # @user.update_attribute(:password, @password) # # # read it back # @user.reload! # @db_password = Password.new(@user.password) # # # compare it after retrieval # @db_password == "my grand secret" #=> true # @db_password == "a paltry guess" #=> false # class Password < String # The hash portion of the stored password hash. attr_reader :checksum # The salt of the store password hash (including version and cost). attr_reader :salt # The version of the bcrypt() algorithm used to create the hash. attr_reader :version # The cost factor used to create the hash. attr_reader :cost class << self # Hashes a secret, returning a BCrypt::Password instance. Takes an optional <tt>:cost</tt> option, which is a # logarithmic variable which determines how computational expensive the hash is to calculate (a <tt>:cost</tt> of # 4 is twice as much work as a <tt>:cost</tt> of 3). The higher the <tt>:cost</tt> the harder it becomes for # attackers to try to guess passwords (even if a copy of your database is stolen), but the slower it is to check # users' passwords. # # Example: # # @password = BCrypt::Password.create("my secret", :cost => 13) def create(secret, options = {}) cost = options[:cost] || BCrypt::Engine.cost raise ArgumentError if cost > 31 Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost))) end def valid_hash?(h) h =~ /^\$[0-9a-z]{2}\$[0-9]{2}\$[A-Za-z0-9\.\/]{53}$/ end end # Initializes a BCrypt::Password instance with the data from a stored hash. def initialize(raw_hash) if valid_hash?(raw_hash) self.replace(raw_hash) @version, @cost, @salt, @checksum = split_hash(self) else raise Errors::InvalidHash.new("invalid hash") end end # Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise. def ==(secret) super(BCrypt::Engine.hash_secret(secret, @salt)) end alias_method :is_password?, :== private # Returns true if +h+ is a valid hash. def valid_hash?(h) self.class.valid_hash?(h) end # call-seq: # split_hash(raw_hash) -> version, cost, salt, hash # # Splits +h+ into version, cost, salt, and hash and returns them in that order. def split_hash(h) _, v, c, mash = h.split('$') return v.to_str, c.to_i, h[0, 29].to_str, mash[-31, 31].to_str end end end
class Answer < ApplicationRecord belongs_to :Question belongs_to :Quiz end
# == Schema Information # # Table name: participants # # id :integer not null, primary key # nombre :string # ocupacion :string # interes :string # correo :string # telefono :string # created_at :datetime not null # updated_at :datetime not null # class Participant < ApplicationRecord validates :nombre, presence: true validates :correo, presence: true validates :telefono, presence: true end
# Christie Finnie # Due: 2019-12-16 # Specs for testing the bowling score keeper require "rspec" require "./bowlingScoreKeeper.rb" RSpec.describe "Bowler" do context "When strike in frame 1" do it "Score is nil" do player = Bowler.new player.rolls("X") expect(player.score).to eq nil end end context "When strink in frame 1, spare in frame 2" do it "Score is 20" do player = Bowler.new player.rolls("X") player.rolls(7, "/") expect(player.score).to eq 20 end end context "When strike in frame 1, 5 in frame 2" do it "Score is 20" do player = Bowler.new player.rolls("X") player.rolls(4, 1) expect(player.score).to eq 20 end end context "When spare in frame 1" do it "Score is nil" do player = Bowler.new player.rolls(7, "/") expect(player.score).to eq nil end end context "When spare in frame 1, 0 for the first roll of frame 2" do it "Score is 10" do player = Bowler.new player.rolls(7, "/") player.rolls(0, "/") expect(player.score).to eq 10 end end context "When there's a gutter for every single roll" do it "Score is 0" do player = Bowler.new player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) player.rolls(0, 0) expect(player.score).to eq 0 end end context "When there's a strike for every single roll" do it "Score is 300" do player = Bowler.new player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X", "X", "X") expect(player.score).to eq 300 end end context "When there's a strike for every single roll but the last is a 5" do it "Score is 295" do player = Bowler.new player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X") player.rolls("X", "X", 5) expect(player.score).to eq 295 end end context "When there's a crazy mix 1" do it "Score is 109" do player = Bowler.new player.rolls("X") player.rolls(5, 1) player.rolls(1, 3) player.rolls(4, 5) player.rolls(7, 2) player.rolls(3, 6) player.rolls(4, 4) player.rolls(8, "/") player.rolls("X") player.rolls(6, 3) expect(player.score).to eq 109 end end context "When there's a crazy mix 2" do it "Score is 79" do player = Bowler.new player.rolls(6, "/") player.rolls(3, 3) player.rolls(3, 3) player.rolls(3, 3) player.rolls(3, 3) player.rolls(3, 3) player.rolls(3, 3) player.rolls(3, 3) player.rolls(3, 3) player.rolls("X", 5, 3) expect(player.score).to eq 79 end end end
# $LICENSE # Copyright 2013-2014 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. require 'ffwd/connection' require_relative 'parser' require_relative 'types_db' module FFWD::Plugin::Collectd class Connection < FFWD::Connection def initialize bind, core, config @bind = bind @core = core @db = TypesDB.open config[:types_db] @key = config[:key] end def receive_data(data) Parser.parse(data) do |m| plugin = m[:plugin] type = m[:type] plugin_i = m[:plugin_instance] type_i = m[:type_instance] read_values(plugin, plugin_i, type, type_i, m[:values]) do |a, v| @core.input.metric( :key => @key, :time => m[:time], :value => v, :host => m[:host], :attributes => a) @bind.increment :received_metrics end end rescue => e @bind.log.error "Failed to receive data", e end def read_values(plugin, plugin_i, type, type_i, values, &block) if values.size == 1 return read_single(plugin, plugin_i, type, type_i, values[0], &block) end read_multiple(plugin, plugin_i, type, type_i, values, &block) end def read_single(plugin, plugin_i, type, type_i, v) a = {:plugin => plugin, :type => type} a[:plugin_instance] = plugin_i unless plugin_i.nil? or plugin_i.empty? a[:type_instance] = type_i unless type_i.nil? or type_i.empty? a[:value_type] = v[0] a[:what] = format_what(a) yield a, v[1] end # Handle payload with multiple values. # # If a database is not available, plugin_instance becomes the running # integer, or index of the value. # # If a database is avaialble, it would follow the current structure and # determine what the name of the plugin_instance is. # # http://collectd.org/documentation/manpages/types.db.5.shtml def read_multiple(plugin, plugin_i, type, type_i, values) values.each_with_index do |v, i| a = {:plugin => plugin, :type => type} a[:plugin_instance] = plugin_i unless plugin_i.nil? or plugin_i.empty? a[:type_instance] = format_type_instance(type, i) a[:value_type] = v[0] a[:what] = format_what(a) yield a, v[1] end end def format_type_instance type, i if @db return @db.get_name(type, i) end i.to_s end def format_what a p = if a[:plugin_instance] "#{a[:plugin]}-#{a[:plugin_instance]}" else a[:plugin].to_s end t = if a[:type_instance] "#{a[:type]}-#{a[:type_instance]}" else a[:type].to_s end "#{p}/#{t}" end end end
require 'spec_helper' describe Submission do context "validations" do it "should validate the presence of a title" do FactoryGirl.build(:submission, title: "").should_not be_valid end it "should validate the presence of a submitter" do FactoryGirl.build(:submission, submitter: "").should_not be_valid end it "should validate the presence of a url" do FactoryGirl.build(:submission, url: "").should_not be_valid end context "against a non-blank url" do it "validates a youtube.com domain" do FactoryGirl.build(:submission, url: "blah").should_not be_valid #implies that urlify kicks in and does not raise error FactoryGirl.build(:submission, url: "http://google.com").should_not be_valid FactoryGirl.build(:submission, url: "http://youtube.com/watch?v=v3MIFSJMKnw").should be_valid FactoryGirl.build(:submission, url: "http://www.youtube.com/watch?v=v3MIFSJMKnw").should be_valid FactoryGirl.build(:submission, url: "http://m.youtube.com/watch?v=v3MIFSJMKnw").should be_valid FactoryGirl.build(:submission, url: "http://youtu.be/1acVM7_rWw4").should be_valid end it "validates that a video id query is valid" do FactoryGirl.build(:submission, url: "http://youtu.be/1acVM7_rWw4").should be_valid # should not complain for lack of query FactoryGirl.build(:submission, url: "http://www.youtube.com").should_not be_valid # missing path, query FactoryGirl.build(:submission, url: "http://youtube.com/blahblah").should_not be_valid # wrong path FactoryGirl.build(:submission, url: "http://youtube.com/?feature=iamawesome").should_not be_valid # missing path /watch FactoryGirl.build(:submission, url: "http://www.youtube.com/watch?list=PL41C0957B91CAA249&feature=mh_lolz").should_not be_valid # missing video id FactoryGirl.build(:submission, url: "http://www.youtube.com/watch?v=v3MIFSJMKnw&list=PL41C0957B91CAA249&feature=mh_lolz").should be_valid end end end end
class RenameTargetTypeColumn < ActiveRecord::Migration[5.2] def change rename_column :targets, :type, :target_type end end
unless ARGV.size == 1 raise "no valid path to outlook-exported file was provided.\n Call script with 'ruby #{__FILE__} /path/to/contacts.csv'" end raise "File #{ARGV[0]} does not exist!" unless File.exist?(ARGV[0]) FNAME = ARGV[0] MAX_FIELDS = 61 FORMAT = 'bom|utf-8'.freeze def i(name) name = name.lower.to_sym if name.is_a? String @header.index(name) end def conform_csv_contact(contact) contact.map! { |c| c.delete('"').strip.chomp } if contact.size == MAX_FIELDS contact elsif contact.size == MAX_FIELDS + 1 contact[0..MAX_FIELDS - 2] + [contact[MAX_FIELDS - 1], contact[MAX_FIELDS]] else puts "contact had size of #{contact.size} and will not be imported.\n raw contact: #{contact.join(', ')}" nil end end def overlap?(entry1, entry2) !(entry1.nil? || entry1.empty? || entry1 == entry2) end def similar_field?(field_a, field_b) field_a.to_s.start_with?(field_b.to_s[0..4]) || field_a.to_s.end_with?(field_b.to_s[-5..-1]) end def first_similar_field(field) @header.find { |name| similar_field?(name, field) } end def next_similar_field(field) ind = i(field) @header[ind + 1] if similar_field?(field, @header[ind + 1]) end def name_field?(contact) name_fields = %i[first_name middle_name last_name nickname given_yomi surname_yomi] name_fields.all? { |field| contact[field].nil? || contact[field].empty? } end def handle_overlaps(overlays, merged_contact) overlays.each do |field, entries| next_field = first_similar_field(field) entries.each do |entry| while overlap?(merged_contact[next_field], entry) next_field = next_similar_field(next_field) break if next_field.nil? end if next_field.nil? puts "Field #{field} could not be merged and will be lost. #{merged_contact[:first_name]} #{merged_contact[:last_name]}: #{entry}" else merged_contact[next_field] = entry end end end end filtered = [] contacts = [] total_contacts = 0 File.open(FNAME, "r:#{FORMAT}") do |f| @header_raw = f.readline.split(',').map { |h| h.strip.chomp } @header = @header_raw.map do |column| column.delete('\'').gsub(%r{\s|-|\/}, '_').downcase.to_sym end f.each_line do |l| contact = conform_csv_contact(l.split(',')) if contact contacts << @header.zip(contact).to_h.reject { |_, entry| entry.empty? } end total_contacts += 1 end end grouped_contacts = contacts .reject { |contact| name_field?(contact) } .group_by { |contact| contact[:first_name].to_s + contact[:last_name].to_s } grouped_contacts.each_value do |same_contacts| merged_contact = {} overlays = {} same_contacts.each do |contact| contact.each do |field, entry| if overlap?(merged_contact[field], entry) overlays[field] ||= [] overlays[field] << entry unless overlays[field].include?(contact[field]) else merged_contact[field] = entry end end end handle_overlaps(overlays, merged_contact) filtered << merged_contact end File.open(FNAME.split('.').first + '_merged.csv', 'w:utf-8', bom: true) do |f| f.puts @header_raw.join(',') filtered.each do |contact| f.puts @header.map { |field| contact[field] }.join(',') end end puts "merged #{total_contacts} contacts to #{filtered.size} contacts."
# -*- mode: ruby -*- # vi: set ft=ruby : BOX_IMAGE = "centos/7" NODE_COUNT = 2 Vagrant.configure("2") do |config| config.vm.define "master" do |subconfig| subconfig.vm.box = BOX_IMAGE subconfig.vm.hostname = "master" subconfig.dns.tld = "master" subconfig.vm.network :private_network, ip: "10.0.0.10" subconfig.vm.provider :virtualbox do |vb| vb.memory = 1024 vb.cpus = 2 vb.gui = false end end (1..NODE_COUNT).each do |i| config.vm.define "node#{i}" do |subconfig| subconfig.vm.box = BOX_IMAGE subconfig.vm.hostname = "node#{i}" subconfig.dns.tld = "node#{i}" subconfig.vm.network :private_network, ip: "10.0.0.#{i + 20}" subconfig.vm.provider :virtualbox do |vb| vb.memory = 1024 vb.cpus = 2 vb.gui = false end end end config.vm.provision "ansible" do |ansible| ansible.playbook = "inicio.yml" end if i >= 1 config.vm.provision :shell, inline: "PYTHONUNBUFFERED=1 ansible-playbook /vagrant/master.yml " else config.vm.provision :shell, inline: "PYTHONUNBUFFERED=1 ansible-playbook /vagrant/nodes.yml " end if Vagrant.has_plugin?("vagrant-cachier") config.cache.scope = :box end end
require File.join(Dir.pwd, 'spec', 'spec_helper') describe 'UserProcessList' do before do simulate_connection_to_server end after do end it 'should pass if user process list attribute is not specifed' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_process_list, { :total_entries => 1, :total_pages => 1, :processes => [FactoryGirl.attributes_for(:user_process)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) process_list = TheCityAdmin::UserProcessList.new({:user_id => user_id}) process = process_list[0] process.name.should == "Member Process" end it 'should pass if user process list is empty' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_process_list, { :total_entries => 1, :total_pages => 1, :processes => [] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) process_list = TheCityAdmin::UserProcessList.new({:user_id => user_id}) process_list.empty?.should be_true end it 'should return a valid list of user processes' do user_id = 123 page = 2 request_data = FactoryGirl.attributes_for(:user_process_list, { :total_entries => 1, :total_pages => 1, :processes => [FactoryGirl.attributes_for(:user_process)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) process_list = TheCityAdmin::UserProcessList.new({:user_id => user_id, :page => page}) process = process_list[0] process.name.should == "Member Process" end it 'should iterate using *each* method' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_process_list, { :total_entries => 1, :total_pages => 1, :processes => [FactoryGirl.attributes_for(:user_process)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) process_list = TheCityAdmin::UserProcessList.new({:user_id => user_id}) processes = [] process_list.each { |process| processes << process.name } processes.should == ["Member Process"] end it 'should iterate using *collect* method' do user_id = 123 request_data = FactoryGirl.attributes_for(:user_process_list, { :total_entries => 1, :total_pages => 1, :processes => [FactoryGirl.attributes_for(:user_process)] }).to_json TheCityAdmin.stub(:admin_request).and_return( TheCityResponse.new(200, request_data) ) process_list = TheCityAdmin::UserProcessList.new({:user_id => user_id}) processes = process_list.collect { |process| process.name } processes.should == ["Member Process"] end end