text
stringlengths
10
2.61M
# Controlador Medicos # Acciones index, detalles, nuevo, crear, borrar class MedicosController < ApplicationController def index @q = Medico.ransack(params[:q]) @medicos = @q.result(distict: true).paginate(page: params[:page]) end def detalles @medico = Medico.find(params[:id]) end def nuevo @medico = Medico.new end def crear @medico = Medico.new(permitted_params[:medico]) if @medico.save flash[:notice] = 'Médico creado con éxito.' redirect_to medico_path(@medico) else render :nuevo end end def editar @medico = Medico.find(params[:id]) end def actualizar @medico = Medico.find(params[:id]) contrasena = params[:medico][:contrasena] @medico.contrasena = contrasena if contrasena != '' if @medico.update_attributes(permitted_params[:medico]) flash[:notice] = 'Médico actualizado con éxito.' redirect_to medico_path(@medico) else render :editar end end def borrar @medico = Medico.find(params[:id]) @medico.destroy flash[:notice] = 'Médico borrado con éxito.' redirect_to medicos_path end private def permitted_params parametros = [:matricula, :nombre, :apellido_paterno, :apellido_materno, :curp, :cedula, :sexo, :fecha_nacimiento, :especialidad, :subespecialidad, :instituto] parametros << :contrasena if params[:medico][:contrasena] != '' parametros << :super_administrador if medico_actual.super_administrador? params.permit(medico: parametros) end end
class Company < ActiveRecord::Base validates :name, :city, presence: true validates :name, uniqueness: true has_many :jobs, dependent: :destroy has_many :comments, dependent: :destroy has_many :contacts, dependent: :destroy def self.top_three top = Job.group(:company_id).average(:level_of_interest) top.sort_by {|key, value| -value }[0..2] end def self.count_by_location Company.joins(:jobs).group(:city).order(:city).count end end
class RoutesController < ApplicationController before_filter :logged_in_user, :only => [:new, :create, :edit, :update, :destroy] layout "flight_log/flight_log" add_breadcrumb 'Home', 'flightlog_path' def index add_breadcrumb 'Routes', 'routes_path' @title = "Routes" @meta_description = "A list of the routes Paul Bogard has flown on, and how often he's flown on each." if logged_in? flights = Flight.all else # Filter out hidden trips for visitors flights = Flight.visitor end # Set values for sort: case params[:sort_category] when "flights" @sort_cat = :flights when "distance" @sort_cat = :distance else @sort_cat = :flights end case params[:sort_direction] when "asc" @sort_dir = :asc when "desc" @sort_dir = :desc else @sort_dir = :desc end sort_mult = (@sort_dir == :asc ? 1 : -1) # Build hash of distances: distances = Hash.new(nil) dist_airport_alphabetize = Array.new() routes = Route.where("distance_mi IS NOT NULL") routes.each do |route| dist_airport_alphabetize[0] = route.airport1.iata_code dist_airport_alphabetize[1] = route.airport2.iata_code dist_airport_alphabetize.sort! distances["#{dist_airport_alphabetize[0]}-#{dist_airport_alphabetize[1]}"] = route.distance_mi end # Build hash of routes and number of flights route_totals = Hash.new(0) airport_alphabetize = Array.new() flights.each do |flight| airport_alphabetize[0] = flight.origin_airport.iata_code airport_alphabetize[1] = flight.destination_airport.iata_code airport_alphabetize.sort! route_totals["#{airport_alphabetize[0]}-#{airport_alphabetize[1]}"] += 1 end # Build array of routes, distances, and number of flights: @route_table = Array.new() route_totals.each do |flight_route, count| @route_table << {:route => flight_route, :distance_mi => distances[flight_route] || -1, :total_flights => count} # Make nil distances negative so we can sort end # Find maxima for graph scaling: @flights_maximum = @route_table.max_by{|i| i[:total_flights].to_i}[:total_flights] @distance_maximum = @route_table.max_by{|i| i[:distance_mi].to_i}[:distance_mi] # Sort route table: if @sort_cat == :flights @route_table = @route_table.sort_by {|value| [sort_mult*value[:total_flights], -value[:distance_mi]]} elsif @sort_cat == :distance @route_table = @route_table.sort_by {|value| [sort_mult*value[:distance_mi], -value[:total_flights]]} end end def show @airports = Array.new if params[:id].to_i > 0 current_route = Route.find(params[:id]) #raise ActiveRecord::RecordNotFound if (current_route.nil?) @airports.push(Airport.find(current_route.airport1_id).iata_code) @airports.push(Airport.find(current_route.airport2_id).iata_code) @route_string = @airports.join('-') else @airports = params[:id].split('-') @route_string = params[:id] end airport_lookup = Array.new() @airports_id = Array.new() @airports_city = Array.new() raise ActiveRecord::RecordNotFound if Airport.where(:iata_code => @airports[0]).length == 0 || Airport.where(:iata_code => @airports[1]).length == 0 @airports.each_with_index do |airport, index| airport_lookup[index] = Airport.where(:iata_code => airport).first @airports_id[index] = airport_lookup[index].id @airports_city[index] = airport_lookup[index].city end add_breadcrumb 'Routes', 'routes_path' add_breadcrumb "#{@airports[0]} - #{@airports[1]}", route_path(@route_string) @title = "#{@airports[0]} - #{@airports[1]}" @meta_description = "Maps and lists of Paul Bogard's flights between #{@airports[0]} and #{@airports[1]}." @logo_used = true if logged_in? @flights = Flight.where("(origin_airport_id = :city1 AND destination_airport_id = :city2) OR (origin_airport_id = :city2 AND destination_airport_id = :city1)", {:city1 => @airports_id[0], :city2 => @airports_id[1]}) else @flights = Flight.visitor.where("(origin_airport_id = :city1 AND destination_airport_id = :city2) OR (origin_airport_id = :city2 AND destination_airport_id = :city1)", {:city1 => @airports_id[0], :city2 => @airports_id[1]}) end raise ActiveRecord::RecordNotFound if @flights.length == 0 @pair_distance = route_distance_by_iata(@airports[0],@airports[1]) # Get trips sharing this city pair: trip_array = Array.new @sections = Array.new section_where_array = Array.new @flights.each do |flight| trip_array.push(flight.trip_id) @sections.push( {:trip_id => flight.trip_id, :trip_name => flight.trip.name, :trip_section => flight.trip_section, :departure => flight.departure_date, :trip_hidden => flight.trip.hidden} ) section_where_array.push("(trip_id = #{flight.trip_id.to_i} AND trip_section = #{flight.trip_section.to_i})") end trip_array = trip_array.uniq # Create list of trips sorted by first flight: if logged_in? @trips = Trip.find(trip_array).sort_by{ |trip| trip.flights.first.departure_date } else @trips = Trip.visitor.find(trip_array).sort_by{ |trip| trip.flights.first.departure_date } end # Create comparitive lists of airlines, aircraft, and classes: airline_frequency(@flights) aircraft_frequency(@flights) class_frequency(@flights) # Create flight arrays for maps of trips and sections: @city_pair_trip_flights = Flight.where(:trip_id => trip_array) @city_pair_section_flights = Flight.where(section_where_array.join(' OR ')) rescue ActiveRecord::RecordNotFound flash[:record_not_found] = "We couldn't find any flights with the route #{params[:id]}. Instead, we'll give you a list of routes." redirect_to routes_path end def edit add_breadcrumb 'Routes', 'routes_path' add_breadcrumb "#{params[:airport1]} - #{params[:airport2]}", route_path("#{params[:airport1]}-#{params[:airport2]}") add_breadcrumb 'Edit', '#' @title = "Edit #{params[:airport1]} - #{params[:airport2]}" # Get airport ids: @airport_ids = Array.new @airport_ids.push(Airport.where(:iata_code => params[:airport1]).first.try(:id)) @airport_ids.push(Airport.where(:iata_code => params[:airport2]).first.try(:id)) raise ArgumentError if @airport_ids.include?(nil) @airport_ids.sort! # Ensure IDs are in order # Check to see if route already exists in database. If so, edit it, if not, new route. current_route = Route.where("(airport1_id = ? AND airport2_id = ?) OR (airport1_id = ? AND airport2_id = ?)", @airport_ids[0], @airport_ids[1], @airport_ids[1], @airport_ids[0]) if current_route.present? # Route exists, edit it. @route = current_route.first else # Route does not exist, create a new one. @route = Route.new end rescue ArgumentError flash[:record_not_found] = "Can't look up route - at least one of these airports does not exist in the database." redirect_to routes_path end def create @route = Route.new(params[:route]) if @route.save flash[:success] = "Successfully added distance to route!" redirect_to routes_path else render 'new' end end def update @route = Route.find(params[:id]) if @route.update_attributes(params[:route]) flash[:success] = "Successfully updated route distance." redirect_to routes_path else render 'edit' end end private def logged_in_user redirect_to flightlog_path unless logged_in? end end
class VantagemsController < ApplicationController before_action :set_vantagem, only: [:show, :edit, :update, :destroy] # GET /vantagem # GET /vantagems.json def index @vantagems = Vantagem.all end # GET /vantagems/1 # GET /vantagems/1.json def show end # GET /vantagems/new def new @vantagem = Vantagem.new end # GET /vantagems/1/edit def edit end # POST /vantagems # POST /vantagems.json def create @vantagem = Vantagem.new(vantagem_params) respond_to do |format| if @vantagem.save format.html { redirect_to @vantagem, notice: 'Tipo criado com sucesso' } format.json { render :show, status: :created, location: @vantagem } else format.html { render :new } format.json { render json: @vantagem.errors, status: :unprocessable_entity } end end end # PATCH/PUT /vantagems/1 # PATCH/PUT /vantagems/1.json def update respond_to do |format| if @vantagem.update(vantagem_params) format.html { redirect_to @vantagem, notice: 'Tipo editado com sucesso' } format.json { render :show, status: :ok, location: @vantagem } else format.html { render :edit } format.json { render json: @vantagem.errors, status: :unprocessable_entity } end end end # DELETE /vantagems/1 # DELETE /vantagems/1.json def destroy @vantagems.destroy respond_to do |format| format.html { redirect_to vantagems_url, notice: 'Tipo apagado com sucesso' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_vantagem @vantagem = Vantagem.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tipo_params params.require(:vantagem).permit(:nome) end end
# frozen_string_literal: true class DrawerComponent < ViewComponent::Base def initialize(current_user:) @current_user = current_user end def user_image helpers.current_user_image end def current_user_path user_path(@current_user) end def current_user_email @current_user.email end end
class CreateTeamTasks < ActiveRecord::Migration[4.2] def change create_table :team_tasks do |t| t.string :label, null: false t.string :task_type, null: false t.text :description t.text :options t.text :project_ids t.text :mapping t.boolean :required, default: false t.integer :team_id, null: false t.integer :order, default: 0 t.string :associated_type, null: false, default: "ProjectMedia" t.string :fieldset, null: false, default: "" t.boolean :show_in_browser_extension, null: false, default: true t.string :json_schema t.text :conditional_info t.timestamps null: false end add_index :team_tasks, [:team_id, :fieldset, :associated_type] end end
class CartItem < ApplicationRecord belongs_to :customer belongs_to :item validates :amount, presence: true def total_price (item.add_tax_price * amount) * 1.1.round end def self.sum_price sum {|cart_item| cart_item.total_price} end def self.total_payment sum {|cart_item| cart_item.total_price} + 800 end end
class Attendance < ActiveRecord::Base validates_presence_of :student_id validates_presence_of :attendance validates_presence_of :Date belongs_to :student end
class Part < ApplicationRecord has_and_belongs_to_many :car validates :name, presence: true, uniqueness: true end
# # Copyright (c) 2013, 2021, Oracle and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Puppet::Type.type(:protocol_properties).provide(:solaris) do desc "Provider for managing Oracle Solaris protocol object properties" confine :operatingsystem => [:solaris] defaultfor :osfamily => :solaris, :kernelrelease => ['5.11'] commands :ipadm => '/usr/sbin/ipadm' mk_resource_methods def self.instances props = Hash.new { |k,v| k[v] = Hash.new } ipadm("show-prop", "-c", "-o", "PROTO,PROPERTY,CURRENT,DEFAULT,PERSISTENT,POSSIBLE,PERM") .each_line do |line| protocol, property, value, _tmp = line.strip.split(':',4) props[protocol][property] = value ? value : :absent end protocols = [] props.each do |key, value| protocols << new(:name => key, :ensure => :present, :properties => value) end protocols end def self.prefetch(resources) things = instances resources.keys.each do |key| things.find do |prop| # key.to_s in case name uses newvalues and is converted to symbol prop.name == key.to_s end.tap do |provider| next if provider.nil? resources[key].provider = provider end end end # Return an array of prop=value strings to change def change_props out_of_sync=[] # Compare the desired values against the current values resource[:properties].each_pair do |prop,should_be| is = properties[prop] # Current Value == Desired Value unless is == should_be # Stash out of sync property out_of_sync.push("%s=%s" % [prop, should_be]) end end out_of_sync end def properties=(value) change_props.each do |prop| ipadm("set-prop", "-p", prop, @resource[:name]) end end def exists? @property_hash[:ensure] == :present end def create fail "protcol must exist before properties can be set" end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe ContractsController, type: :controller do describe '#index' do let(:user) { FactoryBot.create(:user) } let!(:user_contract) { FactoryBot.create(:contract, user: user) } let!(:another_contract) { FactoryBot.create(:contract) } context 'as an user' do it 'should authenticate and render index with user contracts' do get :index, session: { user_id: user.id } expect(response).to render_template(:index) expect(assigns(:contracts)).to eq([user_contract]) end end context 'as a guest' do it 'should not authenticate and redirect to signin path' do get :index expect(response).to redirect_to(signin_path) expect(assigns(:contracts)).to eq(nil) end end end describe '#create' do let(:user) { FactoryBot.create(:user) } let!(:user_contract) { FactoryBot.create(:contract, user: user) } let(:vendor) { FactoryBot.create(:vendor) } let(:category) { FactoryBot.create(:category) } context 'as an user' do context 'with valid attributes' do let(:valid_attributes) do { contract: { vendor_id: vendor.id, category_id: category.id, ends_on: Time.now + 10.weeks, costs: 10.0 } } end it 'should authenticate and create a new contract' do expect do post :create, params: valid_attributes, session: { user_id: user.id } end.to change { Contract.count }.by(1) expect(response).to redirect_to(contracts_path) expect(flash[:notice]).to be_present end end context 'with invalid attributes' do let(:invalid_attributes) do { contract: { vendor_id: vendor.id, category_id: category.id, ends_on: Time.now + 10.weeks } } end it 'should not create a contract' do expect do post :create, params: invalid_attributes, session: { user_id: user.id } end.to change { Contract.count }.by(0) expect(response).to render_template(:new) end end end context 'as a guest' do it 'should not authenticate and redirect to signin path' do get :index expect(response).to redirect_to(signin_path) expect(assigns(:contracts)).to eq(nil) end end end describe '#update' do let(:user) { FactoryBot.create(:user) } let!(:user_contract) { FactoryBot.create(:contract, user: user, costs: 10) } let(:vendor) { FactoryBot.create(:vendor) } let(:category) { FactoryBot.create(:category) } context 'as an user' do context 'with valid attributes' do let(:valid_attributes) do { id: user_contract.id, contract: { costs: 100.0 } } end it 'should authenticate and update the contract' do post :update, params: valid_attributes, session: { user_id: user.id } expect(response).to redirect_to(contracts_path) expect(user_contract.reload.costs).to eq(100.0) expect(flash[:notice]).to be_present end end context 'with invalid attributes' do let(:invalid_attributes) do { id: user_contract.id, contract: { costs: 0 } } end it 'should not update the contract' do post :update, params: invalid_attributes, session: { user_id: user.id } expect(response).to render_template(:edit) expect(user_contract.reload.costs).to eq(10.0) end end end context 'as a guest' do it 'should not authenticate and redirect to signin path' do get :index expect(response).to redirect_to(signin_path) expect(assigns(:contracts)).to eq(nil) end end end end
class WelcomeController < ApplicationController def home @welcome_text = Page.try(:first).try(:content) end end
require 'vizier/executable_unit' module Vizier class TaskList def initialize(*task_lists) @tasks = [] task_lists.each do |list| list.each do |task| unless @tasks.include?(task) @tasks << task end end end end def executable? !@tasks.empty? end def executable(path, input_hash, subject) verify_subject(subject) parsed_hash = parse_hash(input_hash, subject) task_instances = @tasks.map do |task| task.new(path, parsed_hash, subject) end return ExecutableUnit.new(path, task_instances) end def undoable? @tasks.all? {|task| task.undoable?} end def subject_requirements @subject_requirements ||= begin @tasks.inject([]) do |list, task| list + task.subject_requirements end.uniq end end def subject_defaults @subject_defaults ||= begin @tasks.each_with_object({}) do |task, hash| hash.merge! task.subject_defaults end end end def argument_list @argument_list ||= begin list = [] @tasks.each do |task| task.argument_list.each do |argument| idx = list.find_index do |listed| listed.name == argument.name end if idx.nil? list << argument else list[idx] = list[idx].merge(argument) end end end list.sort end end def argument_names @argument_names ||= begin argument_list.inject([]) do |allowed, argument| allowed += [*argument.name] end end end def string_keys(hash) new_hash = {} hash.keys.each do |name| new_hash[name.to_s] = hash[name] end return new_hash end def parse_hash(input_hash, subject) wrong_values = {} missing_names = [] parsed_hash = {} input_hash = string_keys(input_hash) argument_list.each do |argument| begin #??? arguments need to be completely explicit about requirements now parsed_hash.merge! argument.consume_hash(subject, input_hash) rescue ArgumentInvalidException => aie wrong_values.merge! aie.pairs rescue OutOfArgumentsException missing_names += ([*argument.name].find_all {|name| not parsed_hash.has_key?(name)}) end end unless wrong_values.empty? raise ArgumentInvalidException.new(wrong_values) end unless missing_names.empty? raise OutOfArgumentsException, "Missing arguments: #{missing_names.join(", ")}" end return parsed_hash end def verify_subject(subject) return if subject_requirements.nil? subject_requirements.each do |requirement| begin if Subject::UndefinedField === subject.send(requirement) raise CommandException, "\"#{name}\" requires \"#{requirement.to_s}\" to be set" end rescue NameError => ne raise CommandException, "\"#{name}\" requires subject to include \"#{requirement.to_s}\"" end end end end end
class PetController < ApplicationController before_action :authorize, only: [:index, :show, :delete, :create, :edit, :new, :update, :destroy] def new @pet = Pet.new end def create @pet = Pet.new(pet_params) if @pet.save redirect_to controller: 'pet', action: 'index', dni: pet_params[:owner] else render 'new' end end def show @pet = Pet.find(params[:id]) end def index @pets = Pet.where(owner: params[:dni]) end def edit @pet = Pet.find(params[:id]) end def update @pet = Pet.find(params[:id]) if @pet.update(pet_params) redirect_to controller: 'pet', action: 'index', dni: pet_params[:owner] else render 'edit' end end def destroy @pet = Pet.find(params[:id]) @pet.destroy redirect_to action: 'index', dni: params[:dni] end private def pet_params params.require(:pet).permit(:name, :age, :owner, :alive, :sex, :animal_type, :picture) end end
describe "merb-cache-page" do it "should cache page (action5)" do c = get("/cache_controller/action5") c.body.strip.should == "test action5" c.cached_page?("action5").should be_true end it "should expire page (action5)" do CACHE.expire_page("action5") CACHE.cached_page?("action5").should be_false end it "should cache page (action5) with full path" do c = get("/cache_controller/action5/this/is/a/test") c.cached_page?(:action => "action5", :params => %w(this is a test)).should be_true end it "should expire page (action5) with full path" do CACHE.expire_page(:action => "action5", :controller => "cache_controller", :params => %w(this is a test)) CACHE.cached_page?(:key => "/cache_controller/action5/this/is/a/test").should be_false end it "should cache page (action6), use it and expire 3 seconds after" do CACHE.expire_page :match => true, :action => "action6" c = get("/cache_controller/action6") now = Time.now.to_s c.body.strip.should == now c.cached_page?("action6").should be_true sleep 1 c = get("/cache_controller/action6") c.body.strip.should == now sleep 2 c = get("/cache_controller/action6") c.body.strip.should == Time.now.to_s end it "should cache page with full path (action6) and expire in 3 seconds" do CACHE.expire_page "action6" CACHE.cached_page?(:action => "action6", :params => %w(path to nowhere)).should be_false c = get("/cache_controller/action6/path/to/nowhere/") now = Time.now.to_s c.body.strip.should == now c.cached_page?(:action => "action6", :params => %w(path to nowhere)).should be_true sleep 1 c = get("/cache_controller/action6/path/to/nowhere") c.body.strip.should == now sleep 2 c = get("/cache_controller/action6/path/to/nowhere") c.body.strip.should == Time.now.to_s end it "should expire page in many ways" do c = get("/cache_controller/action6") CACHE.expire_page("action6") CACHE.cached_page?("action6").should be_false c = get("/cache_controller/action6") CACHE.expire_page(:match => "/cache_control") CACHE.cached_page?(:action => "action6").should be_false c = get("/cache_controller/action6") CACHE.expire_page(:action => "action6") CACHE.cached_page?(:action => "action6").should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:action => "action6", :params => %w(id1 id2)) CACHE.cached_page?(:action => "action6", :params => %w(id1 id2)).should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:action => "action6", :match => true) CACHE.cached_page?(:action => "action6", :params => %w(id1 id2)).should be_false c = get("/cache_controller/action6") CACHE.expire_page(:action => "action6", :controller => "cache_controller") CACHE.cached_page?(:action => "action6", :controller => "cache_controller").should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:action => "action6", :params => %w(id1), :match => true) CACHE.cached_page?(:action => "action6", :params => %w(id1 id2)).should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:action => "action6", :controller => "cache_controller", :match => true) CACHE.cached_page?(:action => "action6", :params => %w(id1 id2)).should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:action => "action6", :controller => "cache_controller", :params => %w(id1), :match => true) CACHE.cached_page?(:action => "action6", :params => %w(id1 id2)).should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:action => "action6", :controller => "cache_controller", :params => %w(id1 id2)) CACHE.cached_page?(:action => "action6", :controller => "cache_controller", :params => %w(id1 id2)).should be_false c = get("/cache_controller/action6") CACHE.expire_page(:key => "/cache_controller/action6") CACHE.cached_page?(:key => "/cache_controller/action6").should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:key => "/cache_controller/action6", :params => %w(id1 id2)) CACHE.cached_page?(:key => "/cache_controller/action6", :params => %w(id1 id2)).should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:key => "/cache_controller/action6/id1", :match => true) CACHE.cached_page?(:key => "/cache_controller/action6/id1/id2").should be_false c = get("/cache_controller/action6/id1/id2") CACHE.expire_page(:key => "/cache_controller/action6", :params => %w(id1), :match => true) CACHE.cached_page?(:key => "/cache_controller/action6/id1/id2").should be_false end it "should expire all pages" do CACHE.expire_all_pages CACHE.cached_page?("action6").should be_false Dir.glob(Merb::Controller._cache.config[:cache_html_directory] + '/*').should be_empty end end
class GPXstatsmodel attr_accessor :distance attr_accessor :duration_s attr_accessor :speed_avg attr_accessor :elevation_diff attr_accessor :hr_max attr_accessor :hr_avg def initialize(distance, duration_s, speed_avg, speed_max, elevation_max, elevation_min, ele_diff, hr_min, hr_max, hr_avg) @distance = distance @duration_s = duration_s @speed_avg = speed_avg @speed_max = speed_max @elevation_max = elevation_max @elevation_min = elevation_min @elevation_diff = ele_diff @hr_min = hr_min @hr_max = hr_max @hr_avg = hr_avg end end
# Usage: rake givdo:assign_orgs # NOTE: Will assign first organization to all Users and Players. namespace :givdo do desc "Assign organizations to users" task :assign_orgs => :environment do User.where(organization_id: nil).update_all(organization_id: Organization.first.id) Player.where(organization_id: nil).update_all(organization_id: Organization.first.id) end end
require 'colorize' class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @sequence_length = 1 @game_over = false @seq = [] end def play system("clear") puts "Hello and, again, welcome to the App Academy computer-aided enrichment center." system("say Hello and, again, welcome to the App Academy computer-aided enrichment center.") puts "Your specimen has been processed and we are now ready to begin the test proper." system("say Your specimen has been processed and we are now ready to begin the test proper.") puts "Before we start, however, keep in mind that although fun and learning are the primary goals of all enrichment center activities, serious injuries may occur." system("say Before we start, however, keep in mind that although fun and learning are the primary goals of all enrichment center activities, serious injuries may occur.") sleep(1.5) system("clear") puts "We are committed to the well being of all participants. Cake and grief counseling will be available at the conclusion of the test. Thank you for helping us help you help us all." system("say We are committed to the well being of all participants. Cake and grief counseling will be available at the conclusion of the test. Thank you for helping us help you help us all.") sleep(1.5) system("clear") puts "Stand back. The game will begin in three" system("say Stand back. The game will begin in three") sleep(1) puts "two" system("say two") sleep(1) puts "one" system("say one") sleep(1) system("clear") until game_over take_turn end game_over_message reset_game end def take_turn show_sequence require_sequence unless @game_over round_success_message @sequence_length += 1 end end def show_sequence add_random_color system("clear") if @sequence_length < 7 puts "Here is your next test case" system("say Here is your next test case") else puts "The Enrichment Center regrets to inform you that this next test is impossible." system("say The Enrichment Center regrets to inform you that this next test is impossible.") puts "Make no attempt to solve it." system("say Make no attempt to solve it.") puts "Quit now and cake will be served immediately." system("say Quit now and cake will be served immediately.") puts "No one will blame you for giving up. In fact, quitting at this point is a perfectly reasonable response." system("say No one will blame you for giving up. In fact, quitting at this point is a perfectly reasonable response.") end @seq.each do |color| system("clear") puts "#{color}".colorize(color.to_sym) system("say #{color}") sleep(1) end system("clear") end def require_sequence puts "Enter the first letter of the colors you saw in order with no spaces" puts "For example: rgb" system("say Enter the first letter of the colors you saw in order with no spaces") input = gets.chomp.split('') if input.length != @seq.length @game_over = true return end input.each_index do |idx| @game_over = true if input[idx] != @seq[idx][0] end end def add_random_color @seq << COLORS.sample end def round_success_message system("clear") case @sequence_length when 1 puts "Good job! You can remember a color." system("say Good job! You can remember a color.") when 2 puts "Excellent. Please proceed into the next test." system("say Excellent. Please proceed into the next test.") when 3 puts "You are doing very well!" system("say You are doing very well!") when 4 puts "Well done! Remember, App Academy Bring Your Daughter to Work Day is the perfect time to have her tested." system("say Well done! Remember, App Academy Bring Your Daughter to Work Day is the perfect time to have her tested.") when 5 puts "Unbelievable! You, [Subject Name] Here, must be the pride of [Subject Hometown] Here." system("say Unbelievable! You, [Subject Name] Here, must be the pride of [Subject Hometown] Here.") puts "Let's move on to the next round" system("say Lets move on to the next round") when 6 puts "Once again, excellent work." system("say Once again, excellent work.") when 7..100 puts "Fantastic! You remained resolute and resourceful in an atmosphere of extreme pessimism." system("say Fantastic! You remained resolute and resourceful in an atmosphere of extreme pessimism.") end end def game_over_message system("clear") case @sequence_length when 1..3 puts "The Player has been eliminated due to lack of intelligence." system("say The Player has been eliminated due to lack of intelligence.") when 4..6 puts "Perhaps you can try again later, after you upgrade your brain." system("say Perhaps you can try again later, after you upgrade your brain.") when 7..100 puts "You have made this far..." system("say You have made this far...") puts "It's quite impressive for your specimen" system("say Its quite impressive for your specimen") puts "But cake is only given to winners" system("say But cake is only given to winners") end puts "Goodbye" system("say Goodbye") end def reset_game @sequence_length = 1 @game_over = false @seq = [] end end if __FILE__ == $PROGRAM_NAME s = Simon.new s.play end
class MEncrypt < ActiveRecord::Base self.table_name = "m_encrypts" self.primary_key = :encrypt_id # encrypt_id, encryption_type, file_name, created_by, updated_by, # created_at, updated_at, username, hashed_key, :encrypted_key validates_uniqueness_of :encrypt_id validates_presence_of :encrypt_id, :encryption_type, :file_name, :created_by, :updated_by, :created_at, :updated_at, :username, :hashed_keys, :encrypted_keys validates_numericality_of :encryption_type # validates_inclusion_of :is_keep_file, :is_custom_key, :in => after_initialize :sm_default_value def sm_default_value self.is_keep_file ||= false self.is_custom_key ||= false end end
# for order controller class OrdersController < ApplicationController before_action :set_order, only: [:show, :edit, :update, :destroy, :purchase] # GET /orders # GET /orders.json def index @q = Order.order(id: :desc).search(params[:q]) @orders = @q.result.includes(:user).page(params[:page]).per(20) end # GET /orders/1 # GET /orders/1.json def show end # GET /orders/new def new @order = Order.new end # GET /orders/1/edit def edit end # POST /orders # POST /orders.json def create @order = Order.new(order_params) @order.order_time = Time.zone.now @order.user = current_user respond_to do |format| validation_context = params[:ignore_title_unique_validation] == false.to_s ? :check_title_unique : nil if @order.save(context: validation_context) format.html { redirect_to @order, notice: 'Order was successfully created.' } format.json { render :show, status: :created, location: @order } else format.html { render :new } format.json { render json: @order.errors, status: :unprocessable_entity } end end end # PATCH/PUT /orders/1 # PATCH/PUT /orders/1.json def update respond_to do |format| if @order.update(order_params) format.html { redirect_to @order, notice: 'Order was successfully updated.' } format.json { render :show, status: :ok, location: @order } else format.html { render :edit } format.json { render json: @order.errors, status: :unprocessable_entity } end end end # DELETE /orders/1 # DELETE /orders/1.json def destroy @order.destroy respond_to do |format| format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' } format.json { head :no_content } end end def extract_amazon_product_info @order = Order.new(order_params) @order.extract_amazon_product_info! end def purchase if @order.purchase redirect_to books_path, notice: 'Order was successfully purchased.' else redirect_to orders_path, alert: 'Error!! Order was not purchased.' end end private # Use callbacks to share common setup or constraints between actions. def set_order @order = Order.find(params[:id]) end def order_params params.require(:order).permit(:title, :order_time, :state, :url, :origin_html, :image_path) end end
# encoding: utf-8 control "V-52273" do title "The DBMS must support organizational requirements to prohibit password reuse for the organization-defined number of generations." desc "Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks. To meet password policy requirements, passwords need to be changed at specific policy-based intervals. If the information system or application allows the user to consecutively reuse their password when that password has exceeded its defined lifetime, the end result is a password that is not changed as per policy requirements. Password reuse restrictions protect against bypass of password expiration requirements and help protect accounts from password guessing attempts. Note that user authentication and account management must be done via an enterprise-wide mechanism whenever possible. Examples of enterprise-level authentication/access mechanisms include, but are not limited to, Active Directory and LDAP This requirement applies to cases where it is necessary to have accounts directly managed by Oracle.false" impact 0.5 tag "check": "If all user accounts are authenticated by the OS or an enterprise-level authentication/access mechanism, and not by Oracle, this is not a finding. For each profile that can be applied to accounts where authentication is under Oracle's control, determine the password reuse rule, if any, that is in effect: SELECT * FROM SYS.DBA_PROFILES WHERE RESOURCE_NAME IN ('PASSWORD_REUSE_MAX', 'PASSWORD_REUSE_TIME') [AND PROFILE NOT IN (<list of non-applicable profiles>)] ORDER BY PROFILE, RESOURCE_NAME; Bearing in mind that a profile can inherit from another profile, and the root profile is called DEFAULT, determine the value of the PASSWORD_REUSE_MAX effective for each profile. If, for any profile, the PASSWORD_REUSE_MAX value does not enforce the DoD-defined minimum number of password changes before a password may be repeated (5 or greater), this is a finding. PASSWORD_REUSE_MAX is effective if and only if PASSWORD_REUSE_TIME is specified, so if both are UNLIMITED, this is a finding." tag "fix": "If all user accounts are authenticated by the OS or an enterprise-level authentication/access mechanism, and not by Oracle, no fix to the DBMS is required. If any user accounts are managed by Oracle: For each profile, set the PASSWORD_REUSE_MAX to enforce the DoD-defined minimum number of password changes before a password may be repeated (5 or greater). PASSWORD_REUSE_MAX is effective if and only if PASSWORD_REUSE_TIME is specified, so ensure also that it has a meaningful value. Since the minimum password lifetime is 1 day, the smallest meaningful value is the same as the PASSWORD_REUSE_MAX value. Using PPPPPP as an example, the statement to do this is: ALTER PROFILE PPPPPP LIMIT PASSWORD_REUSE_MAX 5 PASSWORD_REUSE_TIME 5;" # Write Check Logic Here end
class InventorySnapshotSerializer < ActiveModel::Serializer self.root = false attributes :user_attributes, :has_active_subscription, :last_subscription_expiry, :purchases has_many :items def purchases object.attributes['in_app_purchases'] || 0 end def has_active_subscription object.subscription_expires_at.present? && object.subscription_expires_at > Time.now.utc end def last_subscription_expiry object.subscription_expires_at end end
class EricWeixin::Cms::Weixin::MediaNewsController < EricWeixin::Cms::BaseController def index end def new end def query_media_articles @media_articles = ::EricWeixin::MediaArticle.common_query params.permit(:tag, :start_date, :end_date, :public_account_id) @total_page = (@media_articles.count/4) + 1 page = params[:page] || 1 @media_articles = @media_articles.paginate(per_page: 4, page: page) @current_page = page.to_i render partial: 'select_article' end def query_weixin_users begin BusinessException.raise '请指定微信公众号。' if params[:public_account_id].blank? options = {} options[:weixin_public_account_id] = params[:public_account_id] options[:nickname] = params[:nickname] @weixin_users = ::EricWeixin::WeixinUser.where(weixin_public_account_id: params[:public_account_id]) @weixin_users = @weixin_users.where("nickname like ?", "%#{params[:nickname]}%") unless params[:nickname].blank? render partial: 'select_user' rescue Exception=>e dispose_exception e render text: "查询失败:#{get_notice_str}" return end end def will_send_articles articles = [] ids_msg = [] unless params[:existed_article_ids].blank? e_ids = params[:existed_article_ids].split(',') e_ids.each do |id| ma = ::EricWeixin::MediaArticle.find_by_id(id) articles << ma ids_msg << ma.id end end if params[:new_article_id].blank? # 处理调整顺序 unless params[:up_article_id].blank? index = ids_msg.index(params[:up_article_id].to_i) if index==0 render text: 'top' return else tmp_article = articles[index] articles[index] = articles[index-1] articles[index-1] = tmp_article tmp_id = ids_msg[index] ids_msg[index] = ids_msg[index-1] ids_msg[index-1] = tmp_id end else unless params[:down_article_id].blank? index = ids_msg.index(params[:down_article_id].to_i) if index==ids_msg.size-1 render text: 'bottom' return else tmp_article = articles[index] articles[index] = articles[index+1] articles[index+1] = tmp_article tmp_id = ids_msg[index] ids_msg[index] = ids_msg[index+1] ids_msg[index+1] = tmp_id end end end else # 处理新增文章 if ids_msg.include? params[:new_article_id].to_i # 文章已经存在 render text: 'existed' return else nma = ::EricWeixin::MediaArticle.find_by_id(params[:new_article_id]) articles << nma ids_msg << nma.id end end @will_send_articles = articles @will_send_article_msg = ids_msg.join(",") render partial: 'will_send_article' end def save_news # will_send_article_msg: will_send_article_msg, # user_group_name: user_group_name, # send_at_fixed_time: send_at_fixed_time, # send_fixed_date: send_fixed_date, # send_fixed_time: send_fixed_time, # send_save_to_history: send_save_to_history # public_account_id begin if params[:media_news_id].blank? media_news = ::EricWeixin::MediaNews.save_news params.permit(:will_send_article_msg,:user_group_name, :send_at_fixed_time,:send_fixed_date, :send_fixed_time,:send_save_to_history,:public_account_id) render text: "#{media_news.id}" return else media_news = ::EricWeixin::MediaNews.find_by_id(params[:media_news_id]) media_news.update_news params.permit(:will_send_article_msg,:user_group_name, :send_at_fixed_time,:send_fixed_date, :send_fixed_time,:send_save_to_history,:public_account_id) render text: "#{media_news.id}" end rescue Exception=>e dispose_exception e render text: "保存失败: #{get_notice_str}" end end def preview begin if params[:media_news_id].blank? media_news = ::EricWeixin::MediaNews.save_news params.permit(:will_send_article_msg,:user_group_name, :send_at_fixed_time,:send_fixed_date, :send_fixed_time,:send_save_to_history,:public_account_id) media_news.preview params.permit(:preview_openid)[:preview_openid] render text: "#{media_news.id}" return else media_news = ::EricWeixin::MediaNews.find_by_id(params.permit(:media_news_id)[:media_news_id]) media_news.update_news params.permit(:will_send_article_msg,:user_group_name, :send_at_fixed_time,:send_fixed_date, :send_fixed_time,:send_save_to_history,:public_account_id) media_news.preview params.permit(:preview_openid)[:preview_openid] render text: "#{media_news.id}" end rescue Exception=>e dispose_exception e render text: "保存失败||预览失败:#{get_notice_str}" end end def send_news_now begin if params[:media_news_id].blank? media_news = ::EricWeixin::MediaNews.save_news params.permit(:will_send_article_msg,:user_group_name, :send_at_fixed_time,:send_fixed_date, :send_fixed_time,:send_save_to_history,:public_account_id) media_news.send_to_openids render text: "#{media_news.id}" return else media_news = ::EricWeixin::MediaNews.find_by_id(params[:media_news_id]) media_news.update_news params.permit(:will_send_article_msg,:user_group_name, :send_at_fixed_time,:send_fixed_date, :send_fixed_time,:send_save_to_history,:public_account_id) media_news.send_to_openids render text: "#{media_news.id}" end rescue Exception=>e dispose_exception e render text: "保存失败||立即发送失败:#{get_notice_str}" end end end
class Day < ApplicationRecord has_many :daily_habits has_many :habits, through: :daily_habits end
class Product < ActiveRecord::Base validates:description, presence:true validates:deadline, presence:true validates:user_id, presence:true belongs_to :user has_many :bids end
class TuftsImageText < TuftsBase has_file_datastream 'Content.html', control_group: 'E' has_file_datastream 'Thumbnail.png', control_group: 'E' has_file_datastream 'Archival.tif', control_group: 'E' has_file_datastream 'Advanced.jpg', control_group: 'E' has_file_datastream 'Basic.jpg', control_group: 'E' def self.to_class_uri 'info:fedora/cm:Object.Generic' end end
class AddFavouriteToOrigami < ActiveRecord::Migration[5.1] def change add_column :origamis, :favourite, :boolean, default: false end end
# begin to build a simple program that models Instagram # you should have a User class, a Photo class and a comment class require "pry" class User attr_accessor :name, :photo, :comments @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def photos Photo.all.select {|photo| photo.user == self} end end class Photo attr_accessor :user, :comments, :photo @@all = [] def initialize @@all << self end def self.all @@all end def comments Comment.all.select { |comment| comment.photo == self} end def make_comment(text) Comment.new(text, self) end def self.comments @@comments end end class Comment attr_accessor :user, :photo, :comments @@all = [] def initialize(comment, photo) @comment = comment @photo = photo @@all << self end def self.all @@all end end sandwich_photo = Photo.new # DONE sophie = User.new("Sophie") # DONE sandwich_photo.user = sophie # DONE sandwich_photo.user.name #DONE # => "Sophie" sophie.photos # DONE # => [#<Photo:0x00007fae2880b370>] sandwich_photo.comments#DONE # => [] sandwich_photo.make_comment("this is such a beautiful photo of your lunch!! I love photos of other people's lunch") sandwich_photo.comments # => [#<Comment:0x00007fae28043700>] Comment.all #=> [#<Comment:0x00007fae28043700>] binding.pry
class User < ActiveRecord::Base INDUSTRIES = ['General', 'Accounting/Bookkeeping/Tax Prep', 'Advertising/Marketing/PR', 'Architecture/Interior Design', 'Automotive', 'Business/Trade/Networking Organization', 'Banking/Finance', 'Business Consulting', 'Construction/Contracting', 'Design/Creative Services', 'Education', 'Engineering', 'Environmental Services', 'Fashion/Apparel', 'Food Services', 'Government', 'Healthcare', 'HR/Benefits/Payroll/Staffing', 'Insurance', 'IT Services/Products', 'Janitorial', 'Law Practice/Legal', 'Services', 'Manufacturing', 'Media', 'Not-For-Profit', 'Office Supplies/Equipment', 'Other', 'Plastics', 'Printing', 'Publishing', 'Real Estate', 'Recreation/Entertainment', 'Recycling', 'Restaurant', 'Retail', 'Security Services', 'Shipping/Warehousing', 'Telecommunications', 'Transportation', 'Travel/Hospitality/Tourism', 'Web Design/Online Marketing'] belongs_to :place belongs_to :event has_attached_file :photo, :storage => :s3, :s3_credentials => "#{Rails.root.to_s}/config/s3.yml", :path => "/userphoto/:style/:filename", :default_url => "http://tap.heroku.com/api/images/profile.png", :styles => { :thumbnail_small => ["45x45", :png], :thumbnail_large => ["100x100", :png]} # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, :lockable and :timeoutable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates :username, :uniqueness => true, :on => :create validates_format_of :password, :with =>/(?=.*\d)/, :message => "Your password must include at least one number", :on => :create validates_format_of :password, :with =>/(?=.*[a-zA-Z])/, :message => "Your password must include at least one letter", :on => :create validates_presence_of :terms, :message => "You must accept the terms and conditions", :on => :create def groups_array if groups return groups.split(/,/).each {|a| a.strip!}.reject(&:blank?) else return [] end end def industries_interested industries = [] if industry_interested_1 industries << industry_interested_1 end if industry_interested_2 industries << industry_interested_2 end if industry_interested_3 industries << industry_interested_3 end industries end def industries_interested_names names = [] if industry_interested_1 names << User::INDUSTRIES[industry_interested_1.to_i] end if industry_interested_2 names << User::INDUSTRIES[industry_interested_2.to_i] end if industry_interested_3 names << User::INDUSTRIES[industry_interested_3.to_i] end names end def industry_name if industry User::INDUSTRIES[industry.to_i] end end def interests_array if interests return interests.split(/,/).each {|a| a.strip!}.reject(&:blank?) else return [] end end def match(matching_user) @match = [] if self != matching_user match_buy(matching_user) match_sell(matching_user) match_like(matching_user) end @match end def first_match_reason @match.first end def match_reasons @match end def matches @match.size > 0 end def name "#{first_name} #{last_name}" end private def match_groups(matching_user) shared_groups = groups_array & matching_user.groups_array if shared_groups.length shared_groups.each{ |groups| @match << "You have an association in common (#{groups})" } end end def match_buy(matching_user) if matching_user.industry != nil and industries_interested.find matching_user.industry @match << "They are interested in your industry: #{matching_user.industry_name}" end end def match_hometown(matching_user) if hometown_city != nil and hometown_state != nil and hometown_city == matching_user.hometown_city and hometown_state == matching_user.hometown_state @match << "You share the same home town (#{hometown_city}, #{hometown_state})" end end def match_interests(matching_user) shared_interests = interests_array & matching_user.interests_array if shared_interests.length shared_interests.each{ |interest| @match << "You have an interest in common (#{interest})" } end end def match_like(matching_user) match_hometown(matching_user) match_school(matching_user) match_major(matching_user) match_interests(matching_user) match_groups(matching_user) end def match_major(matching_user) if major != nil and major == matching_user.major @match << "You had the same major (#{major})" end end def match_school(matching_user) if school != nil and school == matching_user.school @match << "You went to the same school (#{school})" end end def match_sell(matching_user) if industry != nil and matching_user.industries_interested.find industry @match << "You are interested in their industry: #{industry_name}" end end def photo_url self.photo.url end def as_json(options={}) super(:methods => [:photo_url]) end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe OrdersController, type: :controller do describe 'GET /orders' do let(:response_api) { { 'list' => { 'orders' => 'orders' } } } before do allow_any_instance_of(Pitzi::Orders).to receive(:list).and_return(response_api) end it 'returns orders' do get :index expect(response).to have_http_status(:ok) end end describe 'GET /orders/new' do it 'return status 200 - :ok' do get :new expect(response).to have_http_status(:ok) end end describe 'POST /orders' do context 'with valid params' do let(:order_params) do { order: { imei: 448_674_528_976_410, annual_price: 1000, device_model: 'Iphone', installments: 4, user: { name: 'Name', cpf: '329.726.820-41', email: 'tes@tes.com' } } } end let(:response_api) { { 'order' => { 'id' => 'id' } } } before do allow_any_instance_of(Pitzi::Orders).to receive(:create).and_return(response_api) end it 'returns order' do post :create, params: order_params expect(response).to redirect_to '/orders' end end context 'with invalid params' do let(:order) { build(:order) } let(:order_params) do { order: { imei: order.imei, user: { name: 'Name' } } } end let(:response_api) { { 'errors' => { 'order' => 'error' } } } before do allow_any_instance_of(Pitzi::Orders).to receive(:create).and_return(response_api) end it 'returns order' do post :create, params: order_params expect(response).to redirect_to '/orders/new' end end end describe 'DELETE /orders/:id' do let(:response_api) { 1 } let(:order_params) { { id: '1' } } before do allow_any_instance_of(Pitzi::Orders).to receive(:destroy).and_return(response_api) end it 'returns order destroy' do delete :destroy, params: order_params expect(response).to redirect_to '/orders' end end end
require 'rails_helper' RSpec.describe Request, type: :model do before { @request = FactoryGirl.build :request } subject { @request } it { should be_valid } @request_attributes = [:fullname, :phonenumber, :email, :company, :job_title, :contacted, :accepted_offer] # model should respond to attributes @request_attributes.each do |attribute| it { should respond_to attribute } end # test presence of attributes [:fullname, :phonenumber, :email, :company, :job_title].each do |attribute| it { should validate_presence_of attribute } end # validate uniqueness of email it { should validate_uniqueness_of(:email).case_insensitive } describe "test number format of phonenumber" do context "when phonenumber is set to string containing string" do before { @request.phonenumber = "some string" } it "@request should be invalid" do expect(@request).not_to be_valid end end context "when phonenumber is set to string containing numbers" do before { @request.phonenumber = "0204704427" } it "@request should be valid" do expect(@request).to be_valid end end end # instance methods describe "test instance methods" do before { @request.save } it "should return true for contact" do @request.contact expect(@request.contacted).to eq true end it "should return false for no_contact" do @request.no_contact expect(@request.contacted).to eq false end it "should return true for accept_offer" do @request.accept_offer expect(@request.accepted_offer).to eq true end it "should return false for reject_offer" do @request.reject_offer expect(@request.accepted_offer).to eq false end end end
class SubjectsController < ApplicationController load_resource def index @subjects = Subject.all respond_to do |format| format.html format.js end end def show @subject = Subject.find(params[:id]) end def new @subject = Subject.new respond_to do |format| format.js # required or the controller will not respond to AJAX calls end end def create @subject = Subject.new(params[:subject]) @subject[:user_id] = current_user.id respond_to do |format| if @subject.save format.js { redirect_to :action => 'index' } else format.js { render :action => 'new' } end end end def edit @subject = Subject.find(params[:id]) respond_to do |format| format.js # required or the controller will not respond to AJAX calls end end def update @subject = Subject.find(params[:id]) respond_to do |format| if @subject.update_attributes(params[:subject]) format.html { redirect_to @subject, notice: 'Post was successfully updated.' } format.js {redirect_to :action => 'index'} else format.js { render :action => 'edit' } end end end def destroy respond_to do |format| if Subject.find(params[:id]).destroy format.js { redirect_to :action => 'index' } end end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_secure_token :auth_token has_many :orders has_many :purchased_records, -> { purchased }, class_name: :Order has_many :purchased_courses, -> { distinct }, through: :purchased_records, source: :course has_many :available_records, -> { not_expired }, class_name: :Order has_many :available_courses, -> { distinct }, through: :available_records, source: :course enum role: { member: 0, admin: 1 } def renew_token! regenerate_auth_token auth_token end end
module Codegrade class Formatter def initialize(offenses) @offenses = offenses end def print group_by_files working_directory = File.expand_path('.') @categories.each do |category, offenses| puts "#{category} (#{offenses.size}):" puts offenses.each do |offense| puts "- #{offense.line_number}:#{offense.column_number} #{offense.category}" end puts end end private def group_by_files @categories = Hash.new @offenses.each do |offense| @categories[offense.file] ||= [] @categories[offense.file].push(offense) end end end end
require 'rails_helper' feature 'User tries to login with steam' do before do # Disable news feed Rails.configuration.news['type'] = 'none' end scenario 'for the first time' do visit teams_path OmniAuth.mock_auth_hash(name: 'Kenneth') find('#login').click expect(current_url).to eq(new_user_url(name: 'Kenneth')) end scenario 'when already registered' do user = create(:user) visit teams_path OmniAuth.mock_auth_hash(name: user.name, steam_id: user.steam_id) find('#login').click expect(current_path).to eq('/') end scenario 'when login fails' do visit teams_path OmniAuth.mock_auth_fail find('#login').click expect(current_path).to eq(teams_path) end end
json.array!(@organizations) do |organization| json.extract! organization, :id, :name, :email, :slogan, :mission, :vision, :phone, :status json.url organization_url(organization, format: :json) end
FactoryGirl.define do factory :customer do first_name { Faker::Name.first_name } last_name { Faker::Name.last_name } created_at { Faker::Time.between(DateTime.now - 5, DateTime.now - 2) } updated_at { Faker::Time.between(DateTime.now - 2, DateTime.now) } end factory :item do name { Faker::Commerce.product_name } description { Faker::Hipster.sentence(3) } unit_price { Faker::Number.number(6) } created_at { Faker::Time.between(DateTime.now - 5, DateTime.now - 2) } updated_at { Faker::Time.between(DateTime.now - 2, DateTime.now) } merchant end factory :invoice_item do quantity { Faker::Number.between(1,10) } unit_price { Faker::Number.number(6) } created_at { Faker::Time.between(DateTime.now - 5, DateTime.now - 2) } updated_at { Faker::Time.between(DateTime.now - 2, DateTime.now) } item invoice end factory :invoice do created_at { Faker::Time.between(DateTime.now - 5, DateTime.now - 2) } updated_at { Faker::Time.between(DateTime.now - 2, DateTime.now) } status { "Shipped" } customer merchant { create(:merchant_with_items) } end factory :merchant do name { Faker::Company.name } created_at { Faker::Time.between(DateTime.now - 5, DateTime.now - 2) } updated_at { Faker::Time.between(DateTime.now - 2, DateTime.now) } factory :merchant_with_items do transient do items_count 5 end after(:create) do |merchant, evaluator| create_list(:item, evaluator.items_count, merchant: merchant) end end factory :transaction do credit_card_number { Faker::Business.credit_card_number } result { ["success","failed"] } created_at { Faker::Time.between(DateTime.now - 5, DateTime.now - 2) } updated_at { Faker::Time.between(DateTime.now - 2, DateTime.now) } invoice { create(:invoice) } end end end
Write a method that takes two Array arguments in which each Array contains a list of numbers, and returns a new Array that contains the product of each pair of numbers from the arguments that have the same index. You may assume that the arguments contain the same number of elements. Examples: multiply_list([3, 5, 7], [9, 10, 11]) == [27, 50, 77] Question: Write a method that takes two array arguments containing two lists of numbers and returns a new array that contains the product of each pair of numbers that have the same index. Input vs Output: Input: 2 arrays Output: new array Explicit vs Implicit Rules: Explicit: 1) We are returning a new array 2) We are multiplying pairs of numbers within the two input arrays Implicit: 1) arguments contain the same number of elements Algorithm: multiply_lists method with inputs arr1 and arr2 1) initialize variable 'result' and set it to empty array 2) set variable 'idx1' to integer value 0 3) set variable 'idx2' to integer value 0 4) loop do a. product = arr1[idx1] * arr2[idx2] b. result << product c. idx1 += 1 d. idx2 += 1 e. break idx1 == (arr1.size - 1) || idx == (arr2.size - 1) end 5) return result def multiply_lists(arr1, arr2) result = [] idx1 = 0 idx2 = 0 loop do product = arr1[idx1] * arr2[idx2] result << product idx1 += 1 idx2 += 1 break if idx1 == (arr1.size) || idx2 == (arr2.size) end result end faster method: def multiply_list(arr1, arr2) products = [] arr1.size.times do |index| products << (arr1[index] * arr2[index]) end products end fastest method: def multiply_list(arr1, arr2) arr1.zip(arr2).map { |x, y| x * y } end
require 'net/http' require 'json' # Using URI and Net:HTTP which are already included with Rails uri = URI('https://urlxray.expeditedaddons.com') # Change the input parameters here uri.query = URI.encode_www_form({ api_key: 'DG3R6H4UL3E9JSY72XP0KC891ZWB16057T84NIOVFAMQ25', url: 'http://www.forexarena.com', fetch_content: false }) # Results are returned as a JSON object result = JSON.parse(Net::HTTP.get_response(uri).body) # For reference, here are all the outputs # Is this a valid well-formed URL result['valid'] # Is this URL actually serving real content result['real'] # True if this URL responded with an HTTP OK (200) status result['http_ok'] # The HTTP status code this URL responded with result['http_status'] # The HTTP status message assoicated with the status code result['http_status_message'] # True if this URL responded with a HTTP redirect result['http_redirect'] # The fully qualified URL. This may be different to the URL requested if http-redirect is True result['url'] # The URL protocol (usually http or https) result['url_protocol'] # The URL port result['url_port'] # The URL path result['url_path'] # A key:value map of the URL query paramaters result['query'] # The actual content this URL responded with. This is only set if the 'fetch-content' parameter was set result['content'] # The size of the URL content in bytes result['content_size'] # The content-type the URL points to result['content_type'] # The encoding type the URL uses result['content_encoding'] # The time taken to load the URL content (in seconds) result['load_time'] # The IP address of the server hosting this URL result['server_ip'] # The name of the server software hosting this URL result['server_name'] # Server IP geo-location: full country name result['server_country'] # Server IP geo-location: ISO 2-letter country code result['server_country_code'] # Server IP geo-location: full city name (if detectable) result['server_city'] # Server IP geo-location: full region name (if detectable) result['server_region'] # The server hostname (PTR) result['server_hostname'] Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Attempt to read encrypted secrets from `config/secrets.yml.enc`. # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or # `config/secrets.yml.key`. config.read_encrypted_secrets = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "forex_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
require_relative 'piece' require_relative 'stepping' class Rook < Piece include Sliding def initialize super @first_move = true end def to_s if color == :white " ♟ " else " ♙ " end end def specific_moves new_moves = [] if color == :white if @first_move else end else if @first_move else end end # 8.times do |multiplier| # new_moves += xy_moves.map {|x,y| [x * (multiplier + 1), y * (multiplier + 1)] } # end moves(new_moves) end # def moves # moves = [] # # xy_moves = [[0,-1],[0,1],[1,0],[-1,0]] # potential_moves = xy_moves.map do |x,y| # [x + @pos[0], y + @pos[1]] # end # potential_moves.each {|move| moves << move if in_bounds?(move)} # moves # end end
# encoding: utf-8 class InstallationPurchasesController < ApplicationController before_filter :require_signin before_filter :require_employee before_filter :load_installation helper_method :has_show_right?, :has_create_right?, :has_update_right?, :has_log_right?, :need_approve?, :has_warehousing_right? def index @title = '安装物料' @installation_purchases = @installation.present? ? @installation.installation_purchases.order("need_date DESC, qty_in_stock DESC, id DESC").paginate(:per_page => 40, :page => params[:page]) : InstallationPurchase.where('created_at > ?', Time.now - 1000.day).order("need_date DESC, qty_in_stock DESC, id DESC").paginate(:per_page => 40, :page => params[:page]) end def new @title = '物料申请' @installation = Installation.find(params[:installation_id]) @installation_purchase = @installation.installation_purchases.new() if !has_create_right? redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=权限不足!") end end def create if has_create_right? @installation = Installation.find(params[:installation_id]) @installation_purchase = @installation.installation_purchases.new(params[:installation_purchase], :as => :role_new) @installation_purchase.input_by_id = session[:user_id] if @installation_purchase.save redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=申请已保存!") else flash.now[:error] = '数据错误,无法保存!' render 'new' end end end def edit @title = '修改物料申请' @installation = Installation.find(params[:installation_id]) @installation_purchase = @installation.installation_purchases.find(params[:id]) if !has_update_right? redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=权限不足!") end end def update if has_update_right? @installation = Installation.find(params[:installation_id]) @installation_purchase = @installation.installation_purchases.find(params[:id]) @installation_purchase.input_by_id = session[:user_id] if @installation_purchase.update_attributes(params[:installation_purchase], :as => :role_update) redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=申请已更改!") else flash.now[:error] = '数据错误,无法保存!' render 'edit' end end end def show @title = '物料申请内容' @installation = Installation.find(params[:installation_id]) @installation_purchase = @installation.installation_purchases.find(params[:id]) if !has_show_right? redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=权限不足!") end end def approve @installation = Installation.find(params[:installation_id]) @installation_purchase = @installation.installation_purchases.find(params[:id]) if need_approve?(@installation_purchase) if vp_eng? @installation_purchase.update_attributes(:approved_by_vp_eng => true, :approve_vp_eng_id => session[:user_id], :approve_date_vp_eng => Date.today, :as => :role_approve) elsif ceo? @installation_purchase.update_attributes(:approved_by_ceo => true, :approve_ceo_id => session[:user_id], :approve_date_ceo => Time.now, :as => :role_approve) end redirect_to installation_installation_purchase_path(@installation, @installation_purchase) else redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=权限不足!") end end def warehousing @installation_purchase = InstallationPurchase.find(params[:id]) @part = Part.new(params[:part], :as => :role_new) if has_warehousing_right? && !@installation_purchase.warehoused @part.name = @installation_purchase.part_name @part.spec = @installation_purchase.spec @part.in_qty = @installation_purchase.qty_in_stock @part.stock_qty = @installation_purchase.qty_in_stock @part.unit = @installation_purchase.unit @part.unit_price = @installation_purchase.unit_price @part.input_by_id = session[:user_id] @part.transaction do if @part.save && @installation_purchase.update_attribute(:warehoused, true) #update_attribute skips validation, will raise exception if a connection or remote service error. redirect_to installation_installation_purchase_path(@installation_purchase.installation, @installation_purchase), :notice => "物料已入库!" else redirect_to installation_installation_purchase_path(@installation_purchase.installation, @installation_purchase), :notice => "数据错误,无法入库!" end end end end protected def need_approve?(inst_pur) if vp_eng? && !inst_pur.approved_by_ceo return true elsif ceo? && inst_pur.approved_by_vp_eng return true end return false end def has_show_right? is_eng? || acct? || comp_sec? || vp_eng? || vp_sales? || coo? || ceo? end def has_create_right? inst_eng? || vp_eng? end def has_update_right? vp_eng? || ceo? end def has_log_right? inst_eng? || vp_eng? || comp_sec? || coo? || ceo? end def has_warehousing_right? pur_eng? || vp_eng? || ceo? end def load_installation @installation = Installation.find(params[:installation_id]) if params[:installation_id].present? end end
#!/usr/bin/env ruby require 'digest' require 'thor' require 'fuzzy_match' require 'launchy' require 'coursesdesc' # for production # require '../lib/coursesdesc/courses.rb' # for cmd line testing purposes class KiwiCLI < Thor desc 'search COURSENAME', 'Search a course on ShareCourse' def search(coursename) sc = KiwiScraper::ShareCourse.new result = FuzzyMatch.new(sc.course_name).find(coursename) puts result end desc 'list', 'List all courses on ShareCourse' def list sc = KiwiScraper::ShareCourse.new sc.course_name.each do |ele_courses| puts ele_courses end end desc 'open COURSENAME', 'open the course page on browser' def open(coursename) sc = KiwiScraper::ShareCourse.new # puts sc.courses_name_to_url_mapping input_key = Digest::SHA256.digest coursename course_url = sc.courses_name_to_url_mapping[input_key] Launchy.open(course_url) end end KiwiCLI.start(ARGV)
# frozen_string_literal: true class FinancialEntry < ApplicationRecord belongs_to :user validates :content_file, presence: true end
require 'spec/rack_helper' describe Avito::API::V1::Users, type: :controller do let(:user) { Fabricate :user } describe 'GET /v1/users/:id' do subject { get "/api/v1/users/#{user.id}" } context 'with authenticated user' do login_user it { is_expected.to be_ok } it { is_expected.to match_response_schema('user') } end context 'without authenticated user' do it_behaves_like 'unauthorized request' end end end
class RemoveColumnFromUsersAddToCampaign < ActiveRecord::Migration def change remove_column :users, :donation_alerts add_column :campaigns, :donation_alerts, :boolean end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo # ClusterTime encapsulates cluster time storage and operations. # # The primary operation performed on the cluster time is advancing it: # given another cluster time, pick the newer of the two. # # This class provides comparison methods that are used to figure out which # cluster time is newer, and provides diagnostics in lint mode when # the actual time is missing from a cluster time document. # # @api private class ClusterTime < BSON::Document def initialize(elements = nil) super if Lint.enabled? && !self['clusterTime'] raise ArgumentError, 'Creating a cluster time without clusterTime field' end end # Advances the cluster time in the receiver to the cluster time in +other+. # # +other+ can be nil or be behind the cluster time in the receiver; in # these cases the receiver is returned unmodified. If receiver is advanced, # a new ClusterTime object is returned. # # Return value is nil or a ClusterTime instance. def advance(other) if self['clusterTime'] && other['clusterTime'] && other['clusterTime'] > self['clusterTime'] then ClusterTime[other] else self end end # Compares two ClusterTime instances by comparing their timestamps. def <=>(other) if self['clusterTime'] && other['clusterTime'] self['clusterTime'] <=> other['clusterTime'] elsif !self['clusterTime'] raise ArgumentError, "Cannot compare cluster times when receiver is missing clusterTime key: #{inspect}" else other['clusterTime'] raise ArgumentError, "Cannot compare cluster times when other is missing clusterTime key: #{other.inspect}" end end # Older Rubies do not implement other logical operators through <=>. # TODO revise whether these methods are needed when # https://jira.mongodb.org/browse/RUBY-1622 is implemented. def >=(other) (self <=> other) != -1 end def >(other) (self <=> other) == 1 end def <=(other) (self <=> other) != 1 end def <(other) (self <=> other) == -1 end # Compares two ClusterTime instances by comparing their timestamps. def ==(other) if self['clusterTime'] && other['clusterTime'] && self['clusterTime'] == other['clusterTime'] then true else false end end class << self # Converts a BSON::Document to a ClusterTime. # # +doc+ can be nil, in which case nil is returned. def [](doc) if doc.nil? || doc.is_a?(ClusterTime) doc else ClusterTime.new(doc) end end end # This module provides common cluster time tracking behavior. # # @note Although attributes and methods defined in this module are part of # the public API for the classes including this module, the fact that # the methods are defined on this module and not directly on the # including classes is not part of the public API. module Consumer # The cluster time tracked by the object including this module. # # @return [ nil | ClusterTime ] The cluster time. # # Changed in version 2.9.0: This attribute became an instance of # ClusterTime, which is a subclass of BSON::Document. # Previously it was an instance of BSON::Document. # # @since 2.5.0 attr_reader :cluster_time # Advance the tracked cluster time document for the object including # this module. # # @param [ BSON::Document ] new_cluster_time The new cluster time document. # # @return [ ClusterTime ] The resulting cluster time. # # @since 2.5.0 def advance_cluster_time(new_cluster_time) if @cluster_time @cluster_time = @cluster_time.advance(new_cluster_time) else @cluster_time = ClusterTime[new_cluster_time] end end end end end
require 'rails_helper' RSpec.describe User, type: :model do let(:admin) { build(:admin) } include_examples "create models" describe "Model" do it 'has an email' do expect(user.email).to eq("tom_example@yahoo.com") end it 'has a first name' do expect(user.first_name).to eq("Tom") end it 'has a last name' do expect(user.last_name).to eq("Johnson") end it 'has a first street address' do expect(user.first_street_address).to eq("1234 Example Rd.") end it "has a city" do expect(user.city).to eq("Exampletown") end it 'has a state' do expect(user.state).to eq("Example") end it 'has a zipcode' do expect(user.zipcode).to eq(12345) end it "has a role" do expect(user.role).to eq("owner") expect(admin.role).to eq("admin") end it "responds to name" do expect(user.name).to eq("Tom Johnson") end it "responds to address with a second street address" do expect(user.address).to eq("1234 Example Rd., Apt 201, Exampletown, Example 12345") end it "responds to address without a second street address" do expect(admin.address).to eq("1234 Example Dr., Exampletown, Example 12345") end end describe "Associations" do it "has many pets" do expect(user.pets.size).to eq(1) expect(user.pets).to include(pet) end it "has many appointments, through pets" do expect(user.appointments).to include(appointment) end it "has many invoices, through pets" do expect(user.invoices).to include(invoice) end end end
class BaseService attr_reader :data def self.call(*args) new(*args).call end def call payload self end def success? errors.empty? end def errors @errors ||= ActiveModel::Errors.new(self) end end
# frozen_string_literal: true class ApplicationController < ActionController::Base include Pundit before_action :authenticate_user!, except: :health def append_info_to_payload(payload) super payload[:user_email] = current_user.try :email end def health conn = ActiveRecord::Base.connection.raw_connection migrations = conn.exec('SELECT * FROM schema_migrations').values render json: migrations, status: :ok end def current_user # Including roles in Devise's current_user so we can use has_cached_role? and avoid N+1 when checking for roles # https://stackoverflow.com/questions/6902531/how-to-eager-load-associations-with-the-current-user @current_user ||= super && User.includes(:roles).where(id: @current_user.id).first end # Uncomment this to skip authentication in development # def authenticate_user! # return true if Rails.env.development? # # raise SecurityError # end # # def current_user # raise SecurityError unless Rails.env.development? # # user = User.find_or_create_by!(email: 'test@example.com') # user.add_role :super_admin # user # end end
class MealPlansController < ApplicationController before_action :set_meal_plan, only: [:edit, :update, :destroy, :replace_meal] # before_action :authenticate_user! def show @mealplan = MealPlan.find(params[:id]) meals = @mealplan.daily_meals end def try_out_mealplan ############################################################################################## ### these will need to change to reflect the amount of the recipebook but for now set this ### ############################################################################################## if !session[:settings] || session[:settings] == nil || session[:settings] == [] session[:settings] = { name: "", description: "", protein: 25, carbs: 55, fat: 20, breakfast: 20, lunch: 30, diner: 30, snacks: 20 } end if !session[:user_stats] || session[:user_stats] == nil || session[:user_stats] == [] if user_signed_in? setup_user_stats if current_user.stats end end @mealplan = MealPlan.find(params[:mealplan_id]) day_array = ['monday', "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] meal_times = ["breakfast", "lunch", "diner", "snacks"] session[:tryout_meal_plan] = {} day_array.each do |day| session[:tryout_meal_plan][day] = {} session[:tryout_meal_plan][day][:calories] = 0 meal_times.each do |meal_time| session[:tryout_meal_plan][day][meal_time] = {} session[:tryout_meal_plan][day][meal_time][:recipes] = [] end end @mealplan.daily_meals.each do |meal| session[:tryout_meal_plan][meal.day_of_week][meal.meal_time][:recipes] << { recipe: meal.recipe_id} session[:tryout_meal_plan][meal.day_of_week][:calories] += Recipe.find(meal.recipe_id).calories end if !session[:user_stats] || session[:user_stats] == nil || session[:user_stats] == [] else session[:temp_mealplan] = [] day_array.each do |day| meal_times.each do |meal_time| daily_calories = session[:tryout_meal_plan][day][:calories] session[:tryout_meal_plan][day][meal_time][:recipes].each_with_index do |recipe, i| ratio = Recipe.find(recipe[:recipe]).calories / daily_calories.to_f calories = (ratio * session[:user_stats][:calories].to_f).to_i ####################################################################### ##### MAKE A CALL TO Recipe.get_servings_based_on_calorie_amount ###### ####################################################################### amount = Recipe.get_servings_based_on_calorie_amount recipe[:recipe], calories session[:tryout_meal_plan][day][meal_time][:recipes][i][:amount] = amount session[:temp_mealplan] << { recipe: Recipe.find(recipe[:recipe]), day: day, meal_time: meal_time, amount: amount } end end end end end def get_tryout_session MealPlan.find(params[:id]) render json: { meals: session[:temp_mealplan] }.to_json(:methods => :thumbnail_image_url) end def save_to_user_profile @meal_plan = current_user.meal_plans.new({name: params[:name]}) if @meal_plan.save && !session[:temp_mealplan] != nil session[:temp_mealplan].each do |recipe| @meal_plan.daily_meals.create(recipe_id: recipe[:recipe].id, meal_time: recipe[:meal_time], day_of_week: recipe[:day], serving_size: recipe[:amount]) end session[:settings] = nil session[:mealplan] = nil render json: { status: 200, message: "saved successfully", url: "/mealplan/#{@meal_plan.id}" } else render json: { status: 500, message: "could not be saved", errors: @meal_plan.errors } end end def destroy @mealplan = MealPlan.find(params[:id]) @mealplan.destroy respond_to do |format| format.html { redirect_to recipes_url, notice: 'Meal plan was successfully destroyed.' } format.json { head :no_content } end end def fat_shredder @mealplan = MealPlan.third end def edit @mealplan = MealPlan.find(params[:id]) @recommended_breakfast = Recipe.find([45,46,47,48,49, 57, 58, 59]) if user_signed_in? @fav_recipes = current_user.fav_recipes @user_recipes = current_user.recipes end if !session[:settings] || session[:settings] == nil || session[:settings] == [] session[:settings] = { name: @mealplan.name, description: @mealplan, protein: 25, carbs: 55, fat: 20, breakfast: 20, lunch: 30, diner: 30, snacks: 20 } end end private # Use callbacks to share common setup or constraints between actions. def set_meal_plan @user = current_user @meal_plan = @user.meal_plans.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def meal_plan_params params.require(:meal_plan).permit(:name, :calories, :protein, :carbs, :fat) end def setup_user_stats days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] session[:user_stats] = {} session[:user_stats][:calories] = current_user.stats.daily_calories.to_i daily_calories = current_user.stats.daily_calories.to_i daily_protein = ((daily_calories * (session[:settings][:protein]/100.0)) / 4.0).to_i daily_carbs = ((daily_calories * (session[:settings][:carbs]/100.0)) / 4.0).to_i daily_fat = ((daily_calories * (session[:settings][:fat]/100.0)) / 8.0).to_i session[:user_stats]["daily_calories"] = daily_calories session[:user_stats]["daily_protein"] = daily_protein session[:user_stats]["daily_carbs"] = daily_carbs session[:user_stats]["daily_fat"] = daily_fat days.each do |day| session[:user_stats][day] ={} session[:user_stats][day]["breakfast"] = { calories: (daily_calories*(session[:settings][:breakfast]/100.0)).to_i, protein: (daily_protein*(session[:settings][:breakfast]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:breakfast]/100.0)).to_i, fat: (daily_fat*(session[:settings][:breakfast]/100.0)).to_i } session[:user_stats][day]["lunch"] = { calories: (daily_calories*(session[:settings][:lunch]/100.0)).to_i, protein: (daily_protein*(session[:settings][:lunch]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:lunch]/100.0)).to_i, fat: (daily_fat*(session[:settings][:lunch]/100.0)).to_i } session[:user_stats][day]["diner"] = { calories: (daily_calories*(session[:settings][:diner]/100.0)).to_i, protein: (daily_protein*(session[:settings][:diner]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:diner]/100.0)).to_i, fat: (daily_fat*(session[:settings][:diner]/100.0)).to_i } session[:user_stats][day]["snacks"] = { calories: (daily_calories*(session[:settings][:snacks]/100.0)).to_i, protein: (daily_protein*(session[:settings][:snacks]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:snacks]/100.0)).to_i, fat: (daily_fat*(session[:settings][:snacks]/100.0)).to_i } end session[:user_stats]["breakfast"] = { calories: (daily_calories*(session[:settings][:breakfast]/100.0)).to_i, protein: (daily_protein*(session[:settings][:breakfast]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:breakfast]/100.0)).to_i, fat: (daily_fat*(session[:settings][:breakfast]/100.0)).to_i } session[:user_stats]["lunch"] = { calories: (daily_calories*(session[:settings][:lunch]/100.0)).to_i, protein: (daily_protein*(session[:settings][:lunch]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:lunch]/100.0)).to_i, fat: (daily_fat*(session[:settings][:lunch]/100.0)).to_i } session[:user_stats]["diner"] = { calories: (daily_calories*(session[:settings][:diner]/100.0)).to_i, protein: (daily_protein*(session[:settings][:diner]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:diner]/100.0)).to_i, fat: (daily_fat*(session[:settings][:diner]/100.0)).to_i } session[:user_stats]["snacks"] = { calories: (daily_calories*(session[:settings][:snacks]/100.0)).to_i, protein: (daily_protein*(session[:settings][:snacks]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:snacks]/100.0)).to_i, fat: (daily_fat*(session[:settings][:snacks]/100.0)).to_i } end def set_user_stats_if_not_signed_in days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] calories = params[:calories] session[:user_stats] = {} session[:user_stats][:calories] = calories daily_calories = calories.to_i daily_protein = ((daily_calories * (session[:settings][:protein]/100.0)) / 4.0).to_i daily_carbs = ((daily_calories * (session[:settings][:carbs]/100.0)) / 4.0).to_i daily_fat = ((daily_calories * (session[:settings][:fat]/100.0)) / 8.0).to_i session[:user_stats][:daily_calories] = daily_calories session[:user_stats][:daily_protein] = daily_protein session[:user_stats][:daily_carbs] = daily_carbs session[:user_stats][:daily_fat] = daily_fat days.each do |day| session[:user_stats][day] ={} session[:user_stats][day]["breakfast"] = { calories: (daily_calories*(session[:settings][:breakfast]/100.0)).to_i, protein: (daily_protein*(session[:settings][:breakfast]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:breakfast]/100.0)).to_i, fat: (daily_fat*(session[:settings][:breakfast]/100.0)).to_i } session[:user_stats][day]["lunch"] = { calories: (daily_calories*(session[:settings][:lunch]/100.0)).to_i, protein: (daily_protein*(session[:settings][:lunch]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:lunch]/100.0)).to_i, fat: (daily_fat*(session[:settings][:lunch]/100.0)).to_i } session[:user_stats][day]["diner"] = { calories: (daily_calories*(session[:settings][:diner]/100.0)).to_i, protein: (daily_protein*(session[:settings][:diner]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:diner]/100.0)).to_i, fat: (daily_fat*(session[:settings][:diner]/100.0)).to_i } session[:user_stats][day]["snacks"] = { calories: (daily_calories*(session[:settings][:snacks]/100.0)).to_i, protein: (daily_protein*(session[:settings][:snacks]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:snacks]/100.0)).to_i, fat: (daily_fat*(session[:settings][:snacks]/100.0)).to_i } end session[:user_stats]["breakfast"] = { calories: (daily_calories*(session[:settings][:breakfast]/100.0)).to_i, protein: (daily_protein*(session[:settings][:breakfast]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:breakfast]/100.0)).to_i, fat: (daily_fat*(session[:settings][:breakfast]/100.0)).to_i } session[:user_stats]["lunch"] = { calories: (daily_calories*(session[:settings][:lunch]/100.0)).to_i, protein: (daily_protein*(session[:settings][:lunch]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:lunch]/100.0)).to_i, fat: (daily_fat*(session[:settings][:lunch]/100.0)).to_i } session[:user_stats]["diner"] = { calories: (daily_calories*(session[:settings][:diner]/100.0)).to_i, protein: (daily_protein*(session[:settings][:diner]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:diner]/100.0)).to_i, fat: (daily_fat*(session[:settings][:diner]/100.0)).to_i } session[:user_stats]["snacks"] = { calories: (daily_calories*(session[:settings][:snacks]/100.0)).to_i, protein: (daily_protein*(session[:settings][:snacks]/100.0)).to_i, carbs: (daily_carbs*(session[:settings][:snacks]/100.0)).to_i, fat: (daily_fat*(session[:settings][:snacks]/100.0)).to_i } render json:{ status: 200, message: "updated successfully", meal_amounts: session[:user_stats] } end end
class CardsetsController < ApplicationController before_action :signed_in_user, only: [:new, :create, :edit, :update, :destroy] before_action :correct_user, only: [:edit, :update, :destroy] def index @cardsets = Cardset.all end def new @cardset = Cardset.new end def create @cardset = Cardset.new(cardset_params.merge(author_id: current_user.id)) if @cardset.save flash[:success] = "A new set of cards is created!" redirect_to @cardset else render 'new' end end def show @cardset = Cardset.find(params[:id]) @cards = @cardset.cards.with_levels_for(current_user.id).group_by_level(current_user) end def edit @cardset = Cardset.find(params[:id]) end def update @cardset = Cardset.find(params[:id]) if @cardset.update_attributes(cardset_params) flash[:success] = "The card set is updated!" redirect_to @cardset else render 'edit' end end def destroy @cardset.destroy redirect_to current_user end private def cardset_params params.require(:cardset).permit(:topic, :description) end def correct_user cardset = Cardset.find(params[:id]) if cardset.author_id != current_user.id flash[:error] = "You have to be owner of the cardset!" redirect_to current_user end end end
#!/usr/bin/env ruby # Usage: hr otd # Summary: Print a random event that happened on this day in history, courtesy # of Wikipedia. require 'nokogiri' require 'open-uri' def todays_url todays_date = Time.now.strftime("%B_%-e") "https://en.wikipedia.org/wiki/#{todays_date}" end def events Nokogiri::HTML(open(todays_url)) .xpath('//ul')[1] .elements .collect {|node| node.text.strip} end puts "On this day in #{events.sample}"
require 'spec_helper' describe ActivityCreator, '#post' do include DelayedJobSpecHelper it 'posts to the Yammer API on post' do Yam.stubs(:post) user = build_user action = 'vote' event = build_stubbed(:event_with_invitees) ActivityCreator.new(user: user, action: action, event: event).post work_off_delayed_jobs Yam.should have_received(:post).with( '/activity', expected_json(event) ) end it 'creates a delayed job' do user = build_stubbed(:user) action = 'vote' event = build_stubbed(:event) expect { ActivityCreator.new(user: user, action: action, event: event).post }.to change(Delayed::Job, :count).by(1) end it 'expires the access_token if it is stale' do Delayed::Worker.delay_jobs = false user = build_user('OLDTOKEN') Yam.oauth_token = user.access_token action = 'vote' event = build_stubbed(:event_with_invitees) ActivityCreator.new(user: user, action: action, event: event).post user.access_token.should == 'EXPIRED' Delayed::Worker.delay_jobs = true Yam.set_defaults end private def build_user(token = 'ABC123') user = create( :user, email: 'fred@example.com', access_token: token, name: 'Fred Jones' ) end def expected_json(event) { activity: { actor: { name: 'Fred Jones', email: 'fred@example.com' }, action: 'vote', object: { url: Rails.application.routes.url_helpers.event_url(event), type: 'poll', title: event.name, image: 'http://' + ENV['HOSTNAME'] + '/logo.png' } }, message: '', users: event.invitees_for_json } end end
class AddPageFaqsCountToFaqs < ActiveRecord::Migration def change add_column :faqs, :page_faqs_count, :integer, default: 0 Faq.reset_column_information Faq.find(:all).each do |p| Faq.update_counters p.id, page_faqs_count: p.page_faqs.length end end end
# == Schema Information # # Table name: events # # id :integer not null, primary key # title :string # description :string # caption :string # event_date :datetime # timeline_id :integer # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Event, type: :model do context 'associations' do it {should belong_to(:timeline)} end context 'factory' do it 'has a valid base factory' do create(:events) end it 'has built association factory' do event = nil expect do event = create(:events, :with_built_timeline) end.to_not change{Timeline.count} expect(event.timeline.new_record?).to be_truthy end it 'has created association factory' do event = nil expect do event = create(:events, :with_created_timeline) end.to change{Timeline.count}.to(1) expect(event.timeline.new_record?).to be_falsey end end end
require 'json' require_relative 'base_reddit' require_relative 'user_comment' require_relative 'user_submission' class User < BaseReddit attr_accessor :name, :metadata, :submissions_ended_at, :submissions_after attr_accessor :comments_ended_at, :comments_after, :reddit_object attr_accessor :comments, :submissions def initialize(props = {}) @submissions = [] @comments = [] @submissions_ended_at = 0 @comments_ended_at = 0 super(props) end def reddit_object if(@reddit_object.nil?) @reddit_object = @@reddit_client.user_from_name(@name) end @reddit_object end def set_counters(klass, ended_at, after) if(klass == UserComment) @comments_ended_at = ended_at @comments_after = after else @submissions_ended_at = ended_at @submissions_after = after end end def get_counters(klass) if(klass == UserComment) return { ended_at: @comments_ended_at, after: @comments_after } else return { ended_at: @submissions_ended_at, after: @submissions_after } end end def save @@db.execute "insert or ignore into users (name) values (#{quote(name)});" @@db.execute <<-SQL update users set metadata=#{quote(metadata)}, submissions_ended_at=#{submissions_ended_at}, submissions_after=#{quote(submissions_after)}, comments_ended_at=#{quote(comments_ended_at)}, comments_after=#{quote(comments_after)} where name=#{quote(name)} collate nocase; SQL for submission in submissions do submission.save end for comment in comments do comment.save end return true end def get_submissions(limit, count) result = get_from_reddit(UserSubmission, @submissions, @submissions_ended_at, @submissions_after, limit, count) @submissions = result[:result_list] || [] @submissions_ended_at = result[:ended_at] @submissions_after = result[:after] return true end def get_comments(limit, count) result = get_from_reddit(UserComment, @comments, @comments_ended_at, @comments_after, limit, count) @comments = result[:result_list]|| [] @comments_ended_at = result[:ended_at] @comments_after = result[:after] return true end def self.find_or_create(name) self.find(name) || self.create(name) end def self.find(name) row = self.find_one <<-SQL select name, metadata, submissions_ended_at, submissions_after, comments_ended_at, comments_after from users where name = #{quote(name)} COLLATE NOCASE; SQL unless (row.nil?) user = User.new user.name = row[0] user.metadata = row[1] user.submissions_ended_at = row[2] user.submissions_after = row[3] user.comments_ended_at = row[4] user.comments_after = row[5] user.submissions = UserSubmission.find_for(user) user.comments = UserComment.find_for(user) return user else return nil end end def self.create(name) user = User.new(name: name) user.metadata = JSON.pretty_generate(JSON.parse(user.reddit_object.to_json)) user.save return user end def self.init_table @@db.execute <<-SQL create table if not exists users ( name varchar(255) PRIMARY KEY, metadata text, submissions_ended_at integer, submissions_after varchar(255), comments_ended_at integer, comments_after varchar(255) ); SQL end # private # # # def get_from_reddit(klass, list_attr, ended_at, after, limit, count) # args = { limit: limit, count: count } # if(after) # args[:after] = after # end # if klass == UserComment # list = reddit_object.get_comments(args) # else # list = reddit_object.get_submissions(args) # end # if (list.length > 0) # list_attr = (list_attr + list.map {|r| klass.new({ user: self, subreddit_name: r.subreddit}) }).uniq { |c| self.name + c.subreddit_name } # ended_at += limit # after = list.last.fullname # end # return {ended_at: ended_at, after: after} # end end
name 'nginx_sinatra' maintainer 'amazedkoumei' maintainer_email 'amazed.koumei@gmail.com' license 'All rights reserved' description 'Installs/Configures sinatra' version '0.1.0'
class RenameConsumerUserFavourite < ActiveRecord::Migration def change rename_column :favourites, :consumer_id, :user_id end end
require 'friendly/scope' module Friendly class NamedScope attr_reader :klass, :parameters, :scope_klass def initialize(klass, parameters, scope_klass = Scope) @klass = klass @parameters = parameters @scope_klass = scope_klass end def scope @scope_klass.new(@klass, @parameters) end end end
module TutorialsHelper VIDEO_HEIGHT = 450 VIDEO_WIDTH = 800 def tag_cloud(tags, classes) max = tags.sort_by(&:count).last tags.each do |tag| index = tag.count.to_f / max.count * (classes.size-1) yield(tag, classes[index.round]) end end def user_id(id) if current_user.admin? id || current_user.id else current_user.id end end def format_page(text) text = remove_tags(text) text = to_markdown(text) parse_links(text) end def to_markdown(text) Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(render_options = {}), extensions = {}).render(text) end def remove_tags(text) scrubber = Rails::Html::PermitScrubber.new scrubber.tags = ['img', 'a'] Loofah.fragment(text).scrub!(scrubber).to_s end def parse_links(text) while !youtube_link(text).nil? link = youtube_link(text).to_s id = get_youtube_id(link) text = text.sub(link, "<iframe width='#{VIDEO_WIDTH}' height='#{VIDEO_HEIGHT}' src='https://www.youtube.com/embed/#{get_youtube_id(link)}'></iframe>") end text end def youtube_link(source_url) regex = /((?:https|http):\/\/\w{0,3}.youtube+\.\w{2,3}\/watch\?v=[\w-]{11})/ regex.match(source_url) end def get_youtube_id(url) id = '' url = url.gsub(/(>|<)/i,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/) if url[2] != nil id = url[2].split(/[^0-9a-z_\-]/i) id = id[0]; else id = url; end id end end
class MessagesController < ApplicationController def index @messages = Message.all end def new @message = Message.new end def create @message = Message.new(message_params) if @message.save redirect_to '/messages' else render 'new' end end def show @message = Message.find(params[:id]) end def edit @message = Message.find(params[:id]) end def update @message = Message.find(params[:id]) if @message.update(message_params) redirect_to '/messages' else render 'edit' end end def destroy @message = Message.find(params[:id]) @message.destroy redirect_to '/messages' end private def message_params params.require(:message).permit(:content) end end
require_relative "../hotness.rb" describe Hotness do before do class Image include Hotness end @image = Image.new end it "should return a start date" do aug_13 = Time.local(2014, 8, 13) expect(Hotness::START_DATE).to eq(aug_13) end it "#seconds_from_start_time should return seconds from a given time" do seconds_in_a_day = 86400 thursday = Time.local(2014, 8, 14) expect(@image.seconds_from_start_date(thursday)).to eq(seconds_in_a_day) end context "#hot" do it "should return 1 hot score when 1 day later, 0 ups, 0 downs" do thursday = Time.local(2014, 8, 14) expect(@image.hot(0, 0, thursday)).to be == 1 end it "should return 2 hot score when 2 days, 0 ups, 0 downs" do friday = Time.local(2014, 8, 15) expect(@image.hot(0, 0, friday)).to be == 2 end it "should return 7 hot score when 1 week later, 0 ups, 0 downs" do one_week_later = Time.local(2014, 8, 20) expect(@image.hot(0, 0, one_week_later)).to be == 7 end it "should return > 30 hot score when 1 month later, 0 ups, 0 downs" do one_month_later = Time.local(2014, 9, 13) expect(@image.hot(0, 0, one_month_later)).to be > 30 end it "should return hot score > 1, 1 day later, 5 ups, 0 downs" do thursday = Time.local(2014, 8, 14) expect(@image.hot(5, 0, thursday)).to be > 1 end it "should return hot score > 2, 1 day later, 20 ups, 0 downs" do thursday = Time.local(2014, 8, 14) expect(@image.hot(20, 0, thursday)).to be > 2 end it "should return hot score < 1, 1 day later, 0 ups, 5 downs" do thursday = Time.local(2014, 8, 14) expect(@image.hot(0, 5, thursday)).to be < 1 end it "should return hot score < 0, 1 day later, 0 ups, 20 downs" do thursday = Time.local(2014, 8, 14) expect(@image.hot(0, 20, thursday)).to be < 0 end end end
people = 30 cars = 40 trucks = 15 #if, elsif, and else functions. #In this case, cars are greater than people so the first if statement will be printed. if cars > people puts "We should take the cars." elsif cars < people puts "We should not take the cars." else puts "We can't decide." end #if elsif and else statement. #trucks are not greater than cars, so it moves to the elsif statements #trucks are less than cars, so the elsif statement will be printed. if trucks > cars puts "That's too many trucks." elsif trucks < cars puts "Maybe we could take the trucks." else puts "We still can't decide." end #if and else statement #people are greater than trucks, so the first statement will be printed. if people > trucks puts "Alright, let's just take the trucks." else puts "Fine, let's stay home then." end #Study drills #What are elseif and else doing? # They are giving the code more options than a simple if statement. # elseif is basically saying if the first one isn't true, try this. # else is basically saying if neither is true, put this #Try boolean if cars < people && trucks < cars puts "Looks like it's cars." elsif cars < people && trucks > cars puts "Trucks it is then." else puts "Why don't we just go home?" end
module Meiosis class Transaction attr_accessor :inputs, :outputs, :deps, :version, :fee, :input_sig, :hash attr_reader :serialized_self, :status # @inputs array of cell outpoints # @outputs array of <Cell> instances def initialize(version=0, inputs=[], outputs=[], deps=[Meiosis::Config.api.system_script_cell]) @inputs = inputs @version = version @outputs = outputs @deps = deps @fee = nil @status = "Unconfirmed" end def build() validate_outputs i = gather_inputs inputs = i.inputs input_capacities = i.capacities formatted_outputs = outputs.map do |output_cell| output_cell.json end if input_capacities > @total_input_capacity outputs << { capacity: input_capacities - @total_input_capacity, data: "0x", lock: Meiosis::Config.wallet.lock } end @serialized_self = { version: 0, deps: [Meiosis::Config.api.system_script_out_point], inputs: CKB::Utils.sign_sighash_all_inputs(inputs, formatted_outputs, Meiosis::Config.wallet.privkey), outputs: formatted_outputs, witnesses: [] } end def send result = Meiosis::Config.wallet.send_tx(serialized_self) self.hash = result self end def self.find_one(hash_of_tx) Meiosis::Config.wallet.get_transaction(hash_of_tx) end def validate_outputs outputs.each_with_index do |cell, idx| if !cell.is_valid_output p cell.json raise "Output cell #{idx} is not valid. Ensure that you have set a lock, a capacity, and that capacity >= its minimum capacity" end end end def fee @fee ? @fee : self.class.calculate_fee end def gather_inputs() capacity_sums = {total: 0, minimum: 0} outputs.each do |cell| capacity_sums[:total] += cell.capacity capacity_sums[:minimum] += cell.min_capacity end @total_input_capacity = capacity_sums[:total] @min_input_capacity = capacity_sums[:minimum] self.class.gather_inputs(@total_input_capacity, @min_input_capacity) end def on_processed(name, &blk) tx_hash = hash tx_ready_check = Proc.new do t1 = Time.now puts "Calling Proc" tx_result = api.get_transaction(tx_hash) while !tx_result while Time.now - t1 >= 5 puts "READY CHECK" t1 = Time.now tx_result = api.get_transaction(tx_hash) end end tx_result end subscription = Meiosis::Subscription.new(name, tx_ready_check) do |result| blk.call(result) end end def api Meiosis::Config.api end def self.gather_inputs(capacity, min_capacity) raise "capacity cannot be less than #{min_capacity}" if capacity < min_capacity input_capacities = 0 inputs = [] Meiosis::Config.wallet.get_unspent_cells.each do |cell| input = { previous_output: cell[:out_point], args: [Meiosis::Config.wallet.lock[:binary_hash]], valid_since: 0 } inputs << input input_capacities += cell[:capacity] break if input_capacities >= capacity && input_capacities - (input_capacities - capacity) >= min_capacity end raise "Not enough capacity!" if input_capacities < capacity OpenStruct.new(inputs: inputs, capacities: input_capacities) end def self.calculate_fee 0 end end end
class AddRatingEvent < ActiveRecord::Migration def self.up add_column :events, :rating, :float, :default => 0, :null => false add_column :events, :rated_count, :integer, :default => 0, :null => false end def self.down remove_column :events, :rating remove_column :events, :rated_count end end
class User < ActiveRecord::Base attr_accessible :birthday, :email, :first_name, :login, :middle_name, :password, :second_name validates :password, presence: true, length: {in: 5..32} validates :login, presence: true, uniqueness: true end
# Encoding: UTF-8 require 'test_helper' require 'traject/indexer' # should be built into every indexer describe "Traject::Macros::Transformation" do before do @indexer = Traject::Indexer.new @record = nil end describe "translation_map" do it "translates" do @indexer.configure do to_field "cataloging_agency", literal("DLC"), translation_map("marc_040a_translate_test") end output = @indexer.map_record(@record) assert_equal ["Library of Congress"], output["cataloging_agency"] end it "can merge multiple" do @indexer.configure do to_field "result", literal("key_to_be_overridden"), translation_map("ruby_map", "yaml_map") end output = @indexer.map_record(@record) assert_equal ["value_from_yaml"], output["result"] end it "can merge multiple with hash" do @indexer.configure do to_field "result", literal("key_to_be_overridden"), translation_map("ruby_map", "yaml_map", {"key_to_be_overridden" => "value_from_inline_hash"}) end output = @indexer.map_record(@record) assert_equal ["value_from_inline_hash"], output["result"] end end describe "transform" do it "transforms with block" do @indexer.configure do to_field "sample_field", literal("one"), literal("two"), transform(&:upcase) end output = @indexer.map_record(@record) assert_equal ["ONE", "TWO"], output["sample_field"] end it "transforms with proc arg" do @indexer.configure do to_field "sample_field", literal("one"), literal("two"), transform(->(val) { val.tr('aeiou', '!') }) end output = @indexer.map_record(@record) assert_equal ["!n!", "tw!"], output["sample_field"] end it "transforms with both, in correct order" do @indexer.configure do to_field "sample_field", literal("one"), literal("two"), transform(->(val) { val.tr('aeiou', '!') }, &:upcase) end output = @indexer.map_record(@record) assert_equal ["!N!", "TW!"], output["sample_field"] end end describe "default" do it "adds default to empty accumulator" do @indexer.configure do to_field "test", default("default") end output = @indexer.map_record(@record) assert_equal ["default"], output["test"] end it "does not add default if value present" do @indexer.configure do to_field "test", literal("value"), default("defaut") end output = @indexer.map_record(@record) assert_equal ["value"], output["test"] end end describe "first_only" do it "takes only first in multi-value" do @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), first_only end output = @indexer.map_record(@record) assert_equal ["one"], output["test"] end it "no-ops on nil" do @indexer.configure do to_field "test", first_only end output = @indexer.map_record(@record) assert_nil output["test"] end it "no-ops on single value" do @indexer.configure do to_field "test", literal("one"), first_only end output = @indexer.map_record(@record) assert_equal ["one"], output["test"] end end describe "unique" do it "uniqs" do @indexer.configure do to_field "test", literal("one"), literal("two"), literal("one"), literal("three"), unique end output = @indexer.map_record(@record) assert_equal ["one", "two", "three"], output["test"] end end describe "strip" do it "strips" do @indexer.configure do to_field "test", literal(" one"), literal(" two "), strip end output = @indexer.map_record(@record) assert_equal ["one", "two"], output["test"] end it "strips unicode whitespace" do @indexer.configure do to_field "test", literal(" \u00A0 \u2002 one \u202F "), strip end output = @indexer.map_record(@record) assert_equal ["one"], output["test"] end end describe "split" do it "splits" do @indexer.configure do to_field "test", literal("one.two"), split(".") end output = @indexer.map_record(@record) assert_equal ["one", "two"], output["test"] end end describe "append" do it "appends suffix" do @indexer.configure do to_field "test", literal("one"), literal("two"), append(".suffix") end output = @indexer.map_record(@record) assert_equal ["one.suffix", "two.suffix"], output["test"] end end describe "prepend" do it "prepends prefix" do @indexer.configure do to_field "test", literal("one"), literal("two"), prepend("prefix.") end output = @indexer.map_record(@record) assert_equal ["prefix.one", "prefix.two"], output["test"] end end describe "gsub" do it "gsubs" do @indexer.configure do to_field "test", literal("one1212two23three"), gsub(/\d+/, ' ') end output = @indexer.map_record(@record) assert_equal ["one two three"], output["test"] end end describe "delete_if" do describe "argument is an Array" do it "filters out selected values from accumulatd values" do arg = [ "one", "three"] @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), delete_if(arg) end output = @indexer.map_record(@record) assert_equal ["two"], output["test"] end end describe "argument is a Set" do it "filters out selected values from accumulatd values" do arg = [ "one", "three"].to_set @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), delete_if(arg) end output = @indexer.map_record(@record) assert_equal ["two"], output["test"] end end describe "argument is a Regex" do it "filters out selected values from accumulatd values" do arg = /^t/ @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), delete_if(arg) end output = @indexer.map_record(@record) assert_equal ["one"], output["test"] end end describe "argument is a Procedure or Lambda" do it "filters out selected values from accumulatd values" do arg = ->(v) { v == "one" } @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), delete_if(arg) end output = @indexer.map_record(@record) assert_equal ["two", "three"], output["test"] end end end describe "select" do describe "argument is an Array" do it "selects a subset of values from accumulatd values" do arg = [ "one", "three", "four"] @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), select(arg) end output = @indexer.map_record(@record) assert_equal ["one", "three"], output["test"] end end describe "argument is a Set" do it "selects a subset of values from accumulatd values" do arg = [ "one", "three", "four"].to_set @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), select(arg) end output = @indexer.map_record(@record) assert_equal ["one", "three"], output["test"] end end describe "argument is a Regex" do it "selects a subset of values from accumulatd values" do arg = /^t/ @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), select(arg) end output = @indexer.map_record(@record) assert_equal ["two", "three"], output["test"] end end describe "argument is a Procedure or Lambda" do it "selects a subset of values from accumulatd values" do arg = ->(v) { v != "one" } @indexer.configure do to_field "test", literal("one"), literal("two"), literal("three"), select(arg) end output = @indexer.map_record(@record) assert_equal ["two", "three"], output["test"] end end end end
class StorageEntry < ActiveRecord::Base scope :by_reason, lambda{|reason_id| where(storage_entry_type_id: reason_id)} scope :by_product, lambda {|product_id| where(product_id: product_id)} scope :by_movement_date, lambda { |min_date, max_date| where('storage_entries.movement_date >= ? and storage_entries.movement_date <= ?', min_date.to_date, max_date.to_date) } validates :movement_date, presence: true validates :product, presence: true validates :point_of_sale, presence: true validates :quantity, presence: true validates :storage_entry_type, presence: true belongs_to :point_of_sale belongs_to :product belongs_to :storage_entry_type end
require 'rspec' require_relative '../model/CalculadoraFactoresPrimos' describe 'CalculadoraFactoresPrimosTest' do let(:calculadora) { CalculadoraFactoresPrimos.new } begin it 'primos de 4 son 2 y 2' do expect(calculadora.calcular("4")).to eq([2, 2]) end it 'primos de 360 son 2, 2, 2, 3, 3 y 5' do expect(calculadora.calcular("360")).to eq([2, 2, 2, 3, 3, 5]) end it '1 no tiene primos' do expect(calculadora.calcular("1")).to eq([]) end it 'A no es valido, da excepcion' do expect{calculadora.calcular("A")}.to raise_exception end end end
class CreateCommands < ActiveRecord::Migration def change create_table :commands do |t| t.datetime :date, null: false t.string :description, null: false t.datetime :limit_date t.string :payment t.string :state, null: false t.decimal :total, precision: 8, scale: 2 t.timestamps null: false end end end
class ApplicationController < ActionController::Base KEYS_FLASH = %i[error warning success info] protect_from_forgery with: :exception include SessionsHelper before_action :authenticate_user def authenticate_user return if signed_in? display_flash(:error, 'You are not signed in.') redirect_to new_session_path end def redirect_authenticated return unless signed_in? display_flash(:error, 'You are already signed in.') redirect_to root_path end protected def display_flash(key, message, now: false) if now flash.now[key] = [] if flash.now[key].nil? flash.now[key] = [flash.now[key]] unless flash.now[key].is_a?(Array) flash.now[key] << message else flash[key] = [] if flash[key].nil? flash[key] = [flash[key]] unless flash[key].is_a?(Array) flash[key] << message end end end
class User < ActiveRecord::Base has_secure_password validates :name, presence: true validates :email, presence: true, uniqueness: true validates :password, presence: true, confirmation: true, length: { minimum: 8} def self.authenticate_with_credentials(email, password) user = User.find_by(email: email.strip.downcase) if user && user.authenticate(password) user end end end
module WelcomeHelper def resource @company ||= Company.new end def resource_name :company end def registration_path(resource_name) company_registration_path end def devise_mapping @devise_mapping ||= Devise.mappings[:company] end end
class RenameOrderItemsToReservations < ActiveRecord::Migration def change rename_table :order_items, :reservations end end
module StorePages def self.included(klass) if klass.respond_to? :helper_method klass.helper_method :is_store? klass.helper_method :news_enabled? klass.helper_method :events_enabled? klass.helper_method :twitter_enabled? klass.helper 'mysears/mystore' end end def news_articles(cobrand, product, page, page_size, published=true, corporate=true) articles(:news, cobrand, product, page, page_size, published, corporate) end def events_articles(cobrand, product, page, page_size, published=true, corporate=true) articles(:events, cobrand, product, page, page_size, published, corporate) end def find_page_for_article(cobrand, store, type, article_id, page_size, initial_page) return initial_page, nil if article_id.blank? cat_ids = get_category_ids(cobrand, store, type, true) article_ids = ActiveRecord::Base.connection.select_all("SELECT id from articles where status='published' and article_category_id in (#{cat_ids.join(',')}) order by published_at DESC").collect{|x| x['id']} index = article_ids.index(article_id.to_s) if index.blank? return initial_page, nil else return ((index / page_size) + 1), article_id end end def articles(type, cobrand, store, page, page_size, published, corporate) cat_ids = get_category_ids(cobrand, store, type, corporate) conditions = ['article_category_id in (?)', cat_ids] order = type == :events ? 'start_time ASC' : 'published_at DESC' if published conditions[0] << ' and status = ?' conditions << 'published' if type == :events offset_date = 3.days.ago.to_date conditions[0] << ' and (all_day = ? AND ? <= DATE(end_time) OR (all_day = ? AND ? <= DATE(start_time)))' conditions << false << offset_date << true << offset_date end else conditions[0] << ' and status != ?' conditions << 'deleted' end count = Article.count(:conditions => conditions) cats = Article.find(:all, :conditions => conditions, :order => order, :limit => (page_size == -1 ? count : page_size), :offset => ((page.to_i-1)*page_size.to_i)) return count, cats end def get_category_ids(cobrand, store, type, corporate) short_name = category_short_name(cobrand, is_corporate?(store), type) cat_ids = [] if pp = store.partner_products.find(:first, :conditions=>['source_id = ?', Source.find_by_short_name('stores').id]) ac = ArticleCategory.find_by_partner_key_and_short_name(pp.partner_key, short_name) cat_ids << ac.id if ac end cat_ids << ArticleCategory.find_by_short_name(cobrand.short_name + '_corporate_' + type.to_s).id if corporate cat_ids end # This is a hack until we can improve the way we determine which products # are infact stores in a more generic manner def is_store?(product) return false unless product return false if @cobrand.short_name == "viewpoints" store_type = product.get_answer_value('Sears or Kmart') product.category.name == 'Department Stores' and (store_type == 'Sears' or store_type == 'Kmart') end def news_enabled?(store) articles_enabled?(:news, store) end def events_enabled?(store) articles_enabled?(:events, store) end def articles_enabled?(type, store) if pp = store.partner_products.find(:first, :conditions=>['source_id = ?', Source.find_by_short_name('stores').id]) if ArticleCategory.find_by_partner_key_and_short_name(pp.partner_key, 'store_' + type.to_s) return true end end end def twitter_enabled?(store) key = store.get_answer_value('Twitter Store Key') secret = store.get_answer_value('Twitter Store Secret') return (!key.blank? and !secret.blank?) end def news_category_for_store(store, cobrand) category_for_store(store, :news, cobrand) end def events_category_for_store(store, cobrand) category_for_store(store, :events, cobrand) end def category_for_store(store, type, cobrand) short_name = category_short_name(cobrand, is_corporate?(store), type) if pp = store.partner_products.find(:first, :conditions=>['source_id = ?', Source.find_by_short_name('stores').id]) return ArticleCategory.find_by_partner_key_and_short_name(pp.partner_key, short_name) end end def is_corporate?(store) store.get_answer_value('Store Number').index('_corporate') end def category_short_name(cobrand, corporate, type) (corporate ? (cobrand.short_name + '_corporate_') : 'store_') + type.to_s end def find_store_by_store_number(store_number) return nil if store_number.blank? store = Product.find_by_sql( <<STORE_SQL SELECT p.* FROM products p JOIN product_answers pa_store_num ON p.id = pa_store_num.product_id JOIN product_answers pa_typ ON p.id = pa_typ.product_id WHERE p.category_id = (SELECT id from categories where name = 'Department Stores') AND pa_store_num.product_question_id = (SELECT id from product_questions WHERE label = 'Store Number' AND category_id = (SELECT id FROM categories where name = 'Department Stores')) AND pa_typ.product_question_id = (SELECT id from product_questions WHERE label = 'Sears or Kmart') AND pa_typ.value = '#{@cobrand.short_name[2..-1].capitalize}' AND pa_store_num.value = #{ActiveRecord::Base.sanitize(store_number)} STORE_SQL ) if !store.empty? return store[0] else return nil end end end #module StorePages module StoreTools class StoreEventUtils # Find all events that start "tomorrow" def self.find_upcoming_events Event.find(:all, :conditions=>['ADDDATE(CURDATE(), 1) = DATE(start_time) and status = ?', 'published']) end # Find all events that ended "yesterday" def self.find_completed_events Event.find(:all, :conditions=>['SUBDATE(CURDATE(), 1) = DATE(end_time) and status = ?', 'published']) end def self.send_event_reminder_emails(event) event.rsvps.each do |rsvp| if !rsvp.opt_out ETTriggeredSendAdd.send_event_reminder_email(rsvp) end end end def self.send_event_unattended_emails(event) event.rsvps.each do |rsvp| if !rsvp.attended && !rsvp.opt_out ETTriggeredSendAdd.send_event_unattended_email(rsvp) end end end end # class StoreEventUtils class StoreFeedbackUtils def self.find_stores_with_feedback ids = ProductFeedback.find_by_sql <<-STORE_SQL SELECT DISTINCT product_id FROM product_feedbacks WHERE status='new' STORE_SQL ids = ids.collect{|x| x.product_id} if !ids.empty? Product.find(:all, :conditions=>['id in (?)', ids]) else [] end end def self.get_feedback_for_store(store) ProductFeedback.find(:all, :conditions=>{:product_id=>store, :status=>'new'}) end def self.generate_feedback_email(from, to, store, feedbacks) store_email = store.get_answer_value('Store Email') to_clone = to.clone to_clone << store_email if store_email content = <<EOM From: Viewpoints Operations <#{from}> To: #{to_clone.map { |email| "<#{email}>" }.join(",")} Subject: Store Feedback - #{store.get_answer_value('Store Name')} (#{store.get_answer_value('Store Number')}) - #{Time.now.strftime("%m.%d.%y")} Content-Type: text/html EOM feedbacks.each do |fb| content += <<CONTENT From: #{fb.email_address.blank? ? 'Anonymous' : fb.email_address} Feedback Type: #{fb.feedback_type} Rating: #{fb.rating} Comments: #{fb.comments} -------------------------------------------------------------------------------- CONTENT end content end end # class StoreFeedbackUtils class StoreFactory STORE_QUESTION_MAP = [ {:param => :store_name, :label => 'Store Name'}, {:param => :store_number, :label => 'Store Number'}, {:param => :store_address, :label => 'Address'}, {:param => :store_city, :label => 'City'}, {:param => :store_state, :label => 'State'}, {:param => :store_zip, :label => 'Zip code'}, {:param => :store_phone, :label => 'Telephone'}, {:param => :store_fax, :label => 'Fax'}, {:param => :store_hours, :label => 'Hours'}, {:param => :store_manager_name, :label => 'Manager Name'}, {:param => :store_email, :label => 'Store Email'}, {:param => :store_type, :label => 'Sears or Kmart'} ] def self.create(params, cobrand, create_categories=true) params[:store_type] = cobrand.short_name[2..-1].capitalize if validate_params(params) p = nil Product.transaction do is_new, count, p = find_or_create_store(params) if p STORE_QUESTION_MAP.each do |item| update_store_answer(p, item[:label], params[item[:param]]) end p.reformat_title p.reformat_subtitle p.save! create_news_and_events_categories_for_store(cobrand, p, create_categories) else @errors[:general] = "#{count} stores exist that match store <#{params[:store_name]} - #{params[:store_city]}, #{params[:store_state]}> for store number: #{params[:store_number]}" end end end return p, @errors end def self.create_news_and_events_categories_for_store(cobrand, store, create_categories) source = Source.find_by_short_name('stores') pp = store.partner_products.find(:first, :conditions=>['source_id = ?', source.id]) || PartnerProduct.new(:source_id => source.id) if pp.partner_key.blank? Product.transaction do create_partner_key_for_store(store, pp) if create_categories create_article_category(cobrand, store, 'news') create_article_category(cobrand, store, 'events') end end else # The partner key already exists, make sure the news and events article categories exist ['news', 'events'].each do |type| if !ArticleCategory.find_by_short_name_and_partner_key('store_' + type, pp.partner_key) create_article_category(cobrand, store, type) if create_categories end end end end def self.update_store_answer(store, question_label, value, question_id=nil) if question_id question = ProductQuestion.find question_id else question = ProductQuestion.find_by_label_and_category_id(question_label, Category.find_by_name('Department Stores')) end if question if value.blank? ProductAnswer.destroy_all :product_id => store.id, :product_question_id => question.id else answer = store.product_answers.first :conditions => { :product_question_id => question.id } answer ||= store.product_answers.build(:question => question, :status => :approved) answer.value = value answer.save! end end end private def self.find_or_create_store(params) category = Category.find_by_name('Department Stores') title = "#{params[:store_name]}%#{params[:store_city]}%#{params[:store_state]}" stores = Product.find(:all, :conditions => ['title like ? and category_id =?', title, category.id]) if stores.count == 1 # Make sure this is the appropriate store via the store number store_number = stores[0].get_answer_value('Store Number') if store_number.blank? or (store_number == params[:store_number] and !params[:store_number].blank?) return false, 1, stores[0] else return true, 1, create_new_store(params) end elsif stores.count > 1 return disambiguate_stores(stores, params) else return true, 1, create_new_store(params) end end def self.create_new_store(params) store_title = create_store_title(params[:store_name], params[:store_city], params[:store_state]) store = Product.new(:source => Source.find_by_short_name('user'), :category => Category.find_by_name('Department Stores'), :title=>store_title) store.save! return store end def self.disambiguate_stores(stores, params) store = stores.find do |store| store_number = store.get_answer_value('Store Number') !store_number.blank? and !params[:store_number].blank? and store_number == params[:store_number] end if store return false, 1, store else return false, stores.count, nil end end def self.validate_params(params) @errors = {} [:store_name, :store_number, :store_city, :store_state].each do |item| @errors[item] = {:message=>' is required'} if params[item].blank? end @errors.empty? end def self.create_partner_key_for_store(store, partner_product) # create a new partner key pk = UUIDTools::UUID.timestamp_create # add it to the partner_product partner_product.partner_key = pk.to_s # add the partner_product to the store store.partner_products << partner_product # save the store store.save! end def self.create_article_category(cobrand, store, type) partner_key = store.partner_products.first.partner_key # find the news article instance ai = ArticleInstance.find_by_short_name("#{cobrand.short_name}_store_#{type}") # create a new article category for news for this store store_title = create_store_article_category_title( store.get_answer_value('Store Name'), store.get_answer_value('Store Number'), store.get_answer_value('City'), store.get_answer_value('State')) display_text = "#{store_title} - #{type.capitalize}" ac = ArticleCategory.new(:display_text=>display_text, :display_order => 1, :page_title =>display_text, :article_instance_id=>ai.id, :short_name => "store_#{type}", :partner_key=>"#{partner_key}") ac.save! end def self.create_store_article_category_title(name, number, city, state) "#{name} (#{number}) - #{city}, #{state}" end def self.create_store_title(name, city, state) "#{name} - #{city}, #{state}" end end # class StoreFactory end # module StoreTools
module Decidim module Participations module Admin class UpdateParticipation < Rectify::Command # Public: Initializes the command. # # form - A form object with the params. # current_user - The current user. # current_participatory_process - The current participatory process # participation - the participation to update. def initialize(form, current_user, current_participatory_process, participation) @form = form @current_user = current_user @current_participatory_process = current_participatory_process @participation = participation end # Executes the command. Broadcasts these events: # # - :ok when everything is valid, together with the participation. # - :invalid if the form wasn't valid and we couldn't proceed. # # Returns nothing. def call return broadcast(:invalid) if form.invalid? transaction do should_notify = recipient_role_will_change? update_participation send_notification_moderation if @participation.unmoderate? update_moderation update_title update_publishing set_deadline send_notification_new_question if should_notify end broadcast(:ok, participation) end private attr_reader :form, :participation, :current_user def update_participation @participation.update_attributes!( body: form.body, participation_type: form.participation_type, category: form.category, recipient_role: form.recipient_role ) end def update_moderation @moderation = @participation.moderation.update_attributes( sqr_status: set_sqr_status, justification: form.moderation.justification, id: @participation.moderation.id ) end def set_sqr_status if @participation.question? && form.moderation.sqr_status == "authorized" "waiting_for_answer" else form.moderation.sqr_status end end def participation_limit_reached? participation_limit = form.current_feature.settings.participation_limit return false if participation_limit.zero? if user_group user_group_participations.count >= participation_limit else current_user_participations.count >= participation_limit end end def recipient_role_will_change? (form.recipient_role != participation.recipient_role) && form.participation_type == "question" && (form.moderation.sqr_status != "refused" ) end def send_notification_new_question recipient_ids = Decidim::ParticipatoryProcessUserRole.where(decidim_participatory_process_id: @current_participatory_process.id, role: participation.recipient_role).map(&:decidim_user_id) Decidim::EventsManager.publish( event: "decidim.events.participations.new_question", event_class: Decidim::Participations::NewParticipationQuestionEvent, resource: @participation, recipient_ids: recipient_ids.uniq, extra: { template: "new_participation_question_event", participatory_process_title: participatory_process_title } ) end def send_notification_moderation Decidim::EventsManager.publish( event: "decidim.events.participations.participation_moderated", event_class: Decidim::Participations::ParticipationModeratedEvent, resource: @participation, recipient_ids: [@participation.author.id], extra: { template: "participation_moderated_#{set_state}_event", participatory_process_title: participatory_process_title, accepted: @form.moderation.sqr_status == "refused" ? false : true, justification: @form.moderation.justification, state: set_state, participation_moderated: true } ) end def set_state # for translations context if @form.moderation.sqr_status == "refused" "refused" else if @form.moderation.justification.present? "modified" else "authorized" end end end def organization @organization ||= current_user.organization end def current_user_participations Participation.where(author: current_user, feature: form.current_feature).where.not(id: participation.id) end def user_group_participations Participation.where(user_group: user_group, feature: form.current_feature).where.not(id: participation.id) end def participatory_process_title if @current_participatory_process.title.is_a?(Hash) @current_participatory_process.title[I18n.locale.to_s] else @current_participatory_process.title end end def update_publishing if @participation.not_publish? && @participation.publishable? @participation.update_attributes(published_on: Time.zone.now) update_state elsif !@participation.publishable? @participation.update_attributes(published_on: nil) end end def update_title if !@participation.publishable? || @participation.refused? @participation.update_attributes(title: nil) else # case : participation is published || A user changed the type of a published participation @participation.update_attributes(title: @participation.generate_title) end end def update_state if @participation.question? && @participation.answer.nil? @participation.update_attributes(state: "waiting_for_answer") end end def set_deadline @participation.update_attributes(answer_deadline: @participation.published_on + 15.days) if @participation.question? && participation.published? end end end end end
cask :v1 => 'openscad' do version '2014.03' sha256 'c324c19c2d36f21517b602f8ae2ec04fa14c90896c91fc8dbb37aed5b3ba16bd' url "http://files.openscad.org/OpenSCAD-#{version}.dmg" name 'OpenSCAD' homepage 'http://www.openscad.org/' license :gpl app 'OpenSCAD.app' end
class WorksController < ApplicationController # Only allow logged in users to access certain pages before_action :logged_in_user, only: [:new, :create, :edit, :update] # Only allow the original user or admin to perform certain actions before_action :check_work_user, only: [:edit, :update, :destroy] # Displays the contents of a single work def show @work = Work.friendly.find(params[:id]) @title = @work.title end # Form to submit a new work def new @work = Work.new @novel = Novel.new @title = 'New Work' end # Creates a new work entry def create if params[:work] && params[:work][:tag_list] && params[:work][:title] # Add the work's title to the list of tags params[:work][:tag_list].downcase! separated_title = params[:work][:title].downcase.split(/\s+/) separated_title.each do |tag| unless params[:work][:tag_list].include? tag params[:work][:tag_list] = params[:work][:tag_list] + ', ' + tag end end end @work = Work.new(work_params) @work.user = current_user if !params[:work][:novel_id].blank? @work.novel = Novel.find(params[:work][:novel_id]) else @work.novel = nil end if @work.save send_new_work_notifications(@work) unless @work.is_private or @work.is_anonymous redirect_to @work else @work_errors = {} @work.errors.each do |attr, msg| @work_errors[attr] = msg end render 'new' end end # Form to edit a previously submitted work def edit @work = Work.friendly.find(params[:id]) @title = 'Edit ' + @work.title end # Updates a previously created work entry def update if params[:work] && params[:work][:tag_list] && params[:work][:title] # Add the work's title to the list of tags params[:work][:tag_list].downcase! separated_title = params[:work][:title].downcase.split(/\s+/) separated_title.each do |tag| unless params[:work][:tag_list].include? tag params[:work][:tag_list] = params[:work][:tag_list] + ', ' + tag end end end @work = Work.friendly.find(params[:id]) @work.slug = nil if !params[:work][:novel_id].blank? @work.novel = Novel.find(params[:work][:novel_id]) else @work.novel = nil end if @work.update(work_params) # Inform users who favourited the work that is has been updated send_new_update_notifications(@work) unless @work.is_private or @work.is_anonymous record_edit_history(@work, current_user) flash[:success] = 'The work was successfully edited.' redirect_to @work else @work_errors = {} @work.errors.each do |attr, msg| @work_errors[attr] = msg end render 'edit' end end # Deletes a single work def destroy @work = Work.friendly.find(params[:id]) unless @work.destroy flash[:error] = 'The work could not be deleted.' end redirect_back_or root_path end private # Parameters required/allowed to create a work entry def work_params params.require(:work).permit(:title, :body, :tag_list, :incomplete, :is_private, :is_anonymous, :novel_id) end # Confirms the user is the owner of the work or an admin def check_work_user owner = Work.friendly.find(params[:id]).user unless owner == current_user || current_user.is_admin? store_location flash[:error] = 'You are not authorized to perform this action.' redirect_to login_path end end end
require('rspec') require('numbers_to_words') describe("Fixnum#numbers_to_words") do it("translates single digit numbers in numeric form into a written word") do expect(1.numbers_to_words()).to(eq("one")) end it("translates numbers less than twenty in numeric form into a written word") do expect(12.numbers_to_words()).to(eq("twelve")) end it("translates numbers less than one-hundred in numeric form into a written word") do expect(73.numbers_to_words()).to(eq("seventy three")) end it("translates numbers less than one_thousand is numeric form into a written word") do expect(192.numbers_to_words()).to(eq("one-hundred ninety two")) end it("translates numbers less than ten_thousand is numeric form into a written word") do expect(7777.numbers_to_words()).to(eq("seven-thousand seven-hundred seventy seven")) end end
class ProcessSanityGenerator < Rails::Generators::Base source_root File.expand_path("../templates", __FILE__) def create_initializer_file copy_file "process_sanity.rb", "config/initializers/process_sanity.rb" end end
class PropertiesController < ApplicationController caches_page :index, if: lambda { |controller| controller.request.xhr? ? false : true } def index @title = "househappy.org" @properties = Property.includes(:neighborhood, :photos).active @properties = @properties.price_lt(params[:price_lt]) if params[:price_lt] @properties = @properties.price_gt(params[:price_gt]) if params[:price_gt] @properties = @properties.bed_gt(params[:bed]) if params[:bed] @properties = @properties.bath_gt(params[:bath]) if params[:bath] @properties = @properties.sqft_lt(params[:sqft_lt]) if params[:sqft_lt] @properties = @properties.sqft_gt(params[:sqft_gt]) if params[:sqft_gt] @properties = @properties.offered_by_in(params[:saleby].split(',')) if params[:saleby] @properties = @properties.sale_types_in(params[:saletype].split(',')) if params[:saletype] @properties = @properties.amenities_in(params[:amenity].split(',')) if params[:amenity] @properties = @properties.parkings_in(params[:parking].split(',')) if params[:parking] @properties = @properties.financing_options_in(params[:financing_option].split(',')) if params[:financing_option] property_types = params[:type].split(',').map { |v| v.to_i } if params[:type] secondary_property_types = params[:secondary_type].split(',').map { |v| v.to_i } if params[:secondary_type] @properties = @properties.type_in(property_types, secondary_property_types) if property_types or secondary_property_types property_styles = params[:style].split(',').map { |v| v.to_i } if params[:style] secondary_property_styles = params[:secondary_style].split(',').map { |v| v.to_i } if params[:secondary_style] @properties = @properties.style_in(property_styles, secondary_property_styles) if property_styles or secondary_property_styles # concessions if params[:concession_ms] or params[:concession_rp] or params[:concession_cc] or params[:concession_mo] concessions = [] concessions << 'concession_motivated_seller' if params[:concession_ms] concessions << 'concession_make_me_an_offer' if params[:concession_mo] concessions << 'concession_reduced_price_amount' if params[:concession_rp] concessions << 'concession_closing_costs_amount' if params[:concession_cc] @properties = @properties.has_concessions(concessions) end if params[:city].nil? && params[:state].nil? if params[:neighborhood].nil? params[:city] = City.closest_city_to_ip(request.remote_ip).id.to_s else params[:city] = Neighborhood.find(params[:neighborhood].split(',').first).city.id.to_s end end if params[:state] @properties = @properties.state_in(params[:state].split(',')) @cities = City.in_states(params[:state].split(',')) end if params[:city] if params[:metro_area] @properties = @properties.city_in(params[:city].split(','), params[:metro_area].to_i) @neighborhoods = Neighborhood.in_cities(params[:city].split(','), params[:metro_area].to_i).order('city_id ASC, name ASC') @attractions = LocalAttraction.in_cities(params[:city].split(','), params[:metro_area].to_i).order('city_id ASC, name ASC') else @properties = @properties.city_in(params[:city].split(',')) @neighborhoods = Neighborhood.in_cities(params[:city].split(',')).order('city_id ASC, name ASC') @attractions = LocalAttraction.in_cities(params[:city].split(',')).order('city_id ASC, name ASC') end if params[:state].blank? @cities = City.in_states(City.find(params[:city].split(',').first).state_id) end @all_cities = City.where(id: params[:city].split(',')).all else @all_cities = [] end @properties = @properties.neighborhood_in(params[:neighborhood].split(',')) if params[:neighborhood] @properties = @properties.local_attractions_in(params[:attraction].split(',')) if params[:attraction] # sorting if params[:sort].nil? then params[:sort] = 'created_desc' end @properties = @properties.price_asc if params[:sort] == 'price_asc' @properties = @properties.price_desc if params[:sort] == 'price_desc' @properties = @properties.created_asc if params[:sort] == 'created_asc' @properties = @properties.created_desc if params[:sort] == 'created_desc' @properties = @properties.likes_asc if params[:sort] == 'likes_asc' @properties = @properties.likes_desc if params[:sort] == 'likes_desc' @properties = @properties.bed_asc if params[:sort] == 'bed_asc' @properties = @properties.bed_desc if params[:sort] == 'bed_desc' # pagination if params[:page] == "1" or params[:page].nil? @properties = @properties.paginate(page: params[:page], per_page: (mobile_browser? ? 20 : 100)) elsif params[:page] @properties = @properties.page(params[:page].to_i + 3) end if mobile_browser? @is_mobile = true end end # ... more magic end
# coding: utf-8 $:.unshift File.expand_path('../lib', __FILE__) require 'vagrant-netinfo/version' Gem::Specification.new do |spec| spec.name = 'vagrant-netinfo' spec.version = VagrantPlugins::Netinfo::VERSION spec.authors = ['Jan Vansteenkiste'] spec.email = ['jan@vstone.eu'] spec.summary = %q{Display network information on a running vagrant box} spec.description = %q{Shows forwarded ports of a running vagrant box} spec.homepage = 'https://github.com/vStone/vagrant-netinfo' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "awesome_print" end
class LinkApplicationsToClients < ActiveRecord::Migration def up add_column :applications, :client_id, :integer end def down remove_column :applications, :client_id end end
class Task < ApplicationRecord belongs_to :user has_many :label_attached_tasks, dependent: :destroy has_many :task_labels, through: :label_attached_tasks validates :title, presence: true, length: { maximum: 30 } validates :description, length: { maximum: 100 } validate :deadline_is_not_past enum status: { not_yet: 0, in_progress: 1, done: 2, pending: 3, discontinued: 4 } enum priority: { low: 1, middle: 2, high: 3 } def self.sort_tasks(column, direction) return order(created_at: :desc) unless column && direction case column when 'priority' order(priority: direction.to_sym) when 'created_at' order(created_at: direction.to_sym) when 'deadline' order(deadline: direction.to_sym) else order(created_at: :desc) end end def self.search_tasks(column, value) case column when 'title' includes(:task_labels).where('tasks.title LIKE ? OR task_labels.title LIKE ?', "%#{value}%", "%#{value}%").references(:task_labels) when 'status' where status: value when 'priority' where priority: value else self end end def save_labels(labels) current_labels = task_labels.pluck(:title) unless task_labels.nil? delete_labels = current_labels - labels new_labels = labels - current_labels delete_labels.each do |label| delete_label = task_labels.find_by(title: label) label_attached_tasks.find_by(task_label_id: delete_label.id).destroy end new_labels.each do |label| post_label = user.task_labels.find_or_create_by(title: label) task_labels << post_label end end def labels_as_string task_labels.pluck(:title).join(",") end private def deadline_is_not_past errors.add(:deadline, 'は過去の日時を設定できません。') if deadline.present? && deadline.past? end end
#!/usr/bin/ruby # This script generates the GERALD command that can be used to create GERALD # directory in the in the flowcell to analyze require 'fileutils' require 'PipelineHelper' require 'ExptDir' class BuildGERALDCommand def initialize(fcName, laneBarcode) # @pipelinePath = "/stornext/snfs5/next-gen/Illumina/GAPipeline/current" + # "/bin/GERALD.pl" @pipelinePath = "/stornext/snfs5/next-gen/Illumina/GAPipeline/CASAVA1_7/" + "CASAVA-1.7.0-Install/bin/GERALD.pl" currentDir = FileUtils.pwd @configPath = currentDir + "/config.txt" @outputFile = currentDir + "/generate_makefiles.sh" @fcName = fcName if @fcName == nil || @fcName.eql?("") raise "Flowcell name is null or empty" end if laneBarcode == nil || laneBarcode.eql?("") raise "Lane barcode is null or empty" end if !File::exist?(@configPath) raise "Config.txt not present in : " + currentDir end # Locate base calls directory for the specified flowcell @pipelineHelperInstance = PipelineHelper.new @baseCallsDir = @pipelineHelperInstance.findBaseCallsDir(@fcName) exptDirFinder = ExptDir.new(@fcName) exptDir = exptDirFinder.getExptDir(laneBarcode) fileHandle = File.new(@outputFile, "w") if !fileHandle || fileHandle == nil raise "Could not create file : generate_makefiles.sh" end # Write the command to generate GERALD directory fileHandle.write(@pipelinePath + " \\\n") fileHandle.write(@configPath + " \\\n") fileHandle.write("--EXPT_DIR \\\n") fileHandle.write(exptDir + " \\\n") fileHandle.write("--make \\\n") fileHandle.write("&> " + @outputFile + ".log\n") fileHandle.close() FileUtils.chmod(0755, @outputFile) end private @pipelinePath = "" # Path to GERALD installation @configPath = "" # Path to GERALD config file @logFilePath = "" # Path to log file created after executing GERALD command @fcName = "" # Full name of Flowcell @fcPath = "" # Path of Flowcell, including its full name @baseCallsDir = "" # Basecalls directory in the flowcell (usually Bustard results) @outputFile = "" # File containing GERALD command end
class ChangeColumnsOrderOnPosts < ActiveRecord::Migration def change change_column :posts, :topic, :string, after: :user_id change_column :posts, :content, :string, after: :topic end end
=begin + Создать модуль InstanceCounter, содержащий следующие методы класса и инстанс-методы, которые подключаются автоматически при вызове include в классе: - Методы класса: - instances, который возвращает кол-во экземпляров данного класса - Инстанс-методы: - register_instance, который увеличивает счетчик кол-ва экземпляров класса и который можно вызвать из конструктора. При этом данный метод не должен быть публичным. + Подключить этот модуль в классы поезда, маршрута и станции. =end module InstanceCounter attr_accessor :instances def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module ClassMethods @@instances = {} def instances @@instances[self] end def increment(initializeClass) if @@instances[initializeClass] @@instances[initializeClass] = @@instances[initializeClass] + 1 else @@instances[initializeClass] = 1 end end end module InstanceMethods protected def register_instance(initializeClass) self.class.increment(initializeClass) end end end
require 'active_support/inflector' require './connection_adapter/column.rb' require './simple_record.rb' class WhereClause def initialize(table_name, col_definitions, primary_key) @col_definitions = col_definitions @table_name = table_name @primary_key = primary_key @value = '' end def build(columns) columns.each_with_index do |(k, v), index| type = column_manipulator.get_column_type(@col_definitions[k][:format_type]) method = "build_#{type}" where_or_and = index == 0 ? 'WHERE' : 'AND' @value += "#{where_or_and} #{self.send(method, k, v)}" end self end def build_chain(columns) @association_cache = {} columns.each_with_index do |(k, v), index| type = column_manipulator.get_column_type(@col_definitions[k][:format_type]) method = "build_#{type}" @value += " AND #{self.send(method, k, v)}" end self end def value @value end private def build_string(key, value) if value.is_a? Array return '1=0' if value.empty? value = value.map do |v| v.is_a?(String) ? "'#{v}'" : nil end.compact "#{key} in (#{value.join(', ')})" else "#{key} = '#{value}'" end end def build_datetime(key, value) if value.is_a? Array return '1=0' if value.empty? value = value.map do |v| v.is_a?(String) ? "'#{v}'" : nil end.compact "#{key} in (#{value.join(', ')})" else "#{key} = '#{value}'" end end def build_integer(key, value) if value.is_a? Array return '1=0' if value.empty? value = value.map do |v| v = v.to_i if v.respond_to?('to_i') v.is_a?(Integer) ? v : nil end.compact "#{key} in (#{value.join(', ')})" else "#{key} = '#{value}'" end end def build_boolean(key, value) if value.is_a? Array return '1=0' if value.empty? value = value.map do |v| v.is_a?(Boolean) ? v : nil end.compact "#{key} in (#{value.join(', ')})" else "#{key} = '#{value}'" end end def column_manipulator Column.column_manipulator(@col_definitions) end def column_exist?(col_name) !!@col_definitions[col_name] end end
# Controlador Pacientes # Acciones index, detalles, nuevo, crear, borrar class PacientesController < ApplicationController def index @q = Paciente.ransack(params[:q]) @pacientes = @q.result(distict: true).paginate(page: params[:page]) end def detalles @paciente = Paciente.find(params[:id]) end def historial @paciente = Paciente.find(params[:id]) @episodios = Episodio.where(paciente: @paciente) .paginate(page: params[:page]).order(:fecha, :hora) end def nuevo @paciente = Paciente.new end def crear @paciente = Paciente.new(permitted_params[:paciente]) if @paciente.save flash[:notice] = 'Paciente agregado con éxito.' redirect_to paciente_path(@paciente) else render :nuevo end end def editar @paciente = Paciente.find(params[:id]) end def actualizar @paciente = Paciente.find(params[:id]) if @paciente.update_attributes(permitted_params[:paciente]) flash[:notice] = 'Paciente actualizado con éxito.' redirect_to paciente_path(@paciente) else render :editar end end def borrar @paciente = Paciente.find(params[:id]) @paciente.destroy flash[:notice] = 'Paciente borrado con éxito.' redirect_to pacientes_path end private def permitted_params params.permit(paciente: [:nombre, :apellido_paterno, :apellido_materno, :curp, :sexo, :fecha_nacimiento, :tipo_sanguineo, :discapacidades, :religion]) end end
require 'spec_helper' describe Page do it { should validate_presence_of :body } it { should validate_presence_of :title } it { should validate_presence_of :page_img_url } it { should validate_presence_of :page_name } it { should allow_mass_assignment_of :body } it { should allow_mass_assignment_of :title } it { should allow_mass_assignment_of :page_img_url } it { should allow_mass_assignment_of :page_name } it { should allow_mass_assignment_of :activate_as_splash } it { should_not allow_mass_assignment_of :id } it { should_not allow_mass_assignment_of :created_at } it { should_not allow_mass_assignment_of :updated_at } end
class Collect < ApplicationRecord belongs_to :custom_collection belongs_to :product validates :position, :sort_value, presence: true validates :sort_value, allow_nil: true, length: { maximum: 10 } end
require 'text_analysis/tokenizer.rb' class BooksController < ApplicationController layout :resolve_layout def open redirect_to root_url if !params[:id] and !/^[0-9]+$/.match(params[:id]) @b = Book.find(params[:id]) redirect_to read_book_path(@b.id) end def request_partial book_id = params[:id] start = params[:start].to_i length = params[:length].to_i book = Book.where(id: book_id.to_i, user_id: current_user.id).first f = File.open(book.book_file_path,"r:UTF-8") text = f.read f.close text = text[start,length] # render json: {start_byte: start_byte, length_bytes: length_bytes, data: []} render json: {start: start, length: length, data: TextAnalysis::Tokenizer.tokenize_text(text)} end # GET /books # GET /books.json def index @books = Book.where(user_id: current_user.id).order("created_at desc") respond_to do |format| format.html # index.html.erb format.json { render json: @books } end end # GET /books/1 # GET /books/1.json def show @book = Book.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @book } end end # GET /books/new # GET /books/new.json def new @book = Book.new flash.clear respond_to do |format| format.html # new.html.erb format.json { render json: @book } end end # GET /books/1/edit def edit @book = Book.find(params[:id]) end # POST /books # POST /books.json def create @book = Book.new(params[:book].permit(:name,:author)) @book.user = current_user if params[:book][:text].length==0 and !params[:book][:file] flash[:error] = "Please upload book file or input some Japanese text" render action: "new" else if params[:book][:text].length>0 @book.book_file = StringIO.new(params[:book][:text]) else @book.book_file = params[:book][:file] end respond_to do |format| if @book.save format.html { redirect_to open_reading_interface_path(@book)} format.json { render json: @book, status: :created, location: @book } else flash[:errors] = @book.errors.full_messages.to_sentence.gsub("Name","Title") format.html { render action: "new" } format.json { render json: @book.errors, status: :unprocessable_entity } end end end end # PUT /books/1 # PUT /books/1.json def update @book = Book.find(params[:id]) respond_to do |format| if @book.update_attributes(params[:book]) format.html { redirect_to @book, notice: 'Book was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @book.errors, status: :unprocessable_entity } end end end # DELETE /books/1 # DELETE /books/1.json def destroy @book = Book.find(params[:id]) @book.destroy respond_to do |format| format.html { redirect_to books_url } format.json { head :no_content } end end private def resolve_layout case action_name when "open" "clear" else "user_area" end end end
json.array!(@student_applications) do |student_application| json.extract! student_application, :id, :student_id, :name, :phone, :email_id, :gpa json.url student_application_url(student_application, format: :json) end
class Contacto < ActiveRecord::Base validates :correo, presence: {message: "El campo correo no debe de estar vacio"} end
# Write a program called name.rb that asks the user to type in their name and then prints out a greeting message with their name included. puts "Give me your name forever!" name = gets.chomp puts "#{name} is mine forever!" # Add another section onto name.rb that prints the name of the user 10 times. You must do this without explicitly writing the puts method 10 times in a row. Hint: you can use the times method to do something repeatedly. 10.times { puts name } # Modify name.rb again so that it first asks the user for their first name, saves it into a variable, and then does the same for the last name. Then outputs their full name all at once. puts "Give me your first name " first_name = gets.chomp puts "Give me your last name " last_name = gets.chomp puts first_name + " " + last_name
class Paradigm < ActiveRecord::Base #Relationships has_many :resources, :dependent => :destroy # Validations validates_presence_of :name, :description, :ranking validates_numericality_of :ranking, only_integer: true validates_uniqueness_of :ranking, :name # Scopes scope :alphabetical, -> { order("name") } scope :by_ranking, -> { order('ranking ASC') } scope :active, -> { where('active = ?', true) } scope :inactive, -> { where('active = ?', false) } # Methods def self.parse(spreadsheet) paradigms_sheet = spreadsheet.sheet("Paradigms") paradigms_hash = paradigms_sheet.parse(name: "Name", description: "Description", ranking: "Ranking") paradigms = [] new_paradigms = [] paradigms_hash.each_with_index do |p, index| # Checks if a Paradigm of the same name exists # If it does, then set the paradigm to the existing paradigm instance # Else create a whole new paradigm instance and add it to the # new_paradigms list in order to be saved later if Paradigm.exists?(name: p[:name]) paradigm = Paradigm.find_by_name(p[:name]) else paradigm = Paradigm.new paradigm.attributes = p.to_hash new_paradigms << paradigm end paradigms << paradigm end return paradigms, new_paradigms end #TODO: Implement methods for ranking alteration based on user input end
class GoogleCalendarReminder < ApplicationRecord belongs_to :google_calendar scope :ready, -> { where(announced: false).where('remind_at < NOW()') } scope :upcoming, -> { where('remind_at > NOW()') } def announce return if announced? SpeechEngine.say(content, volume: 100) update_attribute :announced, true end end
require './sales_calculator' RSpec.configure do |config| config.mock_framework = :mocha end describe SalesCalculator do let(:klass) { SalesCalculator } describe 'calculations' do describe 'SalesCalculator::NEXT_FREE' do # Original price is set to 2$ # Sale will be applied on each second product let(:sale) { {:min_count => 2} } [ {:quantity => 0, :expected_sale => 0}, {:quantity => 1, :expected_sale => 0}, {:quantity => 2, :expected_sale => 2}, {:quantity => 3, :expected_sale => 2}, {:quantity => 4, :expected_sale => 4}, {:quantity => 5, :expected_sale => 4}, {:quantity => 6, :expected_sale => 6} ].each do |test| it "sale should be #{test[:expected_sale]} if quantity is #{test[:quantity]}" do klass::NEXT_FREE.call(test[:quantity], sale, 2).should == test[:expected_sale] end end end describe 'SalesCalculator::MORE_PAY_LESS' do # - Original price is set to 2$ # - Price per item after sale is set to 1$ # - Sale will be applied on each product if # quantity of the product is 3 and more let(:sale) { {:min_count => 3, :new_price => 1} } [ {:quantity => 0, :expected_sale => 0}, {:quantity => 1, :expected_sale => 0}, {:quantity => 2, :expected_sale => 0}, {:quantity => 3, :expected_sale => 3}, {:quantity => 4, :expected_sale => 4}, {:quantity => 5, :expected_sale => 5}, {:quantity => 6, :expected_sale => 6} ].each do |test| it "sale should be #{test[:expected_sale]} if quantity is #{test[:quantity]}" do klass::MORE_PAY_LESS.call(test[:quantity], sale, 2).should == test[:expected_sale] end end end end describe 'SalesCalculator::SALES' do subject { klass::SALES } it do should include({ :product_code => 'FR1', :calculation => klass::NEXT_FREE, :min_count => 2 }) end it do should include({ :product_code => 'SR1',:calculation => klass::MORE_PAY_LESS, :min_count => 3, :new_price => 4.50 }) end end describe 'SalesCalculator::calculate' do let(:calculate) { klass::calculate } let(:product) { { :code => 'FR1', :price => 2 } } context 'more applicable sales' do let(:new_sale) { { :product_code => 'FR1', :calculation => klass::NEXT_FREE, :price => 1 } } before do SalesCalculator::SALES << new_sale # Whenever is sale calculation Next Free caled it returns 2$ SalesCalculator::NEXT_FREE.stubs(:call).returns(2) end it 'should return 4$ sale, because NEXT_FREE is caled 2times' do SalesCalculator::calculate(product, 0).should == 4 end end end end
class CoachesController < ApplicationController before_action :validate_admin # 教练列表首页 def index @coaches = User.coaches.order("updated_at desc") end def search end # 添加教练 def new end # 创建教练 def create User.transaction do coach = User.create(post_params) coach.add_coach end redirect_to coaches_url end # 显示某个教练信息 def show end # 编辑教练信息 def edit end # 更新教练信息 def update end # 删除教练信息 def destroy end private def post_params params.require(:coach).permit(:name, :phone, :sex, :password, :password_confirmation, :description) end end
class Song < ActiveRecord::Base attr_accessible :album_id, :title has_one :artist, :through => :album belongs_to :album end