text
stringlengths
10
2.61M
class CoursesController < ApplicationController before_filter :find_course, except: [] before_filter :authenticate_user!, only: [] before_filter :find_course, except: [] def home remember_current_page @section = get_section respond_to do |format| format.html { render } format.json { render json: @course} end end def get_pane kind = params[:kind] if kind == 'sections' respond_to do |format| format.html { render partial: "courses/sections_pane", locals: {course: @course }} end else pane = @course.doc_of_kind kind respond_to do |format| format.html { render partial: "courses/pane", locals: {pane: pane }} end end end ## ## Rest routes ## # # POST courses # # POST courses.json # def create # @course = Course.new(params[:course]) # # respond_to do |format| # if @course.save # format.html { redirect_to course_url(@course), notice: 'Course was successfully created.' } # format.js # format.json { render json: @course, status: :created, location: @course } # else # format.html { render action: "new" } # format.js # format.json { render json: @course.errors, status: :unprocessable_entity } # end # end # end # # # GET courses/new # # GET courses/new.json # def new # @course = Course.new(params[:course]) # respond_to do |format| # format.html # new.html.erb # format.json { render json: @course } # end # end # # # PUT courses/1 # # PUT courses/1.json # def update # respond_to do |format| # if @course.update_attributes(params[:course]) # format.html { redirect_to course_url(@course), notice: 'Course was successfully updated.' } # format.json { head :no_content } # else # format.html { render action: "edit" } # format.json { render json: @course.errors, status: :unprocessable_entity } # end # end # end protected def get_section if params[:section_id] return Section.find params[:section_id] elsif params[:teacher_id] && params[:teacher_id] && params[:block] && params[:year] return Section.find_by course: @course, teacher: params[:teacher_id], block: params[:block], year: params[:year] else return nil end end def find_course @course = Course.find(params[:id]) end end
class Groups::ResponsesController < ApplicationController before_action :check_user, only: [:create, :accept] before_action :authenticate_user!, only: [:new] before_action :find_group def new @response = Response.new @group.questions.each do |q| @response.answers << Answer.new(question_id: q.id) end end def create @response = Response.create response_params.merge(responce_user_id: current_user.id, group_id: @group.id) flash[:notice] = "Requested to join #{@response.group.name}'s questions" if @response.responce_user_id == @response.group.user_id @response.delete else ResponseMailer.with(response_user: @response.responce_user, group: @response.group).new_response_to_group.deliver_later end redirect_to root_path end def accept unless @group.user == current_user redirect_to access_restricted_path end @response = @group.responses.find(params[:id]) @response.update(accepted: true) render 'accept', layout: false ResponseMailer.with(group: @group, response_user: @response.responce_user).response_to_group_accepted.deliver_later end protected def find_group @group = Group.find(params[:group_id]) end def response_params params.permit(:response).permit(:user_id, :answers_attributes => [:question_id, :text]) end end
require File.expand_path('../../test_helper', __FILE__) class GroupTest < ActiveSupport::TestCase fixtures :users, :roles, :groups_users, :members, :member_roles, :issue_categories, :projects def setup @admin = User.where(:admin => true).first @user = User.logged.where(:admin => false).first @global_role = Role.find(2) @group = Group.first @x_role = GlobalRole.create!(:role => @global_role, :principal => @group) end def test_creates_individual_global_role_when_adding_user add_user_to_group assert @user.global_roles.include?(@global_role) end def test_destroys_individual_global_role_when_removing_user add_user_to_group remove_user_from_group assert !@user.global_roles.include?(@global_role) end def test_destroys_global_roles_when_group_destroyed clear_users assert_difference('GlobalRole.count', -1) do @group.destroy end end private def add_user_to_group(user = @user) @group.users << user @group.save! user.reload end def remove_user_from_group(user = @user) @group.users.delete(user) @group.save! user.reload end def clear_users @group.users.clear @group.save! end end
class Order < ApplicationRecord after_create :sell has_many :order_products validates_presence_of :products has_many :products, through: :order_products def sell products = self.products products.each do |product| product.sell product.sold_out end end end
json.array!(@user_stats) do |user_stat| json.extract! user_stat, :id, :feet_height, :inches_height, :age, :weight, :user_id json.url user_stat_url(user_stat, format: :json) end
class CreateAssociations < ActiveRecord::Migration def change create_table :associations do |t| t.string :name t.text :description t.text :snippet t.string :mls_tag t.string :image t.timestamps end add_index :associations, :mls_tag, :unique => true end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? before_action :store_user_location!, if: :storable_location? layout :layout_by_resource protected def cors_set_access_control_headers headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, PATCH, OPTIONS' headers['Access-Control-Request-Method'] = '*' headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' end def configure_permitted_parameters attributes = [:nombre, :apellido, :dni, :movil , :calle, :ciudad, :provincia, :codigo_postal, :notificacion ,:email, :password_confirmation, :terms, :remember_me, :latitude, :longitude, :pais, :id_heroku__c ] devise_parameter_sanitizer.permit :sign_up, keys: attributes devise_parameter_sanitizer.permit :account_update, keys: attributes end def layout_by_resource if devise_controller? && resource_name == :user && action_name == "edit" "admin" end end protected def after_sign_in_path_for(resource_or_scope) url = stored_location_for(resource_or_scope) if url.nil? admin_index_path else if url.include?("api") admin_index_path else url #|| super end end end def after_sign_out_path_for(resource_or_scope) if !stored_location_for(resource_or_scope).nil? if !stored_location_for(resource_or_scope).include?("api") stored_location_for(resource_or_scope) #|| super else admin_index_path end else admin_index_path end end private def storable_location? request.get? && is_navigational_format? && !devise_controller? && !request.xhr? end def store_user_location! store_location_for(:user, request.fullpath) end end
class StaffsController < ApplicationController def index @staff = Staff.new end def new @staff = Staff.new end def create @staff = Staff.new(staff_params) if @staff.save flash[:notice] = "スタッフを登録しました" redirect_to staffs_path(current_user.id) else flash[:notice] = "入力項目に誤りがあります" render :index end end def destroy staff = current_user.staffs.find(params[:id]) staff.destroy flash[:notice] = "スタッフを除名しました" redirect_to staffs_path(current_user.id) end private def staff_params params.require(:staff).permit(:nickname).merge(user_id: current_user.id) end end
class User include Mongoid::Document include Mongoid::Timestamps API_KEY = ENV['TWITTER_API_KEY'] API_SECRET = ENV['TWITTER_API_SECRET'] has_many :beacons # omniauth fields # should move to separate account object field :provider, type: String field :uid, type: String field :name, type: String field :token, type: String field :secret, type: String field :api_token, type: String field :expires, type: DateTime field :handle, type: String field :email, type: String validates_uniqueness_of :handle validates_uniqueness_of :api_token attr_accessible :name, :handle, :email def self.create_with_omniauth(auth) create! do |user| user.provider = auth["provider"] user.uid = auth["uid"] user.name = auth["info"]["name"] user.token = auth["credentials"]["token"] user.secret = auth["credentials"]["secret"] if user.name user.handle = user.name.split(' ')[0] + user.id.to_s else user.handle = "user#{user.id}" end user.api_token = user.id user.expires = DateTime.now end end def self.addurls(urls) user.urls = urls end def self.prepare_access_token(user) consumer = OAuth::Consumer.new(API_KEY, API_SECRET, { site: "http://www.twitter.com/" }) #token_hash = {:oauth_token => user.token,:oauth_token_secret => user.secret} access_token = OAuth::AccessToken.new(consumer, user.token, user.secret) end def self.with_access_token(token) puts 'hi' puts token user = User.where(api_token: token, expires: {"$gt" => DateTime.now}).first end def as_json(options={}) { id: id, updated_at: updated_at.to_i, name: name, handle: handle } end def authentication_json { id: id, updated_at: updated_at.to_i, name: name, handle: handle, access_token: api_token } end def reset_api_token self.api_token = SecureRandom.urlsafe_base64 self.expires = DateTime.now + 7.days save end def extend_api_token self.expires = DateTime.now + 3.days end def invalidate_token update_attribute :expires, DateTime.now end end
require 'rails_helper' RSpec.describe OrdersController, type: :controller do context 'when user not logged in' do describe 'GET #index' do it 'redirects to login page' do get :index expect(response).to redirect_to new_user_session_path end end end context 'when user logged in' do let(:user) { FactoryGirl.create(:user) } let(:cart) { FactoryGirl.create(:cart) } let(:line_item) { FactoryGirl.create(:line_item) } let(:order_params) { FactoryGirl.create(:order) } before do sign_in user end describe 'GET #index' do it 'renders the :index view' do get :index expect(response).to render_template :index end end describe 'Post #create' do @order = FactoryGirl.create :order it 'should create order' do assert_difference('Order.count') do post :create, order: { name: 'sasha', email: 'hhhh@kkk.com', price: '23', address: 'gfdgdfgdsdfgsdgsdfgsdgsdf' } end assert_redirected_to root_path end end end end
class User < ActiveRecord::Base validates :email, :username, uniqueness: true validates :email, format: {with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/} validates :password, :username, :email, :firstname, :lastname, :birthday, presence: true validates :password, length: {minimum: 6} has_many :wishlists has_secure_password def slug self.username.gsub(" ", "-").downcase end def self.find_by_slug(slug) self.all.find {|user| user.slug == slug} end def firstname=(s) write_attribute(:firstname, s.to_s.titleize) end def lastname=(s) write_attribute(:lastname, s.to_s.titleize) end end
class DNA def initialize(strand1) @strand1 = strand1 end def hamming_distance(strand2) distance = 0 min, max = [@strand1, strand2].sort_by(&:size) min.each_char.with_index do |char, index| distance += 1 unless char == max[index] end distance end end p DNA.new('').hamming_distance('') p DNA.new('GGACTGA').hamming_distance('GGACTGA') p DNA.new('ACT').hamming_distance('GGA') p DNA.new('GGACGGATTCTGACCTGGACTAATTTTGGGG').hamming_distance('AGGACGGATTCTGACCTGGACTAATTTTGGGG')
class AddIsSpamToDmails < ActiveRecord::Migration def change Dmail.without_timeout do add_column :dmails, :is_spam, :boolean, default: false end end end
#!/usr/bin/env ruby # frozen_string_literal: true require 'pathname' require_relative 'intcode' require_relative 'utils' def in_beam?(x, y, program) Intcode.new(program, [x, y]).execute!.outputs.first == 1 end def part_one(program) (0..49).to_a.repeated_permutation(2).map do |x, y| in_beam?(x, y, program) end.count(true) end def display(x, y, w, program) lines = [] (y..y + w).step do |y| line = [] (x..x + w).step do |x| line << if in_beam?(x, y, program) '#' else '.' end end lines << line.join('') end puts lines.join("\n") end def part_two(program) x = 0 w = 99 # advance by 99 to get 100 in a row 0.step do |y| x += 1 until in_beam?(x, y, program) return (x * 10_000) + (y - w) if in_beam?(x + w, y - w, program) end end if $PROGRAM_NAME == __FILE__ puts 'https://adventofcode.com/2019/day/19' program = read_program Pathname(__dir__).parent / 'data' / 'day_19.txt' puts "Part One: #{part_one(program)}" puts "Part Two: #{part_two(program)}" end
module FloatSpecs class CoerceToFloat def coerce(other) [other, 1.0] end end end
class Registration < ActiveRecord::Base belongs_to :tournaments belongs_to :players end
module Adornable class Utils class << self def blank?(value) value.nil? || (value.respond_to?(:empty?) && value.empty?) end def present?(value) !blank?(value) end def presence(value) value if present?(value) end end end end
class E1planprod < ApplicationRecord belongs_to :e1articulo belongs_to :e1recurso end
require('minitest/autorun') require('minitest/rg') require_relative('../river.rb') require_relative('../fish.rb') # attr_reader : class RiverTest < MiniTest::Test def setup() @fish_1 = Fish.new("Salmon") @fish_2 = Fish.new("Trout") @fish_3 = Fish.new("Cod") @fish_4 = Fish.new("Tuna") @fish_pool = [@fish_1, @fish_2, @fish_3, @fish_4] @river = River.new("Amazon",@fish_pool) end def test_river_name() assert_equal("Amazon",@river.name()) end def test_count_fish() assert_equal(4,@fish_pool.length) end # def test_lose_fish(fish) # @river.lose_fish(@fish_1) # assert_equal("[@fish_2, @fish_3, @fish_4]",@river.fish_pool) # end end
module SemanticNavigation module Renderers class BreadCrumb include MixIn::RenderHelpers include MixIn::ActsAsBreadcrumb style_accessor last_as_link: false, breadcrumb_separator: '/' navigation_default_classes [:breadcrumb] show_navigation_active_class false show_node_active_class false show_leaf_active_class false show_link_active_class false private def navigation(object) content_menu_tag({id: show_id(:navigation, object.id), class: merge_classes(:navigation, object.active, object.classes) }.merge(object.html)) do yield end end def node(object) content_tag(:li, nil, {id: show_id(:leaf, object.id), class: merge_classes(:leaf, object.active, object.classes) }.merge(object.html)) do link_to(object_name(object), object.url, {id: show_id(:link, object.id), class: merge_classes(:link, object.active, object.link_classes) }.merge(object.link_html)) end + content_tag(:li) do breadcrumb_separator end + yield end def leaf(object) content_tag :li, nil, {id: show_id(:leaf, object.id), class: merge_classes(:leaf, object.active, object.classes) }.merge(object.html) do if last_as_link link_to object_name(object), object.url, {id: show_id(:link, object.id), class: merge_classes(:link, object.active, object.link_classes) }.merge(object.link_html) else object_name(object) end end end end end end
RaspberryCook::Application.routes.draw do resources :comments, :only => [:new , :create , :update, :destroy , :edit] resources :users match '/signup' , to: 'users#new', :via => [:get, :post] resources :recipes, :only => [:show, :index, :new , :create , :destroy , :edit, :update] match 'recipes/:id/fork', as: 'fork_recipe', to: 'recipes#fork', id: /[0-9]+/, via: [:get, :post] get 'shuffle', to: 'recipes#shuffle', as: 'recipes_shuffle' resources :sessions, :only => [:new , :create , :destroy ] match '/signin' , to: 'sessions#new', :via => [:get, :post] match '/signout' ,to: 'sessions#destroy', :via => [:get, :post] match "/404", to: "errors#not_found", :via => :all match "/500", to: "errors#internal_server_error", :via => :all match '/fridge' , to: 'pages#fridge', as: 'fridge', :via => :all get '/home', to: 'pages#home', as: 'home' get '/legal', to: 'pages#legal', as: 'legal' get '/about', to: 'pages#about', as: 'about' get '/feeds', to: 'pages#feeds', as: 'feeds' get '/credits', to: 'pages#credits', as: 'credits' root to: 'pages#home' end
module Admissions::PromoInstancesHelper def promo_instance_thumb(promo_instance, size='100x75') return "" if promo_instance.image_uid.blank? image_tag promo_instance.image.thumb(size).url end def promo_instance_rollover_thumb(promo_instance, size='100x75') return "" if promo_instance.rollover_uid.blank? image_tag promo_instance.rollover.thumb(size).url end end
module Ricer::Plugins::Admin class Raw < Ricer::Plugin trigger_is :raw permission_is :responsible has_usage :execute, '<..message..>' def execute(message) server.connection.send_raw(current_message, message) end end end
# frozen_string_literal: true RSpec.describe KioskSlide, type: :model do let(:slide_type_test) { SlideType.create(name: 'Basic') } let(:collection_test) { Collection.create(name: 'generic') } let(:test_file) { Rack::Test::UploadedFile.new('spec/fixtures/Board_Game_Slide.jpg', 'image/jpg') } let(:valid_attributes) do { expires_at: Time.utc(2015, 1, 1, 12, 0, 0), caption: 'test caption', title: 'test title', slide_type_id: slide_type_test.id, collection_id: collection_test.id, image: test_file } end let(:test_layout) { KioskLayout.create!(name: 'touch') } let(:test_kiosk) do Kiosk.create(name: 'circ', kiosk_layout_id: test_layout.id) end let(:test_slide) do Slide.create! valid_attributes end it 'is valid with valid attributes' do expect(KioskSlide.new(kiosk_id: test_kiosk.id, slide_id: test_slide.id)).to be_valid end it 'is not valid without a title' do kiosk = KioskSlide.new(kiosk_id: nil, slide_id: nil) expect(kiosk).not_to be_valid end end
class CreateFeaturePrices < ActiveRecord::Migration def change create_table :feature_prices do |t| t.integer :project_type_id t.integer :project_feature_id t.timestamps null: false end add_foreign_key :feature_prices, :project_types add_foreign_key :feature_prices, :project_features end end
require 'rails_helper' RSpec.describe LastLocation, type: :model do describe 'validations' do it { is_expected.to validate_presence_of(:latitude) } it { is_expected.to validate_presence_of(:longitude) } context 'associations' do it { is_expected.to belong_to(:survivor) } end end end
class RenameOrderToOrderIdInBingoChallenges < ActiveRecord::Migration def change rename_column :bingo_challenges, :order, :order_id end end
require 'ostruct' class Rental attr_reader :movie, :days_rented def initialize(movie, days_rented) @movie = movie @days_rented = days_rented end end class Movie REGULAR = 'R' NEW_RELEASE = 'N' CHILDREN = 'C' attr_reader :price_code, :title def initialize(title, price_code) @title = title @price_code = price_code end end class Customer def initialize(name) @name = name @rentals = [] end def rent(rental) @rentals << rental self end def statement total_amount = 0 frequent_renter_points = 0 result = "Rental record for #{@name}" @rentals.each do |rental| this_amount = amount_for(rental) frequent_renter_points+=1 frequent_renter_points+=1 if rental.movie.price_code == Movie::NEW_RELEASE && rental.days_rented >1 result += "\t#{rental.movie.title}\t#{this_amount}" total_amount += this_amount end result += "Amount owed is #{total_amount}.\n" result += "You earned #{frequent_renter_points} frequent renter points.\n" result end private def amount_for(a_rental) the_amount = 0 case a_rental.movie.price_code when Movie::REGULAR the_amount += 2 the_amount += ((a_rental.days_rented-2) * 1.5) if (a_rental.days_rented > 2) when Movie::NEW_RELEASE the_amount += a_rental.days_rented * 3 when Movie::CHILDREN the_amount += 1.5 the_amount += ((a_rental.days_rented-3) * 1.5) if (a_rental.days_rented > 3) end the_amount end end
class RenameHash < ActiveRecord::Migration def change rename_column :events, :hash, :event_hash end end
# frozen_string_literal: true require 'spec_helper' require 'contracts/products/create_product_contract' require 'repos/product_repo' require 'services/products/create_product' RSpec.describe Services::Products::CreateProduct do subject(:call) do described_class.call(name: name, price: price, quantity_in_stock: quantity_in_stock) end let(:create_product_contract) { instance_spy(Contracts::Products::CreateProductContract) } let(:product_repo) { instance_spy(Repos::ProductRepo) } let(:validation_result) { instance_spy(Dry::Validation::Result) } before do allow(create_product_contract).to( receive(:call).with(unvalidated_params).and_return(validation_result) ) App.stub('contracts.products.create_product_contract', create_product_contract) App.stub('repos.product_repo', product_repo) end context 'when product data is valid' do let(:product) { Factory.structs[:product] } let(:name) { product.name } let(:price) { product.price } let(:quantity_in_stock) { product.quantity_in_stock } let(:unvalidated_params) { { name: name, price: price, quantity_in_stock: quantity_in_stock } } let(:validated_params) { unvalidated_params } before do allow(validation_result).to receive(:success?).and_return(true) allow(validation_result).to receive(:to_h).and_return(validated_params) allow(product_repo).to receive(:create).with(validated_params).and_return(product) end it 'validates the product data' do call expect(create_product_contract).to have_received(:call).with(unvalidated_params) end it 'creates the product' do call expect(product_repo).to have_received(:create).with(validated_params) end it 'returns the created product' do expect(call).to be(product) end end context 'when product data is invalid' do let(:product) { Factory.structs[:product] } let(:name) { '' } let(:price) { product.price } let(:quantity_in_stock) { product.quantity_in_stock } let(:unvalidated_params) { { name: name, price: price, quantity_in_stock: quantity_in_stock } } before { allow(validation_result).to receive(:success?).and_return(false) } it 'validates the product data' do call expect(create_product_contract).to have_received(:call).with(unvalidated_params) end it 'does not create a product' do call expect(product_repo).not_to have_received(:create) end it 'returns the validation result' do expect(call).to be(validation_result) end end end
class Lesson < ActiveRecord::Base validates :title, presence: true, length: { minimum: 5 } validates :sport, :datetime, :location, :description, presence: true validates :price, presence: true, numericality: {:greater_than_or_equal_to => 5.0} def mine?(user) User.find(user_id) == user end end
class SearchesController < ApplicationController authorize_resource def index @results = Search.find(params[:query], params[:resource]) end end
class User < ApplicationRecord validates :username, :session_token, presence: true, uniqueness: true validates :password_digest, presence: true validates :password, length: { minimum: 6 }, allow_nil: true validate :ensure_username, :on => :create has_many :playlists, dependent: :destroy has_many :follows, dependent: :destroy has_many :followed_playlists, through: :follows, source: :followable, source_type: 'Playlist', dependent: :destroy has_many :followed_artists, through: :follows, source: :followable, source_type: 'Artist', dependent: :destroy has_many :followed_albums, through: :follows, source: :followable, source_type: 'Album', dependent: :destroy has_many :followed_songs, through: :follows, source: :followable, source_type: 'Song', dependent: :destroy attr_reader :password after_initialize :ensure_session_token def self.find_by_credentials(username, password) user = User.where('lower(username) = ?', username.downcase).first return user if user && user.is_password?(password) return nil end def self.generate_session_token SecureRandom.urlsafe_base64 end def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end def is_password?(password) BCrypt::Password.new(self.password_digest).is_password?(password) end def reset_session_token! self.session_token = User.generate_session_token self.save! self.session_token end private def ensure_session_token self.session_token ||= User.generate_session_token end def ensure_username downcase_username = self.username.downcase user = User.where('lower(username) = ?', downcase_username).first errors.add(:username, 'has already been taken') if user end end
# Extend BinData::IO # BinData::IO.class_eval do alias orig_readbytes readbytes def readbytes(n) str = orig_readbytes n decode_bytes str end # TODO: use 256-element lookup table and test performance def decode_bytes(str) dec_string = "" str.each_byte do |char| dec_string += (((char & 0x3) << 6) | char >> 2).chr end dec_string end end module Kanipyon DEBUG_MODE = false class Helper def self.hexdump(bin, start = 0, finish = nil, width = 16) ascii = '' counter = 0 print '%06x ' % start bin.each_byte do |c| if counter >= start print '%02x ' % c ascii << (c.between?(32, 126) ? c : ?.) if ascii.length >= width puts ascii ascii = '' print '%06x ' % (counter + 1) end end throw :done if finish && finish <= counter counter += 1 end rescue :done puts ' ' * (width - ascii.length) + ascii end end module WillScript class WscOpcode < BinData::BasePrimitive # BinData::BasePrimitive.read_and_return_value() impl # Reads a number of bytes from io and returns a ruby object that represents these bytes. def read_and_return_value(io) @base_offset = io.offset WillScriptAnalyzer.read_one_and_return_value(io) end # BinData::BasePrimitive.value_to_binary_string() impl # Takes a ruby value (String, Numeric etc) and converts it to the appropriate binary string representation. def value_to_binary_string(value) #value.pack("V") raise NotImplementedError end end class WillScriptAnalyzer WSC_INSTRUCTION_LENGTH = { # 0x1 => 11, 0x3 => 8, 0x4 => 1, 0x5 => 2, # 0x6 => 6, 0x7 => '1~', 0x8 => 3, 0x9 => '1~', 0xA => 2, 0xB => 3, 0xC => 4, 0x21 => '5~', 0x22 => 5, 0x23 => '8~', 0x25 => '10~', 0x26 => 3, 0x28 => 6, 0x29 => 5, 0x30 => 5, # 0x41 => '4~', # 0x42 => '5~~', 0x43 => '7~', 0x45 => 5, 0x46 => '10~', 0x47 => 3, 0x48 => '12~', 0x49 => 4, 0x4A => 5, 0x4B => 13, 0x4C => 3, 0x4D => 6, 0x4E => 5, 0x4F => 5, 0x50 => '1~', 0x51 => 6, 0x52 => 3, 0x54 => '1~', 0x55 => 2, 0x61 => '2~', 0x62 => 2, 0x64 => 7, 0x68 => 8, 0x71 => '1~', 0x72 => 2, 0x73 => '10~', 0x74 => 3, 0x81 => 3, 0x82 => 4, 0x83 => 2, 0x85 => 3, 0x86 => 3, 0x88 => 4, 0x89 => 2, 0x8A => 2, 0x8B => 2, 0x8C => 4, 0x8D => 2, 0x8E => 2, 0xB8 => 4, 0xB9 => 3, 0xBC => 5, 0xBD => 3, 0xE0 => '1~', 0xE2 => 2, 0xFF => 1, } # Read an opcode def self.read_one_and_return_value(io) base_offset = io.offset opcode = io.readbytes(1) key = opcode.unpack("C").first # specialized opcode handlers possible_handler_sym = ("read_and_return_for_opcode%02X" % key).to_sym if self.respond_to? possible_handler_sym return self.public_send(possible_handler_sym, io) end # ValidityError if key == 0 puts "[%04X] unexpected 0x00 found at opcode. Check previous opcode for definition mismatch." % [base_offset] # debug information begin while (key == 0) key = io.readbytes(1).unpack("C").first end rescue EOFError => e num_times = io.offset - base_offset raise BinData::ValidityError, "Found 0x00 bytes (#{num_times} times) until EOF." end num_times = io.offset - 1 - base_offset base_offset = io.offset - 1 raise BinData::ValidityError, "Found 0x00 bytes (#{num_times} times) until next opcode." end if WSC_INSTRUCTION_LENGTH.has_key?(key) == false raise BinData::ValidityError, "[%04X] 0x%02X: No parser for this opcode" % [base_offset, key] end return handle_generic_opcode(io, opcode) end end end end Dir[File.dirname(__FILE__) + '/opcodes/*.rb'].each {|file| require file }
module ReportsKit module Reports module FilterTypes class Number < Base DEFAULT_CRITERIA = {} def apply_conditions(records) case criteria[:operator] when '>' records.where(column => (value.to_i...Float::INFINITY)) when '>=' records.where(column => (value.to_i..Float::INFINITY)) when '<' records.where(column => (-Float::INFINITY...value.to_i)) when '<=' records.where(column => (-Float::INFINITY..value.to_i)) when '=' records.where(column => value.to_i) else raise ArgumentError.new("Unsupported operator: '#{criteria[:operator]}'") end end def valid? value.present? end end end end end
class StoriesSequence < ApplicationRecord belongs_to :story has_many :sequence_note end
class RoomReservation < ActiveRecord::Base belongs_to :room belongs_to :reservation end
require('minitest/autorun') require('minitest/rg') require_relative('../Rooms') require_relative('../Songs') require_relative('../Guests') class TestSongs < MiniTest::Test def setup @song1 = Songs.new("Cool Kids", "Echosmith") end def test_song_name_and_artist assert_equal("Cool Kids", @song1.name) assert_equal("Echosmith", @song1.artist) end end
class CompaniesController < ApplicationController def signup @company = Company.new end def create @company = Company.new(params[:company]) if @company.save UserMailer.welcome_email(@company).deliver sign_in @company flash[:success] = "Welcome to ConnectIN!" redirect_to root_path else render 'new' end end def showall @company = Company.all end def show @company = Company.find(params[:id]) @posting = Posting.posting_search(params[:id]) end def edit @company = Company.find(params[:id]) end def update @company = Company.find(params[:id]) if @company.update_attributes(params[:user]) flash[:success] = "Profile updated" redirect_to @company else render 'edit' end end def search @contractors=Contractor.all end def index skills= params[:skills] degree = params[:degree] profession = params[:profession] title = params[:title] if !skills.blank? and degree.blank? and profession.blank? and title.blank? @company = Contractor.skills_conditions(skills ) end if skills.blank? and degree.blank? and !profession.blank? and title.blank? @company = Contractor.profession_conditions(profession ) end if skills.blank? and !degree.blank? and profession.blank? and title.blank? @company = Contractor.degree_conditions(degree ) end if skills.blank? and degree.blank? and profession.blank? and !title.blank? @company = Contractor.title_conditions(title ) end if skills.blank? and degree.blank? and !profession.blank? and !title.blank? @company = Contractor.professionandtitle_conditions(profession,title ) end if skills.blank? and !degree.blank? and profession.blank? and !title.blank? @company = Contractor.degreeandtitle_conditions(degree,title ) end if !skills.blank? and degree.blank? and profession.blank? and !title.blank? @company = Contractor.skillsandtitle_conditions(skills,title ) end if !skills.blank? and !degree.blank? and profession.blank? and title.blank? @company = Contractor.skillsanddegree_conditions(skills,degree ) end if skills.blank? and !degree.blank? and !profession.blank? and title.blank? @company = Contractor.professionanddegree_conditions(degree,profession ) end if !skills.blank? and degree.blank? and !profession.blank? and title.blank? @company = Contractor.skillsandprofession_conditions(skills,profession ) end if !skills.blank? and !degree.blank? and profession.blank? and !title.blank? @company = Contractor.skillsdegreetitle_conditions(skills,degree,title ) end if !skills.blank? and !degree.blank? and !profession.blank? and title.blank? @company = Contractor.skillsdegreeprofession_conditions(skills,degree,profession ) end if skills.blank? and !degree.blank? and !profession.blank? and !title.blank? @company = Contractor.degreeprofessiontitle_conditions(degree,profession,title ) end if !skills.blank? and degree.blank? and !profession.blank? and !title.blank? @company = Contractor.skillseprofessiontitle_conditions(skills,profession,title ) end if skills.blank? and degree.blank? and profession.blank? and title.blank? @company = Contractor.find(:all, :conditions => ['title LIKE ?', ""]) end if !skills.blank? and !degree.blank? and !profession.blank? and !title.blank? @company = Contractor.all_conditions(skills, degree, profession, title) end end end
class AchievementResult < ActiveRecord::Base has_many :achievements validates :name, presence: true end
require 'rails_helper' RSpec.describe "terror_trackers/show", :type => :view do before(:each) do @terror_tracker = assign(:terror_tracker, TerrorTracker.create!()) end it "renders attributes in <p>" do render end end
################################## # # EVM Automate Method: vm2clone # # Notes: This method will clone a VM to a new VM using the perl CLI # FQN : Sample / Methods / vm2clone # ################################### begin @method = 'vm2clone' $evm.log("info", "===== EVM Automate Method: <#{@method}> Started") # Turn of debugging @debug = true # Log the inbound object $evm.log("info", "===========================================") process = $evm.object("process") $evm.log("info", "Listing Process Attributes:") process.attributes.sort.each { |k, v| $evm.log("info", "\t#{k}: #{v}")} if @debug $evm.log("info", "===========================================") vm = $evm.root['vm'] $evm.log("info", "Got VM from root object") $evm.log("info","Inspecting vm: #{vm.inspect}") if @debug ems = vm.ext_management_system $evm.log("info", "Got EMS <#{ems.name}> from VM <#{vm.name}>") $evm.log("info","Inspecting ems: #{ems.inspect}") if @debug host = vm.host $evm.log("info", "Got Host <#{host.name}> from VM <#{vm.name}>") $evm.log("info","Inspecting host: #{host.inspect}") if @debug dest_host = host.ipaddress $evm.log("info", "Using Destination Host <#{dest_host}>") $evm.log("info","Inspecting dest_host: #{dest_host.inspect}") if @debug storages = vm.storage $evm.log("info", "Got Storages <#{storages.name}> from VM <#{vm.name}>") $evm.log("info","Inspecting storages: #{storages.inspect}") if @debug dest_storage = storages.name $evm.log("info", "Using Destination Storage <#{dest_storage}>") $evm.log("info","Inspecting dest_storage: #{dest_storage.inspect}") if @debug #Find the tagged host(s) with the least number of vms #tag = "/managed/function/citrix" #hosts = $evm.vmdb(:host).find_tagged_with(:all => tag, :ns => "*") #$evm.log("info", "Got #{hosts.length} Hosts tagged with #{tag}") #dest_host = hosts.sort{|a,b| a.vms.length <=> b.vms.length}.first #$evm.log("info", "Sorted Hosts") #dest_host = dest_host.name #$evm.log("info", "Selected Host = #{dest_host}") # Find tagged storage(s) with least number of VMs #storages = $evm.vmdb(:storage).find_tagged_with(:all=>tag, :ns=>"*") #$evm.log("info", "Got #{storages.length} Storages tagged with #{tag}") #dest_storage = storages.sort{|a,b| a.vms.length <=> b.vms.length}.first #$evm.log("info", "Sorted Storages") #dest_storage = dest_storage.name #$evm.log("info", "Selected Storage = #{dest_storage}") vm_finder = $evm.vmdb(:vm) $evm.log("info", "Got VMFinder Object") # Name the VM, takes the vm name passed and adds 1 thru 99 till name does not exist in vmdb vm2 = nil 99.times do |i| vm2 = vm.name + "_#{i+1}" $evm.log("info", "Trying #{vm2}") break unless vm_finder.find_by_name(vm2) end $evm.log("info", "Selected VM2 = #{vm2}") # Build the Perl command using the VMDB information cmd = "nohup perl /usr/lib/vmware-vcli/apps/vm/vmclone.pl" cmd += " --url https://#{ems.ipaddress}:443/sdk/vimservice" cmd += " --username \"#{ems.authentication_userid}\"" cmd += " --password \"#{ems.authentication_password}\"" cmd += " --vmname \"#{vm.name}\"" cmd += " --vmname_destination \"#{vm2}\"" cmd += " --datastore \"#{dest_storage}\"" cmd += " --vmhost \"#{dest_host}\"" cmd += " &" $evm.log("info", "Running: #{cmd}") #results = `#{cmd}` results = system(cmd) # # Exit method # $evm.log("info", "===== EVM Automate Method: <#{@method}> Ended") exit MIQ_OK # # Set Ruby rescue behavior # rescue => err $evm.log("error", "<#{@method}>: [#{err}]\n#{err.backtrace.join("\n")}") exit MIQ_ABORT end
class UnitOfMeasuresController < ApplicationController before_action :set_unit_of_measure, only: [:show, :update, :destroy] # GET /unit_of_measures def index @unit_of_measures = UnitOfMeasure.all render json: @unit_of_measures end # GET /unit_of_measures/1 def show render json: @unit_of_measure end # POST /unit_of_measures def create @unit_of_measure = UnitOfMeasure.new(unit_of_measure_params) if @unit_of_measure.save render json: @unit_of_measure, status: :created, location: @unit_of_measure else render json: @unit_of_measure.errors, status: :unprocessable_entity end end # PATCH/PUT /unit_of_measures/1 def update if @unit_of_measure.update(unit_of_measure_params) render json: @unit_of_measure else render json: @unit_of_measure.errors, status: :unprocessable_entity end end # DELETE /unit_of_measures/1 def destroy @unit_of_measure.destroy end private # Use callbacks to share common setup or constraints between actions. def set_unit_of_measure @unit_of_measure = UnitOfMeasure.find(params[:id]) end # Only allow a trusted parameter "white list" through. def unit_of_measure_params params.require(:unit_of_measure).permit(:unit_id, :unit_description, :unit_status, :created_by, :updated_by) end end
class CreateWines < ActiveRecord::Migration[6.0] def change create_table :wines do |t| t.string :name t.string :description t.string :price t.string :millesime t.string :cepage t.references :wine_region, null: false, foreign_key: true t.references :wine_type, null: false, foreign_key: true t.timestamps end end end
require_relative 'piece' class Pawn < Piece def initialize(pos, board, color) super @start_pos = pos end def symbol "\u265f" end def self.directions [] end def populate_moves(dummy_arr) moves = [] # debugger diagonal_directions.each do |direction| next_pos = add_pos(self.pos, direction) moves << next_pos if board.occupied?(next_pos) end in_play_directions.each do |direction| next_pos = add_pos(self.pos, direction) moves << next_pos unless board.occupied?(next_pos) end first_pos = [] start_directions.each_with_index do |direction, idx| next_pos = add_pos(self.pos, direction) # first_pos = next_pos unless idx > 0 if idx == 0 first_pos = next_pos moves << next_pos unless board.occupied?(next_pos) else moves << next_pos unless board.occupied?(first_pos) || board.occupied?(next_pos) end end moves.uniq end private def diagonal_directions if @start_pos.first == 1 [[1,-1], [1,1]] else [[-1,1], [-1,-1]] end end def start_directions if @start_pos.first == 1 [[1,0], [2,0]] else [[-1,0], [-2,0]] end end def in_play_directions if @start_pos.first == 1 [[1,0]] else [[-1,0]] end end end
#!/usr/bin/env ruby # frozen_string_literal: true # Takes the MySQL error messages from sql/share/errmsg-utf8.txt, locates the # provided error message type (for example, ER_HOST_NOT_PRIVILEGED), then # creates XML snippets for each locale to be used in Recog. Note that this # cannot be used as-is to generate mysql_errors.xml, or oftentimes even parts # -- it merely spits out XML snippets that you can start with; many will still # need to be modified by hand. require 'builder' require 'open-uri' require 'securerandom' def generate_recog(error_name, locale, error_message) xml = Builder::XmlMarkup.new(target: $stdout, indent: 2) xml.fingerprint(pattern: error_message) do xml.description "Oracle MySQL error #{error_name} (#{locale})" xml.example(error_message) xml.param(pos: 0, name: 'service.vendor', value: 'Oracle') xml.param(pos: 0, name: 'service.family', value: 'MySQL') xml.param(pos: 0, name: 'service.product', value: 'MySQL') end end raise "Usage: #{$PROGRAM_NAME} <path/URI for errmsg-utf8.txt> <error name>" unless ARGV.size == 2 path = ARGV.first error_name = ARGV.last lines = IO.readlines(open(path)) raise "Nothing read from #{path}" if lines.empty? unless (error_start = lines.find_index { |line| line.strip =~ /^#{error_name}(?:\s+\S+)?$/ }) raise "Unable to find #{error_name} in #{path}" end locale_map = {} lines.slice(error_start + 1, lines.size).each do |line| break unless /^\s+(?<locale>\S+)\s+"(?<error_message>.*)",?$/ =~ line locale_map[locale] = error_message end # Many of the error messages contain format strings. This can be problematic # in that they need to be removed or otherwise handled as part of the 'pattern' # attribute and appropriately filled in in any example elements. So simply try # a rough count of the possible format strings and warn the user so that they # can deal with it. format_count = locale_map.values.map { |error_message| error_message.scan(/%/).size }.inject(&:+) warn("#{format_count} possible format strings found -- you'll need to deal with this") unless format_count == 0 Hash[locale_map.sort].map do |locale, error_message| generate_recog(error_name, locale, error_message) end
class Product < ApplicationRecord include Redis::Objects include Likable serialize :like, Array has_many :comments, dependent: :destroy has_many :users, through: :comments has_many :images, as: :imagable, inverse_of: :imagable, dependent: :destroy accepts_nested_attributes_for :images, allow_destroy: true, reject_if: :nested validates_uniqueness_of :name counter :view def nested(attributes) attributes['file'].blank? end end
require 'json' class HHoldSnapshot < ActiveRecord::Base after_find :parse_users_arr validates :hhid, presence: true validates :users_arr, presence: true def self.createLineitemsAndSnapshotChronology(lineitems,hhid,users_hash) #Create a composite list of lineitems and hholdsnapshots in descending order of date #Get history of snapshot hholdsnapshots = HHoldSnapshot.where(hhid: hhid).order('created_at ASC') #Chronology of Snapshots and Lineitems, chronology = Array.new(hholdsnapshots.length + lineitems.length) chronology_indx = 0 lineitems.each do |lineitem| if lineitem.txtype=="BILL" chronology[chronology_indx] = {"type"=>"BILL", "txdate"=> lineitem.txdate, "amount"=> lineitem.amount, "txname"=> lineitem.txname, "id"=> lineitem.id, "payer"=> users_hash["users_array"][ users_hash["users_array_indx"].index(lineitem.payer) ][0], "payer_id"=> lineitem.payer, "applicable_members"=> lineitem.applicable_members } else #PAYMENT chronology[chronology_indx] = {"type"=>"PAYMENT", "txdate"=> lineitem.txdate, "amount"=> lineitem.amount, "id"=> lineitem.id, "payer"=> users_hash["users_array"][ users_hash["users_array_indx"].index(lineitem.payer) ][0], "payer_id"=> lineitem.payer, "payee"=> users_hash["users_array"][ users_hash["users_array_indx"].index(lineitem.payee) ][0], "payee_id"=> lineitem.payee} end chronology_indx = chronology_indx + 1 end hholdsnapshots.each_with_index do |hholdsnapshot,hholdsnapshots_indx| snapshotdelta = HHoldSnapshot.determineSnapshotDelta(hholdsnapshots, hholdsnapshots_indx, users_hash) chronology[chronology_indx] = {"type"=>"HHSNAPSHOT", "txdate"=> hholdsnapshot.created_at, "action"=>snapshotdelta["action"], "member_nickname"=>snapshotdelta["member_nickname"], "member_id"=>snapshotdelta["member_id"], "numberOfMembers"=>snapshotdelta["numberOfMembers"]} chronology_indx = chronology_indx + 1 end #Sort in order of descending dates chronology.sort!{|x,y| y["txdate"]<=>x["txdate"]} return chronology end def self.determineSnapshotDelta(hholdsnapshots_arr, indx, users_hash) #Given an array of ascendaing hhsnaphots (HHoldSnapshot.where(hhid: hhid).order('created_at ASC')), # and a particular index, determine if a member was added or removed # since the previous hhsnapshot if indx==0 #First snapshot, hhold owner was added user_id = hholdsnapshots_arr[0].users_arr[0] if users_hash["users_array_indx"].index( user_id ).nil? #User has deleted their account nickname = '(former user)' else nickname = users_hash["users_array"][ users_hash["users_array_indx"].index( user_id ) ][0] end return {"action"=>"joined", "member_nickname"=>nickname, "member_id"=> user_id, "numberOfMembers"=>hholdsnapshots_arr[0].users_arr.size} end if (hholdsnapshots_arr[indx].users_arr - hholdsnapshots_arr[indx-1].users_arr).empty? # Member left the household user_id = (hholdsnapshots_arr[indx-1].users_arr - hholdsnapshots_arr[indx].users_arr)[0] if users_hash["users_array_indx"].index( user_id ).nil? #User has deleted their account nickname = '(former user)' else nickname = users_hash["users_array"][ users_hash["users_array_indx"].index( user_id ) ][0] end return {"action"=>"withdrew","member_nickname"=>nickname, "member_id"=> user_id, "numberOfMembers"=>hholdsnapshots_arr[indx].users_arr.size} else # Member joined the household user_id = (hholdsnapshots_arr[indx].users_arr - hholdsnapshots_arr[indx-1].users_arr)[0] if users_hash["users_array_indx"].index( user_id ).nil? #User has deleted their account nickname = '(former user)' else nickname = users_hash["users_array"][ users_hash["users_array_indx"].index( user_id ) ][0] end return {"action"=>"joined","member_nickname"=>nickname, "member_id"=> user_id, "numberOfMembers"=>hholdsnapshots_arr[indx].users_arr.size} end # If proper data integrity the end of this method should not be reached. end private def parse_users_arr self.users_arr = JSON.parse(self.users_arr) end end # == Schema Information # # Table name: h_hold_snapshots # # id :integer not null, primary key # hhid :integer # users_arr :string(255) # created_at :datetime # updated_at :datetime #
class Category < ActiveRecord::Base validates :name, :presence => true, :uniqueness => {:scope => :user_id, :message => "Category already exists"} has_many :items belongs_to :user mount_uploader :picture1, Picture1Uploader end
require 'test_helper' class ControltleitsControllerTest < ActionDispatch::IntegrationTest setup do @controltleit = controltleits(:one) end test "should get index" do get controltleits_url assert_response :success end test "should get new" do get new_controltleit_url assert_response :success end test "should create controltleit" do assert_difference('Controltleit.count') do post controltleits_url, params: { controltleit: { limite: @controltleit.limite, n1: @controltleit.n1, n2: @controltleit.n2, n3: @controltleit.n3, siglas: @controltleit.siglas, vendida: @controltleit.vendida } } end assert_redirected_to controltleit_url(Controltleit.last) end test "should show controltleit" do get controltleit_url(@controltleit) assert_response :success end test "should get edit" do get edit_controltleit_url(@controltleit) assert_response :success end test "should update controltleit" do patch controltleit_url(@controltleit), params: { controltleit: { limite: @controltleit.limite, n1: @controltleit.n1, n2: @controltleit.n2, n3: @controltleit.n3, siglas: @controltleit.siglas, vendida: @controltleit.vendida } } assert_redirected_to controltleit_url(@controltleit) end test "should destroy controltleit" do assert_difference('Controltleit.count', -1) do delete controltleit_url(@controltleit) end assert_redirected_to controltleits_url end end
class Room < ApplicationRecord has_many :messages, dependent: :destroy has_many :room_users, dependent: :destroy has_many :users, through: :room_users validates :name, presence: true, length: { maximum: 20 } validate :icon_size mount_uploader :icon, RoomIconUploader private def icon_size if icon.size > 5.megabytes errors.add(:icon, "should be less than 5MB") end end end
class Employee attr_reader :first_name, :middle_name, :last_name, :email, :phone_number attr_accessor :review, :performance def initialize(first_name, last_name, email, phone_number, salary, middle_name = "") @first_name = first_name @middle_name = middle_name @last_name = last_name @email = email @phone_number = phone_number @salary = salary.to_f @review = "" @performance = nil end def salary @salary.to_f end def name @middle_name != "" ? "#{@first_name} #{@middle_name} #{@last_name}" : "#{@first_name} #{@last_name}" end def give_raise!(amount) amount > 1.0 ? @salary += amount : @salary = @salary * (1 + amount) end def ==(e) @first_name == e.first_name @middle_name == e.middle_name @last_name == e.last_name @email == e.email @phone_number == e.phone_number @salary == salary end def import_employee_review(filename) input = File.open(filename, "r") temp_array = input.readlines("\n") input.close reg = /\b#{@first_name}\b/i temp_array.each {|s| @review += s.gsub("\n", "") if s.match(reg)} end def assign_employee_performance #expected tokens in order of negative, negative qualifiers, positive, positive qualifiers temp_tokens = get_review_tokens total = 0 temp_tokens[0].each do |w| if @review.match(/\b#{w}\b/i) total -= 1 total -= get_negative_score(temp_tokens[1], w) end end temp_tokens[2].each do |w| if @review.match(/\b#{w}\b/i) total += 1 total += get_positive_score(temp_tokens[1],temp_tokens[3],w) end end puts "#{@first_name} #{total}" total > 0 ? @performance = true : @performance = false end private def get_negative_score(qualifiers, word) total = 0 qualifiers.each do |q| total += 2 if @review.match(/\b#{q}\b\s(\S+\s){,2}\b#{word}\b/i) end total end private def get_positive_score(negative_qualifiers, positive_qualifiers, word) total = 0 positive_qualifiers.each do |pq| if @review.match(/\b#{pq}\b\s(\S+\s){,2}\b#{word}\b/i) negative = false negative_qualifiers.each do |nq| negative = true if @review.match(/\b#{nq}\b\s(\S+\s)\b#{pq}\b/i) end negative ? total -= 3 : total += 2 end end total end private def get_score(words, qualifiers) total = 0 words.each do |w| if @review.match(/\b#{w}\b/i) qualifiers.each do |q| total += 2 if @review.match(/\b#{q}\b\s(\S+\s){,2}\b#{w}\b/i) end total += 1 end end total end private def get_review_tokens input = File.open("tokens") results = [] temp_array = input.readlines("\n") temp_array.each do |s| s.strip! results << s.split(",") end input.close results end end
class Appointment < ActiveRecord::Base belongs_to :location validates_presence_of :appointment_reason, :contact_time, :appointment_date, :approximate_event_date, :contact_method, :location_id, :zip_code, :contact_phone, :contact_email, :last_name, :first_name validates :apt_time, presence: { message: "must include both hours and minutes" } validate :appointment_date_cannot_be_in_the_past validates_email_format_of :contact_email, message: "must be a valid email address.", if: :contact_email validates :contact_phone, format: { with: /\A([01][- .()])?(\(\d{3}\)|\d{3})[- .]*?\d{3}[- .]*\d{4}\Z/, message: "must be a valid 10-digit phone number." } def appointment_date_cannot_be_in_the_past errors.add(:appointment_date, "can't be in the past") if !appointment_date.blank? && appointment_date.past? errors.add(:approximate_event_date, "can't be in the past") if !approximate_event_date.blank? && approximate_event_date.past? end def self.human_attribute_name(attr, options = {}) attr == :apt_time ? 'Appointment Time' : ( attr == :appointment_date_string ? 'Appointment date' : super ) end def demilitarize_time self.apt_time.to_time.strftime("%I:%M %p") end def has_appointment_date? self.appointment_date.present? end def self.add_exisiting_appointments csv_file_path = 'db/seeds/old_appointments.csv' CSV.foreach(csv_file_path, :headers => true ) do |row| row["appointment_date"] = DateTime.strptime(row["appointment_date"], '%m/%d/%Y').to_time location_name = row["location_name"] created_at = DateTime.strptime(row["created_at"], '%m/%d/%Y').to_t row.delete "location_name" row.delete "created_at" a = Appointment.create!(row.to_hash) a.update_attributes({created_at: created_at}) location = Location.find_by_store_name location_name a.location = location a.save end end def adjust_year if self.created_at.year == 16 self.update_attributes({created_at: (self.created_at + 2000.year) }) end end def self.to_csv attributes = %w{first_name last_name contact_email contact_phone zip_code location group_code contact_time contact_method appointment_date approximate_event_date apt_time appointment_reason other_explain wedding_apt_details message created_at} CSV.generate( { headers: true } ) do |csv| csv << attributes self.order(created_at: :desc).each do |appointment| location = Location.find appointment.location_id if appointment.location_id.present? location.present? ? location_name = appointment.location.store_name : location_name = "not specified" csv << [ appointment.first_name, appointment.last_name, appointment.contact_email, appointment.contact_phone, appointment.zip_code, location_name, appointment.group_code, appointment.contact_time, appointment.contact_method, (appointment.appointment_date && (appointment.appointment_date.in_time_zone("Central Time (US & Canada)")).strftime("%m/%d/%Y") || "not specified"), (appointment.approximate_event_date && appointment.approximate_event_date.strftime("%m/%d/%Y") || "not specified" ), appointment.demilitarize_time, appointment.appointment_reason, appointment.other_explain, appointment.wedding_apt_details, appointment.message, (appointment.created_at.in_time_zone("Central Time (US & Canada)")).strftime("%m/%d/%Y")] end end end end
# Een class om makkelijk barcodes te genereren class Barcode def self.create(code) require 'barby' require 'barby/barcode/ean_13' require 'barby/outputter/png_outputter' justified_code = code.to_s.rjust(12, '0') barcode = Barby::EAN13.new(justified_code) File.open("app/assets/images/barcodes/#{code}.png", 'w+')do|f| f.write barcode.to_png(height: 20, margin: 5) end "app/assets/images/barcodes/#{code}.png" end end
class Time include Comparable def initialize(hours, minutes) @timestamp = hours * 60 + minutes end attr_reader :timestamp def +(other) Time.new(0, @timestamp + other.timestamp) end def -(other) Time.new(0, @timestamp - other.timestamp) end def <=>(other) timestamp <=> other.timestamp end def hours @timestamp / 60 end def minutes @timestamp % 60 end end Citizen = Struct.new(:arrival, :duration) def solve(n_counters, citizens) counters = (0...n_counters).map { Time.new(0, 0) } served_at, waiting_time = citizens.map do |citizen| counter_index = (0...counters.size).min_by { |i| counters[i] } served_at = [ counters[counter_index], citizen.arrival ].max waiting_time = served_at - citizen.arrival counters[counter_index] = served_at + Time.new(0, citizen.duration) [ served_at, waiting_time ] end.transpose [ served_at, waiting_time.map(&:timestamp).max ] end def main n = gets.to_i (1..n).each do |index| n_counters = gets.to_i n_citizens = gets.to_i citizens = (1..n_citizens).map do h, m = gets.strip.split(/ /).map(&:to_i) d = gets.to_i Citizen.new(Time.new(h, m), d) end served_at, max_waiting_time = solve(n_counters, citizens) served_at_string = served_at.map { |time| "#{time.hours} #{time.minutes}" }.join(' ') puts "#{index} #{served_at_string} #{max_waiting_time}" end end main
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :registrations, only: [:create, :destroy] do post 'confirm', on: :collection end resources :sessions, only: [ :create, :destroy ] resources :articles, only: [ :create, :show ] end
require_relative '../lib/high_scores' describe HighScores do it "test_list_of_scores" do scores = [30, 50, 20, 70] expect(HighScores.new(scores).scores).to eq [30, 50, 20, 70] end it "test_latest_score" do scores = [100, 0, 90, 30] expect(HighScores.new(scores).latest).to eq 30 end it "test_personal_best" do scores = [40, 100, 70] expect(HighScores.new(scores).personal_best).to eq 100 end it "test_personal_top_three_from_a_list_of_scores" do scores = [10, 30, 90, 30, 100, 20, 10, 0, 30, 40, 40, 70, 70] expect(HighScores.new(scores).personal_top_three).to eq [100, 90, 70] end it "test_personal_top_highest_to_lowest" do scores = [20, 10, 30] expect(HighScores.new(scores).personal_top_three).to eq [30, 20, 10] end it "test_personal_top_when_there_is_a_tie" do scores = [40, 20, 40, 30] expect(HighScores.new(scores).personal_top_three).to eq [40, 40, 30] end it "test_personal_top_when_there_are_less_than_3" do scores = [30, 70] expect(HighScores.new(scores).personal_top_three).to eq [70, 30] end it "test_personal_top_when_there_is_only_one" do scores = [40] expect(HighScores.new(scores).personal_top_three).to eq [40] end it "test_latest_score_is_not_the_personal_best" do scores = [100, 40, 10, 70] expect(HighScores.new(scores).latest_is_personal_best?).to eq false end it "test_latest_score_is_the_personal_best" do scores = [70, 40, 10, 100] expect(HighScores.new(scores).latest_is_personal_best?).to eq true end end
module Export class S3UploaderConfig def initialize(use_public_bucket:) @use_public_bucket = use_public_bucket end def region credentials.fetch("aws_region") end def bucket credentials.fetch("bucket_name") end def key_id credentials.fetch("aws_access_key_id") end def secret_key credentials.fetch("aws_secret_access_key") end private attr_reader :use_public_bucket def credentials JSON.parse(ENV.fetch("VCAP_SERVICES")) .fetch("aws-s3-bucket") .find { |config| config.fetch("name").match?(bucket_name_regex) } .fetch("credentials") rescue KeyError, NoMethodError => _error raise "AWS S3 credentials not found" end def bucket_name_regex use_public_bucket ? /s3-export-download-bucket$/ : /s3-export-download-bucket-private/ end end end
class GithubService def initialize(current_user) @user = current_user @token = current_user.token @conn = Faraday.new(url: "https://api.github.com") do |faraday| faraday.request :url_encoded # form-encode POST params faraday.adapter Faraday.default_adapter # make requests with Net::HTTP faraday.params[:access_token] = @token end end def repos response = conn.get("/users/#{@user.name}/repos") json_response = JSON.parse(response.body, symbolize_names: true) json_response.map do |repo| Repository.new(repo) end end def users response = conn.get("/users/#{@user.name}") json_response = JSON.parse(response.body, symbolize_names: true) json_response.map do |user| User.new(user) require "pry"; binding.pry end end private attr_reader :token, :conn end
class AddIndexToDocuments < ActiveRecord::Migration def change add_index :documents, :meeting_date end end
require 'test_helper' class AnalyzerControllerTest < ActionDispatch::IntegrationTest i_suck_and_my_tests_are_order_dependent! test 'should get index url' do get analyzer_index_url assert_response :success end test 'should redirect post results if url is invalid' do post analyzer_results_url, params: { play: 'http://www.invalid.xml' } assert_response :redirect end test 'should redirect post results if url is empty' do post analyzer_results_url, params: { play: '' } assert_response :redirect end test 'should post results url with valid url' do post analyzer_results_url, params: { play: 'http://www.ibiblio.org/xml/examples/shakespeare/macbeth.xml' } assert_response :success end end
class StaticController < ApplicationController def about render "Hello World" end end
class PastesController < ApplicationController impressionist actions: [:show, :download, :raw] before_action :paste_owner, only: [:edit, :update, :destroy] before_action :paste_view, only: [:show, :download, :raw] def index @paste = Paste.new @pastes = public_pastes @my_pastes = my_pastes end def show end def create if user_signed_in? @paste = current_user.pastes.new(paste_params) else @paste = Paste.new(paste_params) end if @paste.save redirect_to @paste else @pastes = public_pastes @my_pastes = my_pastes render :index end end def edit end def update if @paste.update_attributes(paste_params) redirect_to @paste else render :edit end end def destroy @paste.destroy redirect_to root_url end def download send_data @paste.content, filename: "#{@paste.title}.#{@paste.file_extension}", type: Mime::TEXT end def raw render plain: @paste.content end private def paste_params params.require(:paste).permit(:title, :content, :language, :visibility) end def paste_owner @paste = Paste.find(params[:id]) return unless @paste.user.nil? || @paste.user != current_user redirect_to root_url, alert: 'You must be the owner of the paste to do that.' end def paste_view @paste = Paste.where('"pastes"."visibility" IN (0,2) OR "pastes"."user_id" = ?', current_user).find(params[:id]) rescue ActiveRecord::RecordNotFound redirect_to root_url # TODO: redirect to 404 page end def public_pastes Paste.where(visibility: 0).order(created_at: :desc).limit(10) end def my_pastes Paste.where(user: current_user).order(created_at: :desc).limit(10) if user_signed_in? end end
class CreateTr8nTranslationSourceLanguages < ActiveRecord::Migration def change create_table :tr8n_translation_source_languages do |t| t.integer :language_id t.integer :translation_source_id t.timestamps end add_index :tr8n_translation_source_languages, [:language_id, :translation_source_id], :name => :tsllt end end
class Dog attr_accessor:name @@all = [] def initialize(name) @name=name @@all << self end def self.clear_all @@all.clear end def self.all @@all.each do|puppy| puts puppy.name end end end
module Spree class OrderPaymentSerializer < BaseSerializer attributes *_helper.payment_attributes has_one :payment_method, serializer: PaymentMethodSerializer has_one :source, serializer: SourceSerializer end end
require 'forwardable' class Course::Compiler extend Forwardable WEEK_HEADER = "h2" COURSE_TITLE_HEADER = "h1" def_delegators :@course, :repo_dir def initialize(course, version = nil) raise "repo does not exist" if !File.exist?(course.repo_dir) @course = course end # @return {Array<String>} Return name of directories that has an index document def list_of_pages directories = Dir[repo_dir+"*"].select { |path| if File.directory?(path) %w(md xmd).any? { |ext| (Pathname.new(path) + "index.#{ext}").exist? } end } # just want relative path names directories.map { |dir| File.basename(dir) } end # @return {Nokogiri::XML} DOM of course index. def dom_for_index @dom_for_index ||= dom_for("") end # Translates dir/index.{md,xmd} to DOM, relative to repo dir. # @param {String} dir Name of a directory from which to read an index document. # @return {Nokogiri::XML} DOM of a page index. def dom_for(dir) dir = repo_dir + dir %w(md xmd).each do |ext| file = (dir + "index.#{ext}").to_s if File.exists?(file) case ext when "xmd" dom = compile_xmd(file) when "md" dom = compile_md(file) end return dom end end raise "Cannot find index{.md,.xmd} file for: #{dir}" end def course_xml xml = <<-THERE <course name="#{course_title}"> #{index_xml} #{pages_xml} </course> THERE xml end def course_title @course_title ||= dom_for_index.css(COURSE_TITLE_HEADER)[0].text end def page_names Dir[repo_dir].select {} end def index_xml <<-THERE <index> #{weeks_xml} </index> THERE end def weeks_xml weeks = "" xml = dom_for_index node = xml.child nodes_in_week = nil while node if node.name == WEEK_HEADER if nodes_in_week week = <<-THERE <week> #{nodes_in_week} </week> THERE weeks << week end nodes_in_week = "" nodes_in_week << node.to_xhtml elsif node.name == "lesson" lesson = <<-THERE <lesson day="#{node["day"]}" name="#{node["name"]}" old-name="#{node["old-name"]}" project="#{node["project"]}"> <overview>#{node.children.to_xhtml}</overview> </lesson> THERE nodes_in_week << lesson if nodes_in_week else nodes_in_week << node.to_xhtml if nodes_in_week end node = node.next_sibling if node == nil week = <<-THERE <week> #{nodes_in_week} </week> THERE weeks << week end end <<-THERE #{weeks} THERE end def pages_xml pages = [] list_of_pages.each do |page_name| dom = dom_for(page_name) xml = <<-THERE <page name="#{page_name}"> #{dom.children.to_xhtml} </page> THERE pages.push xml end pages.join "\n" end def compile_xmd(path) str = IO.popen(["xmd", path]).read Nokogiri::HTML(str).css("body")[0].child end def compile_md(path) str = IO.popen(["marked", "-i", path]).read Nokogiri::HTML(str).css("body")[0] end end
class PortfoliosController < FolioApplicationController def index @portfolios = Portfolio.sorted end def create create! { [:edit, @portfolio] } end def update update! { [:edit, @portfolio] } end def destroy destroy! { [:portfolios] } end def regenerate_images portfolio = Portfolio.find(params[:id]) Rails.logger.debug portfolio.title portfolio.portfolio_items.each do |item| Rails.logger.debug "Entering #{item.title} with #{item.images.length} images." item.images.each do |image| Rails.logger.debug "Recreating #{image.title}." image.image.recreate_versions! end end redirect_to [:edit, portfolio] end def apply_indices ids = params[:ids] ids.each_index do |i| pf = Portfolio.find(ids[i]) pf.index = i pf.save! end respond_to do |format| format.json { render :json => {:was_success => true} } end end end
# frozen_string_literal: true require "forwardable" module Openapi3Parser module Node class Map extend Forwardable include Enumerable def_delegators :node_data, :each, :keys, :empty? attr_reader :node_data, :node_context def initialize(data, context) @node_data = data @node_context = context end # Look up an attribute of the node by the name it has in the OpenAPI # document. # # @example Look up by OpenAPI naming # obj["externalDocs"] # # @example Look up by symbol # obj[:servers] # # @example Look up an extension # obj["x-myExtension"] # # @param [String, Symbol] value # # @return anything def [](value) node_data[value.to_s] end # Look up an extension provided for this map, doesn't need a prefix of # "x-" # # @example Looking up an extension provided as "x-extra" # obj.extension("extra") # # @param [String, Symbol] value # # @return [Hash, Array, Numeric, String, true, false, nil] def extension(value) node_data["x-#{value}"] end # Used to access a node relative to this node # @param [Context::Pointer, ::Array, ::String] pointer_like # @return anything def node_at(pointer_like) current_pointer = node_context.document_location.pointer node_context.document.node_at(pointer_like, current_pointer) end # @return [String] def inspect fragment = node_context.document_location.pointer.fragment %{#{self.class.name}(#{fragment})} end end end end
# Gemfile for bundler (gem install bundler) # # To update all gem dependencies: # # bundle # # To run a rake task: # # bundle exec rake <task> # Variables: # # SIMP_GEM_SERVERS | a space/comma delimited list of rubygem servers # PUPPET_VERSION | specifies the version of the puppet gem to load # ------------------------------------------------------------------------------ gem_sources = ENV.key?('SIMP_GEM_SERVERS') ? ENV['SIMP_GEM_SERVERS'].split(/[, ]+/) : ['https://rubygems.org'] gem_sources.each { |gem_source| source gem_source } # mandatory gems gem 'mg' gem 'puppet', ENV.fetch('PUPPET_VERSION', '~> 5.5') gem 'rake' gem 'simp-rake-helpers', ENV.fetch('SIMP_RAKE_HELPERS_VERSION', '>= 5.8.1') gem 'r10k', ENV.fetch('R10K_VERSION', '3.1.1') group :testing do # bootstrap common environment variables gem 'dotenv' # Testing framework gem 'rspec' gem 'rspec-its' # A dependency of simp-rake-helpers gem 'simp-beaker-helpers', ENV.fetch('SIMP_BEAKER_HELPERS_VERSION', ['>= 1.14.0', '< 2.0']) end
require("./cell.rb") require("./game_of_life.rb") # RSpec.describe Cell do RSpec.describe '#regenerate' do it "regenerates a live cell from a live cell if it has 2 neighbours" do cell1 = Cell.new(1, [0,0,0,0,0,0,1,1]) expect(cell1.regenerate).to eq(1) end end describe '#regenerate' do it "regenerates a dead cell from a dead cell if it has 0 neighbours" do cell1 = Cell.new(0, [0,0,0,0,0,0,0,0]) expect(cell1.regenerate).to eq(0) end end describe '#regenerate' do it "regenerates a dead cell from a live cell if it has exactly 3 neighbours" do cell1 = Cell.new(0, [1,1,1,0,0,0,0,0]) expect(cell1.regenerate).to eq(1) end end describe '#regenerate' do it "kills the cell if it has more than 3 neighbours" do cell1 = Cell.new(1, [1,1,1,1,0,0,0,0]) expect(cell1.regenerate).to eq(0) end end describe 'GameOfLife' do it "runs the simulation once and checks the location of a couple of positions" do rows_master = { :row1 => [nil, nil, nil, nil, nil, nil, nil], :row2 => [nil, 1, 0, 0, 0, 1, nil], :row3 => [nil, 0, 1, 0, 1, 0, nil], :row4 => [nil, 0, 0, 1, 0, 0, nil], :row5 => [nil, 0, 1, 1, 1, 0, nil], :row6 => [nil, 0, 0, 1, 0, 1, nil], :row7 => [nil, nil, nil, nil, nil, nil, nil] } game = GameOfLife.new(rows_master).play_game expect(game.row_master[:row2][1]).to eq(0) expect(game.row_master[:row3][2]).to eq(1) end end # end
require "rails_helper" RSpec.describe Job, type: :model do let(:job) {FactoryGirl.create :job} subject {job} context "associations" do it {should belong_to :user} it {should belong_to :company} it {is_expected.to have_many :applies} it {is_expected.to have_many :feedbacks} it {is_expected.to have_many :bookmark_likes} it {is_expected.to have_many :reward_benefits} end context "columns" do it {should have_db_column(:content).of_type(:text)} it {should have_db_column(:name).of_type(:string)} it {should have_db_column(:level).of_type(:string)} it {should have_db_column(:language).of_type(:string)} it {should have_db_column(:skill).of_type(:string)} it {should have_db_column(:position).of_type(:string)} it {should have_db_column(:user_id).of_type(:integer)} it {should have_db_column(:company_id).of_type(:integer)} end context "validates" do it {is_expected.to validate_presence_of(:content)} it {is_expected.to validate_presence_of(:name)} it {is_expected.to validate_presence_of(:level)} it {is_expected.to validate_presence_of(:description)} it {is_expected.to validate_presence_of(:language)} it {is_expected.to validate_presence_of(:position)} it {is_expected.to validate_presence_of(:skill)} end context "when name is not valid" do before {subject.name = ""} it {is_expected.not_to be_valid} end context "when content is not valid" do before {subject.content = ""} it {is_expected.not_to be_valid} end context "when level is not valid" do before {subject.level = ""} it {is_expected.not_to be_valid} end context "when description is not valid" do before {subject.description = ""} it {is_expected.not_to be_valid} end context "when language is not valid" do before {subject.language = ""} it {is_expected.not_to be_valid} end context "when position is not valid" do before {subject.position = ""} it {is_expected.not_to be_valid} end context "when skill is not valid" do before {subject.skill = ""} it {is_expected.not_to be_valid} end end
nodes = [ { :hostname => 'web1', :ip => '192.168.200.11', :box => 'precise64', :forward => '2201' }, { :hostname => 'web2', :ip => '192.168.200.12', :box => 'precise64', :forward => '2202' }, { :hostname => 'django1', :ip => '192.168.200.13', :box => 'precise64', :forward => '2203' }, { :hostname => 'django1', :ip => '192.168.200.14', :box => 'precise64', :forward => '2204' }, ] Vagrant.configure("2") do |config| nodes.each do |node| config.vm.define node[:hostname] do |nodeconfig| nodeconfig.vm.box = "ubuntu/trusty64" nodeconfig.vm.hostname = node[:hostname] + ".box" nodeconfig.vm.network :private_network, ip: node[:ip] nodeconfig.vm.network :forwarded_port, guest: 22, host: node[:forward], id: 'ssh' memory = node[:ram] ? node[:ram] : 256; nodeconfig.vm.provider :virtualbox do |vb| vb.customize [ "modifyvm", :id, "--cpuexecutioncap", "50", "--memory", memory.to_s, ] end end end end
require 'test_helper' class LatLngTest < ActiveSupport::TestCase def setup @location = GeoKit::LatLng.new(41.38676, 1.93205) end test "latlng to utm location transformation" do utm_location = @location.to_utm assert_in_delta 410710.177361338, utm_location.e, 0.001 assert_in_delta 4582242.73580142, utm_location.n, 0.001 end test "latlng to point transformation" do point = @location.to_point assert_in_delta 410710.177361338, point.x, 0.001 assert_in_delta 4582242.73580142, point.y, 0.001 end end
class PhoneModel < ActiveRecord::Base attr_accessible :name, :product_manual_homepage_url, :product_homepage_url, :uuid # Associations # belongs_to :manufacturer, :touch => true has_many :phones, :dependent => :destroy # Validations # validates_presence_of :name validate :validate_product_manual_homepage_url validate :validate_product_homepage_url validates_presence_of :uuid validates_uniqueness_of :uuid def to_s self.name end # State machine: # default_scope where(:state => 'active') state_machine :initial => :active do event :deactivate do transition [:active] => :deactivated end event :activate do transition [:deactivated] => :active end end private def validate_product_manual_homepage_url if ! self.product_manual_homepage_url.blank? if ! CustomValidators.validate_url( self.product_manual_homepage_url ) errors.add( :product_manual_homepage_url, "is invalid." ) end end end def validate_product_homepage_url if ! self.product_homepage_url.blank? if ! CustomValidators.validate_url( self.product_homepage_url ) errors.add( :product_homepage_url, "is invalid." ) end end end end
class PerfilTutoresController < ApplicationController before_action :set_perfil_tutor, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! before_action :solo_admin!, only:[:index,:show,:update,:destroy] # GET /perfil_tutores # GET /perfil_tutores.json def index @seccion="Perfiles Tutores" @perfil_tutores = PerfilTutor.paginate(:page => params[:page], :per_page => 10).order('created_at DESC') end # GET /perfil_tutores/1 # GET /perfil_tutores/1.json def show @seccion="Perfil Tutor" end # GET /perfil_tutores/new #def new # @perfil_tutor = PerfilTutor.new #end # GET /perfil_tutores/1/edit #def edit #end # POST /perfil_tutores # POST /perfil_tutores.json def create @perfil_tutor = PerfilTutor.new(perfil_tutor_params) @perfil_tutor.user= current_user respond_to do |format| if @perfil_tutor.save current_user.update(perfilado:true) format.html { redirect_to root_path, notice: '¡Bienvenido! Ya puedes disfrutar de tu cuenta' } #format.json { render :show, status: :created, location: @perfil_tutor } else format.html { render :new } #format.json { render json: @perfil_tutor.errors, status: :unprocessable_entity } end end end # PATCH/PUT /perfil_tutores/1 # PATCH/PUT /perfil_tutores/1.json def update respond_to do |format| if @perfil_tutor.update(perfil_tutor_params) format.html { redirect_to @perfil_tutor, notice: 'Perfil tutor se actualizó correctamente' } #format.json { render :show, status: :ok, location: @perfil_tutor } else format.html { render :edit } #format.json { render json: @perfil_tutor.errors, status: :unprocessable_entity } end end end # DELETE /perfil_tutores/1 # DELETE /perfil_tutores/1.json def destroy @perfil_tutor.destroy @perfil_tutor.user.update(perfilado:false) respond_to do |format| format.html { redirect_to perfil_tutores_url, notice: 'Perfil tutor fue eliminado correctamente' } #format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_perfil_tutor @perfil_tutor = PerfilTutor.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def perfil_tutor_params params.require(:perfil_tutor).permit(:ap_paterno, :ap_materno, :nombre, :fecha_de_nacimiento, :genero_id, :calle, :numero_exterior, :numero_interior, :colonia, :delegacion_municipio, :codigo_postal, :telefono_casa, :telefono_celular, :telefono_recados, :extension_recados) end end
require 'spec_helper' RSpec.describe RubyBranch do it 'has a version number' do expect(RubyBranch::VERSION).not_to be nil end describe '#configure' do before :each do RubyBranch.configure do |config| config.api_key = 'api_key' config.secret_key = 'secret_key' config.branch_domain = 'branch_domain' config.link_to_homepage = 'https://mydomain.com' end end it 'returns configuration options' do expect(RubyBranch.config.api_key).to eq('api_key') expect(RubyBranch.config.secret_key).to eq('secret_key') expect(RubyBranch.config.branch_domain).to eq('branch_domain') expect(RubyBranch.config.link_to_homepage).to eq('https://mydomain.com') end after :each do RubyBranch.reset end end end
class User < ActiveRecord::Base validates :username, :password_digest, :session_token, presence: true validates :username, uniqueness: true validates :password, length: { minimum: 6, allow_nil: true } attr_reader :password has_many :listings, class_name: :Listing, foreign_key: :lessor_id has_many :rentals, through: :listings has_many :reviews, foreign_key: :lessee_id after_initialize :ensure_session_token def self.find_by_credentials(username, password) user = User.find_by(username: username) return nil unless user && user.valid_password?(password) user end def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end def valid_password?(password) BCrypt::Password.new(self.password_digest).is_password?(password) end def reset_token! self.session_token = SecureRandom.urlsafe_base64(16) self.save! self.session_token end def average_listing_rating (self.total_ratings_received / self.review_count_received.to_f).round(2) end def total_ratings_received self.listings.inject(0) do |acc, listing| acc + listing.reviews.inject(0) do |acc2, review| acc2 + review.review end end end def review_count_by_rating(rating) total = 0 self.listings.each do |listing| listing.reviews.each do |review| total += 1 if review.review == rating end end total end def review_count_received self.listings.inject(0) { |acc, listing| acc + listing.review_count } end private def ensure_session_token self.session_token ||= SecureRandom.urlsafe_base64(16) end end
class CreateEras < ActiveRecord::Migration def change create_table :eras do |t| t.string :abbrev t.string :name t.integer :number t.boolean :direction #if true then ascending t.integer :anchor # input as start year, convert to day t.belongs_to :calendar, index: true, foreign_key: true t.timestamps null: false end add_index :eras, :abbrev end end
# frozen_string_literal: true RSpec.describe 'ArrayJsonb::Tags' do before(:all) do Entity.pg_tags_on :tags_jsonb, key: :name truncate && Factory.array_jsonb end let(:column) { :tags_jsonb } let(:relation) { Entity.send(column) } it 'find all tags' do tags = relation.all.order('name') expect(tags.size).to be_eql(6) expect(tags.map(&:name)).to be_eql(%w[a b c d e1 e2]) end it 'find all tags for filtered records' do tags = Entity.where(attr: 'test2').send(column).all expect(tags.size).to be_eql(2) expect(tags.map(&:name)).to be_eql(%w[b c]) end it 'find all tags with counts' do tag = relation.all_with_counts.first expect(tag.count).to be_eql(1) end it 'count tags' do expect(relation.count).to be_eql(6) end it 'count tags for filtered records' do expect(Entity.where(attr: 'test2').send(column).count).to be_eql(2) end end
require 'erb' require 'net/http' require_relative 'string' module ScannerExtensions module Helpers # XML templates, used as payloads for XXE detections module XmlTemplates TEMPLATES = [ { template: ERB.new( <<-fin.margin |<?xml version="1.0"?> |<!DOCTYPE a SYSTEM "http://<%=dns%>/a.dtd"[ | <!ENTITY % b SYSTEM "http://<%=dns%>/b.ent"> | %b; |]> |<a>wlrm-scnr</a> fin ), request_class: Net::HTTP::Post, method: :post }, { template: ERB.new( <<-fin.margin |<?xml version="1.0"?> |<!DOCTYPE a PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://<%=dns%>/a.dtd"> |<a>wlrm-scnr</a> fin ), request_class: Net::HTTP::Post, method: :post } ].freeze WEBDAV_TEMPLATES = [{ template: ERB.new( <<-fin.margin |<?xml version="1.0" encoding="utf-8"?> |<!DOCTYPE wlrm [ |<!ENTITY % dtd SYSTEM "http://<%=dns%>/"> |%dtd;]> |<propfind xmlns="DAV:"><allprop/></propfind> fin ), request_class: Net::HTTP::Propfind, method: :propfind }].freeze module_function def each(&block) TEMPLATES.each &block end def fill(template, dns) template[:template].result(Kernel.binding) end def fill16(template, dns) r = template[:template].result(Kernel.binding) data = r.split("\n") data[0] = '<?xml version="1.0" encoding="utf-16"?>' data = data.join("\n") data.encode('utf-16').unpack('C*')[0..-1].pack('C*') end end end end
class Region < ActiveRecord::Base belongs_to :country has_many :cities attr_accessible :name, :short_name end
FactoryBot.define do factory :response do entry_id { FactoryBot.create(:entry).id } question { "How are you?" } body { "I am good" } sequence(:position) { |index| index } end end
Gem::Specification.new do |s| s.name = 'red-glass' s.version = '0.1.5' s.date = '2014-09-23' s.summary = 'Red Glass: Selenium event pane' s.description = 'Red Glass works alongside Selenium to observe browser events, and provides an interactive log which illustrates changes to the DOM during an automation session.' s.authors = ["Frank O'Hara"] s.email = 'frankj.ohara@gmail.com' s.files = Dir.glob('{lib}/**/*') s.homepage = 'https://github.com/fohara/red-glass' s.add_dependency 'sinatra' s.add_dependency 'em-websocket', '~> 0.5.0' s.add_dependency 'thin' s.add_dependency 'selenium-webdriver', '>= 2.42.0' s.add_dependency 'json' s.add_dependency 'uuid' s.add_development_dependency 'rack-test' s.add_development_dependency 'rspec' end
class Member < ActiveRecord::Base has_one :room_assignment #has_one :room, :through :room_assignment belongs_to :member_type belongs_to :family validates_presence_of :family_id validates_presence_of :member_type_id validates_presence_of :first_name validates_presence_of :family_name validates_presence_of :gender validates_presence_of :relationship validates_presence_of :age, :if => "[4].include?(member_type_id)", :message => "must be provided for specified group type" validates_presence_of :grade, :if => "[4].include?(member_type_id)", :message => "must be provided for specified group type" validates_format_of :cell_phone, :with => /[0-9]{10}/, :message => "must be 10 digit phone number", :allow_nil => true, :allow_blank => true validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :allow_nil => true, :allow_blank => true validates_numericality_of :age, :only_integer => true, :greater_than => 0, :less_than => 100, :message => "must be a number between 0-100", :allow_nil => true, :allow_blank => true end
module Validate class ElectricityConsumption include ActiveModel::Validations attr_accessor :start_date, :end_date, :price, :group_by validates :start_date, :end_date, presence: true, format: { with: /\A\d\d-\d\d-\d\d\d\d\z/, message: 'only date in dd-mm-yyyy format' } validates :group_by, inclusion: { in: %w[day week month], message: '%{value} is not a valid type' }, allow_blank: true validates :price, numericality: true, allow_blank: true def initialize(params = ActionController::Parameters.new) @start_date = params[:start_date] @end_date = params[:end_date] @group_by = params[:group_by] if params[:group_by] @price = params[:price] if params[:price] params.permit(:start_date, :end_date, :group_by, :price) end end end
class Honeydo < ActiveRecord::Base validates_presence_of :title validates :title, :length => { :minimum => 2} validates_uniqueness_of :title end
namespace :check do namespace :migrate do task remove_cancelled_string_from_smooch_bot_installations: :environment do old_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = nil started = Time.now.to_i RequestStore.store[:skip_notifications] = true RequestStore.store[:skip_clear_cache] = true RequestStore.store[:skip_rules] = true bot = BotUser.find_by(login: 'smooch') unless bot.nil? n = 0 TeamBotInstallation.where(user_id: bot.id).each do |tbi| tbi.get_smooch_workflows.each { |w| w.to_h.delete('cancelled') } tbi.save! n += 1 end end minutes = ((Time.now.to_i - started) / 60).to_i puts "[#{Time.now}] Removed string from #{n} Smooch Bot installations in #{minutes} minutes." RequestStore.store[:skip_notifications] = false RequestStore.store[:skip_clear_cache] = false RequestStore.store[:skip_rules] = false ActiveRecord::Base.logger = old_logger end end end
require "optparse" require "time" module BTWATTCH2 class CLI attr_reader :index, :addr, :interval, :switch, :time attr_accessor :conn def initialize @opt = OptionParser.new @opt.on("-i", "--index <index>", "Specify adapter index, e.g. hci0."){|v|@index=v.to_i} @opt.on("-a", "--addr <addr>", "Specify the destination address."){|v|@addr=v} @opt.on("-n", "--interval <second(s)>", "Specify the seconds to wait between updates."){|v|@interval=v.to_i} @opt.on("--on", "Turn on the power switch."){|v|@switch="on"} @opt.on("--off", "Turn off the power switch."){|v|@switch="off"} @opt.on("--set-rtc <time>", "Specify the time to set to RTC."){|v|@time=Time.parse(v)} @opt.on("--set-rtc-now", "Set the current time of this system to RTC."){|v|@time=Time.now} @opt.on("--test-led", "Blink the LED on the main unit."){|v|@switch="blink_led"} yield(@opt) if block_given? @opt.parse(ARGV) @index = 0 if @index.nil? @interval = 1 if @interval.nil? end def help puts @opt end def main @conn = Connection.new(self) if !@time.nil? @conn.set_rtc!(@time) elsif !@switch.nil? eval("@conn.#{@switch}") else @conn.measure end rescue SignalException @conn.disconnect! exit end end end
class Dog def initialize(name) @name = name end def bark "#@name barks: Woof Woof" #illustrates a shorthand syntax for string interpolation end def eat "Yum yum" end def chase_cat "Cat cat cat" end end my_dogs = %w(Fido Lassie Pluto Tramp Lady).map do |name| Dog.new(name) end methods = %w(bark eat chase_cat) my_dogs.each do |dog| methods.each do |m| puts dog.send(m) end end
require 'rails_helper' describe "A visitor" do context "visits the trip show page" do it "sees a list of all attributes of a trip" do station = create(:station) trip = create(:trip, start_station: station, end_station: station, duration: 120) visit trip_path(trip) expect(page).to have_content(trip.duration / 60) expect(page).to have_content(trip.start_date.strftime('%b %d %Y')) expect(page).to have_content(trip.start_station.name) expect(page).to have_content(trip.start_station_id) expect(page).to have_content(trip.end_date.strftime('%b %d %Y')) expect(page).to have_content(trip.end_station.name) expect(page).to have_content(trip.end_station_id) expect(page).to have_content(trip.bike_id) expect(page).to have_content(trip.subscription_type) expect(page).to have_content(trip.zip_code) end end end
require_relative 'spec_helper' require_relative '../lib/gitlab_projects' describe GitlabProjects do before do GitlabConfig.any_instance.stub(repos_path: tmp_repos_path) FileUtils.mkdir_p(tmp_repos_path) $logger = double('logger').as_null_object end after do FileUtils.rm_rf(tmp_repos_path) end describe :create_hooks do let(:repo_path) { File.join(tmp_repos_path, 'hook-test.git') } let(:hooks_dir) { File.join(repo_path, 'hooks') } let(:target_hooks_dir) { File.join(ROOT_PATH, 'hooks') } let(:existing_target) { File.join(repo_path, 'foobar') } before do FileUtils.rm_rf(repo_path) FileUtils.mkdir_p(repo_path) end context 'hooks is a directory' do let(:existing_file) { File.join(hooks_dir, 'my-file') } before do FileUtils.mkdir_p(hooks_dir) FileUtils.touch(existing_file) GitlabProjects.create_hooks(repo_path) end it { File.readlink(hooks_dir).should == target_hooks_dir } it { Dir[File.join(repo_path, "hooks.old.*/my-file")].count.should == 1 } end context 'hooks is a valid symlink' do before do FileUtils.mkdir_p existing_target File.symlink(existing_target, hooks_dir) GitlabProjects.create_hooks(repo_path) end it { File.readlink(hooks_dir).should == target_hooks_dir } end context 'hooks is a broken symlink' do before do FileUtils.rm_f(existing_target) File.symlink(existing_target, hooks_dir) GitlabProjects.create_hooks(repo_path) end it { File.readlink(hooks_dir).should == target_hooks_dir } end end describe :initialize do before do argv('add-project', repo_name) @gl_projects = GitlabProjects.new end it { @gl_projects.project_name.should == repo_name } it { @gl_projects.instance_variable_get(:@command).should == 'add-project' } it { @gl_projects.instance_variable_get(:@full_path).should == "#{GitlabConfig.new.repos_path}/gitlab-ci.git" } end describe :create_branch do let(:gl_projects_create) { build_gitlab_projects('import-project', repo_name, 'https://github.com/randx/six.git') } let(:gl_projects) { build_gitlab_projects('create-branch', repo_name, 'test_branch', 'master') } it "should create a branch" do gl_projects_create.exec gl_projects.exec branch_ref = capture_in_tmp_repo(%W(git rev-parse test_branch)) master_ref = capture_in_tmp_repo(%W(git rev-parse master)) branch_ref.should == master_ref end end describe :rm_branch do let(:gl_projects_create) { build_gitlab_projects('import-project', repo_name, 'https://github.com/randx/six.git') } let(:gl_projects_create_branch) { build_gitlab_projects('create-branch', repo_name, 'test_branch', 'master') } let(:gl_projects) { build_gitlab_projects('rm-branch', repo_name, 'test_branch') } it "should remove a branch" do gl_projects_create.exec gl_projects_create_branch.exec branch_ref = capture_in_tmp_repo(%W(git rev-parse test_branch)) gl_projects.exec branch_del = capture_in_tmp_repo(%W(git rev-parse test_branch)) branch_del.should_not == branch_ref end end describe :create_tag do let(:gl_projects_create) { build_gitlab_projects('import-project', repo_name, 'https://github.com/randx/six.git') } context "lightweight tag" do let(:gl_projects) { build_gitlab_projects('create-tag', repo_name, 'test_tag', 'master') } it "should create a tag" do gl_projects_create.exec gl_projects.exec tag_ref = capture_in_tmp_repo(%W(git rev-parse test_tag)) master_ref = capture_in_tmp_repo(%W(git rev-parse master)) tag_ref.should == master_ref end end context "annotated tag" do msg = 'some message' tag_name = 'test_annotated_tag' let(:gl_projects) { build_gitlab_projects('create-tag', repo_name, tag_name, 'master', msg) } it "should create an annotated tag" do gl_projects_create.exec system(*%W(git --git-dir=#{tmp_repo_path} config user.name Joe)) system(*%W(git --git-dir=#{tmp_repo_path} config user.email joe@smith.com)) gl_projects.exec tag_ref = capture_in_tmp_repo(%W(git rev-parse #{tag_name}^{})) master_ref = capture_in_tmp_repo(%W(git rev-parse master)) tag_msg = capture_in_tmp_repo(%W(git tag -l -n1 #{tag_name})) tag_ref.should == master_ref tag_msg.should == tag_name + ' ' + msg end end end describe :rm_tag do let(:gl_projects_create) { build_gitlab_projects('import-project', repo_name, 'https://github.com/randx/six.git') } let(:gl_projects_create_tag) { build_gitlab_projects('create-tag', repo_name, 'test_tag', 'master') } let(:gl_projects) { build_gitlab_projects('rm-tag', repo_name, 'test_tag') } it "should remove a branch" do gl_projects_create.exec gl_projects_create_tag.exec branch_ref = capture_in_tmp_repo(%W(git rev-parse test_tag)) gl_projects.exec branch_del = capture_in_tmp_repo(%W(git rev-parse test_tag)) branch_del.should_not == branch_ref end end describe :add_project do let(:gl_projects) { build_gitlab_projects('add-project', repo_name) } it "should create a directory" do gl_projects.stub(system: true) GitlabProjects.stub(create_hooks: true) gl_projects.exec File.exists?(tmp_repo_path).should be_true end it "should receive valid cmd" do valid_cmd = ['git', "--git-dir=#{tmp_repo_path}", 'init', '--bare'] gl_projects.should_receive(:system).with(*valid_cmd).and_return(true) GitlabProjects.should_receive(:create_hooks).with(tmp_repo_path) gl_projects.exec end it "should log an add-project event" do $logger.should_receive(:info).with("Adding project #{repo_name} at <#{tmp_repo_path}>.") gl_projects.exec end end describe :list_projects do let(:gl_projects) do build_gitlab_projects('add-project', "list_test/#{repo_name}") end before do FileUtils.mkdir_p(tmp_repos_path) end it 'should create projects and list them' do GitlabProjects.stub(create_hooks: true) gl_projects.exec gl_projects.send(:list_projects).should == ["list_test/#{repo_name}"] end end describe :mv_project do let(:gl_projects) { build_gitlab_projects('mv-project', repo_name, 'repo.git') } let(:new_repo_path) { File.join(tmp_repos_path, 'repo.git') } before do FileUtils.mkdir_p(tmp_repo_path) end it "should move a repo directory" do File.exists?(tmp_repo_path).should be_true gl_projects.exec File.exists?(tmp_repo_path).should be_false File.exists?(new_repo_path).should be_true end it "should fail if no destination path is provided" do incomplete = build_gitlab_projects('mv-project', repo_name) $logger.should_receive(:error).with("mv-project failed: no destination path provided.") incomplete.exec.should be_false end it "should fail if the source path doesn't exist" do bad_source = build_gitlab_projects('mv-project', 'bad-src.git', 'dest.git') $logger.should_receive(:error).with("mv-project failed: source path <#{tmp_repos_path}/bad-src.git> does not exist.") bad_source.exec.should be_false end it "should fail if the destination path already exists" do FileUtils.mkdir_p(File.join(tmp_repos_path, 'already-exists.git')) bad_dest = build_gitlab_projects('mv-project', repo_name, 'already-exists.git') message = "mv-project failed: destination path <#{tmp_repos_path}/already-exists.git> already exists." $logger.should_receive(:error).with(message) bad_dest.exec.should be_false end it "should log an mv-project event" do message = "Moving project #{repo_name} from <#{tmp_repo_path}> to <#{new_repo_path}>." $logger.should_receive(:info).with(message) gl_projects.exec end end describe :rm_project do let(:gl_projects) { build_gitlab_projects('rm-project', repo_name) } before do FileUtils.mkdir_p(tmp_repo_path) end it "should remove a repo directory" do File.exists?(tmp_repo_path).should be_true gl_projects.exec File.exists?(tmp_repo_path).should be_false end it "should log an rm-project event" do $logger.should_receive(:info).with("Removing project #{repo_name} from <#{tmp_repo_path}>.") gl_projects.exec end end describe :update_head do let(:gl_projects) { build_gitlab_projects('update-head', repo_name, 'stable') } let(:gl_projects_fail) { build_gitlab_projects 'update-head', repo_name } before do FileUtils.mkdir_p(tmp_repo_path) system(*%W(git init --bare #{tmp_repo_path})) FileUtils.touch(File.join(tmp_repo_path, "refs/heads/stable")) File.read(File.join(tmp_repo_path, 'HEAD')).strip.should == 'ref: refs/heads/master' end it "should update head for repo" do gl_projects.exec.should be_true File.read(File.join(tmp_repo_path, 'HEAD')).strip.should == 'ref: refs/heads/stable' end it "should log an update_head event" do $logger.should_receive(:info).with("Update head in project #{repo_name} to <stable>.") gl_projects.exec end it "should failed and log an error" do $logger.should_receive(:error).with("update-head failed: no branch provided.") gl_projects_fail.exec.should be_false end end describe :import_project do context 'success import' do let(:gl_projects) { build_gitlab_projects('import-project', repo_name, 'https://github.com/randx/six.git') } it { gl_projects.exec.should be_true } it "should import a repo" do gl_projects.exec File.exists?(File.join(tmp_repo_path, 'HEAD')).should be_true end it "should log an import-project event" do message = "Importing project #{repo_name} from <https://github.com/randx/six.git> to <#{tmp_repo_path}>." $logger.should_receive(:info).with(message) gl_projects.exec end end context 'already exists' do let(:gl_projects) { build_gitlab_projects('import-project', repo_name, 'https://github.com/randx/six.git') } it 'should import only once' do gl_projects.exec.should be_true gl_projects.exec.should be_false end end context 'timeout' do let(:gl_projects) { build_gitlab_projects('import-project', repo_name, 'https://github.com/gitlabhq/gitlabhq.git', '1') } it { gl_projects.exec.should be_false } it "should not import a repo" do gl_projects.exec File.exists?(File.join(tmp_repo_path, 'HEAD')).should be_false end it "should log an import-project event" do message = "Importing project #{repo_name} from <https://github.com/gitlabhq/gitlabhq.git> failed due to timeout." $logger.should_receive(:error).with(message) gl_projects.exec end end end describe :fork_project do let(:source_repo_name) { File.join('source-namespace', repo_name) } let(:dest_repo) { File.join(tmp_repos_path, 'forked-to-namespace', repo_name) } let(:gl_projects_fork) { build_gitlab_projects('fork-project', source_repo_name, 'forked-to-namespace') } let(:gl_projects_import) { build_gitlab_projects('import-project', source_repo_name, 'https://github.com/randx/six.git') } before do gl_projects_import.exec end it "should not fork without a destination namespace" do missing_arg = build_gitlab_projects('fork-project', source_repo_name) $logger.should_receive(:error).with("fork-project failed: no destination namespace provided.") missing_arg.exec.should be_false end it "should not fork into a namespace that doesn't exist" do message = "fork-project failed: destination namespace <#{tmp_repos_path}/forked-to-namespace> does not exist." $logger.should_receive(:error).with(message) gl_projects_fork.exec.should be_false end it "should fork the repo" do # create destination namespace FileUtils.mkdir_p(File.join(tmp_repos_path, 'forked-to-namespace')) gl_projects_fork.exec.should be_true File.exists?(dest_repo).should be_true File.exists?(File.join(dest_repo, '/hooks/pre-receive')).should be_true File.exists?(File.join(dest_repo, '/hooks/post-receive')).should be_true end it "should not fork if a project of the same name already exists" do # create a fake project at the intended destination FileUtils.mkdir_p(File.join(tmp_repos_path, 'forked-to-namespace', repo_name)) # trying to fork again should fail as the repo already exists message = "fork-project failed: destination repository <#{tmp_repos_path}/forked-to-namespace/#{repo_name}> " message << "already exists." $logger.should_receive(:error).with(message) gl_projects_fork.exec.should be_false end it "should log a fork-project event" do message = "Forking project from <#{File.join(tmp_repos_path, source_repo_name)}> to <#{dest_repo}>." $logger.should_receive(:info).with(message) # create destination namespace FileUtils.mkdir_p(File.join(tmp_repos_path, 'forked-to-namespace')) gl_projects_fork.exec.should be_true end end describe :exec do it 'should puts message if unknown command arg' do gitlab_projects = build_gitlab_projects('edit-project', repo_name) gitlab_projects.should_receive(:puts).with('not allowed') gitlab_projects.exec end it 'should log a warning for unknown commands' do gitlab_projects = build_gitlab_projects('hurf-durf', repo_name) $logger.should_receive(:warn).with('Attempt to execute invalid gitlab-projects command "hurf-durf".') gitlab_projects.exec end end def build_gitlab_projects(*args) argv(*args) gl_projects = GitlabProjects.new gl_projects.stub(repos_path: tmp_repos_path) gl_projects.stub(full_path: File.join(tmp_repos_path, gl_projects.project_name)) gl_projects end def argv(*args) args.each_with_index do |arg, i| ARGV[i] = arg end end def tmp_repos_path File.join(ROOT_PATH, 'tmp', 'repositories') end def tmp_repo_path File.join(tmp_repos_path, repo_name) end def repo_name 'gitlab-ci.git' end def capture_in_tmp_repo(cmd) IO.popen([*cmd, {chdir: tmp_repo_path}]).read.strip end end
# encoding: utf-8 # control 'V-81015' do title 'The Red Hat Enterprise Linux operating system must be configured to use the au-remote plugin.' desc 'Information stored in one location is vulnerable to accidental or incidental deletion or alteration. Off-loading is a common process in information systems with limited audit storage capacity. Without the configuration of the "au-remote" plugin, the audisp-remote daemon will not off-load the logs from the system being audited. ' impact 0.5 tag 'check': 'Verify the "au-remote" plugin is active on the system: # grep "active" /etc/audisp/plugins.d/au-remote.conf active = yes If the "active" setting is not set to "yes", or the line is commented out, this is a finding.' tag 'fix': 'Edit the /etc/audisp/plugins.d/au-remote.conf file and change the value of "active" to "yes". The audit daemon must be restarted for changes to take effect: # service auditd restart' describe file('/etc/audisp/plugins/au-remote.conf') do its('content') { should match(%r{^active.*=.*yes$}) } end end
require Helper action :create do converge_by("Create or overwrite #{new_resource}") do create_inifile new_resource.updated_by_last_action(true) end end action :create_if_missing do if !exists? converge_by("Create #{new_resource} because it does not exist") do create_inifile(new_resource.path, new_resource.settings) new_resource.updated_by_last_action(true) end end end action :update do if exists? converge_by("Update #{current_resource} because it already exists") do update_inifile(new_resource.path, new_resource.settings) new_resource.updated_by_last_action(true) end else converge_by("Create #{new_resource} because it does not exist") do create_inifile(new_resource.path, new_resource.settings) new_resource.updated_by_last_action(true) end end end def why_supported? true end def load_current_resource @current_resource = Chef::Resource::IniFile.new(new_resource.name) @current_resource.path(new_resource.path) end def exists? ::File.exists?(new_resource.path) end
class UserNotification < ActionMailer::Base default from: '"POLLIFY" <info@owli.de>' def notify_user(email, code) @code = code @poll = Poll.find_by_code(@code) mail(:to => email, :subject => "You've been invited to a POLLIFY poll.") end def notify_admin(email, code) @code = code @poll = Poll.find_by_code(@code) mail(:to => email, :subject => "Your new feedback-survey at POLLIFY was created.") end def notify_admin_of_comment(email, code) @code = code @poll = Poll.find_by_code(@code) mail(:to => email, :subject => "New comment and rating on your POLLIFY feedback-survey received.") end end
class CreateItemFormatsProducts < ActiveRecord::Migration extend MigrationHelpers def self.up create_table "item_formats_products", :id => false do |t| t.column "item_format_id", :integer, :null => false t.column "product_id", :integer, :null => false end foreign_key(:item_formats_products, :item_format_id, :item_formats) foreign_key(:item_formats_products, :product_id, :products) end def self.down drop_table "item_formats_products" end end
class ProductImage < ActiveRecord::Base attr_accessible :product_id, :product_image belongs_to :product validates :product_id, :presence => true image_accessor :product_image end
class Patient attr_accessor :name, :appointments def initialize(name) @name=name @appointments=[] end def add_appointment(appt) @appointments <<appt appt.patient=self end def doctors self.appointments.collect {|appt| appt.doctor} end end
# frozen_string_literal: true module Renalware module Diaverum module DiaverumHelpers def using_a_tmp_diaverum_path Dir.mktmpdir do |dir| ENV["DIAVERUM_FOLDER"] = dir Renalware::Diaverum::Paths.setup yield end end def create_dry_weight Clinical::DryWeight.create!( patient: Clinical.cast_patient(patient), assessor: user, weight: 123.4, assessed_on: Time.zone.now, by: user ) end # rubocop:disable Metrics/MethodLength, Metrics/AbcSize def create_patient_xml_document(options: {}) erb_template = options.fetch( :erb_template, Engine.root.join("spec", "fixtures", "files", "diaverum_example.xml.erb") ) system_user = create(:user, username: SystemUser.username) access_map = AccessMap.create!( diaverum_location_id: "LEJ", diaverum_type_id: 7, access_type: create(:access_type), side: :left ) hospital_unit = create(:hospital_unit) dialysate = create(:hd_dialysate) provider = HD::Provider.create!(name: "Diaverum") dialysis_unit = HD::ProviderUnit.create!( hospital_unit: hospital_unit, hd_provider: provider, providers_reference: "123" ) xml_filepath = Engine.root.join("spec", "fixtures", "files", "diaverum_example.xml.erb") xml_string = ERB.new(xml_filepath.read).result(binding) Nokogiri::XML(xml_string) end # rubocop:enable Metrics/MethodLength, Metrics/AbcSize def create_access_map AccessMap.create!( diaverum_location_id: "LEJ", diaverum_type_id: 7, access_type: access_type, side: :left ) end def create_hd_type_map HDTypeMap.create!(diaverum_type_id: "HFLUX", hd_type: :hd) end end end end
class WriterProfilesController < WriterApplicationController before_action :set_profile, only: [:show, :edit, :update] def new @profile = WriterProfile.new end def create @profile = WriterProfile.new(profile_params) @profile.screen_writer = current_writer if @profile.save redirect_to root_path, notice: "Profile created successfully" else redirect_to new_writer_profile_path, notice: "Profile could not be created! Please try again" end end def show end def edit authorize @profile, :edit? end def update if @profile.update(profile_params) redirect_to writer_profile_path(@profile), notice: 'Profile was successfully updated.' else redirect_to edit_writer_profile_path(@profile), notice: "Couldn't update profile" end end private def profile_params params.require(:writer_profile).permit(:fname,:mname,:lname,:gender,:dob,:profile_pic) end def set_profile @profile = WriterProfile.find(params[:id]) end def help1 # while deleting this please delete the tests covering this too. Gracias. @profile = WriterProfile.first @profile.screen_writer = current_writer if @profile.save else end end def help2 @profile = WriterProfile.last @profile.screen_writer = current_writer if @profile.save else end end end